node.py 14 KB

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