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)
| 360 | return expr |
| 361 | |
| 362 | def simplify_once(self, dependents: defaultdict, simplified: dict): |
| 363 | """Simplify an expression |
| 364 | |
| 365 | This leverages the ``._simplify_down`` and ``._simplify_up`` |
| 366 | methods defined on each class |
| 367 | |
| 368 | Parameters |
| 369 | ---------- |
| 370 | |
| 371 | dependents: defaultdict[list] |
| 372 | The dependents for every node. |
| 373 | simplified: dict |
| 374 | Cache of simplified expressions for these dependents. |
| 375 | |
| 376 | Returns |
| 377 | ------- |
| 378 | expr: |
| 379 | output expression |
| 380 | """ |
| 381 | # Check if we've already simplified for these dependents |
| 382 | if self._name in simplified: |
| 383 | return simplified[self._name] |
| 384 | |
| 385 | expr = self |
| 386 | |
| 387 | while True: |
| 388 | out = expr._simplify_down() |
| 389 | if out is None: |
| 390 | out = expr |
| 391 | if not isinstance(out, Expr): |
| 392 | return out |
| 393 | if out._name != expr._name: |
| 394 | expr = out |
| 395 | |
| 396 | # Allow children to simplify their parents |
| 397 | for child in expr.dependencies(): |
| 398 | out = child._simplify_up(expr, dependents) |
| 399 | if out is None: |
| 400 | out = expr |
| 401 | |
| 402 | if not isinstance(out, Expr): |
| 403 | return out |
| 404 | if out is not expr and out._name != expr._name: |
| 405 | expr = out |
| 406 | break |
| 407 | |
| 408 | # Rewrite all of the children |
| 409 | new_operands = [] |
| 410 | changed = False |
| 411 | for operand in expr.operands: |
| 412 | if isinstance(operand, Expr): |
| 413 | # Bandaid for now, waiting for Singleton |
| 414 | dependents[operand._name].append(weakref.ref(expr)) |
| 415 | new = operand.simplify_once( |
| 416 | dependents=dependents, simplified=simplified |
| 417 | ) |
| 418 | simplified[operand._name] = new |
| 419 | if new._name != operand._name: |
no test coverage detected