node.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # vim: set fileencoding=utf-8 :
  2. import os.path
  3. import sys
  4. import copy
  5. sys.path.insert(0, os.path.realpath('external'))
  6. from graph_drawing.graph import generate_graph
  7. from graph_drawing.line import generate_line
  8. from graph_drawing.node import Node, Leaf
  9. TYPE_OPERATOR = 1
  10. TYPE_IDENTIFIER = 2
  11. TYPE_INTEGER = 4
  12. TYPE_FLOAT = 8
  13. # Unary
  14. OP_NEG = 1
  15. # Binary
  16. OP_ADD = 2
  17. OP_SUB = 3
  18. OP_MUL = 4
  19. OP_DIV = 5
  20. OP_POW = 6
  21. OP_MOD = 7
  22. # N-ary (functions)
  23. OP_INT = 8
  24. OP_COMMA = 9
  25. OP_SQRT = 10
  26. # Goniometry
  27. OP_SIN = 11
  28. OP_COS = 12
  29. OP_TAN = 13
  30. OP_SOLVE = 14
  31. OP_EQ = 15
  32. OP_POSSIBILITIES = 16
  33. OP_HINT = 17
  34. OP_REWRITE_ALL = 18
  35. OP_REWRITE = 19
  36. TYPE_MAP = {
  37. int: TYPE_INTEGER,
  38. float: TYPE_FLOAT,
  39. str: TYPE_IDENTIFIER,
  40. }
  41. OP_MAP = {
  42. ',': OP_COMMA,
  43. '+': OP_ADD,
  44. '-': OP_SUB,
  45. '*': OP_MUL,
  46. '/': OP_DIV,
  47. '^': OP_POW,
  48. 'sin': OP_SIN,
  49. 'cos': OP_COS,
  50. 'tan': OP_TAN,
  51. 'sqrt': OP_SQRT,
  52. 'int': OP_INT,
  53. 'solve': OP_SOLVE,
  54. '=': OP_EQ,
  55. '??': OP_POSSIBILITIES,
  56. '?': OP_HINT,
  57. '@@': OP_REWRITE_ALL,
  58. '@': OP_REWRITE,
  59. }
  60. TOKEN_MAP = {
  61. OP_COMMA: 'COMMA',
  62. OP_ADD: 'PLUS',
  63. OP_SUB: 'MINUS',
  64. OP_MUL: 'TIMES',
  65. OP_DIV: 'DIVIDE',
  66. OP_POW: 'POW',
  67. OP_SQRT: 'FUNCTION',
  68. OP_SIN: 'FUNCTION',
  69. OP_COS: 'FUNCTION',
  70. OP_TAN: 'FUNCTION',
  71. OP_INT: 'FUNCTION',
  72. OP_SOLVE: 'FUNCTION',
  73. #OP_SQRT: 'SQRT',
  74. #OP_SIN: 'SIN',
  75. #OP_COS: 'COS',
  76. #OP_TAN: 'TAN',
  77. #OP_INT: 'INT',
  78. #OP_SOLVE: 'SOLVE',
  79. OP_EQ: 'EQ',
  80. OP_POSSIBILITIES: 'POSSIBILITIES',
  81. OP_HINT: 'HINT',
  82. OP_REWRITE_ALL: 'REWRITE_ALL',
  83. OP_REWRITE: 'REWRITE',
  84. }
  85. def to_expression(obj):
  86. return obj if isinstance(obj, ExpressionBase) else ExpressionLeaf(obj)
  87. class ExpressionBase(object):
  88. def __init__(self, *args, **kwargs):
  89. self.negated = 0
  90. def clone(self):
  91. return copy.deepcopy(self)
  92. def __lt__(self, other):
  93. """
  94. Comparison between this expression{node,leaf} and another
  95. expression{node,leaf}. This comparison will return True if this
  96. instance has less value than the other expression{node,leaf}.
  97. Otherwise, False is returned.
  98. The comparison is based on the following conditions:
  99. 1. Both are leafs. String comparison of the value is used.
  100. 2. This is a leaf and other is a node. This leaf has less value, thus
  101. True is returned.
  102. 3. This is a node and other is a leaf. This leaf has more value, thus
  103. False is returned.
  104. 4. Both are nodes. Compare the polynome properties of the nodes. True
  105. is returned if this node's root property is less than other's root
  106. property, or this node's exponent property is less than other's
  107. exponent property, or this node's coefficient property is less than
  108. other's coefficient property. Otherwise, False is returned.
  109. """
  110. if self.is_leaf:
  111. if other.is_leaf:
  112. # Both are leafs, string compare the value.
  113. self_value = '-' * (self.negated & 1) + str(self.value)
  114. other_value = '-' * (other.negated & 1) + str(other.value)
  115. return self_value < other_value
  116. # Self is a leaf, thus has less value than an expression node.
  117. return True
  118. if other.is_leaf:
  119. # Self is an expression node, and the other is a leaf. Thus, other
  120. # is greater than self.
  121. return False
  122. # Both are nodes, compare the polynome properties.
  123. s_coeff, s_root, s_exp = self.extract_polynome_properties()
  124. o_coeff, o_root, o_exp = other.extract_polynome_properties()
  125. return s_root < o_root or s_exp < o_exp or s_coeff < o_coeff
  126. def is_op(self, op):
  127. return not self.is_leaf and self.op == op
  128. def is_power(self, exponent=None):
  129. if self.is_leaf or self.op != OP_POW:
  130. return False
  131. return exponent == None or self[1] == exponent
  132. def is_nary(self):
  133. return not self.is_leaf and self.op in [OP_ADD, OP_SUB, OP_MUL]
  134. def is_identifier(self):
  135. return self.type == TYPE_IDENTIFIER
  136. def is_int(self):
  137. return self.type == TYPE_INTEGER
  138. def is_float(self):
  139. return self.type == TYPE_FLOAT
  140. def is_numeric(self):
  141. return self.type & (TYPE_FLOAT | TYPE_INTEGER)
  142. def __add__(self, other):
  143. return ExpressionNode('+', self, to_expression(other))
  144. def __sub__(self, other):
  145. return ExpressionNode('-', self, to_expression(other))
  146. def __mul__(self, other):
  147. return ExpressionNode('*', self, to_expression(other))
  148. def __div__(self, other):
  149. return ExpressionNode('/', self, to_expression(other))
  150. def __pow__(self, other):
  151. return ExpressionNode('^', self, to_expression(other))
  152. def __pos__(self):
  153. return self.reduce_negation()
  154. def reduce_negation(self, n=1):
  155. """Remove n negation flags from the node."""
  156. assert self.negated
  157. return self.negate(-n)
  158. def negate(self, n=1):
  159. """Negate the node n times."""
  160. return negate(self, self.negated + n)
  161. class ExpressionNode(Node, ExpressionBase):
  162. def __init__(self, *args, **kwargs):
  163. super(ExpressionNode, self).__init__(*args, **kwargs)
  164. self.type = TYPE_OPERATOR
  165. self.op = OP_MAP[args[0]]
  166. def __str__(self): # pragma: nocover
  167. return generate_line(self)
  168. def __eq__(self, other):
  169. """
  170. Check strict equivalence.
  171. """
  172. return isinstance(other, ExpressionNode) and self.op == other.op \
  173. and self.negated == other.negated and self.nodes == other.nodes
  174. def substitute(self, old_child, new_child):
  175. self.nodes[self.nodes.index(old_child)] = new_child
  176. def graph(self): # pragma: nocover
  177. return generate_graph(self)
  178. def extract_polynome_properties(self):
  179. """
  180. Extract polynome properties into tuple format: (coefficient, root,
  181. exponent). Thus: c * r ^ e will be extracted into the tuple (c, r, e).
  182. This function will normalize the expression before extracting the
  183. properties. Therefore, the expression r ^ e * c results the same tuple
  184. (c, r, e) as the expression c * r ^ e.
  185. >>> from src.node import ExpressionNode as N, ExpressionLeaf as L
  186. >>> c, r, e = L('c'), L('r'), L('e')
  187. >>> n1 = N('*', c, N('^', r, e))
  188. >>> n1.extract_polynome()
  189. (c, r, e)
  190. >>> n2 = N('*', N('^', r, e), c)
  191. >>> n2.extract_polynome()
  192. (c, r, e)
  193. >>> n3 = N('-', r)
  194. >>> n3.extract_polynome()
  195. (1, -r, 1)
  196. """
  197. # TODO: change "get_polynome" -> "extract_polynome".
  198. # TODO: change retval of c * r ^ e to (c, r, e).
  199. # was: (root, exponent, coefficient, literal_exponent)
  200. # rule: r ^ e -> (1, r, e)
  201. if self.is_power():
  202. return (ExpressionLeaf(1), self[0], self[1])
  203. # rule: -r -> (1, r, 1)
  204. # rule: --r -> (1, r, 1)
  205. # rule: ---r -> (1, r, 1)
  206. if self.negated:
  207. return (ExpressionLeaf(1), self, ExpressionLeaf(1))
  208. if self.op != OP_MUL:
  209. return
  210. # rule: 3 * 7 ^ e | 'a' * 'b' ^ e
  211. # expression: c * r ^ e ; tree:
  212. #
  213. # *
  214. # ╭┴───╮
  215. # c ^
  216. # ╭─┴╮
  217. # r e
  218. #
  219. # rule: c * r ^ e | (r ^ e) * c
  220. for i, j in ((0, 1), (1, 0)):
  221. if self[j].is_power():
  222. return (self[i], self[j][0], self[j][1])
  223. # Normalize c * r and r * c -> c * r. Otherwise, the tuple will not
  224. # match if the order of the expression is different. Example:
  225. # r ^ e * c == c * r ^ e
  226. # without normalization, those expressions will not match.
  227. #
  228. # rule: c * r | r * c
  229. if self[0] < self[1]:
  230. return (self[0], self[1], ExpressionLeaf(1))
  231. return (self[1], self[0], ExpressionLeaf(1))
  232. def equals(self, other, ignore_negation=False):
  233. """
  234. Perform a non-strict equivalence check between two nodes:
  235. - If the other node is a leaf, it cannot be equal to this node.
  236. - If their operators differ, the nodes are not equal.
  237. - If both nodes are additions or both are multiplications, match each
  238. node in one scope to one in the other (an injective relationship).
  239. Any difference in order of the scopes is irrelevant.
  240. - If both nodes are divisions, the nominator and denominator have to be
  241. non-strictly equal.
  242. """
  243. if not isinstance(other, ExpressionNode) or other.op != self.op:
  244. return False
  245. if self.op in (OP_ADD, OP_MUL):
  246. s0 = Scope(self)
  247. s1 = set(Scope(other))
  248. # Scopes should be of equal size
  249. if len(s0) != len(s1):
  250. return False
  251. # Each node in one scope should have an image node in the other
  252. matched = set()
  253. for n0 in s0:
  254. found = False
  255. for n1 in s1 - matched:
  256. if n0.equals(n1):
  257. found = True
  258. matched.add(n1)
  259. break
  260. if not found:
  261. return False
  262. else:
  263. # Check if all children are non-strictly equal, preserving order
  264. for i, child in enumerate(self):
  265. if not child.equals(other[i]):
  266. return False
  267. if ignore_negation:
  268. return True
  269. return self.negated == other.negated
  270. class ExpressionLeaf(Leaf, ExpressionBase):
  271. def __init__(self, *args, **kwargs):
  272. super(ExpressionLeaf, self).__init__(*args, **kwargs)
  273. self.type = TYPE_MAP[type(args[0])]
  274. def __eq__(self, other):
  275. """
  276. Check strict equivalence.
  277. """
  278. other_type = type(other)
  279. if other_type in TYPE_MAP:
  280. return TYPE_MAP[other_type] == self.type \
  281. and self.actual_value() == other
  282. return self.negated == other.negated and self.type == other.type \
  283. and self.value == other.value
  284. def __repr__(self):
  285. return '-' * self.negated + str(self.value)
  286. def equals(self, other, ignore_negation=False):
  287. """
  288. Check non-strict equivalence.
  289. Between leaves, this is the same as strict equivalence, except when
  290. negations must be ignored.
  291. """
  292. if ignore_negation:
  293. other_type = type(other)
  294. if other_type in (int, float):
  295. return TYPE_MAP[other_type] == self.type \
  296. and self.value == abs(other)
  297. elif other_type == str:
  298. return self.type == TYPE_IDENTIFIER and self.value == other
  299. return self.type == other.type and self.value == other.value
  300. else:
  301. return self == other
  302. def extract_polynome_properties(self):
  303. """
  304. An expression leaf will return the polynome tuple (1, r, 1), where r is
  305. the leaf itself. See also the method extract_polynome_properties in
  306. ExpressionBase.
  307. """
  308. # rule: 1 * r ^ 1 -> (1, r, 1)
  309. return (ExpressionLeaf(1), self, ExpressionLeaf(1))
  310. def actual_value(self):
  311. assert self.is_numeric()
  312. return (1 - 2 * (self.negated & 1)) * self.value
  313. class Scope(object):
  314. def __init__(self, node):
  315. self.node = node
  316. self.nodes = get_scope(node)
  317. def __getitem__(self, key):
  318. return self.nodes[key]
  319. def __setitem__(self, key, value):
  320. self.nodes[key] = value
  321. def __len__(self):
  322. return len(self.nodes)
  323. def __iter__(self):
  324. return iter(self.nodes)
  325. def __eq__(self, other):
  326. return isinstance(other, Scope) and self.node == other.node \
  327. and self.nodes == other.nodes
  328. def __repr__(self):
  329. return '<Scope of "%s">' % repr(self.node)
  330. def remove(self, node, **kwargs):
  331. if node.is_leaf:
  332. node_cmp = hash(node)
  333. else:
  334. node_cmp = node
  335. for i, n in enumerate(self.nodes):
  336. if n.is_leaf:
  337. n_cmp = hash(n)
  338. else:
  339. n_cmp = n
  340. if n_cmp == node_cmp:
  341. if 'replacement' in kwargs:
  342. self[i] = kwargs['replacement']
  343. else:
  344. del self.nodes[i]
  345. return
  346. raise ValueError('Node "%s" is not in the scope of "%s".'
  347. % (node, self.node))
  348. def replace(self, node, replacement):
  349. self.remove(node, replacement=replacement)
  350. def as_nary_node(self):
  351. return nary_node(self.node.value, self.nodes).negate(self.node.negated)
  352. def nary_node(operator, scope):
  353. """
  354. Create a binary expression tree for an n-ary operator. Takes the operator
  355. and a list of expression nodes as arguments.
  356. """
  357. if len(scope) == 1:
  358. return scope[0]
  359. return ExpressionNode(operator, nary_node(operator, scope[:-1]), scope[-1])
  360. def get_scope(node):
  361. """
  362. Find all n nodes within the n-ary scope of an operator node.
  363. """
  364. scope = []
  365. for child in node:
  366. if child.is_op(node.op):
  367. scope += get_scope(child)
  368. else:
  369. scope.append(child)
  370. return scope
  371. def negate(node, n=1):
  372. """Negate the given node n times."""
  373. assert n >= 0
  374. new_node = node.clone()
  375. new_node.negated = n
  376. return new_node