Simplify an expression This leverages the ``._simplify_down`` and ``._simplify_up`` methods defined on each class Parameters ---------- dependents: defaultdict[list] The dependents for every node. simplified: dict Cache of si
(self, dependents: defaultdict, simplified: dict)
| 375 | return expr |
| 376 | |
| 377 | def simplify_once(self, dependents: defaultdict, simplified: dict): |
| 378 | """Simplify an expression |
| 379 | |
| 380 | This leverages the ``._simplify_down`` and ``._simplify_up`` |
| 381 | methods defined on each class |
| 382 | |
| 383 | Parameters |
| 384 | ---------- |
| 385 | |
| 386 | dependents: defaultdict[list] |
| 387 | The dependents for every node. |
| 388 | simplified: dict |
| 389 | Cache of simplified expressions for these dependents. |
| 390 | |
| 391 | Returns |
| 392 | ------- |
| 393 | expr: |
| 394 | output expression |
| 395 | """ |
| 396 | # Check if we've already simplified for these dependents |
| 397 | if self._name in simplified: |
| 398 | return simplified[self._name] |
| 399 | |
| 400 | expr = self |
| 401 | |
| 402 | while True: |
| 403 | out = expr._simplify_down() |
| 404 | if out is None: |
| 405 | out = expr |
| 406 | if not isinstance(out, Expr): |
| 407 | return out |
| 408 | if out._name != expr._name: |
| 409 | expr = out |
| 410 | |
| 411 | # Allow children to simplify their parents |
| 412 | for child in expr.dependencies(): |
| 413 | out = child._simplify_up(expr, dependents) |
| 414 | if out is None: |
| 415 | out = expr |
| 416 | |
| 417 | if not isinstance(out, Expr): |
| 418 | return out |
| 419 | if out is not expr and out._name != expr._name: |
| 420 | expr = out |
| 421 | break |
| 422 | |
| 423 | # Rewrite all of the children |
| 424 | new_operands = [] |
| 425 | changed = False |
| 426 | for operand in expr.operands: |
| 427 | if isinstance(operand, Expr): |
| 428 | # Bandaid for now, waiting for Singleton |
| 429 | dependents[operand._name].append(weakref.ref(expr)) |
| 430 | new = operand.simplify_once( |
| 431 | dependents=dependents, simplified=simplified |
| 432 | ) |
| 433 | simplified[operand._name] = new |
| 434 | if new._name != operand._name: |
no test coverage detected