simplify: one scoring path, bare AST formulas, localhost-only dev server
- move _score_raw into scorer.score_raw; Scorer delegates to it - compile_formula returns ast.Expression directly (drop CompiledFormula) - secret key from env or random; drop hand-rolled .env parsing/appending - dev server binds 127.0.0.1 by default (HOST env override); Docker sets HOST=0.0.0.0 so container port mapping still works - trim pipeline comments narrating past bugs (history lives in git) - snapshot free-var/formula (de)serialization via asdict/**kwargs - domains routes: shared form parsing and partial rendering helpers Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -10,14 +10,14 @@ from datetime import datetime, timezone
|
||||
from physcom.db.repository import Repository
|
||||
from physcom.engine.combinator import generate_combinations
|
||||
from physcom.engine.constraint_resolver import ConstraintResolver, ConstraintResult
|
||||
from physcom.engine.scorer import Scorer, composite_score, normalize
|
||||
from physcom.engine.scorer import Scorer, score_raw
|
||||
from physcom.llm.base import LLMProvider, LLMRateLimitError
|
||||
from physcom.llm.parsing import parse_rating
|
||||
from physcom.models.combination import Combination, ScoredResult
|
||||
from physcom.models.domain import Domain, MetricBound
|
||||
from physcom.models.entity import Entity
|
||||
|
||||
# Stub-estimator heuristics (used only when no LLM provider is configured).
|
||||
# Pass-2 estimator heuristics.
|
||||
# Keyed by the same categorical vocabulary already used in seed data — never
|
||||
# by entity name, so new entities inherit sensible behavior automatically.
|
||||
|
||||
@@ -72,8 +72,7 @@ INFRASTRUCTURE_AVAILABILITY: dict[tuple[str, str], float] = {
|
||||
}
|
||||
|
||||
# Crude freight-capacity proxy: kg of cargo per kg of vehicle structural
|
||||
# mass. Was 500 -- a magnitude error (500x cargo-to-structure has no real
|
||||
# vehicle analog). Real cargo ships run deadweight/lightship ratios of
|
||||
# mass. Real cargo ships run deadweight/lightship ratios of
|
||||
# roughly 1.5-4x depending on class; 2.5 is a reasonable general-cargo
|
||||
# midpoint for this domain-agnostic proxy.
|
||||
CARGO_KG_PER_STRUCTURAL_KG: float = 2.5
|
||||
@@ -209,8 +208,7 @@ def _solve_achievable_speed_mps(
|
||||
(derivative 3*A*v^2 + B > 0 everywhere), so it has exactly one
|
||||
non-negative real root -- solved directly via Cardano's formula, no
|
||||
iteration needed. Falls back to the plain linear model (v = power/k_med)
|
||||
when there's no drag coefficient for this medium, so ungraded media
|
||||
behave exactly as before."""
|
||||
when there's no drag coefficient for this medium."""
|
||||
if power_density <= 0 or k_med is None:
|
||||
return 0.0
|
||||
if drag_coeff <= 0 or floor_total <= 0:
|
||||
@@ -245,8 +243,7 @@ AMBIENT_ENERGY_FORMS: set[str] = {"wind", "radiation_pressure", "gravitational"}
|
||||
# aircraft, hull drag for water. Keyed by the platform's declared `medium`,
|
||||
# not per-platform -- a real train's steel-wheel-on-rail is far more
|
||||
# efficient than a car's tire, both currently "ground" -- flagged as the
|
||||
# coarsest approximation here, same spot the earlier LLM comparison found
|
||||
# every model's range_fuel guess off by 10-25x from real vehicles.
|
||||
# coarsest approximation here.
|
||||
SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M: dict[str, float] = {
|
||||
"ground": 0.016 * 9.81, # combined rolling + aero "road load", Crr-equivalent ~ 0.016
|
||||
"air": 9.81 / 10, # cruise flight, effective L/D ~ 10
|
||||
@@ -257,42 +254,15 @@ SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M: dict[str, float] = {
|
||||
# mass)" shape is the wrong model for them; real range is governed by the
|
||||
# rocket equation (delta-v = exhaust velocity * ln(mass ratio)), which this
|
||||
# pass does not implement. Space is deliberately left out of the dict above
|
||||
# so it falls through to the old placeholder formula in the code below
|
||||
# so it falls through to the placeholder formula in the code below
|
||||
# rather than silently claiming a resistance-based number that isn't real.
|
||||
#
|
||||
# FORMERLY A KNOWN GAP, now fixed below: the table above is mass-proportional
|
||||
# resistance only (rolling resistance, effectively) -- no aerodynamic drag
|
||||
# term (force ~ frontal_area * velocity^2, independent of mass). That's a
|
||||
# reasonable approximation for something car-scale, where rolling resistance
|
||||
# genuinely dominates at typical speeds and this was validated against real
|
||||
# car range. It badly overestimated range for light/human-scale vehicles,
|
||||
# where drag is the dominant resistance term and doesn't scale down with
|
||||
# mass the way this formula assumes -- confirmed on a real combo (Light
|
||||
# Personal Vehicle + Electric Motor + Rechargeable Battery, #876): a sane
|
||||
# 9kg battery on a realistic 31kg vehicle came out to ~1,977km, a 6-9x
|
||||
# overestimate against real e-bikes on comparable battery energy (~50-80km
|
||||
# on ~500Wh). It also meant an achieved-speed metric derived from power
|
||||
# alone (see DRAG_POWER_COEFF_BY_MEDIUM / _solve_achievable_speed_mps below)
|
||||
# had no ceiling at all -- without a v^2-scaling force to push back, more
|
||||
# power always bought proportionally more speed, forever.
|
||||
#
|
||||
# DRAG_POWER_COEFF_BY_MEDIUM below adds that missing term: a mass-INDEPENDENT
|
||||
# drag power coefficient (0.5 * air_density * drag_coefficient * frontal_area,
|
||||
# W per (m/s)^3) added on top of the existing mass-proportional term.
|
||||
#
|
||||
# "air" was originally left out of this table on the reasoning that its
|
||||
# L/D-based cruise model was already a reasonable velocity-roughly-linear
|
||||
# approximation -- true for computing energy per meter during a normal
|
||||
# cruise, but WRONG for the exact same reason ground was wrong: L/D-based
|
||||
# drag force is also roughly velocity-independent within a design cruise
|
||||
# band, so it's still just "resistance = mass-proportional constant" with
|
||||
# no v^2 term, and inverting power/resistance for achieved speed still had
|
||||
# no ceiling. Confirmed live: a Rotorcraft + Gas Turbine combo showed a
|
||||
# "speed" of 3,127 m/s (Mach 9) with phi4's pass-4 review flagging it
|
||||
# directly ("unrealistic for urban commuting, likely indicating an
|
||||
# error"). Added below with an aircraft-like reference cross-section.
|
||||
# Water hull drag would need its own (different) treatment rather than
|
||||
# reusing either reference, so it's left as a known remaining gap.
|
||||
# DRAG_POWER_COEFF_BY_MEDIUM adds the mass-INDEPENDENT aerodynamic drag term
|
||||
# the table above lacks: 0.5 * air_density * drag_coefficient * frontal_area,
|
||||
# W per (m/s)^3, added on top of the mass-proportional term. Without it,
|
||||
# light vehicles (where drag dominates) get wildly overestimated range, and
|
||||
# achieved speed derived from power has no ceiling. Water hull drag needs
|
||||
# its own treatment and is a known remaining gap.
|
||||
DRAG_POWER_COEFF_BY_MEDIUM: dict[str, float] = {
|
||||
# 0.5 * rho_air(1.225 kg/m^3) * Cd(~0.3) * frontal_area(~2.2 m^2, small
|
||||
# car reference) -- sanity check: at 30 m/s (108 km/h) this alone costs
|
||||
@@ -340,8 +310,7 @@ HARDWARE_COST_PER_KG_BY_ENERGY_FORM: dict[str, float] = {
|
||||
# Consumable energy price, $ per MJ delivered. Ambient sources (sun, wind,
|
||||
# gravity) are genuinely free; food is a real recurring cost even though it
|
||||
# isn't range-limiting -- cost and range are different questions, see
|
||||
# AMBIENT_ENERGY_FORMS above. Replaces the old flat $/m ENERGY_FORM_BASE_COST
|
||||
# placeholder with a real energy-priced figure.
|
||||
# AMBIENT_ENERGY_FORMS above.
|
||||
FUEL_PRICE_PER_MJ: dict[str, float] = {
|
||||
"wind": 0.0,
|
||||
"gravitational": 0.0,
|
||||
@@ -1126,8 +1095,7 @@ class Pipeline:
|
||||
return float(dep.value)
|
||||
return None
|
||||
|
||||
# Step 1: the required floor (same solve as before -- now a floor
|
||||
# for the search below, not the final answer).
|
||||
# Step 1: the required floor for the search below.
|
||||
min_accel = dep_value(ctx.platform, "min_effective_accel", "range_min")
|
||||
specific_thrust = dep_value(ctx.actuator, "specific_thrust", "provides")
|
||||
target_velocity = dep_value(ctx.platform, "target_velocity", "provides")
|
||||
@@ -1167,8 +1135,8 @@ class Pipeline:
|
||||
# space-medium platform paired with an actuator that declares
|
||||
# neither specific_thrust nor a usable target velocity) --
|
||||
# fall back to bare floors, with the same near-zero-mass
|
||||
# nominal reference used elsewhere so this doesn't silently
|
||||
# degenerate to 0 power the way the original stub did.
|
||||
# nominal reference used elsewhere so this doesn't
|
||||
# degenerate to 0 power.
|
||||
required_actuator = ctx.a_min if ctx.a_min > 0.0 else 10.0
|
||||
required_storage = ctx.s_min
|
||||
|
||||
@@ -1222,17 +1190,7 @@ class Pipeline:
|
||||
bounds_by_name, units_by_name,
|
||||
platform_mass=platform_mass,
|
||||
)
|
||||
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)
|
||||
return score_raw(raw, bounds_by_name.values())[0]
|
||||
|
||||
def best_at_platform(p: float, grid: int, rounds: int) -> tuple[float, float, float]:
|
||||
budget = min(ctx.p_max - p, p * CARGO_KG_PER_STRUCTURAL_KG)
|
||||
@@ -1332,10 +1290,8 @@ class Pipeline:
|
||||
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).
|
||||
platform/actuator/energy_storage physics model below runs for
|
||||
every domain that declares no formulas.
|
||||
|
||||
power_density, speed, range_fuel, cost_efficiency, and
|
||||
cargo_capacity/cargo_capacity_kg are all computed from the
|
||||
@@ -1344,8 +1300,8 @@ class Pipeline:
|
||||
comment above BIOLOGICAL_OPERATOR_MASS_KG for the full formula
|
||||
rationale.
|
||||
|
||||
safety/availability/reliability/environmental_impact are untouched
|
||||
— these are judgment calls (regulatory, economic, qualitative),
|
||||
safety/availability/reliability/environmental_impact are
|
||||
judgment calls (regulatory, economic, qualitative),
|
||||
not physics, and stay on the categorical lookup-table heuristics
|
||||
below (actuator's thrust_profile and energy_form and the combo's
|
||||
infrastructure requirements).
|
||||
@@ -1373,8 +1329,7 @@ class Pipeline:
|
||||
bounds_by_name = {mb.metric_name: mb for mb in metric_bounds}
|
||||
raw: dict[str, float] = {m: 0.0 for m in metric_names}
|
||||
|
||||
# Extract intrinsic properties from entities (unchanged — still
|
||||
# drives the untouched blocks below).
|
||||
# Extract intrinsic properties from entities.
|
||||
power_density = 0.0 # W/kg
|
||||
energy_density = 0.0 # J/kg
|
||||
thrust_profile: str | None = None
|
||||
@@ -1448,8 +1403,8 @@ class Pipeline:
|
||||
|
||||
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
|
||||
kinds of names to resolve: dep(key, constraint_type="provides")
|
||||
-- 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
|
||||
@@ -1469,19 +1424,19 @@ class 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)
|
||||
def dep(key: str, constraint_type: str = "provides") -> float:
|
||||
value = aggregate_dependency_value(combo, key, constraint_type)
|
||||
return value if value is not None else 0.0
|
||||
|
||||
functions = {"dep": dep}
|
||||
|
||||
metric_names = [mf.metric_name for mf in domain.metric_formulas]
|
||||
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
|
||||
continue
|
||||
|
||||
compiled_vars: list[tuple[str, object, object]] = []
|
||||
for fv in sorted(domain.free_variables, key=lambda v: v.sort_order):
|
||||
@@ -1492,33 +1447,17 @@ class Pipeline:
|
||||
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] = {}
|
||||
raw = dict.fromkeys(metric_names, 0.0)
|
||||
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
|
||||
pass
|
||||
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)
|
||||
return score_raw(evaluate_metrics(resolved), domain.metric_bounds)[0]
|
||||
|
||||
resolved, _score, feasible = self._search_free_variables(
|
||||
compiled_vars, {}, functions, objective
|
||||
@@ -1656,18 +1595,7 @@ class Pipeline:
|
||||
platform_mass=p_mass,
|
||||
)
|
||||
|
||||
normalized: dict[str, float] = {}
|
||||
scores, weights = [], []
|
||||
for mb in domain.metric_bounds:
|
||||
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
|
||||
normalized[mb.metric_name] = n
|
||||
scores.append(n)
|
||||
weights.append(mb.weight)
|
||||
composite, normalized = score_raw(raw, domain.metric_bounds)
|
||||
|
||||
# Loose slider ceilings for the UI: how big this component could
|
||||
# get if platform and the other component sat at their own floors
|
||||
@@ -1697,5 +1625,5 @@ class Pipeline:
|
||||
"insufficient_structure": (a_mass + s_mass) > p_mass * CARGO_KG_PER_STRUCTURAL_KG,
|
||||
"raw_metrics": raw,
|
||||
"normalized_scores": normalized,
|
||||
"composite_score": composite_score(scores, weights),
|
||||
"composite_score": composite,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user