node.py 13 KB

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