PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/YieldProlog/Modules/BagofAnswers.cs

https://bitbucket.org/VirtualReality/optional-modules
C# | 236 lines | 149 code | 17 blank | 70 comment | 18 complexity | c4f34006691b5481d627d5eac7d678fb MD5 | raw file
  1. /*
  2. * Copyright (c) Contributors, http://aurora-sim.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the Aurora-Sim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
  31. {
  32. /// <summary>
  33. /// A BagofAnswers holds answers for bagof and setof.
  34. /// </summary>
  35. public class BagofAnswers
  36. {
  37. private object _template;
  38. private Variable[] _freeVariables;
  39. private Dictionary<object[], List<object>> _bagForFreeVariables;
  40. private List<object> _findallBagArray;
  41. private static TermArrayEqualityComparer _termArrayEqualityComparer =
  42. new TermArrayEqualityComparer();
  43. /// <summary>
  44. /// To get the free variables, split off any existential qualifiers from Goal such as the X in
  45. /// "X ^ f(Y)", get the set of unbound variables in Goal that are not qualifiers, then remove
  46. /// the unbound variables that are qualifiers as well as the unbound variables in Template.
  47. /// </summary>
  48. /// <param name="Template"></param>
  49. /// <param name="Goal"></param>
  50. public BagofAnswers(object Template, object Goal)
  51. {
  52. _template = Template;
  53. // First get the set of variables that are not free variables.
  54. List<Variable> variableSet = new List<Variable>();
  55. YP.addUniqueVariables(Template, variableSet);
  56. object UnqualifiedGoal = YP.getValue(Goal);
  57. while (UnqualifiedGoal is Functor2 && ((Functor2)UnqualifiedGoal)._name == Atom.HAT)
  58. {
  59. YP.addUniqueVariables(((Functor2)UnqualifiedGoal)._arg1, variableSet);
  60. UnqualifiedGoal = YP.getValue(((Functor2)UnqualifiedGoal)._arg2);
  61. }
  62. // Remember how many non-free variables there are so we can find the unique free variables
  63. // that are added.
  64. int nNonFreeVariables = variableSet.Count;
  65. YP.addUniqueVariables(UnqualifiedGoal, variableSet);
  66. int nFreeVariables = variableSet.Count - nNonFreeVariables;
  67. if (nFreeVariables == 0)
  68. {
  69. // There were no free variables added, so we won't waste time with _bagForFreeVariables.
  70. _freeVariables = null;
  71. _findallBagArray = new List<object>();
  72. }
  73. else
  74. {
  75. // Copy the free variables.
  76. _freeVariables = new Variable[nFreeVariables];
  77. for (int i = 0; i < nFreeVariables; ++i)
  78. _freeVariables[i] = variableSet[i + nNonFreeVariables];
  79. _bagForFreeVariables = new Dictionary<object[], List<object>>(_termArrayEqualityComparer);
  80. }
  81. }
  82. public void add()
  83. {
  84. if (_freeVariables == null)
  85. // The goal has bound the values in _template but we don't bother with _freeVariables.
  86. _findallBagArray.Add(YP.makeCopy(_template, new Variable.CopyStore()));
  87. else
  88. {
  89. // The goal has bound the values in _template and _freeVariables.
  90. // Find the entry for this set of _freeVariables values.
  91. object[] freeVariableValues = new object[_freeVariables.Length];
  92. for (int i = 0; i < _freeVariables.Length; ++i)
  93. freeVariableValues[i] = YP.getValue(_freeVariables[i]);
  94. List<object> bagArray;
  95. if (!_bagForFreeVariables.TryGetValue(freeVariableValues, out bagArray))
  96. {
  97. bagArray = new List<object>();
  98. _bagForFreeVariables[freeVariableValues] = bagArray;
  99. }
  100. // Now copy the template and add to the bag for the freeVariables values.
  101. bagArray.Add(YP.makeCopy(_template, new Variable.CopyStore()));
  102. }
  103. }
  104. // disable warning on l1, don't see how we can
  105. // code this differently
  106. #pragma warning disable 0168, 0219
  107. /// <summary>
  108. /// For each result, unify the _freeVariables and unify bagArrayVariable with the associated bag.
  109. /// </summary>
  110. /// <param name="bagArrayVariable">this is unified with the List<object> of matches for template that
  111. /// corresponds to the bindings for freeVariables. Be very careful: this does not unify with a Prolog
  112. /// list.</param>
  113. /// <returns></returns>
  114. public IEnumerable<bool> resultArray(Variable bagArrayVariable)
  115. {
  116. if (_freeVariables == null)
  117. {
  118. // No unbound free variables, so we only filled one bag. If empty, bagof fails.
  119. if (_findallBagArray.Count > 0)
  120. {
  121. foreach (bool l1 in bagArrayVariable.unify(_findallBagArray))
  122. yield return false;
  123. }
  124. }
  125. else
  126. {
  127. foreach (KeyValuePair<object[], List<object>> valuesAndBag in _bagForFreeVariables)
  128. {
  129. foreach (bool l1 in YP.unifyArrays(_freeVariables, valuesAndBag.Key))
  130. {
  131. foreach (bool l2 in bagArrayVariable.unify(valuesAndBag.Value))
  132. yield return false;
  133. }
  134. // Debug: Should we free memory of the answers already returned?
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// For each result, unify the _freeVariables and unify Bag with the associated bag.
  140. /// </summary>
  141. /// <param name="Bag"></param>
  142. /// <returns></returns>
  143. public IEnumerable<bool> result(object Bag)
  144. {
  145. Variable bagArrayVariable = new Variable();
  146. foreach (bool l1 in resultArray(bagArrayVariable))
  147. {
  148. foreach (bool l2 in YP.unify(Bag, ListPair.make((List<object>)bagArrayVariable.getValue())))
  149. yield return false;
  150. }
  151. }
  152. /// <summary>
  153. /// For each result, unify the _freeVariables and unify Bag with the associated bag which is sorted
  154. /// with duplicates removed, as in setof.
  155. /// </summary>
  156. /// <param name="Bag"></param>
  157. /// <returns></returns>
  158. public IEnumerable<bool> resultSet(object Bag)
  159. {
  160. Variable bagArrayVariable = new Variable();
  161. foreach (bool l1 in resultArray(bagArrayVariable))
  162. {
  163. List<object> bagArray = (List<object>)bagArrayVariable.getValue();
  164. YP.sortArray(bagArray);
  165. foreach (bool l2 in YP.unify(Bag, ListPair.makeWithoutRepeatedTerms(bagArray)))
  166. yield return false;
  167. }
  168. }
  169. public static IEnumerable<bool> bagofArray
  170. (object Template, object Goal, IEnumerable<bool> goalIterator, Variable bagArrayVariable)
  171. {
  172. BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
  173. foreach (bool l1 in goalIterator)
  174. bagOfAnswers.add();
  175. return bagOfAnswers.resultArray(bagArrayVariable);
  176. }
  177. public static IEnumerable<bool> bagof
  178. (object Template, object Goal, IEnumerable<bool> goalIterator, object Bag)
  179. {
  180. BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
  181. foreach (bool l1 in goalIterator)
  182. bagOfAnswers.add();
  183. return bagOfAnswers.result(Bag);
  184. }
  185. public static IEnumerable<bool> setof
  186. (object Template, object Goal, IEnumerable<bool> goalIterator, object Bag)
  187. {
  188. BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
  189. foreach (bool l1 in goalIterator)
  190. bagOfAnswers.add();
  191. return bagOfAnswers.resultSet(Bag);
  192. }
  193. #pragma warning restore 0168, 0219
  194. /// <summary>
  195. /// A TermArrayEqualityComparer implements IEqualityComparer to compare two object arrays using YP.termEqual.
  196. /// </summary>
  197. private class TermArrayEqualityComparer : IEqualityComparer<object[]>
  198. {
  199. public bool Equals(object[] array1, object[] array2)
  200. {
  201. if (array1.Length != array2.Length)
  202. return false;
  203. for (int i = 0; i < array1.Length; ++i)
  204. {
  205. if (!YP.termEqual(array1[i], array2[i]))
  206. return false;
  207. }
  208. return true;
  209. }
  210. public int GetHashCode(object[] array)
  211. {
  212. int hashCode = 0;
  213. for (int i = 0; i < array.Length; ++i)
  214. hashCode ^= array[i].GetHashCode();
  215. return hashCode;
  216. }
  217. }
  218. }
  219. }