Files
claude-config/bin/plan/formula.py
T

66 lines
3.0 KiB
Python

"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can't hold anything else, and evaluated to a float."""
import ast
import math
from failure import Failure
# The most parts and characters a formula may hold.
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure:
if isinstance(source, Failure):
return source
# Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts.
if len(source) > LONGEST_FORMULA:
return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters")
try:
tree = ast.parse(source, mode="eval")
except (SyntaxError, ValueError):
return Failure(f"the formula {source!r} does not parse")
nodes = list(ast.walk(tree))
if len(nodes) > LARGEST_FORMULA:
return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts")
for node in nodes:
numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)):
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses")
return tree
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
"""Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan."""
match node:
case ast.Expression(body):
return evaluate(body, values)
case ast.Constant(value) if isinstance(value, (int, float)):
return float(value)
case ast.Name(name):
return values[name]
case ast.UnaryOp(ast.USub(), operand):
return -evaluate(operand, values)
case ast.UnaryOp(ast.UAdd(), operand):
return evaluate(operand, values)
case ast.BinOp(left, ast.Add(), right):
return evaluate(left, values) + evaluate(right, values)
case ast.BinOp(left, ast.Sub(), right):
return evaluate(left, values) - evaluate(right, values)
case ast.BinOp(left, ast.Mult(), right):
return evaluate(left, values) * evaluate(right, values)
case ast.BinOp(left, ast.Div(), right):
divisor = evaluate(right, values)
return evaluate(left, values) / divisor if divisor else math.nan
case ast.BinOp(left, ast.Pow(), right):
base, exponent = evaluate(left, values), evaluate(right, values)
# A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1.
if math.isnan(base) or math.isnan(exponent):
return math.nan
# math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three.
try:
return math.pow(base, exponent)
except (OverflowError, ValueError):
return math.nan
return math.nan