API-Reference
SimpliPy Engine¶
SimplificationStatistics
dataclass
¶
SimplificationStatistics(rule_application_counts: defaultdict[tuple, int] = (lambda: defaultdict(int))(), explicit_rule_applications: int = 0, pattern_rule_applications: int = 0, post_operand_rule_applications: int = 0, constant_folding_count: int = 0, rule_match_attempts: int = 0, rule_match_hits: int = 0, cancellation_events: list[dict[str, Any]] = list(), iterations_used: int = 0, converged: bool = False, result_rejected: bool = False, per_iteration_lengths: list[dict[str, int]] = list(), stage_timings: dict[str, float] = (lambda: {'cancel_terms': 0.0, 'apply_rules': 0.0, 'sort_operands': 0.0, 'mask_literals': 0.0})())
Collects detailed statistics about a simplification run.
This dataclass is populated by :meth:SimpliPyEngine.simplify when
collect_statistics=True. It replaces the former
rule_application_statistics dict with a richer set of metrics that
cover every stage of the simplification pipeline.
| ATTRIBUTE | DESCRIPTION |
|---|---|
rule_application_counts |
How many times each
TYPE:
|
explicit_rule_applications |
Total number of explicit (no-wildcard) rule applications.
TYPE:
|
pattern_rule_applications |
Total number of wildcard-pattern rule applications.
TYPE:
|
post_operand_rule_applications |
Rules that fired only after children were simplified first.
TYPE:
|
constant_folding_count |
How often the all-operands-are-
TYPE:
|
rule_match_attempts |
Total
TYPE:
|
rule_match_hits |
How many of those attempts succeeded.
TYPE:
|
cancellation_events |
One entry per term cancellation with keys
TYPE:
|
iterations_used |
Number of simplification iterations that were executed.
TYPE:
|
converged |
Whether the loop stopped before reaching
TYPE:
|
result_rejected |
Whether the simplified result was longer than the input and therefore discarded.
TYPE:
|
per_iteration_lengths |
For each iteration, a dict with keys
TYPE:
|
stage_timings |
Cumulative wall-clock seconds keyed by stage name:
TYPE:
|
SimpliPyEngine ¶
Manages and manipulates symbolic expressions.
This class provides a comprehensive toolkit for parsing, transforming, and simplifying mathematical expressions. It operates on expressions in prefix notation (a list of tokens) and uses a customizable set of operators and simplification rules.
| PARAMETER | DESCRIPTION |
|---|---|
operators
|
A dictionary defining the operators. Each key is the operator's canonical name (e.g., 'add', 'sin'), and the value is another dictionary specifying its properties like 'arity', 'realization' (the corresponding Python function), 'inverse', etc.
TYPE:
|
rules
|
A list of simplification rules. Each rule is a tuple containing two lists of strings: the pattern to match and the replacement expression, both in prefix notation. If None, the engine is initialized with no rules.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
operator_tokens |
A list of all defined operator names.
TYPE:
|
operator_arity |
A mapping from operator names to their arity (number of arguments).
TYPE:
|
simplification_rules |
The list of simplification rules loaded into the engine.
TYPE:
|
simplification_rules_patterns |
A compiled version of rules that involve pattern variables (e.g., _0), organized for efficient matching.
TYPE:
|
simplification_rules_no_patterns |
A compiled version of explicit rules without pattern variables.
TYPE:
|
Source code in src/simplipy/engine.py
compile_rules ¶
Compiles the text-based rules into an efficient internal format.
This method processes the self.simplification_rules list,
separating them into rules with patterns (like '_0', '_1') and
explicit rules. It then converts the patterns into a tree-based
structure optimized for fast matching against expression subtrees.
Source code in src/simplipy/engine.py
prune_redundant_rules ¶
Remove explicit rules that are subsumed by wildcard-pattern rules.
An explicit rule (e, r_e) is redundant if the engine still
simplifies e to r_e when that single rule is removed. This
happens when a wildcard-pattern rule already covers the same
transformation, or when constant folding / term cancellation achieve
the same result.
Rules are tested and removed serially: once a rule is found redundant it stays removed for all subsequent tests. This avoids over-pruning in the case where two explicit rules each appear redundant in the presence of the other but neither is covered by a pattern rule alone.
| PARAMETER | DESCRIPTION |
|---|---|
verbose
|
If True, shows a progress bar and prints a summary. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
The number of rules that were pruned. |
Source code in src/simplipy/engine.py
import_modules ¶
Imports Python modules required by operator realizations.
The engine inspects the 'realization' strings of all operators (e.g., 'np.sin') to identify necessary modules (e.g., 'numpy') and imports them into the global namespace to make them available for expression evaluation.
Source code in src/simplipy/engine.py
from_config
classmethod
¶
Creates a SimpliPyEngine instance from a JSON configuration file.
The configuration file should specify the operators and can
optionally provide a path to a rules file.
| PARAMETER | DESCRIPTION |
|---|---|
config_path
|
The absolute or relative path to the JSON configuration file.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SimpliPyEngine
|
A new instance of the engine configured as per the file. |
Source code in src/simplipy/engine.py
load
classmethod
¶
load(path: str, install: bool = False, local_dir: Path | str | None = None, repo_id: str | None = None, manifest_filename: str | None = None) -> SimpliPyEngine
Loads a pre-defined engine configuration from the asset manager.
This provides a convenient way to load standard engine configurations
distributed with the simplipy package.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
The name of the configuration to load (e.g., 'default').
TYPE:
|
install
|
If True, forces the download of the asset if not found locally. Defaults to False.
TYPE:
|
local_dir
|
A local directory to search for the assets. Defaults to None, which uses the default asset directory.
TYPE:
|
repo_id
|
The Hugging Face repository ID where the manifest is stored. If None, the default repository ID is used.
TYPE:
|
manifest_filename
|
The filename of the manifest file. If None, the default filename is used.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SimpliPyEngine
|
A new instance of the engine. |
Source code in src/simplipy/engine.py
is_valid ¶
Checks if a prefix expression is syntactically valid.
An expression is valid if every operator has the correct number of operands according to its defined arity.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The expression in prefix notation.
TYPE:
|
verbose
|
If True, prints the reason for invalidity. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the expression is valid, False otherwise. |
Source code in src/simplipy/engine.py
prefix_to_infix ¶
prefix_to_infix(tokens: list[str], power: Literal['func', '**'] = 'func', realization: bool = False) -> str
Converts a prefix expression to an infix string with minimal parentheses.
| PARAMETER | DESCRIPTION |
|---|---|
tokens
|
The prefix expression to render.
TYPE:
|
power
|
Controls how power operators are emitted.
TYPE:
|
realization
|
If True, operator tokens are replaced with their runtime
realizations (for example,
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The formatted infix expression. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the provided tokens do not form a well-formed prefix expression. |
Source code in src/simplipy/engine.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 | |
infix_to_prefix ¶
Converts an infix expression string to prefix notation.
This method uses a standard algorithm (related to Shunting-yard) to parse the infix string, respecting operator precedence and parentheses.
| PARAMETER | DESCRIPTION |
|---|---|
infix_expression
|
The mathematical expression in infix notation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
A list of tokens representing the expression in prefix notation. |
Source code in src/simplipy/engine.py
convert_expression ¶
Normalizes an expression into the engine's standard internal format.
This method performs several key conversions:
1. Converts standard binary operators like ** into the engine's
unary power operators (e.g., pow2, pow1_3).
2. Combines chained power operators (e.g., pow2(pow3(x)) becomes
pow6(x)).
3. Handles unary negation, applying it directly to numbers where
possible.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expr
|
The prefix expression to convert.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The normalized prefix expression. |
Source code in src/simplipy/engine.py
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 | |
parse ¶
parse(infix_expression: str, convert_expression: bool = True, mask_numbers: bool = False) -> list[str]
Parses an infix string into a standardized prefix expression.
This is a high-level parsing utility that combines infix_to_prefix
with optional canonicalization and number masking. The resulting token
list is additionally cleaned up via remove_pow1 to drop redundant
pow1_1 occurrences.
| PARAMETER | DESCRIPTION |
|---|---|
infix_expression
|
The mathematical expression in infix notation.
TYPE:
|
convert_expression
|
If True, the expression is normalized using
TYPE:
|
mask_numbers
|
If True, all numerical literals in the expression are replaced
with a generic '
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The processed prefix expression after conversion, masking (if
enabled), and |
Source code in src/simplipy/engine.py
prefix_to_tree ¶
Converts a flat prefix expression into a nested tree structure.
The tree is represented as a nested list, where each subtree is a
list of the form [operator, [operand1, operand2, ...]] and leaves
are lists of the form [variable].
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
The expression in prefix notation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
The nested list representing the expression tree. |
Source code in src/simplipy/engine.py
construct_rule_patterns ¶
construct_rule_patterns(rules_list: list[tuple[tuple[str, ...], tuple[str, ...]]], verbose: bool = False) -> dict[tuple, list[tuple[list, list]]]
Transforms a list of rules into a structured dictionary of pattern trees.
This pre-processes rules for efficient matching. It groups rules by the
length and root operator of their patterns and converts the flat
prefix patterns into tree structures using prefix_to_tree.
| PARAMETER | DESCRIPTION |
|---|---|
rules_list
|
A list of simplification rules to process.
TYPE:
|
verbose
|
If True, displays a progress bar. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
A dictionary mapping |
Source code in src/simplipy/engine.py
parse_subtree ¶
Parses a complete subtree from a token list starting at a given index.
Recursively consumes tokens corresponding to an operator and its operands to build a single expression tree.
| PARAMETER | DESCRIPTION |
|---|---|
tokens
|
A sequence of tokens in prefix notation.
TYPE:
|
start_idx
|
The index in
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
subtree
|
The parsed subtree as a nested list.
TYPE:
|
next_idx
|
The index of the token immediately following the parsed subtree.
TYPE:
|
Source code in src/simplipy/engine.py
apply_rules_top_down ¶
apply_rules_top_down(subtree: list, max_pattern_length: int | None = None, collect_statistics: bool = False, verbose: bool = False) -> list
Recursively applies simplification rules to an expression tree.
It attempts to match rules at the current node (top-down). If no rule matches, it recursively calls itself on the node's children. After the children are simplified, it re-checks for matching rules at the current node, in case a child's simplification enables a new rule.
| PARAMETER | DESCRIPTION |
|---|---|
subtree
|
The expression tree (nested list) to simplify.
TYPE:
|
max_pattern_length
|
The maximum length of a rule pattern to consider. Defaults to None.
TYPE:
|
collect_statistics
|
If True, records which rules are successfully applied. Defaults to False.
TYPE:
|
verbose
|
If True, prints detailed information about rule applications. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
The simplified expression tree. |
Source code in src/simplipy/engine.py
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 | |
apply_simplifcation_rules ¶
apply_simplifcation_rules(expression: list[str] | tuple[str, ...], max_pattern_length: int | None = None, collect_statistics: bool = False, verbose: bool = False) -> list[str]
Applies all loaded simplification rules to a prefix expression.
This method serves as a wrapper around apply_rules_top_down. It
first converts the flat prefix expression into a tree, applies the
rules recursively, and then flattens the resulting tree back into
prefix notation.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
The expression in prefix notation.
TYPE:
|
max_pattern_length
|
The maximum length of rule patterns to attempt to match.
TYPE:
|
collect_statistics
|
If True, updates statistics on rule application counts.
TYPE:
|
verbose
|
If True, enables detailed logging of the simplification process.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The simplified expression in prefix notation. |
Source code in src/simplipy/engine.py
collect_multiplicities ¶
collect_multiplicities(expression: list[str] | tuple[str, ...], verbose: bool = False) -> tuple[list, list, list]
Traverses an expression tree to find subtrees that can be cancelled.
This method performs a bottom-up traversal of the expression, counting
the occurrences of each unique subtree within additive (+, -) and
multiplicative (*, /) contexts. For example, in (a*b) + (a*b),
it identifies that the subtree (a*b) appears twice in an additive
context.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
The expression in prefix notation.
TYPE:
|
verbose
|
If True, prints detailed debugging information. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
expression_tree
|
A stack-based representation of the expression tree. Each entry is a
nested list of the form
TYPE:
|
annotations_tree
|
A parallel stack holding multiplicity annotations for each subtree, organized by connection class.
TYPE:
|
labels_tree
|
A parallel stack containing stable identifiers for every subtree, used to detect duplicates during cancellation.
TYPE:
|
Source code in src/simplipy/engine.py
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 | |
cancel_terms ¶
cancel_terms(expression_tree: list, expression_annotations_tree: list, stack_labels: list, collect_statistics: bool = False, verbose: bool = False) -> list[str]
Reconstructs an expression, cancelling terms based on multiplicity counts.
Using the annotated tree from collect_multiplicities, this method
identifies the best candidate for cancellation (e.g., a term that appears
with both positive and negative signs). It then rebuilds the expression
while replacing the cancelled terms with the appropriate neutral element
('0' for addition, '1' for multiplication) or a simplified form (e.g.,
x + x becomes 2 * x).
| PARAMETER | DESCRIPTION |
|---|---|
expression_tree
|
The stack produced by
TYPE:
|
expression_annotations_tree
|
The parallel stack of multiplicity annotations returned by
TYPE:
|
stack_labels
|
The parallel stack of subtree labels returned by
TYPE:
|
collect_statistics
|
If True, records cancellation events in
TYPE:
|
verbose
|
If True, prints detailed debugging information. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
A simplified prefix expression with the detected duplicates merged or removed. |
Source code in src/simplipy/engine.py
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 | |
sort_operands ¶
Sorts the operands of commutative operators to create a canonical form.
This method traverses the expression and, for any commutative operator
(like + or *), it sorts its operands based on a consistent key.
This ensures that expressions like b + a and a + b are treated as
identical.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
The expression in prefix notation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The expression with sorted operands, in prefix notation. |
Source code in src/simplipy/engine.py
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 | |
simplify ¶
simplify(expression: str | list[str] | tuple[str, ...] | ndarray, max_iter: int = 5, max_pattern_length: int | None = None, mask_elementary_literals: bool = True, apply_simplification_rules: bool = True, inplace: bool = False, collect_statistics: bool = False, verbose: bool = False) -> str | list[str] | tuple[str, ...] | np.ndarray
Performs a full simplification of a mathematical expression.
This is the main public method for simplification. It iteratively
applies term cancellation, rule-based simplification, and operand
sorting until the expression stops changing or max_iter is reached.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
The expression to simplify, given as an infix string, a prefix token list/tuple, or a one-dimensional numpy array of tokens.
TYPE:
|
max_iter
|
The maximum number of simplification iterations. Defaults to 5.
TYPE:
|
max_pattern_length
|
The maximum length of a rule pattern to consider.
TYPE:
|
mask_elementary_literals
|
If True, replaces literals like '0' and '1' that result from
cancellation with a generic
TYPE:
|
apply_simplification_rules
|
If False, skips the rule-based simplification step. Defaults to True.
TYPE:
|
inplace
|
If the input is a list, this modifies it directly. Defaults to False.
TYPE:
|
collect_statistics
|
If True, populates
TYPE:
|
verbose
|
If True, prints the expression after each simplification step.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str or list[str] or tuple[str, ...] or ndarray
|
The simplified expression, in the same format as the input. If the simplification results in a longer expression, the original expression is returned. |
Source code in src/simplipy/engine.py
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 | |
exist_constants_that_fit ¶
exist_constants_that_fit(expression: list[str] | tuple[str, ...], variables: list[str], X: ndarray, y_target: ndarray) -> bool
Checks if numerical constants exist to make an expression fit data.
Given an expression with <constant> placeholders, this method uses
scipy.optimize.curve_fit to determine if there is a set of numerical
values for these placeholders that makes the expression accurately
model the relationship between input data X and target data y_target.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
The prefix expression, potentially containing
TYPE:
|
variables
|
A list of variable names corresponding to the columns of
TYPE:
|
X
|
The input data, with shape (n_samples, n_variables).
TYPE:
|
y_target
|
The target data to be fitted.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if a set of constants is found that results in a close fit, False otherwise. |
Source code in src/simplipy/engine.py
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 | |
find_rule_worker ¶
find_rule_worker(worker_id: int, work_queue: Queue, result_queue: Queue, X_shape: tuple, X_dtype: dtype, X_shm_name: str, expressions_of_length_and_variables: dict, dummy_variables: list[str], operator_arity: dict, constants_fit_challenges: int, constants_fit_retries: int) -> None
A worker process for discovering simplification rules in parallel.
This function runs in a separate process. It fetches work items of the
form (expression, simplified_length, allowed_candidate_lengths) from
work_queue, evaluates the expression on shared random data, and
compares the result against a library of simpler candidate expressions.
If a numerical equivalence is found, it is considered a potential new
simplification rule and is placed on the result_queue; otherwise None
is queued to signal that no rule was discovered. A sentinel None work
item triggers a graceful shutdown.
Notes
This method is designed for internal use by the find_rules method
and is not intended to be called directly.
Source code in src/simplipy/engine.py
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 | |
find_rules ¶
find_rules(max_source_pattern_length: int = 7, max_target_pattern_length: int | None = None, dummy_variables: int | list[str] | None = None, extra_internal_terms: list[str] | None = None, X: ndarray | int | None = None, constants_fit_challenges: int = 5, constants_fit_retries: int = 5, output_file: str | None = None, save_every: int = 100, reset_rules: bool = True, prune: bool = False, verbose: bool = False, n_workers: int | None = None) -> None
Systematically discovers new simplification rules.
This powerful method automates the discovery of simplification rules.
It operates in two phases:
1. Generation: It combinatorially generates all possible valid
expressions up to max_source_pattern_length.
2. Verification: It uses a pool of worker processes to test each
generated expression for equivalence with any shorter expression.
Equivalences are found by evaluating both expressions on random
numerical data.
Discovered rules are deduplicated, compiled into the running engine, and can optionally be saved to disk.
| PARAMETER | DESCRIPTION |
|---|---|
max_source_pattern_length
|
The maximum length of expressions to generate and test.
TYPE:
|
max_target_pattern_length
|
The maximum length of a valid simplified expression. If None, any shorter expression is considered a valid simplification.
TYPE:
|
dummy_variables
|
The variables to use when generating expressions.
TYPE:
|
extra_internal_terms
|
Additional leaf nodes (e.g., '
TYPE:
|
X
|
The numerical data for testing equivalence. If an int, specifies the number of samples to generate. If None, defaults to 1024 samples.
TYPE:
|
constants_fit_challenges
|
Number of random constant sets to test for equivalence.
TYPE:
|
constants_fit_retries
|
Number of retries for the curve fitting process.
TYPE:
|
output_file
|
If provided, saves the discovered rules to this JSON file.
TYPE:
|
save_every
|
How often to save the rules to the output file.
TYPE:
|
reset_rules
|
If True, clears existing rules before starting.
TYPE:
|
prune
|
If True, runs :meth:
TYPE:
|
verbose
|
If True, shows progress bars and status updates.
TYPE:
|
n_workers
|
Number of parallel processes to use. Defaults to the number of CPU cores.
TYPE:
|
Source code in src/simplipy/engine.py
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 | |
operand_key ¶
Generates a key for sorting operands of a commutative operator.
The key is a tuple designed to produce a consistent, canonical ordering. It prioritizes variables, then numbers, and finally complex subtrees. Subtrees are sorted by length and then recursively by their contents.
| PARAMETER | DESCRIPTION |
|---|---|
operands
|
The operand to generate a key for, represented as a tree node.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
A sortable key. |
Source code in src/simplipy/engine.py
operators_to_realizations ¶
operators_to_realizations(prefix_expression: list[str] | tuple[str, ...]) -> list[str] | tuple[str, ...]
Converts operator names in an expression to their Python realizations.
This method replaces tokens like 'add' or 'sin' with their executable counterparts like '+' or 'np.sin', making the expression ready for evaluation.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression with canonical operator names.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str] or tuple[str, ...]
|
The prefix expression with Python-executable operator realizations. |
Source code in src/simplipy/engine.py
realizations_to_operators ¶
Converts Python realizations in an expression back to operator names.
This is the inverse of operators_to_realizations, replacing tokens
like '+' or 'np.sin' with their canonical engine names like 'add' or 'sin'.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression with Python-executable realizations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The prefix expression with canonical operator names. |
Source code in src/simplipy/engine.py
code_to_lambda
staticmethod
¶
Converts a Python code object into an executable lambda function.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
The compiled code object to convert.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[..., float]
|
An executable lambda function. |
Source code in src/simplipy/engine.py
Asset Management¶
get_default_cache_dir ¶
Get the default OS-appropriate cache directory for SimpliPy assets.
This function determines the standard cache location based on the user's operating system, following the XDG Base Directory Specification on Linux. It ensures the directory exists, creating it if necessary.
| RETURNS | DESCRIPTION |
|---|---|
Path
|
The path to the cache directory. |
Source code in src/simplipy/asset_manager.py
fetch_manifest ¶
Download the latest asset manifest from Hugging Face Hub.
The manifest is a JSON file that contains metadata for all official assets, including engines and test data. This function handles potential network errors gracefully.
| PARAMETER | DESCRIPTION |
|---|---|
repo_id
|
The Hugging Face repository ID where the manifest is stored. If None, the default repository ID is used.
TYPE:
|
manifest_filename
|
The filename of the manifest file. If None, the default filename is used.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
The parsed JSON manifest as a dictionary. Returns an empty dictionary if the download fails. |
Source code in src/simplipy/asset_manager.py
get_path ¶
get_path(asset: str, install: bool = False, local_dir: Path | str | None = None, repo_id: str | None = None, manifest_filename: str | None = None) -> str
Resolve the local filesystem path to an asset's entrypoint file.
This function serves as a universal resolver for SimpliPy assets. It first
checks if the asset string is a valid local path. If not, it treats it
as an official asset name and looks it up in the manifest.
| PARAMETER | DESCRIPTION |
|---|---|
asset
|
The identifier for the asset. This can be a direct path to a local file (e.g., './my_rules.yaml') or the name of an official asset (e.g., 'core-rules-v1').
TYPE:
|
install
|
If True, automatically downloads and installs the asset from Hugging Face Hub if it is not found locally. Defaults to False.
TYPE:
|
local_dir
|
The directory to check for the asset or install it into. If None, the default cache directory is used. Defaults to None.
TYPE:
|
repo_id
|
The Hugging Face repository ID where the manifest is stored. If None, the default repository ID is used.
TYPE:
|
manifest_filename
|
The filename of the manifest file. If None, the default filename is used.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The absolute path to the asset's entrypoint file. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the asset manifest cannot be fetched from Hugging Face Hub or if
the installation fails when |
ValueError
|
If |
FileNotFoundError
|
If the asset is not found locally and |
Source code in src/simplipy/asset_manager.py
install_asset ¶
install_asset(asset: str, force: bool = False, local_dir: Path | str | None = None, repo_id: str | None = None, manifest_filename: str | None = None) -> bool
Install a SimpliPy asset from Hugging Face Hub.
Downloads all files associated with a given asset from its corresponding Hugging Face repository and places them in the specified local directory.
| PARAMETER | DESCRIPTION |
|---|---|
asset
|
The name of the official asset to install.
TYPE:
|
force
|
If True, any existing local version of the asset will be removed before the new version is installed. Defaults to False.
TYPE:
|
local_dir
|
The directory to install the asset into. If None, the default cache directory is used. Defaults to None.
TYPE:
|
repo_id
|
The Hugging Face repository ID where the manifest is stored. If None, the default repository ID is used.
TYPE:
|
manifest_filename
|
The filename of the manifest file. If None, the default filename is used.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the installation was successful or if the asset was already installed. False if the asset name is unknown or a download error occurs. |
Source code in src/simplipy/asset_manager.py
uninstall_asset ¶
uninstall_asset(asset: str, quiet: bool = False, local_dir: Path | str | None = None, repo_id: str | None = None, manifest_filename: str | None = None) -> bool
Remove a locally installed SimpliPy asset.
This function deletes the entire directory associated with the specified asset from the local filesystem.
| PARAMETER | DESCRIPTION |
|---|---|
asset
|
The name of the asset to uninstall.
TYPE:
|
quiet
|
If True, suppresses console output messages. Defaults to False.
TYPE:
|
local_dir
|
The directory from which to uninstall the asset. If None, the default cache directory is used. Defaults to None.
TYPE:
|
repo_id
|
The Hugging Face repository ID where the manifest is stored. If None, the default repository ID is used.
TYPE:
|
manifest_filename
|
The filename of the manifest file. If None, the default filename is used.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the asset was successfully removed or was not installed to begin with. False if an OS error occurs during removal. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/simplipy/asset_manager.py
list_assets ¶
list_assets(asset_type: AssetType, installed_only: bool = False, local_dir: Path | str | None = None, repo_id: str | None = None, manifest_filename: str | None = None) -> None
List available or installed SimpliPy assets.
Fetches the asset manifest and checks the local filesystem to print a formatted list of assets, their descriptions, and their installation status to standard output.
| PARAMETER | DESCRIPTION |
|---|---|
asset_type
|
The category of assets to list.
TYPE:
|
installed_only
|
If True, the list is filtered to show only assets that are currently installed locally. Defaults to False.
TYPE:
|
local_dir
|
The directory to check for installed assets. If None, the default cache directory is used. Defaults to None.
TYPE:
|
repo_id
|
The Hugging Face repository ID where the manifest is stored. If None, the default repository ID is used.
TYPE:
|
manifest_filename
|
The filename of the manifest file. If None, the default filename is used.
TYPE:
|
Source code in src/simplipy/asset_manager.py
Operators¶
neg ¶
inv ¶
Return the element-wise multiplicative inverse of x.
Source code in src/simplipy/operators.py
div ¶
Return the element-wise division of x by y.
Source code in src/simplipy/operators.py
mult2 ¶
mult3 ¶
mult4 ¶
mult5 ¶
div2 ¶
div3 ¶
div4 ¶
div5 ¶
pow2 ¶
pow3 ¶
pow4 ¶
pow5 ¶
pow1_2 ¶
pow1_3 ¶
Return the real-valued cube root of x.
Source code in src/simplipy/operators.py
pow1_4 ¶
pow1_5 ¶
Return the real-valued fifth root of x.
Source code in src/simplipy/operators.py
abs ¶
Return the element-wise absolute value of x.
Source code in src/simplipy/operators.py
sin ¶
Return the element-wise sine of x.
Source code in src/simplipy/operators.py
cos ¶
Return the element-wise cosine of x.
Source code in src/simplipy/operators.py
tan ¶
Return the element-wise tangent of x.
Source code in src/simplipy/operators.py
asin ¶
Return the element-wise inverse sine of x.
Source code in src/simplipy/operators.py
acos ¶
Return the element-wise inverse cosine of x.
Source code in src/simplipy/operators.py
atan ¶
Return the element-wise inverse tangent of x.
Source code in src/simplipy/operators.py
sinh ¶
Return the element-wise hyperbolic sine of x.
Source code in src/simplipy/operators.py
cosh ¶
Return the element-wise hyperbolic cosine of x.
Source code in src/simplipy/operators.py
tanh ¶
Return the element-wise hyperbolic tangent of x.
Source code in src/simplipy/operators.py
asinh ¶
Return the element-wise inverse hyperbolic sine of x.
Source code in src/simplipy/operators.py
acosh ¶
Return the element-wise inverse hyperbolic cosine of x.
Source code in src/simplipy/operators.py
atanh ¶
Return the element-wise inverse hyperbolic tangent of x.
Source code in src/simplipy/operators.py
exp ¶
Return the element-wise exponential of x.
Source code in src/simplipy/operators.py
log ¶
Return the element-wise natural logarithm of x.
Source code in src/simplipy/operators.py
pow ¶
Return x raised to the power of y, element-wise.
Source code in src/simplipy/operators.py
Utilities¶
apply_on_nested ¶
Recursively apply a function to all non-structural values in a nested container.
This function traverses a nested dictionary or list and applies func to
every value that is not itself a dict or list. The original
structure is mutated; the same instance is returned for convenience. If
structure is neither a list nor a dictionary, it is returned unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
structure
|
The nested list or dictionary to process.
TYPE:
|
func
|
The function to apply to each non-structural value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list or dict
|
The input |
Examples:
>>> data = {'a': 1, 'b': {'c': 2, 'd': [{'e': 3}, {'f': 4}, 3]}}
>>> result = apply_on_nested(data, lambda x: x * 10)
>>> result
{'a': 10, 'b': {'c': 20, 'd': [{'e': 30}, {'f': 40}, 30]}}
>>> data is result
True
Source code in src/simplipy/utils.py
traverse_dict ¶
Recursively traverse a nested dictionary and yield key-value pairs.
This generator function walks through a dictionary, descending into any nested dictionaries it finds. It yields the key and value for any value that is not a dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
dict_
|
The nested dictionary to traverse.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
tuple[str, Any]
|
A tuple containing the key and its corresponding non-dictionary value. |
Examples:
>>> data = {'a': 1, 'b': {'c': 2, 'd': 3}}
>>> list(traverse_dict(data))
[('a', 1), ('c', 2), ('d', 3)]
Source code in src/simplipy/utils.py
codify ¶
Compile a string expression into a Python code object.
This function takes a string representing a mathematical expression and
compiles it into a code object that can be executed later using eval or
converted into a lambda function. It wraps the expression in a lambda
function signature.
| PARAMETER | DESCRIPTION |
|---|---|
code_string
|
The mathematical expression string to compile.
TYPE:
|
variables
|
A list of variable names to be used as arguments for the lambda function, by default None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CodeType
|
The compiled code object, ready for execution. |
Examples:
>>> code_obj = codify("x + y", variables=['x', 'y'])
>>> compiled_func = eval(code_obj)
>>> compiled_func(2, 3)
5
Source code in src/simplipy/utils.py
get_used_modules ¶
Return the names of top-level Python modules referenced in an infix expression.
The function scans for dotted attribute accesses that look like module
usages (for example numpy.sin(...) or math.cos(...)) and collects
their leading module names. The module numpy is always included so that
downstream evaluation logic can rely on it being available.
| PARAMETER | DESCRIPTION |
|---|---|
infix_expression
|
The mathematical expression in infix notation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
Unique module names referenced in |
Examples:
Source code in src/simplipy/utils.py
substitude_constants ¶
substitude_constants(prefix_expression: list[str], values: list | ndarray, constants: list[str] | None = None, inplace: bool = False) -> list[str]
Substitute placeholders in a prefix expression with numeric values.
This helper replaces constant placeholders such as "<constant>" or the
tokens listed in constants with the values supplied in values. Values
are consumed from left to right as matching tokens are encountered.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression containing constant placeholders.
TYPE:
|
values
|
The numeric values to substitute into the expression.
TYPE:
|
constants
|
An explicit list of placeholder names to be replaced. When
TYPE:
|
inplace
|
If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The prefix expression with placeholders replaced by strings holding the given numeric values. |
| RAISES | DESCRIPTION |
|---|---|
IndexError
|
If there are more placeholders than supplied |
Examples:
>>> expr = ['*', '<constant>', '+', 'x', '<constant>']
>>> substitude_constants(expr, [3.14, 2.71])
['*', '3.14', '+', 'x', '2.71']
>>> expr = ['*', 'C_0', '+', 'x', 'C_1']
>>> substitude_constants(expr, [3.14, 2.71], constants=['C_0', 'C_1'])
['*', '3.14', '+', 'x', '2.71']
>>> expr = ['*', 'k1', '+', 'x', 'k2']
>>> substitude_constants(expr, [3.14, 2.71], constants=['k1', 'k2'])
['*', '3.14', '+', 'x', '2.71']
Source code in src/simplipy/utils.py
apply_variable_mapping ¶
Rename variables in a prefix expression using a mapping.
Applies a given mapping to rename variables within a prefix expression. Any token in the expression that is a key in the mapping will be replaced by its corresponding value.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression to modify.
TYPE:
|
variable_mapping
|
A dictionary mapping original variable names to new names.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
A new prefix expression with variables renamed. |
Examples:
>>> expr = ['+', 'var1', 'var2']
>>> mapping = {'var1': 'x', 'var2': 'y'}
>>> apply_variable_mapping(expr, mapping)
['+', 'x', 'y']
Source code in src/simplipy/utils.py
numbers_to_constant ¶
Replace all numeric literals in a prefix expression with '
This function standardizes an expression by replacing all tokens that can be
interpreted as numbers with a generic <constant> placeholder. This is
useful for structural comparison and rule matching.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression to process.
TYPE:
|
inplace
|
If True, modifies the list in-place; otherwise, returns a new list. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The modified prefix expression. |
Examples:
>>> expr = ['+', 'x', '3.14', '*', 'y', '-2']
>>> numbers_to_constant(expr)
['+', 'x', '<constant>', '*', 'y', '<constant>']
Source code in src/simplipy/utils.py
explicit_constant_placeholders ¶
explicit_constant_placeholders(prefix_expression: list[str], constants: list[str] | None = None, inplace: bool = False, convert_numbers_to_constant: bool = True) -> tuple[list[str], list[str]]
Convert placeholder tokens to explicit constant names (for example C_0, C_1).
"<constant>" tokens — and, when convert_numbers_to_constant is True,
integer-like numeric strings or existing C_i tokens — are replaced with
explicit constant identifiers. This is useful for generating call signatures
where constants are passed as named arguments.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression to process.
TYPE:
|
constants
|
Initial constant names to reuse before generating new ones. The returned list includes these values plus any newly generated identifiers.
TYPE:
|
inplace
|
If
TYPE:
|
convert_numbers_to_constant
|
If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[list[str], list[str]]
|
Two items: the modified prefix expression and the list of constant names used in order of appearance. |
Examples:
>>> expr = ['*', '<constant>', '+', 'x', '2']
>>> explicit_constant_placeholders(expr)
(['*', 'C_0', '+', 'x', 'C_1'], ['C_0', 'C_1'])
>>> explicit_constant_placeholders(['+', 'C_3', '<constant>'], constants=['K'])
(['+', 'K', 'C_0'], ['K', 'C_0', 'C_1'])
Source code in src/simplipy/utils.py
flatten_nested_list ¶
Flatten an arbitrarily nested list into a single list of leaf values.
A stack-based traversal is used to avoid recursion limits. Because a LIFO
stack is employed, values appear in reverse depth-first order relative to
the original nesting. list(reversed(...)) can be used to restore a
left-to-right ordering if required.
| PARAMETER | DESCRIPTION |
|---|---|
nested_list
|
The nested list to flatten.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The flattened list of elements encountered during traversal. |
Examples:
Source code in src/simplipy/utils.py
is_prime ¶
Check if an integer is a prime number.
Determines if the input number n is prime. The implementation includes
optimizations such as checking for even numbers and only testing divisors
up to the square root of n.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
The integer to check.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if |
Examples:
Source code in src/simplipy/utils.py
safe_f ¶
Safely evaluate a compiled function on an array of inputs.
The callable f is invoked with the columns of X unpacked as separate
arguments, followed by any optional constants. Scalar results are
broadcast to all samples to guarantee a one-dimensional NumPy array of
length X.shape[0].
| PARAMETER | DESCRIPTION |
|---|---|
f
|
The function to evaluate.
TYPE:
|
X
|
Two-dimensional array of input samples. Each column is passed as a
positional argument to
TYPE:
|
constants
|
Extra constant values appended when calling
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
A one-dimensional array with the evaluation results for each row of
|
Examples:
>>> import numpy as np
>>> f = lambda x, y: x + y
>>> safe_f(f, np.array([[1, 2], [3, 4]]))
array([3, 7])
>>> g = lambda x, y, c0: c0
>>> safe_f(g, np.array([[1, 2], [3, 4]]), constants=np.array([5]))
array([5, 5])
Source code in src/simplipy/utils.py
remap_expression ¶
remap_expression(source_expression: list[str], dummy_variables: list[str], variable_mapping: dict | None = None, variable_prefix: str = '_', enumeration_offset: int = 0) -> tuple[list[str], dict]
Standardize variable names in a prefix expression for canonical representation.
Remaps variables (identified from dummy_variables) to a generic,
enumerated format (e.g., _0, _1). This is crucial for comparing the
structure of two expressions regardless of their original variable names.
| PARAMETER | DESCRIPTION |
|---|---|
source_expression
|
The prefix expression to remap.
TYPE:
|
dummy_variables
|
A list of tokens to be treated as variables.
TYPE:
|
variable_mapping
|
An existing mapping to apply. If None, a new one is created. Defaults to None.
TYPE:
|
variable_prefix
|
The prefix for the new standardized variable names, by default "_".
TYPE:
|
enumeration_offset
|
The starting number for enumeration, by default 0.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[list[str], dict]
|
A tuple containing: - The remapped prefix expression. - The variable mapping that was created or used. |
Source code in src/simplipy/utils.py
deduplicate_rules ¶
deduplicate_rules(rules_list: list[tuple[tuple[str, ...], tuple[str, ...]]], dummy_variables: list[str], verbose: bool = False) -> list[tuple[tuple[str, ...], tuple[str, ...]]]
Deduplicate a list of simplification rules by canonicalizing variables.
This function processes a list of (source, target) simplification rules. It standardizes the variables in each rule to a canonical form and then
removes duplicates. If multiple rules simplify to different targets from the same canonical source, it keeps the one with the shortest target.
| PARAMETER | DESCRIPTION |
|---|---|
rules_list
|
The list of simplification rules to deduplicate.
TYPE:
|
dummy_variables
|
A list of tokens to be treated as variables for remapping.
TYPE:
|
verbose
|
If True, displays a progress bar. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[tuple[tuple[str, ...], tuple[str, ...]]]
|
The deduplicated and optimized list of simplification rules. |
Source code in src/simplipy/utils.py
is_numeric_string ¶
Check if a string represents a number (integer or float).
This function determines if the given string can be interpreted as a numeric value. It handles integers, floats, and scientific notation.
Original author: Cecil Curry Source: https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-represents-a-number-float-or-int
| PARAMETER | DESCRIPTION |
|---|---|
s
|
The string to check.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the string represents a number, False otherwise. |
Examples:
>>> is_numeric_string("123")
True
>>> is_numeric_string("-1.5e-2")
True
>>> is_numeric_string("abc")
False
Source code in src/simplipy/utils.py
factorize_to_at_most ¶
Factorize an integer into factors limited by max_factor.
This helper decomposes p into a list of factors whose product equals
p such that every factor is less than or equal to max_factor. If the
decomposition is impossible (for example because p contains a prime
factor larger than max_factor) a :class:ValueError is raised instead of
returning an invalid factorization.
| PARAMETER | DESCRIPTION |
|---|---|
p
|
The integer to factorize. Must be greater than or equal to
TYPE:
|
max_factor
|
The maximum allowable value for any single factor. Must be at least 2.
TYPE:
|
max_iter
|
A soft cap on the number of prime factors processed. If the algorithm
exceeds this limit, a :class:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[int]
|
The factors of |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
Source code in src/simplipy/utils.py
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 | |
mask_elementary_literals ¶
Replace all numeric string literals with the '
Scans a prefix expression and replaces any token that represents a number
(e.g., "0", "1", "3.14") with the generic placeholder "
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression to modify.
TYPE:
|
inplace
|
If True, modifies the list in-place; otherwise, returns a new list. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The expression with numeric literals masked. |
Source code in src/simplipy/utils.py
construct_expressions ¶
construct_expressions(expressions_of_length: dict[int, set[tuple[str, ...]]], non_leaf_nodes: dict[str, int], must_have_sizes: list | set | None = None) -> Generator[tuple[str, ...], None, None]
Generate new prefix expressions by combining existing building blocks.
Expressions are grouped by length in expressions_of_length. For each
operator in non_leaf_nodes the generator enumerates every compatible
tuple of child expressions and yields the resulting prefix encoding. When
must_have_sizes is provided, at least one operand must have a length
contained in that collection before the expression is yielded.
| PARAMETER | DESCRIPTION |
|---|---|
expressions_of_length
|
Mapping from expression length to the set of expressions with that length.
TYPE:
|
non_leaf_nodes
|
Mapping from operator tokens to their arity.
TYPE:
|
must_have_sizes
|
If provided, filters generated combinations so that at least one child
expression has a length contained in this collection. Defaults to
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
Newly constructed prefix expressions. |
Examples:
>>> expressions = {1: {('x',), ('y',)}}
>>> operators = {'+': 2}
>>> sorted(construct_expressions(expressions, operators))
[('+', 'x', 'x'), ('+', 'x', 'y'), ('+', 'y', 'x'), ('+', 'y', 'y')]
Source code in src/simplipy/utils.py
apply_mapping ¶
Apply a placeholder-to-subtree mapping to a target expression tree.
Trees are represented as [operator, [operands...]] where each operand is
itself a tree. Leaves are encoded as one-element lists, for example
['x']. Placeholders such as '_0' are replaced with the corresponding
subtree provided in mapping.
| PARAMETER | DESCRIPTION |
|---|---|
tree
|
The target expression tree containing placeholders.
TYPE:
|
mapping
|
Dictionary mapping placeholder names to the subtrees that should replace them.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
A new expression tree with placeholders substituted. |
Examples:
>>> template = ['mul', [['_0'], ['_1']]]
>>> mapping = {'_0': ['x'], '_1': ['add', [['y'], ['z']]]}
>>> apply_mapping(template, mapping)
['mul', [['x'], ['add', [['y'], ['z']]]]]
Source code in src/simplipy/utils.py
match_pattern ¶
match_pattern(tree: list, pattern: list, mapping: dict[str, Any] | None = None) -> tuple[bool, dict[str, Any]]
Recursively match an expression tree against a pattern tree.
tree and pattern use the same representation as described in
:func:apply_mapping. Placeholders in pattern (for example '_0')
match any subtree. When a match succeeds the mapping is populated with the
subtrees that correspond to each placeholder.
| PARAMETER | DESCRIPTION |
|---|---|
tree
|
The expression tree to be matched.
TYPE:
|
pattern
|
The pattern tree to match against.
TYPE:
|
mapping
|
Initial mapping dictionary. If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[bool, dict[str, Any]]
|
|
Examples:
>>> tree = ['mul', [['x'], ['add', [['y'], ['z']]]]]
>>> pattern = ['mul', [['_a'], ['_b']]]
>>> match_pattern(tree, pattern)
(True, {'_a': ['x'], '_b': ['add', [['y'], ['z']]]})
Source code in src/simplipy/utils.py
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 | |
remove_pow1 ¶
Remove identity power operations from a prefix expression.
This utility cleans up an expression by removing pow1 operators, which
represent raising to the power of 1 (an identity operation), and replaces
pow_1 (power of -1) with its canonical equivalent, inv.
| PARAMETER | DESCRIPTION |
|---|---|
prefix_expression
|
The prefix expression to clean.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The cleaned prefix expression without |
Examples:
Source code in src/simplipy/utils.py
violates_wildcard_multiplicity ¶
violates_wildcard_multiplicity(lhs: list[str] | tuple[str, ...], rhs: list[str] | tuple[str, ...]) -> bool
Check whether a rule violates the non-increasing wildcard multiplicity condition.
A rule lhs -> rhs violates the condition when any wildcard token
(matching _\d+) appears more times on the right-hand side than on
the left-hand side. Enforcing this property prevents duplication of
wildcard-matched subtrees by ensuring that no wildcard occurs more often
in the replacement than in the pattern.
| PARAMETER | DESCRIPTION |
|---|---|
lhs
|
The source (left-hand side) of the rule in prefix notation.
TYPE:
|
rhs
|
The target (right-hand side) of the rule in prefix notation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
Source code in src/simplipy/utils.py
I/O Functions¶
load_config ¶
Load a configuration file.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
The configuration dictionary or path to the configuration file.
TYPE:
|
resolve_paths
|
Whether to resolve relative paths in the configuration file, by default True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
The configuration dictionary. |
Source code in src/simplipy/io.py
save_config ¶
save_config(config: dict[str, Any], directory: str, filename: str, reference: str = 'relative', recursive: bool = True, resolve_paths: bool = False) -> None
Save a configuration dictionary to a YAML file.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
The configuration dictionary to save.
TYPE:
|
directory
|
The directory to save the configuration file to.
TYPE:
|
filename
|
The name of the configuration file.
TYPE:
|
reference
|
Determines the reference base path. One of - 'project': relative to the project root - 'absolute': absolute paths
TYPE:
|
recursive
|
Save any referenced configs too
TYPE:
|