public int CalculateHashCode(int emptyHashCode, SubstitutionSet subs) { var set = GetGroundedSubstitutions(subs); if (!set.Any()) return emptyHashCode; var hashs = set.Select(s => s.GetHashCode()); var h = hashs.Aggregate((v1, v2) => v1 ^ v2); return emptyHashCode ^ h; }
private static bool FindSubst(Name n1, Name n2, bool allowPartialTerms, SubstitutionSet bindings) { n1 = n1.MakeGround(bindings); n2 = n2.MakeGround(bindings); var t = GetTerms(n1, n2, allowPartialTerms); if (t == null) return false; foreach (var p in t) { Substitution candidate = null; bool isVar1 = p.Item1.IsVariable; bool isVar2 = p.Item2.IsVariable; // Case 1: x = t, where t is not a variable and x is a variable, and create substitution x/t if (isVar1 != isVar2) { Name variable = (isVar1 ? p.Item1 : p.Item2); Name value = isVar1 ? p.Item2 : p.Item1; if (value.ContainsVariable(variable)) //Occurs check to prevent cyclical evaluations return false; candidate = new Substitution(variable, value); } else if (isVar1) //isVar1 == isVar2 == true { //Case 2: x = x, where x is a variable, ignore it. otherwise add the substitution if (!(p.Item1 == p.Item2)) candidate = new Substitution(p.Item1, p.Item2); } else //isVar1 == isVar2 == false { // Case 3: t1 = t2, where t1,t2 are not variables. // If they don't contain variables, compare them to see if they are equal. If they are not equal the unification fails. if (p.Item1.IsGrounded && p.Item2.IsGrounded) { if (p.Item1 == p.Item2) continue; return false; } //If one or both contain variables, unify the terms if (!FindSubst(p.Item1, p.Item2,allowPartialTerms, bindings)) return false; } if (candidate != null) { // Step 4: check to see if the newly created substitution conflicts with any of the already created substitution. // If it does, the unification fails. if (!bindings.AddSubstitution(candidate)) return false; } } return true; }
public bool TestConflict(Substitution subs, SubstitutionSet set, out bool canAdd) { canAdd = true; Name value; if (!m_substitutions.TryGetValue(subs.Variable, out value)) return false; canAdd = false; var G1 = value.MakeGround(set); var G2 = subs.Value.MakeGround(set); return !G1.Equals(G2); //Conflict!!! }
public bool TestConflict(Substitution subs, SubstitutionSet set, out bool canAdd) { canAdd = true; Constraint c; if (!m_constraints.TryGetValue(subs.Variable, out c)) return false; Name G1 = c.Value; Name G2; if (subs.Value.IsVariable) { if (c.EquivalentVariables.Contains(subs.Value)) { canAdd = false; return false; } Constraint c2; if (!m_constraints.TryGetValue(subs.Value, out c2)) return false; if (c.Value == null || c2.Value == null) return false; G2 = c2.Value; } else { if (G1 == null) return false; canAdd = false; G2 = subs.Value; return !G1.Equals(G2); //Conflict!!! } G1 = G1.MakeGround(set); G2 = G2.MakeGround(set); return !G1.Equals(G2); //Conflict!!! }
public void SubstitutionSet_Contains_Assert_Name_as_Variable(string variable, string[] substitutions) { var s = new SubstitutionSet(substitutions.Select(str => new Substitution(str))); Assert.Throws<ArgumentException>(()=>s.Contains((Name) variable)); }
public void SubstitutionSet_CountTest(int amount, string[] substitutions) { var s = new SubstitutionSet(substitutions.Select(str => new Substitution(str))); Assert.AreEqual(s.Count(), amount); }
private static IEnumerable<DynamicPropertyResult> HasLiteralPropertyCalculator(IQueryContext context, Name x, Name y) { if (!(y.IsVariable || y.IsComposed)) return Enumerable.Empty<DynamicPropertyResult>(); List<DynamicPropertyResult> results = ObjectPool<List<DynamicPropertyResult>>.GetObject(); try { IEnumerable<Name> candidates; if (y.IsVariable) { candidates = context.Constraints.Select(s => s[y]).Where(n => n != null); } else if (!y.IsGrounded) { candidates = context.Constraints.Select(y.MakeGround).Where(c => c.IsConstant); } else { candidates = new[] { y }; } foreach (var c in candidates) { foreach (var t in c.GetTerms()) { if (x.IsVariable) { var sub = new Substitution(x,new ComplexValue(t)); foreach (var g in context.Constraints) { if(g.Conflicts(sub)) continue; var s = new SubstitutionSet(g); s.AddSubstitution(sub); results.Add(new DynamicPropertyResult(new ComplexValue(Name.BuildName(true)),s)); } } else { foreach (var x2 in context.AskPossibleProperties(x)) { if (x2.Item1.Value == t) { var r = Name.BuildName(true); foreach (var s in x2.Item2) { results.Add(new DynamicPropertyResult(new ComplexValue(r), s)); } } } } } } return results.ToArray(); } finally { results.Clear(); ObjectPool<List<DynamicPropertyResult>>.Recycle(results); } }
public void AddSubstitutions_V4_Fail(string[] s1, string[] s2) { var set1 = new SubstitutionSet(s1.Select(str => new Substitution(str))); set1.AddSubstitutions(s2.Select(str => new Substitution(str))); }
public IEnumerable <Pair <DialogStateAction, SubstitutionSet> > GetAllDialogsForKey(Name key, SubstitutionSet bindings = null) { var a = m_nameToDialogues.Unify(key, bindings); foreach (var pair in a) { foreach (var d in pair.Item1) { yield return(Tuples.Create(d, pair.Item2)); } } }
private IEnumerable<DynamicPropertyResult> EventAgePropertyCalculator(IQueryContext context, Name id) { if(!context.Perspective.Match(Name.SELF_SYMBOL)) yield break; if (id.IsVariable) { foreach (var record in m_registry.Values) { var idSub = new Substitution(id, Name.BuildName(record.Id)); foreach (var c in context.Constraints) { if (c.Conflicts(idSub)) continue; var newSet = new SubstitutionSet(c); newSet.AddSubstitution(idSub); var value = Tick - record.Timestamp; yield return new DynamicPropertyResult(Name.BuildName(value), newSet); } } yield break; } foreach (var pair in context.AskPossibleProperties(id)) { uint idValue; if(!pair.Item1.TryConvertToValue(out idValue)) continue; var record = m_registry[idValue]; var value = (Tick - record.Timestamp); foreach (var c in pair.Item2) yield return new DynamicPropertyResult(Name.BuildName(value), c); } }
public float VolitionValue(Name step, Name targ, Name mode, KB m_Kb) { if (m_Kb.Perspective == targ) { return(-1); } var targetSub = new Substitution(Target, new ComplexValue(targ)); var constraints = new SubstitutionSet(); constraints.AddSubstitution(targetSub); float total = Single.NegativeInfinity; // List<SubstitutionSet> resultingConstraints = new List<SubstitutionSet>(); if (step == this.Steps.FirstOrDefault()) { var resultingConstraints = StartingConditions.FirstOrDefault().Unify(m_Kb, m_Kb.Perspective, new[] { constraints }).ToList(); if (StartingConditions.Count() > 1) { int counter = 0; foreach (var c in StartingConditions) // For instance SI([x]) >= 40 { if (counter == 0) { continue; } resultingConstraints = c.Unify(m_Kb, m_Kb.Perspective, resultingConstraints).ToList(); // Whats the sub here [x]/John } } if (resultingConstraints.Count() == 0) { return(total); } foreach (var res in resultingConstraints) { if (resultingConstraints.Count() > 0) // Assuming all Starting COnditions match lets go into the Influence Rules { foreach (var constraint in resultingConstraints) // var condition = c.ToString(); { var contraintVolitionValue = .0f; // var certainty = res.FindMinimumCertainty(); // How do I ask SI(John) >= 40 and get its certainty //total += certainty; var influenceRuleList = new List <InfluenceRule>(); if (mode.IsUniversal) { influenceRuleList = this.InfluenceRules; } else { influenceRuleList = this.InfluenceRules.FindAll(x => x.Mode == mode); } foreach (var inf in influenceRuleList) { var toSum = inf.EvaluateInfluenceRule(m_Kb, constraint); contraintVolitionValue += toSum; } if (contraintVolitionValue > total) { total = contraintVolitionValue; } } } } //What if the step is beyond the first one, we should not consider Starting Conditions, or any conditions at all, only the influence rules } else { var VolVal = .0f; var influenceRuleList = new List <InfluenceRule>(); if (mode.IsUniversal) { influenceRuleList = this.InfluenceRules; } else { influenceRuleList = this.InfluenceRules.FindAll(x => x.Mode == mode); } foreach (var inf in influenceRuleList) { var toSum = inf.EvaluateInfluenceRule(m_Kb, constraints); VolVal += toSum; } if (VolVal > total) { total = VolVal; } } return(total); }
public DynamicPropertyMatch(DynamicKnowledgeEntry entry, SubstitutionSet variables) { _entry = entry; _variable = variables; }
public IEnumerable <DynamicPropertyResult> Evaluate(IQueryable kb, Name perspective, SubstitutionSet args2, IEnumerable <SubstitutionSet> constraints) { var args = ObjectPool <List <Name> > .GetObject(); try { args.AddRange(_parameters.Select(p => args2[p]).Select(v => v == null ? Name.UNIVERSAL_SYMBOL : v.RemoveBoundedVariables(TMP_MARKER))); return(_surogate(new QueryContext(kb, constraints, perspective), args)); } finally { args.Clear(); ObjectPool <List <Name> > .Recycle(args); } }
public void AddSubstitutions_V3_Fail(string s1, string s2) { var set1 = new SubstitutionSet(new Substitution(s1)); var set2 = new SubstitutionSet(new Substitution(s2)); set2.AddSubstitutions(set1); }
public IEnumerable <DynamicPropertyResult> VolitionPropertyCalculator(IQueryContext context, Name socialMoveName, Name Step, Name Target, Name Mode) { Dictionary <SubstitutionSet, Name> ret = new Dictionary <SubstitutionSet, Name>(); var stringVolition = ""; var possibleSE = new List <SocialExchange>(); bool SEConstraint = false; if (context.Perspective != Name.SELF_SYMBOL) { yield break; } if (this.m_kB.Perspective == Target) { yield break; } List <Name> possibleSEs = new List <Name>(); if (socialMoveName.IsVariable) { foreach (var s in context.AskPossibleProperties(socialMoveName)) { possibleSEs.Add(s.Item1.Value); } foreach (var se in this.m_SocialExchanges) { possibleSEs.Add(se.Name); } } else if (socialMoveName.IsUniversal) { foreach (var se in this.m_SocialExchanges) { possibleSEs.Add(se.Name); } } else { possibleSEs.Add(socialMoveName); } List <Name> possibleTargets = new List <Name>(); if (Target.IsVariable) { foreach (var s in context.AskPossibleProperties(Target)) { possibleTargets.Add(s.Item1.Value); } } else { possibleTargets.Add(Target); } List <Name> possibleModes = new List <Name>(); if (Mode.IsVariable) { foreach (var s in context.AskPossibleProperties(Mode)) { possibleModes.Add(s.Item1.Value); } } else { possibleModes.Add(Mode); } foreach (var seName in possibleSEs) { if (!m_SocialExchanges.Exists(x => x.Name == seName)) { continue; } foreach (var targ in possibleTargets) { var actualStep = FilterStep(seName, targ); if (actualStep.ToString() == "-") { continue; } foreach (var seMode in possibleModes) { var volValue = CalculateSocialMoveVolition(seName, actualStep, targ, seMode); if (volValue != Single.NegativeInfinity) { var subSet = new SubstitutionSet(); if (socialMoveName.IsVariable) { var sub = new Substitution(socialMoveName, new ComplexValue(seName, 1)); subSet.AddSubstitution(sub); } if (Step.IsVariable) { var sub = new Substitution(Step, new ComplexValue(actualStep, 1)); subSet.AddSubstitution(sub); } if (Target.IsVariable) { var sub = new Substitution(Target, new ComplexValue(targ, 1)); subSet.AddSubstitution(sub); } if (Mode.IsVariable) { var sub = new Substitution(Mode, new ComplexValue(seMode, 1)); subSet.AddSubstitution(sub); } if (context.Constraints.Count() > 0) { foreach (var c in context.Constraints) { if (c.Conflicts(subSet)) { continue; } var newcontext = new SubstitutionSet(); newcontext.AddSubstitutions(c); newcontext.AddSubstitutions(subSet); yield return(new DynamicPropertyResult(new ComplexValue(Name.BuildName(volValue)), newcontext)); } } else { yield return(new DynamicPropertyResult(new ComplexValue(Name.BuildName(volValue)), subSet)); } } } } } }
public void AddSubstitutions_V3_Pass(params string[] substitutions) { var s = new SubstitutionSet(substitutions.Select(s1 => new Substitution(s1))); var s2 = new SubstitutionSet(); s2.AddSubstitutions(s); }
public IEnumerable<DynamicPropertyResult> Evaluate(IQueryable kb, Name perspective, SubstitutionSet args2, IEnumerable<SubstitutionSet> constraints) { //var dic = ObjectPool<Dictionary<Name, Name>>.GetObject(); var args = ObjectPool<List<Name>>.GetObject(); try { //foreach(var s in args2) //{ // var p = s.Variable.RemoveBoundedVariables(TMP_MARKER); // dic[p] = s.Value; // if (!s.Value.IsVariable) // continue; // dic[s.Value] = p; //} args.AddRange(_parameters.Select(p => args2[p]).Select(v => v == null ? Name.UNIVERSAL_SYMBOL : v.RemoveBoundedVariables(TMP_MARKER))); //args.AddRange(_parameters.Select(p => //{ // Name v; // if (dic.TryGetValue(p, out v)) // return v; // return Name.UNIVERSAL_SYMBOL; //})); return _surogate(new QueryContext(kb, constraints, perspective),args); } finally { args.Clear(); ObjectPool<List<Name>>.Recycle(args); //dic.Clear(); //ObjectPool<Dictionary<Name, Name>>.Recycle(dic); } }
public void AddSubstitution_V1_Pass(params string[] substitutions) { var s = new SubstitutionSet(); foreach (var s2 in substitutions.Select(s1 => new Substitution(s1))) s.AddSubstitution(s2); }
public IEnumerable <Pair <T, SubstitutionSet> > Unify(Stack <Name> stack, SubstitutionSet binding) { if (stack.Count == 0) //End stack { if (m_hasValue) { yield return(Tuples.Create(m_value, binding)); } yield break; } TreeNode nodeToEvaluate; Name term = stack.Pop(); if (!term.IsVariable) { int numOfTerms = term.NumberOfTerms; if (numOfTerms == 1) { var selectedNodes = Enumerable.Empty <TreeNode>(); Name key = term; if (key.IsUniversal) { if (m_universal != null) { selectedNodes = selectedNodes.Append(m_universal); } selectedNodes = selectedNodes.Union(GetNextLevel().SelectMany(p => p.Item2)); } else { if (m_nextSymbol != null && m_nextSymbol.TryGetValue(key, out nodeToEvaluate)) { selectedNodes = selectedNodes.Append(nodeToEvaluate); } if (m_universal != null) { selectedNodes = selectedNodes.Append(m_universal); } } foreach (var pair in selectedNodes.SelectMany(n => n.Unify(stack, binding))) { yield return(pair); } } else { if (m_nextComposed != null && m_nextComposed.TryGetValue(numOfTerms, out nodeToEvaluate)) { using (var it = term.GetTerms().Reverse().GetEnumerator()) { while (it.MoveNext()) { stack.Push(it.Current); } } foreach (var pair in nodeToEvaluate.Unify(stack, binding)) { yield return(pair); } for (int i = 0; i < term.NumberOfTerms; i++) { stack.Pop(); } } if (m_universal != null) { foreach (var pair in m_universal.Unify(stack, binding)) { yield return(pair); } } } if (m_nextVariable != null) { //Find bindings with stored variables foreach (var pair in m_nextVariable) { var sub = new Substitution(pair.Key, new ComplexValue(term)); if (binding.Conflicts(sub)) { continue; } var set = new SubstitutionSet(binding); set.AddSubstitution(sub); foreach (var r in pair.Value.Unify(stack, set)) { yield return(r); } } } } else { //Find bindings var nextLevel = GetNextLevel(); foreach (var pair in nextLevel) { SubstitutionSet set = binding; if (!pair.Item1.IsVariable || pair.Item1 != term) { //Very odd trick to make certainty work var sub = new Substitution(term, new ComplexValue(pair.Item1, 1)); if (binding.Conflicts(sub)) { continue; } set = new SubstitutionSet(set); set.AddSubstitution(sub); } foreach (var node in pair.Item2) { foreach (var r in node.Unify(stack, set)) { yield return(r); } } } } stack.Push(term); }
public void SubstitutionSet_Contains_Pass(string variable, string[] substitutions) { var s = new SubstitutionSet(substitutions.Select(str => new Substitution(str))); Assert.True(s.Contains((Name) variable)); }
public DynamicPropertyResult(Name value, SubstitutionSet constraint) { Value = value; Constraints = constraint; }
public IEnumerable<Substitution> GetGroundedSubstitutions(SubstitutionSet other) { if (m_substitutions.Count == 0) yield break; var cloned = ObjectPool<HashSet<Name>>.GetObject(); foreach (var key in m_constraints.Keys) { if (cloned.Contains(key)) continue; var constraint = m_constraints[key]; foreach (var v in constraint.EquivalentVariables) { if (constraint.Value != null) yield return new Substitution(v, constraint.Value.MakeGround(other)); cloned.Add(v); } } cloned.Clear(); ObjectPool<HashSet<Name>>.Recycle(cloned); }
public void NameDictionary_Invalid_Unify(NameSearchTree<int> dict, Name expression, SubstitutionSet bindings) { var result = dict.Unify(expression, bindings); Assert.That(!result.Any(),"The unification returned valid results."); }
public int CalculateHashCode(int emptyHash, SubstitutionSet set) { if (m_hashIsDirty) { m_hash = emptyHash; if (m_substitutions.Count > 0) { var cloned = ObjectPool<HashSet<Name>>.GetObject(); foreach (var key in m_constraints.Keys) { if (cloned.Contains(key)) continue; var constraint = m_constraints[key]; m_hash ^= constraint.EquivalentVariables.Select(v => v.GetHashCode()).Aggregate((h1, h2) => h1 ^ h2); if (constraint.Value != null) m_hash ^= constraint.Value.GetHashCode(); } cloned.Clear(); ObjectPool<HashSet<Name>>.Recycle(cloned); } m_hashIsDirty = false; } return m_hash; }
public void NameDictionary_Valid_Unify(NameSearchTree<int> dict, Name expression, SubstitutionSet bindings, IEnumerable<Pair<int, SubstitutionSet>> expectedResults) { var result = dict.Unify(expression, bindings); var resultDict = result.ToDictionary(p => p.Item1, p => p.Item2); var expectDict = expectedResults.ToDictionary(p => p.Item1, p => p.Item2); Assert.AreEqual(expectDict.Count, resultDict.Count, "Number of results mismatch"); foreach (var pair in resultDict) { SubstitutionSet t; Assert.That(expectDict.TryGetValue(pair.Key, out t), "Unable to find entry"); Assert.That(t.Equals(pair.Value), "Binding list is not equal to the expected"); } }
public IEnumerable<Substitution> GetGroundedSubstitutions(SubstitutionSet other) { if (m_substitutions.Count > 0) return m_substitutions.Select(e => new Substitution(e.Key, e.Value.MakeGround(other))).Distinct(); return Enumerable.Empty<Substitution>(); }
public void AddSubstitutions_V2_Fail(params string[] substitutions) { var s = new SubstitutionSet(); s.AddSubstitutions(substitutions.Select(s1 => new Substitution(s1))); }
public void MakeGround_GroundedName(string n1, string var, string sub, string expectedResult, Refactorization r) { String result = string.Empty; if (r == Refactorization.New) { var name = new SimpleName(n1); SimpleName nameResult = null; Dictionary<string, SimpleName> subs = new Dictionary<string, SimpleName>(); subs[var] = new SimpleName(sub); for (long i = 0; i < reps; i++) { nameResult = SimpleWFN.MakeGround(name, subs); } result = nameResult.ToString(); } else if (r == Refactorization.Current) { var name = Name.BuildName(n1); Name nameResult = null; SubstitutionSet subSet = new SubstitutionSet(); subSet.AddSubstitution(new Substitution("[x]/J(I)")); for (long i = 0; i < reps; i++) { nameResult = name.MakeGround(subSet); } } Assert.AreEqual(expectedResult, result); }
private static IEnumerable<Substitution> FindSubst(Name n1, Name n2, bool allowPartial) { SubstitutionSet bindings = new SubstitutionSet(); if (!FindSubst(n1, n2,allowPartial, bindings)) return null; return bindings; }