node.py 12 KB

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