node.py 14 KB

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