let domains author their own pass-2 estimator as formulas, not Python
Pass 2 previously only knew one estimator: a hardcoded physics model that matches dimensions literally named platform/actuator/energy_storage. Any domain outside that shape (e.g. archery) got all-zero estimates and failed every combo. Domains can now declare free variables and per-metric formulas as data instead; a safe AST-based evaluator (engine/formula.py, no eval()) resolves declared entity properties via dep(key, constraint_type) and generalizes the existing hand-nested mass-budget search into an N-variable recursive optimizer. Fully additive -- the legacy platform/actuator/ energy_storage path is untouched and still runs unchanged for every domain that declares no formulas. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -60,6 +60,40 @@ KEY_AGGREGATION: dict[str, str] = {
|
||||
OVERRUN_TOLERANCE: float = 0.10
|
||||
|
||||
|
||||
def aggregate_dependency_value(
|
||||
combination: Combination,
|
||||
key: str,
|
||||
constraint_type: str,
|
||||
key_aggregation: dict[str, str] | None = None,
|
||||
) -> float | None:
|
||||
"""Collapse every numeric dependency matching (key, constraint_type)
|
||||
across a combination's entities into one system-level number: summed for
|
||||
extensive keys (KEY_AGGREGATION says "sum", e.g. mass/footprint --
|
||||
independent components sharing one physical vehicle), otherwise the
|
||||
strongest single value wins (today's default pairwise behavior). Returns
|
||||
None if no entity declares a matching numeric dependency. Shared by
|
||||
ConstraintResolver._check_provides_vs_range and the formula evaluator's
|
||||
injected dep() builtin (see engine/formula.py, engine/pipeline.py) so
|
||||
there's one implementation of "how do these entities' declared numbers
|
||||
combine," not two.
|
||||
"""
|
||||
key_aggregation = KEY_AGGREGATION if key_aggregation is None else key_aggregation
|
||||
values: list[float] = []
|
||||
for entity in combination.entities:
|
||||
for dep in entity.dependencies:
|
||||
if dep.key != key or dep.constraint_type != constraint_type:
|
||||
continue
|
||||
try:
|
||||
values.append(float(dep.value))
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if not values:
|
||||
return None
|
||||
if key_aggregation.get(key) == "sum":
|
||||
return sum(values)
|
||||
return max(values)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConstraintResult:
|
||||
"""Outcome of constraint resolution for a combination."""
|
||||
@@ -250,11 +284,13 @@ class ConstraintResolver:
|
||||
required.setdefault(dep.key, []).append((entity.name, val))
|
||||
|
||||
for key in set(provided) & set(required):
|
||||
prov_val = aggregate_dependency_value(
|
||||
combination, key, "provides", self.key_aggregation
|
||||
)
|
||||
if self.key_aggregation.get(key) == "sum":
|
||||
prov_name = " + ".join(name for name, _ in provided[key])
|
||||
prov_val = sum(val for _, val in provided[key])
|
||||
else:
|
||||
prov_name, prov_val = max(provided[key], key=lambda t: t[1])
|
||||
prov_name, _ = max(provided[key], key=lambda t: t[1])
|
||||
|
||||
for req_name, req_val in required[key]:
|
||||
if prov_val < req_val * self.deficit_threshold:
|
||||
|
||||
139
src/physcom/engine/formula.py
Normal file
139
src/physcom/engine/formula.py
Normal file
@@ -0,0 +1,139 @@
|
||||
"""Safe arithmetic expression language for domain-authored estimator formulas.
|
||||
|
||||
No eval()/exec() anywhere -- compile_formula validates every AST node against
|
||||
a fixed whitelist (arithmetic, numeric/string constants, name lookups, calls
|
||||
to an explicitly supplied function table) before evaluate_formula ever walks
|
||||
it, so a formula can express "how much drawback_force does this combo
|
||||
produce" but never anything with attribute/subscript/import access.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import math
|
||||
import operator
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
|
||||
class FormulaError(Exception):
|
||||
"""Raised for invalid formula syntax/structure or a failed evaluation."""
|
||||
|
||||
|
||||
_ALLOWED_NODES = (
|
||||
ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant, ast.Name, ast.Load,
|
||||
ast.Call, ast.keyword,
|
||||
ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.USub, ast.UAdd,
|
||||
)
|
||||
|
||||
_BINOPS: dict[type, Callable[[float, float], float]] = {
|
||||
ast.Add: operator.add,
|
||||
ast.Sub: operator.sub,
|
||||
ast.Mult: operator.mul,
|
||||
ast.Div: operator.truediv,
|
||||
ast.Pow: operator.pow,
|
||||
}
|
||||
|
||||
_UNARYOPS: dict[type, Callable[[float], float]] = {
|
||||
ast.USub: operator.neg,
|
||||
ast.UAdd: operator.pos,
|
||||
}
|
||||
|
||||
DEFAULT_FUNCTIONS: dict[str, Callable[..., float]] = {
|
||||
"min": min,
|
||||
"max": max,
|
||||
"abs": abs,
|
||||
"sqrt": math.sqrt,
|
||||
"log": math.log,
|
||||
"log1p": math.log1p,
|
||||
"exp": math.exp,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompiledFormula:
|
||||
source: str
|
||||
_tree: ast.Expression
|
||||
|
||||
|
||||
def _validate(tree: ast.AST) -> None:
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, _ALLOWED_NODES):
|
||||
raise FormulaError(
|
||||
f"disallowed expression element: {type(node).__name__}"
|
||||
)
|
||||
if isinstance(node, ast.Constant):
|
||||
if isinstance(node.value, bool) or not isinstance(node.value, (int, float, str)):
|
||||
raise FormulaError(
|
||||
f"disallowed constant type: {type(node.value).__name__}"
|
||||
)
|
||||
if isinstance(node, ast.Name) and node.id.startswith("__"):
|
||||
raise FormulaError(f"disallowed name: {node.id}")
|
||||
if isinstance(node, ast.Call) and not isinstance(node.func, ast.Name):
|
||||
raise FormulaError("only direct function calls are allowed")
|
||||
|
||||
|
||||
def compile_formula(source: str) -> CompiledFormula:
|
||||
try:
|
||||
tree = ast.parse(source, mode="eval")
|
||||
except SyntaxError as exc:
|
||||
raise FormulaError(f"invalid syntax in '{source}': {exc}") from exc
|
||||
_validate(tree)
|
||||
return CompiledFormula(source=source, _tree=tree)
|
||||
|
||||
|
||||
def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Callable]):
|
||||
if isinstance(node, ast.Expression):
|
||||
return _eval(node.body, variables, functions)
|
||||
if isinstance(node, ast.Constant):
|
||||
# Numeric constants are cast to float (not left as int) so a formula
|
||||
# like a**b**c can't build an arbitrary-precision giant int before
|
||||
# ever raising -- float exponentiation overflows to inf/OverflowError
|
||||
# quickly instead. String constants (dep() key/constraint_type args)
|
||||
# pass through unchanged.
|
||||
return node.value if isinstance(node.value, str) else float(node.value)
|
||||
if isinstance(node, ast.Name):
|
||||
if node.id not in variables:
|
||||
raise FormulaError(f"unknown variable '{node.id}'")
|
||||
return variables[node.id]
|
||||
if isinstance(node, ast.BinOp):
|
||||
op = _BINOPS.get(type(node.op))
|
||||
if op is None:
|
||||
raise FormulaError(f"unsupported operator: {type(node.op).__name__}")
|
||||
return op(
|
||||
_eval(node.left, variables, functions),
|
||||
_eval(node.right, variables, functions),
|
||||
)
|
||||
if isinstance(node, ast.UnaryOp):
|
||||
op = _UNARYOPS.get(type(node.op))
|
||||
if op is None:
|
||||
raise FormulaError(f"unsupported operator: {type(node.op).__name__}")
|
||||
return op(_eval(node.operand, variables, functions))
|
||||
if isinstance(node, ast.Call):
|
||||
fname = node.func.id # validated as ast.Name by _validate
|
||||
func = functions.get(fname)
|
||||
if func is None:
|
||||
raise FormulaError(f"unknown function '{fname}'")
|
||||
args = [_eval(a, variables, functions) for a in node.args]
|
||||
kwargs = {kw.arg: _eval(kw.value, variables, functions) for kw in node.keywords}
|
||||
return func(*args, **kwargs)
|
||||
raise FormulaError(f"unsupported expression element: {type(node).__name__}")
|
||||
|
||||
|
||||
def evaluate_formula(
|
||||
compiled: CompiledFormula,
|
||||
variables: dict[str, float],
|
||||
functions: dict[str, Callable] | None = None,
|
||||
) -> float:
|
||||
effective_functions = {**DEFAULT_FUNCTIONS, **(functions or {})}
|
||||
try:
|
||||
result = _eval(compiled._tree, variables, effective_functions)
|
||||
except FormulaError:
|
||||
raise
|
||||
except (TypeError, ValueError, ArithmeticError) as exc:
|
||||
raise FormulaError(f"error evaluating '{compiled.source}': {exc}") from exc
|
||||
if not isinstance(result, (int, float)) or isinstance(result, bool):
|
||||
raise FormulaError(
|
||||
f"formula '{compiled.source}' did not evaluate to a number"
|
||||
)
|
||||
return float(result)
|
||||
@@ -674,7 +674,7 @@ class Pipeline:
|
||||
result.pass2_estimated += 1
|
||||
return
|
||||
|
||||
raw_metrics, feasible = self._estimate_physics(combo, domain.metric_bounds)
|
||||
raw_metrics, feasible = self._estimate_physics(combo, domain)
|
||||
|
||||
if not feasible:
|
||||
# No platform mass within its own declared ceiling could
|
||||
@@ -1324,11 +1324,19 @@ class Pipeline:
|
||||
return best_a, best_s, best_score
|
||||
|
||||
def _estimate_physics(
|
||||
self, combo: Combination, metric_bounds: list[MetricBound]
|
||||
self, combo: Combination, domain: Domain
|
||||
) -> tuple[dict[str, float], bool]:
|
||||
"""Deterministic physics-based estimation from declared entity
|
||||
attributes (no LLM) -- pass 2's estimator.
|
||||
|
||||
Domains that declare their own metric_formulas (see
|
||||
_estimate_via_formulas) are estimated entirely by those
|
||||
domain-authored formulas instead -- this method's hardcoded
|
||||
platform/actuator/energy_storage physics model below is additive,
|
||||
not the only path: it's untouched and still runs unchanged for
|
||||
every domain that declares no formulas (every existing transport
|
||||
domain today).
|
||||
|
||||
power_density, speed, range_fuel, cost_efficiency, and
|
||||
cargo_capacity/cargo_capacity_kg are all computed from the
|
||||
platform's declared mass envelope treated as a combo-wide budget,
|
||||
@@ -1356,6 +1364,10 @@ class Pipeline:
|
||||
whose absolute mass tramples its own platform's declared ceiling
|
||||
can still produce perfectly plausible-looking per-kg ratios.
|
||||
"""
|
||||
if domain.metric_formulas:
|
||||
return self._estimate_via_formulas(combo, domain)
|
||||
|
||||
metric_bounds = domain.metric_bounds
|
||||
metric_names = [mb.metric_name for mb in metric_bounds]
|
||||
units_by_name = {mb.metric_name: mb.unit for mb in metric_bounds}
|
||||
bounds_by_name = {mb.metric_name: mb for mb in metric_bounds}
|
||||
@@ -1427,6 +1439,169 @@ class Pipeline:
|
||||
|
||||
return raw, feasible
|
||||
|
||||
def _estimate_via_formulas(
|
||||
self, combo: Combination, domain: Domain
|
||||
) -> tuple[dict[str, float], bool]:
|
||||
"""Generic estimator for domains that declare their own
|
||||
metric_formulas/free_variables instead of matching the
|
||||
platform/actuator/energy_storage shape _estimate_physics assumes.
|
||||
|
||||
Every formula (free-variable floor/ceiling, and each metric) is
|
||||
evaluated through the same safe engine.formula evaluator, given two
|
||||
kinds of names to resolve: dep(key, constraint_type="provides",
|
||||
agg=None) -- a declared entity property, aggregated across the
|
||||
combo's entities via constraint_resolver.aggregate_dependency_value
|
||||
(the exact sum-vs-max rule ConstraintResolver itself already
|
||||
applies to mass/footprint) -- and any free variable already chosen
|
||||
earlier in its declared sort_order, as a bare name. Free variables
|
||||
are resolved by _search_free_variables, a generalization of
|
||||
_search_best_allocation/_decide_masses's hand-nested 2-3-variable
|
||||
search to an arbitrary domain-declared list; with zero free
|
||||
variables (most new domains -- nothing needs sizing) it degenerates
|
||||
to a single direct formula evaluation, no search at all.
|
||||
|
||||
An invalid formula (bad syntax, unknown name, division by zero for
|
||||
this combo's values) degrades that one metric to 0.0 / that one free
|
||||
variable to being skipped, rather than failing the whole combo --
|
||||
symmetric with how a metric_bounds entry with no matching raw value
|
||||
already defaults to 0.0 elsewhere in this pipeline.
|
||||
"""
|
||||
from physcom.engine.constraint_resolver import aggregate_dependency_value
|
||||
from physcom.engine.formula import FormulaError, compile_formula, evaluate_formula
|
||||
|
||||
def dep(key: str, constraint_type: str = "provides", agg: str | None = None) -> float:
|
||||
key_aggregation = None if agg is None else {key: agg}
|
||||
value = aggregate_dependency_value(combo, key, constraint_type, key_aggregation)
|
||||
return value if value is not None else 0.0
|
||||
|
||||
functions = {"dep": dep}
|
||||
|
||||
compiled_metrics: dict[str, object] = {}
|
||||
for mf in domain.metric_formulas:
|
||||
try:
|
||||
compiled_metrics[mf.metric_name] = compile_formula(mf.formula)
|
||||
except FormulaError:
|
||||
compiled_metrics[mf.metric_name] = None
|
||||
|
||||
compiled_vars: list[tuple[str, object, object]] = []
|
||||
for fv in sorted(domain.free_variables, key=lambda v: v.sort_order):
|
||||
try:
|
||||
compiled_vars.append((
|
||||
fv.name, compile_formula(fv.floor_formula), compile_formula(fv.ceiling_formula),
|
||||
))
|
||||
except FormulaError:
|
||||
continue
|
||||
|
||||
bounds_by_name = {mb.metric_name: mb for mb in domain.metric_bounds}
|
||||
|
||||
def evaluate_metrics(resolved: dict[str, float]) -> dict[str, float]:
|
||||
raw: dict[str, float] = {}
|
||||
for name, compiled in compiled_metrics.items():
|
||||
if compiled is None:
|
||||
raw[name] = 0.0
|
||||
continue
|
||||
try:
|
||||
raw[name] = evaluate_formula(compiled, resolved, functions)
|
||||
except FormulaError:
|
||||
raw[name] = 0.0
|
||||
return raw
|
||||
|
||||
def objective(resolved: dict[str, float]) -> float:
|
||||
raw = evaluate_metrics(resolved)
|
||||
scores, weights = [], []
|
||||
for mb in bounds_by_name.values():
|
||||
val = raw.get(mb.metric_name)
|
||||
if val is None:
|
||||
continue
|
||||
n = normalize(val, mb.norm_min, mb.norm_max)
|
||||
if mb.lower_is_better:
|
||||
n = 1.0 - n
|
||||
scores.append(n)
|
||||
weights.append(mb.weight)
|
||||
return composite_score(scores, weights)
|
||||
|
||||
resolved, _score, feasible = self._search_free_variables(
|
||||
compiled_vars, {}, functions, objective
|
||||
)
|
||||
return evaluate_metrics(resolved), feasible
|
||||
|
||||
def _search_free_variables(
|
||||
self,
|
||||
var_specs: list[tuple[str, object, object]],
|
||||
resolved: dict[str, float],
|
||||
functions: dict,
|
||||
objective,
|
||||
grid: int = 10,
|
||||
rounds: int = 5,
|
||||
) -> tuple[dict[str, float], float, bool]:
|
||||
"""Recursive generalization of _search_best_allocation/_decide_masses's
|
||||
hand-nested outer-platform/inner-(actuator,storage) search to an
|
||||
arbitrary ordered list of free variables: resolve var_specs[0]'s
|
||||
floor/ceiling against what's already been resolved plus dep(...),
|
||||
coarse-to-fine grid-search it, and recurse into the rest for each
|
||||
candidate -- exactly the same nesting the hardcoded 3-variable
|
||||
search already does by hand, just generalized to N. grid/rounds
|
||||
shrink with remaining depth (cost is grid**depth * rounds**depth)
|
||||
for the same reason the hardcoded search's outer loop already uses
|
||||
a cheaper inner search per candidate; tuned for a handful of free
|
||||
variables (transport's own 3 is the reference point), not domains
|
||||
declaring dozens. Returns (resolved, score, feasible); feasible is
|
||||
False only when no candidate at some depth has floor <= ceiling.
|
||||
"""
|
||||
from physcom.engine.formula import FormulaError, evaluate_formula
|
||||
|
||||
if not var_specs:
|
||||
return dict(resolved), objective(resolved), True
|
||||
|
||||
name, floor_f, ceiling_f = var_specs[0]
|
||||
rest = var_specs[1:]
|
||||
try:
|
||||
floor = evaluate_formula(floor_f, resolved, functions)
|
||||
ceiling = evaluate_formula(ceiling_f, resolved, functions)
|
||||
except FormulaError:
|
||||
result = dict(resolved)
|
||||
result[name] = 0.0
|
||||
return result, -1.0, False
|
||||
|
||||
if ceiling < floor:
|
||||
result = dict(resolved)
|
||||
result[name] = floor
|
||||
return result, -1.0, False
|
||||
|
||||
inner_grid = max(4, grid - 2 * len(rest))
|
||||
inner_rounds = max(2, rounds - len(rest))
|
||||
|
||||
if ceiling == floor:
|
||||
candidate = dict(resolved)
|
||||
candidate[name] = floor
|
||||
return self._search_free_variables(
|
||||
rest, candidate, functions, objective, inner_grid, inner_rounds
|
||||
)
|
||||
|
||||
win_lo, win_hi = floor, ceiling
|
||||
best_resolved, best_score, best_feasible = None, -1.0, False
|
||||
for _round in range(rounds):
|
||||
for i in range(grid + 1):
|
||||
v = win_lo + (win_hi - win_lo) * i / grid
|
||||
candidate = dict(resolved)
|
||||
candidate[name] = v
|
||||
r_resolved, r_score, r_feasible = self._search_free_variables(
|
||||
rest, candidate, functions, objective, inner_grid, inner_rounds
|
||||
)
|
||||
if r_score > best_score:
|
||||
best_resolved, best_score, best_feasible = r_resolved, r_score, r_feasible
|
||||
if best_resolved is None:
|
||||
break
|
||||
span = max((win_hi - win_lo) / grid * 2, 1e-9)
|
||||
center = best_resolved[name]
|
||||
win_lo, win_hi = max(floor, center - span), min(ceiling, center + span)
|
||||
|
||||
if best_resolved is None:
|
||||
result = dict(resolved)
|
||||
result[name] = floor
|
||||
return result, -1.0, False
|
||||
return best_resolved, best_score, best_feasible
|
||||
|
||||
def evaluate_allocation(
|
||||
self,
|
||||
combo: Combination,
|
||||
|
||||
Reference in New Issue
Block a user