node.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. # vim: set fileencoding=utf-8 :
  2. import os.path
  3. import sys
  4. import copy
  5. import re
  6. sys.path.insert(0, os.path.realpath('external'))
  7. from graph_drawing.graph import generate_graph
  8. from graph_drawing.line import generate_line
  9. from graph_drawing.node import Node, Leaf
  10. TYPE_OPERATOR = 1
  11. TYPE_IDENTIFIER = 2
  12. TYPE_INTEGER = 4
  13. TYPE_FLOAT = 8
  14. # Unary
  15. OP_NEG = 1
  16. OP_ABS = 2
  17. # Binary
  18. OP_ADD = 3
  19. OP_SUB = 4
  20. OP_MUL = 5
  21. OP_DIV = 6
  22. OP_POW = 7
  23. OP_SUBSCRIPT = 8
  24. OP_AND = 9
  25. OP_OR = 10
  26. # Binary operators that are considered n-ary
  27. NARY_OPERATORS = [OP_ADD, OP_SUB, OP_MUL, OP_AND, OP_OR]
  28. # N-ary (functions)
  29. OP_INT = 11
  30. OP_INT_INDEF = 12
  31. OP_COMMA = 13
  32. OP_SQRT = 14
  33. OP_DER = 15
  34. OP_LOG = 16
  35. # Goniometry
  36. OP_SIN = 17
  37. OP_COS = 18
  38. OP_TAN = 19
  39. OP_SOLVE = 20
  40. OP_EQ = 21
  41. OP_POSSIBILITIES = 22
  42. OP_HINT = 23
  43. OP_REWRITE_ALL = 24
  44. OP_REWRITE_ALL_VERBOSE = 25
  45. OP_REWRITE = 26
  46. # Special identifiers
  47. PI = 'pi'
  48. E = 'e'
  49. INFINITY = 'oo'
  50. SPECIAL_TOKENS = [PI, E, INFINITY]
  51. # Default base to use in parsing 'log(...)'
  52. DEFAULT_LOGARITHM_BASE = 10
  53. TYPE_MAP = {
  54. int: TYPE_INTEGER,
  55. float: TYPE_FLOAT,
  56. str: TYPE_IDENTIFIER,
  57. }
  58. OP_MAP = {
  59. ',': OP_COMMA,
  60. '+': OP_ADD,
  61. '-': OP_SUB,
  62. '*': OP_MUL,
  63. '/': OP_DIV,
  64. '^': OP_POW,
  65. '_': OP_SUBSCRIPT,
  66. '^^': OP_AND,
  67. 'vv': OP_OR,
  68. 'sin': OP_SIN,
  69. 'cos': OP_COS,
  70. 'tan': OP_TAN,
  71. 'sqrt': OP_SQRT,
  72. 'int': OP_INT,
  73. 'der': OP_DER,
  74. 'solve': OP_SOLVE,
  75. 'log': OP_LOG,
  76. '=': OP_EQ,
  77. '??': OP_POSSIBILITIES,
  78. '?': OP_HINT,
  79. '@': OP_REWRITE,
  80. '@@': OP_REWRITE_ALL,
  81. '@@@': OP_REWRITE_ALL_VERBOSE,
  82. }
  83. OP_VALUE_MAP = dict([(v, k) for k, v in OP_MAP.iteritems()])
  84. OP_MAP['ln'] = OP_LOG
  85. OP_VALUE_MAP[OP_INT_INDEF] = 'indef'
  86. OP_VALUE_MAP[OP_ABS] = 'abs'
  87. TOKEN_MAP = {
  88. OP_COMMA: 'COMMA',
  89. OP_ADD: 'PLUS',
  90. OP_SUB: 'MINUS',
  91. OP_MUL: 'TIMES',
  92. OP_DIV: 'DIVIDE',
  93. OP_POW: 'POW',
  94. OP_SUBSCRIPT: 'SUB',
  95. OP_AND: 'AND',
  96. OP_OR: 'OR',
  97. OP_SQRT: 'FUNCTION',
  98. OP_SIN: 'FUNCTION',
  99. OP_COS: 'FUNCTION',
  100. OP_TAN: 'FUNCTION',
  101. OP_INT: 'INTEGRAL',
  102. OP_DER: 'FUNCTION',
  103. OP_SOLVE: 'FUNCTION',
  104. OP_LOG: 'FUNCTION',
  105. OP_EQ: 'EQ',
  106. OP_POSSIBILITIES: 'POSSIBILITIES',
  107. OP_HINT: 'HINT',
  108. OP_REWRITE: 'REWRITE',
  109. OP_REWRITE_ALL: 'REWRITE_ALL',
  110. OP_REWRITE_ALL_VERBOSE: 'REWRITE_ALL_VERBOSE',
  111. }
  112. def to_expression(obj):
  113. if isinstance(obj, ExpressionBase):
  114. return obj.clone()
  115. return ExpressionLeaf(obj)
  116. class ExpressionBase(object):
  117. def __lt__(self, other):
  118. """
  119. Comparison between this expression{node,leaf} and another
  120. expression{node,leaf}. This comparison will return True if this
  121. instance has less value than the other expression{node,leaf}.
  122. Otherwise, False is returned.
  123. The comparison is based on the following conditions:
  124. 1. Both are leafs. String comparison of the value is used.
  125. 2. This is a leaf and other is a node. This leaf has less value, thus
  126. True is returned.
  127. 3. This is a node and other is a leaf. This leaf has more value, thus
  128. False is returned.
  129. 4. Both are nodes. Compare the polynome properties of the nodes. True
  130. is returned if this node's root property is less than other's root
  131. property, or this node's exponent property is less than other's
  132. exponent property, or this node's coefficient property is less than
  133. other's coefficient property. Otherwise, False is returned.
  134. """
  135. if self.is_leaf:
  136. if other.is_leaf:
  137. # Both are leafs, string compare the value.
  138. self_value = '-' * (self.negated & 1) + str(self.value)
  139. other_value = '-' * (other.negated & 1) + str(other.value)
  140. return self_value < other_value
  141. # Self is a leaf, thus has less value than an expression node.
  142. return True
  143. if other.is_leaf:
  144. # Self is an expression node, and the other is a leaf. Thus, other
  145. # is greater than self.
  146. return False
  147. # Both are nodes, compare the polynome properties.
  148. s_coeff, s_root, s_exp = self.extract_polynome_properties()
  149. o_coeff, o_root, o_exp = other.extract_polynome_properties()
  150. return s_root < o_root or s_exp < o_exp or s_coeff < o_coeff
  151. def __gt__(self, other):
  152. return other < self
  153. def __ne__(self, other):
  154. """
  155. Check strict inequivalence, using the strict equivalence operator.
  156. """
  157. return not (self == other)
  158. def clone(self):
  159. return copy.deepcopy(self)
  160. def is_op(self, *ops):
  161. return not self.is_leaf and self.op in ops
  162. def is_power(self, exponent=None):
  163. if self.is_leaf or self.op != OP_POW:
  164. return False
  165. return exponent == None or self[1] == exponent
  166. def is_nary(self):
  167. return not self.is_leaf and self.op in NARY_OPERATORS
  168. def is_identifier(self, identifier=None):
  169. return self.type == TYPE_IDENTIFIER \
  170. and (identifier == None or self.value == identifier)
  171. def is_variable(self):
  172. return self.type == TYPE_IDENTIFIER and self.value not in (PI, E)
  173. def is_int(self):
  174. return self.type == TYPE_INTEGER
  175. def is_float(self):
  176. return self.type == TYPE_FLOAT
  177. def is_numeric(self):
  178. return self.type & (TYPE_FLOAT | TYPE_INTEGER)
  179. def __add__(self, other):
  180. return ExpressionNode(OP_ADD, self, to_expression(other))
  181. def __sub__(self, other):
  182. return ExpressionNode(OP_ADD, self, -to_expression(other))
  183. #FIXME: return ExpressionNode(OP_SUB, self, to_expression(other))
  184. def __mul__(self, other):
  185. return ExpressionNode(OP_MUL, self, to_expression(other))
  186. def __div__(self, other):
  187. return ExpressionNode(OP_DIV, self, to_expression(other))
  188. def __pow__(self, other):
  189. return ExpressionNode(OP_POW, self, to_expression(other))
  190. def __pos__(self):
  191. return self.reduce_negation()
  192. def __and__(self, other):
  193. return ExpressionNode(OP_AND, self, to_expression(other))
  194. def __or__(self, other):
  195. return ExpressionNode(OP_OR, self, to_expression(other))
  196. def reduce_negation(self, n=1):
  197. """Remove n negation flags from the node."""
  198. assert self.negated >= n
  199. return self.negate(-n)
  200. def negate(self, n=1):
  201. """Negate the node n times."""
  202. return negate(self, self.negated + n, clone=True)
  203. def contains(self, node, include_self=True):
  204. """
  205. Check if a node equal to the specified one exists within this node.
  206. """
  207. if include_self and self.equals(node, ignore_negation=True):
  208. return True
  209. if not self.is_leaf:
  210. for child in self:
  211. if child.contains(node, include_self=True):
  212. return True
  213. return False
  214. class ExpressionNode(Node, ExpressionBase):
  215. def __init__(self, *args, **kwargs):
  216. super(ExpressionNode, self).__init__(*args, **kwargs)
  217. self.type = TYPE_OPERATOR
  218. op = args[0]
  219. if isinstance(op, str):
  220. self.value = op
  221. self.op = OP_MAP[op]
  222. else:
  223. self.value = OP_VALUE_MAP[op]
  224. self.op = op
  225. def construct_derivative(self, children):
  226. f = children[0]
  227. if len(children) < 2:
  228. # der(der(x ^ 2)) -> [x ^ 2]''
  229. if self[0].is_op(OP_DER) and len(self[0]) < 2:
  230. return f + '\''
  231. # der(x ^ 2) -> [x ^ 2]'
  232. return '[' + f + ']\''
  233. # der(x ^ 2, x) -> d/dx (x ^ 2)
  234. return 'd/d%s (%s)' % (children[1], f)
  235. def construct_logarithm(self, children):
  236. if self[0].is_op(OP_ABS):
  237. content = children[0]
  238. else:
  239. content = '(' + children[0] + ')'
  240. # log(a, e) -> ln(a)
  241. if self[1].is_identifier(E):
  242. return 'ln%s' % content
  243. # log(a, 10) -> log(a)
  244. if self[1] == 10:
  245. return 'log%s' % content
  246. # log(a, 2) -> log_2(a)
  247. if children[1].isdigit():
  248. return 'log_%s%s' % (children[1], content)
  249. def construct_integral(self, children):
  250. # Make sure that any needed parentheses around f(x) are generated,
  251. # and append ' dx' to it (result 'f(x) dx')
  252. fx, x = self[:2]
  253. operand = re.sub(r'(\s*\*)?\s*d$', ' d' + x.value, str(fx * 'd'))
  254. op = 'int'
  255. # Add bounds
  256. if len(self) > 2:
  257. lbnd, ubnd = self[2:]
  258. lbnd = str(ExpressionNode(OP_SUBSCRIPT, lbnd))
  259. ubnd = str(ExpressionNode(OP_POW, ubnd))
  260. op += lbnd + ubnd
  261. # int x ^ 2 -> int x ^ 2 dx
  262. # int x + 1 -> int (x + 1) dx
  263. # int_a^b x ^ 2 -> int_a^b x ^ 2 dx
  264. return op + ' ' + operand
  265. def construct_indef_integral(self, children):
  266. # [x ^ 2]_a^b
  267. F, lbnd, ubnd = self
  268. lbnd = str(ExpressionNode(OP_SUBSCRIPT, lbnd))
  269. ubnd = str(ExpressionNode(OP_POW, ubnd))
  270. return '[%s]%s%s' % (F, lbnd, ubnd)
  271. def construct_function(self, children):
  272. if self.op == OP_ABS:
  273. return '|%s|' % children[0]
  274. constructors = {
  275. OP_DER: self.construct_derivative,
  276. OP_LOG: self.construct_logarithm,
  277. OP_INT: self.construct_integral,
  278. OP_INT_INDEF: self.construct_indef_integral
  279. }
  280. if self.op in constructors:
  281. result = constructors[self.op](children)
  282. if result != None:
  283. return result
  284. # Function with absolute value as only parameter does not need
  285. # parentheses
  286. if self.op in TOKEN_MAP and TOKEN_MAP[self.op] == 'FUNCTION' \
  287. and len(self) == 1 and self[0].is_op(OP_ABS):
  288. return self.title() + children[0]
  289. def __str__(self): # pragma: nocover
  290. return generate_line(self)
  291. def __eq__(self, other):
  292. """
  293. Check strict equivalence.
  294. """
  295. return isinstance(other, ExpressionNode) and self.op == other.op \
  296. and self.negated == other.negated and self.nodes == other.nodes
  297. def substitute(self, old_child, new_child):
  298. self.nodes[self.nodes.index(old_child)] = new_child
  299. def graph(self): # pragma: nocover
  300. return generate_graph(negation_to_node(self))
  301. def extract_polynome_properties(self):
  302. """
  303. Extract polynome properties into tuple format: (coefficient, root,
  304. exponent). Thus: c * r ^ e will be extracted into the tuple (c, r, e).
  305. This function will normalize the expression before extracting the
  306. properties. Therefore, the expression r ^ e * c results the same tuple
  307. (c, r, e) as the expression c * r ^ e.
  308. >>> from src.node import ExpressionNode as N, ExpressionLeaf as L
  309. >>> c, r, e = L('c'), L('r'), L('e')
  310. >>> n1 = N(OP_MUL), c, N('^', r, e))
  311. >>> n1.extract_polynome()
  312. (c, r, e)
  313. >>> n2 = N(OP_MUL, N('^', r, e), c)
  314. >>> n2.extract_polynome()
  315. (c, r, e)
  316. >>> n3 = -r
  317. >>> n3.extract_polynome()
  318. (1, -r, 1)
  319. """
  320. # TODO: change "get_polynome" -> "extract_polynome".
  321. # TODO: change retval of c * r ^ e to (c, r, e).
  322. # was: (root, exponent, coefficient, literal_exponent)
  323. # rule: r ^ e -> (1, r, e)
  324. if self.is_power():
  325. return (ExpressionLeaf(1), self[0], self[1])
  326. # rule: -r -> (1, -r, 1)
  327. # rule: --r -> (1, --r, 1)
  328. # rule: ---r -> (1, ---r, 1)
  329. #if self.negated:
  330. # return (ExpressionLeaf(1), self, ExpressionLeaf(1))
  331. if self.op != OP_MUL:
  332. return
  333. # rule: 3 * 7 ^ e | 'a' * 'b' ^ e
  334. # expression: c * r ^ e ; tree:
  335. #
  336. # *
  337. # ╭┴───╮
  338. # c ^
  339. # ╭─┴╮
  340. # r e
  341. #
  342. # rule: c * r ^ e | (r ^ e) * c
  343. for i, j in ((0, 1), (1, 0)):
  344. if self[j].is_power():
  345. return (self[i], self[j][0], self[j][1])
  346. # Normalize c * r and r * c -> c * r. Otherwise, the tuple will not
  347. # match if the order of the expression is different. Example:
  348. # r ^ e * c == c * r ^ e
  349. # without normalization, those expressions will not match.
  350. #
  351. # rule: c * r | r * c
  352. if self[0] < self[1]:
  353. return (self[0], self[1], ExpressionLeaf(1))
  354. return (self[1], self[0], ExpressionLeaf(1))
  355. def equals(self, other, ignore_negation=False):
  356. """
  357. Perform a non-strict equivalence check between two nodes:
  358. - If the other node is a leaf, it cannot be equal to this node.
  359. - If their operators differ, the nodes are not equal.
  360. - If both nodes are additions or both are multiplications, match each
  361. node in one scope to one in the other (an injective relationship).
  362. Any difference in order of the scopes is irrelevant.
  363. - If both nodes are divisions, the nominator and denominator have to be
  364. non-strictly equal.
  365. """
  366. if not isinstance(other, ExpressionNode) or other.op != self.op:
  367. return False
  368. if self.op in NARY_OPERATORS:
  369. s0 = Scope(self)
  370. s1 = set(Scope(other))
  371. # Scopes should be of equal size
  372. if len(s0) != len(s1):
  373. return False
  374. # Each node in one scope should have an image node in the other
  375. matched = set()
  376. for n0 in s0:
  377. found = False
  378. for n1 in s1 - matched:
  379. if n0.equals(n1):
  380. found = True
  381. matched.add(n1)
  382. break
  383. if not found:
  384. return False
  385. else:
  386. # Check if all children are non-strictly equal, preserving order
  387. for i, child in enumerate(self):
  388. if not child.equals(other[i]):
  389. return False
  390. if ignore_negation:
  391. return True
  392. return self.negated == other.negated
  393. class ExpressionLeaf(Leaf, ExpressionBase):
  394. def __init__(self, *args, **kwargs):
  395. super(ExpressionLeaf, self).__init__(*args, **kwargs)
  396. self.type = TYPE_MAP[type(args[0])]
  397. def __eq__(self, other):
  398. """
  399. Check strict equivalence.
  400. """
  401. other_type = type(other)
  402. if other_type in TYPE_MAP:
  403. return self.type == TYPE_MAP[other_type] \
  404. and self.actual_value() == other
  405. return self.negated == other.negated and self.type == other.type \
  406. and self.value == other.value
  407. def __repr__(self):
  408. return str(self)
  409. def equals(self, other, ignore_negation=False):
  410. """
  411. Check non-strict equivalence.
  412. Between leaves, this is the same as strict equivalence, except when
  413. negations must be ignored.
  414. """
  415. if ignore_negation:
  416. other_type = type(other)
  417. if other_type in (int, float):
  418. return TYPE_MAP[other_type] == self.type \
  419. and self.value == abs(other)
  420. elif other_type == str:
  421. return self.type == TYPE_IDENTIFIER and self.value == other
  422. return self.type == other.type and self.value == other.value
  423. else:
  424. return self == other
  425. def extract_polynome_properties(self):
  426. """
  427. An expression leaf will return the polynome tuple (1, r, 1), where r is
  428. the leaf itself. See also the method extract_polynome_properties in
  429. ExpressionBase.
  430. """
  431. # rule: 1 * r ^ 1 -> (1, r, 1)
  432. return (ExpressionLeaf(1), self, ExpressionLeaf(1))
  433. def actual_value(self):
  434. if self.type == TYPE_IDENTIFIER:
  435. return self.value
  436. return (1 - 2 * (self.negated & 1)) * self.value
  437. class Scope(object):
  438. def __init__(self, node):
  439. self.node = node
  440. self.nodes = get_scope(node)
  441. for i, n in enumerate(self.nodes):
  442. n.scope_index = i
  443. def __getitem__(self, key):
  444. return self.nodes[key]
  445. def __setitem__(self, key, value):
  446. self.nodes[key] = value
  447. def __len__(self):
  448. return len(self.nodes)
  449. def __iter__(self):
  450. return iter(self.nodes)
  451. def __eq__(self, other):
  452. return isinstance(other, Scope) and self.node == other.node \
  453. and self.nodes == other.nodes
  454. def __repr__(self):
  455. return '<Scope of "%s">' % repr(self.node)
  456. def index(self, node):
  457. return node.scope_index
  458. def remove(self, node, replacement=None):
  459. try:
  460. i = node.scope_index
  461. if replacement:
  462. self[i] = replacement
  463. replacement.scope_index = i
  464. else:
  465. del self.nodes[i]
  466. # Update remaining scope indices
  467. for n in self.nodes[i:]:
  468. n.scope_index -= 1
  469. except AttributeError:
  470. raise ValueError('Node "%s" is not in the scope of "%s".'
  471. % (node, self.node))
  472. def replace(self, node, replacement):
  473. self.remove(node, replacement=replacement)
  474. def as_nary_node(self):
  475. return nary_node(self.node.op, self.nodes).negate(self.node.negated)
  476. #return negate(nary_node(self.node.op, self.nodes), self.node.negated)
  477. def all_except(self, node):
  478. before = range(0, node.scope_index)
  479. after = range(node.scope_index + 1, len(self))
  480. nodes = [self[i] for i in before + after]
  481. return nary_node(self.node.op, nodes).negate(self.node.negated)
  482. def nary_node(operator, scope):
  483. """
  484. Create a binary expression tree for an n-ary operator. Takes the operator
  485. and a list of expression nodes as arguments.
  486. """
  487. if len(scope) == 1:
  488. return scope[0]
  489. return ExpressionNode(operator, nary_node(operator, scope[:-1]), scope[-1])
  490. def get_scope(node):
  491. """
  492. Find all n nodes within the n-ary scope of an operator node.
  493. """
  494. scope = []
  495. for child in node:
  496. if child.is_op(node.op) and not child.negated:
  497. scope += get_scope(child)
  498. else:
  499. scope.append(child)
  500. return scope
  501. def negate(node, n=1, clone=False):
  502. """
  503. Negate the given node n times. If clone is set to true, return a new node
  504. so that the original node is not altered.
  505. """
  506. assert n >= 0
  507. if clone:
  508. node = node.clone()
  509. node.negated = n
  510. return node
  511. def infinity():
  512. """
  513. Return an infinity leaf node.
  514. """
  515. return ExpressionLeaf(INFINITY)
  516. def absolute(exp):
  517. """
  518. Put an 'absolute value' operator on top of the given expression.
  519. """
  520. return ExpressionNode(OP_ABS, exp)
  521. def sin(*args):
  522. """
  523. Create a sinus function node.
  524. """
  525. return ExpressionNode(OP_SIN, *args)
  526. def cos(*args):
  527. """
  528. Create a cosinus function node.
  529. """
  530. return ExpressionNode(OP_COS, *args)
  531. def tan(*args):
  532. """
  533. Create a tangens function node.
  534. """
  535. return ExpressionNode(OP_TAN, *args)
  536. def log(exponent, base=10):
  537. """
  538. Create a logarithm function node (default base is 10).
  539. """
  540. if not isinstance(base, ExpressionLeaf):
  541. base = ExpressionLeaf(base)
  542. return ExpressionNode(OP_LOG, exponent, base)
  543. def ln(exponent):
  544. """
  545. Create a natural logarithm node.
  546. """
  547. return log(exponent, base=E)
  548. def der(f, x=None):
  549. """
  550. Create a derivative node.
  551. """
  552. return ExpressionNode(OP_DER, f, x) if x else ExpressionNode(OP_DER, f)
  553. def integral(*args):
  554. """
  555. Create an integral node.
  556. """
  557. return ExpressionNode(OP_INT, *args)
  558. def indef(*args):
  559. """
  560. Create an indefinite integral node.
  561. """
  562. return ExpressionNode(OP_INT_INDEF, *args)
  563. def eq(left, right):
  564. """
  565. Create an equality operator node.
  566. """
  567. return ExpressionNode(OP_EQ, left, right)
  568. def sqrt(exp):
  569. """
  570. Create a square root node.
  571. """
  572. return ExpressionNode(OP_SQRT, exp)
  573. def negation_to_node(node):
  574. """
  575. Recursively replace negation flags inside a node by explicit unary negation
  576. nodes.
  577. """
  578. if node.negated:
  579. negations = node.negated
  580. node = negate(node, 0)
  581. for i in range(negations):
  582. node = ExpressionNode('-', node)
  583. if node.is_leaf:
  584. return node
  585. return ExpressionNode(node.op, *map(negation_to_node, node))