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:
2026-08-16 21:28:15 -05:00
parent 3795a7e826
commit 3429bce8d0
15 changed files with 1064 additions and 9 deletions

View File

@@ -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,