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:
2026-09-25 15:03:59 -05:00
parent 3429bce8d0
commit b2ccd94fd5
8 changed files with 111 additions and 270 deletions

View File

@@ -9,7 +9,7 @@ PhysCom (Physical Combinatorics) — innovation discovery engine that generates
## Commands ## Commands
- **Install**: `pip install -e ".[dev,web]"` (editable install with test and web deps) - **Install**: `pip install -e ".[dev,web]"` (editable install with test and web deps)
- **Tests (all)**: `python -m pytest tests/ -q` (48 tests, ~5s). Run after every change. - **Tests (all)**: `python -m pytest tests/ -q` (134 tests, ~2 min). Run after every change.
- **Single test file**: `python -m pytest tests/test_scorer.py -q` - **Single test file**: `python -m pytest tests/test_scorer.py -q`
- **Single test**: `python -m pytest tests/test_scorer.py::test_score_combination -q` - **Single test**: `python -m pytest tests/test_scorer.py::test_score_combination -q`
- **Web dev server**: `python -m physcom_web` - **Web dev server**: `python -m physcom_web`

View File

@@ -9,6 +9,7 @@ RUN pip install --no-cache-dir ".[web,gemini]"
VOLUME /app/data VOLUME /app/data
ENV PHYSCOM_DB=/app/data/physcom.db ENV PHYSCOM_DB=/app/data/physcom.db
ENV HOST=0.0.0.0
EXPOSE 5000 EXPOSE 5000
CMD ["python", "-m", "physcom_web"] CMD ["python", "-m", "physcom_web"]

View File

@@ -12,7 +12,6 @@ from __future__ import annotations
import ast import ast
import math import math
import operator import operator
from dataclasses import dataclass
from typing import Callable from typing import Callable
@@ -50,12 +49,6 @@ DEFAULT_FUNCTIONS: dict[str, Callable[..., float]] = {
} }
@dataclass(frozen=True)
class CompiledFormula:
source: str
_tree: ast.Expression
def _validate(tree: ast.AST) -> None: def _validate(tree: ast.AST) -> None:
for node in ast.walk(tree): for node in ast.walk(tree):
if not isinstance(node, _ALLOWED_NODES): if not isinstance(node, _ALLOWED_NODES):
@@ -73,13 +66,13 @@ def _validate(tree: ast.AST) -> None:
raise FormulaError("only direct function calls are allowed") raise FormulaError("only direct function calls are allowed")
def compile_formula(source: str) -> CompiledFormula: def compile_formula(source: str) -> ast.Expression:
try: try:
tree = ast.parse(source, mode="eval") tree = ast.parse(source, mode="eval")
except SyntaxError as exc: except SyntaxError as exc:
raise FormulaError(f"invalid syntax in '{source}': {exc}") from exc raise FormulaError(f"invalid syntax in '{source}': {exc}") from exc
_validate(tree) _validate(tree)
return CompiledFormula(source=source, _tree=tree) return tree
def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Callable]): def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Callable]):
@@ -97,18 +90,12 @@ def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Calla
raise FormulaError(f"unknown variable '{node.id}'") raise FormulaError(f"unknown variable '{node.id}'")
return variables[node.id] return variables[node.id]
if isinstance(node, ast.BinOp): if isinstance(node, ast.BinOp):
op = _BINOPS.get(type(node.op)) return _BINOPS[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.left, variables, functions),
_eval(node.right, variables, functions), _eval(node.right, variables, functions),
) )
if isinstance(node, ast.UnaryOp): if isinstance(node, ast.UnaryOp):
op = _UNARYOPS.get(type(node.op)) return _UNARYOPS[type(node.op)](_eval(node.operand, variables, functions))
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): if isinstance(node, ast.Call):
fname = node.func.id # validated as ast.Name by _validate fname = node.func.id # validated as ast.Name by _validate
func = functions.get(fname) func = functions.get(fname)
@@ -121,19 +108,17 @@ def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Calla
def evaluate_formula( def evaluate_formula(
compiled: CompiledFormula, compiled: ast.Expression,
variables: dict[str, float], variables: dict[str, float],
functions: dict[str, Callable] | None = None, functions: dict[str, Callable] | None = None,
) -> float: ) -> float:
effective_functions = {**DEFAULT_FUNCTIONS, **(functions or {})} effective_functions = {**DEFAULT_FUNCTIONS, **(functions or {})}
try: try:
result = _eval(compiled._tree, variables, effective_functions) result = _eval(compiled, variables, effective_functions)
except FormulaError:
raise
except (TypeError, ValueError, ArithmeticError) as exc: except (TypeError, ValueError, ArithmeticError) as exc:
raise FormulaError(f"error evaluating '{compiled.source}': {exc}") from exc raise FormulaError(f"error evaluating '{ast.unparse(compiled)}': {exc}") from exc
if not isinstance(result, (int, float)) or isinstance(result, bool): if not isinstance(result, (int, float)) or isinstance(result, bool):
raise FormulaError( raise FormulaError(
f"formula '{compiled.source}' did not evaluate to a number" f"formula '{ast.unparse(compiled)}' did not evaluate to a number"
) )
return float(result) return float(result)

View File

@@ -10,14 +10,14 @@ from datetime import datetime, timezone
from physcom.db.repository import Repository from physcom.db.repository import Repository
from physcom.engine.combinator import generate_combinations from physcom.engine.combinator import generate_combinations
from physcom.engine.constraint_resolver import ConstraintResolver, ConstraintResult 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.base import LLMProvider, LLMRateLimitError
from physcom.llm.parsing import parse_rating from physcom.llm.parsing import parse_rating
from physcom.models.combination import Combination, ScoredResult from physcom.models.combination import Combination, ScoredResult
from physcom.models.domain import Domain, MetricBound from physcom.models.domain import Domain, MetricBound
from physcom.models.entity import Entity 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 # Keyed by the same categorical vocabulary already used in seed data — never
# by entity name, so new entities inherit sensible behavior automatically. # 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 # 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 # mass. Real cargo ships run deadweight/lightship ratios of
# vehicle analog). Real cargo ships run deadweight/lightship ratios of
# roughly 1.5-4x depending on class; 2.5 is a reasonable general-cargo # roughly 1.5-4x depending on class; 2.5 is a reasonable general-cargo
# midpoint for this domain-agnostic proxy. # midpoint for this domain-agnostic proxy.
CARGO_KG_PER_STRUCTURAL_KG: float = 2.5 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 (derivative 3*A*v^2 + B > 0 everywhere), so it has exactly one
non-negative real root -- solved directly via Cardano's formula, no non-negative real root -- solved directly via Cardano's formula, no
iteration needed. Falls back to the plain linear model (v = power/k_med) 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 when there's no drag coefficient for this medium."""
behave exactly as before."""
if power_density <= 0 or k_med is None: if power_density <= 0 or k_med is None:
return 0.0 return 0.0
if drag_coeff <= 0 or floor_total <= 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`, # 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 # 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 # efficient than a car's tire, both currently "ground" -- flagged as the
# coarsest approximation here, same spot the earlier LLM comparison found # coarsest approximation here.
# every model's range_fuel guess off by 10-25x from real vehicles.
SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M: dict[str, float] = { SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M: dict[str, float] = {
"ground": 0.016 * 9.81, # combined rolling + aero "road load", Crr-equivalent ~ 0.016 "ground": 0.016 * 9.81, # combined rolling + aero "road load", Crr-equivalent ~ 0.016
"air": 9.81 / 10, # cruise flight, effective L/D ~ 10 "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 # 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 # rocket equation (delta-v = exhaust velocity * ln(mass ratio)), which this
# pass does not implement. Space is deliberately left out of the dict above # 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. # 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 # DRAG_POWER_COEFF_BY_MEDIUM adds the mass-INDEPENDENT aerodynamic drag term
# resistance only (rolling resistance, effectively) -- no aerodynamic drag # the table above lacks: 0.5 * air_density * drag_coefficient * frontal_area,
# term (force ~ frontal_area * velocity^2, independent of mass). That's a # W per (m/s)^3, added on top of the mass-proportional term. Without it,
# reasonable approximation for something car-scale, where rolling resistance # light vehicles (where drag dominates) get wildly overestimated range, and
# genuinely dominates at typical speeds and this was validated against real # achieved speed derived from power has no ceiling. Water hull drag needs
# car range. It badly overestimated range for light/human-scale vehicles, # its own treatment and is a known remaining gap.
# 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: dict[str, float] = { 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 # 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 # 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, # Consumable energy price, $ per MJ delivered. Ambient sources (sun, wind,
# gravity) are genuinely free; food is a real recurring cost even though it # gravity) are genuinely free; food is a real recurring cost even though it
# isn't range-limiting -- cost and range are different questions, see # isn't range-limiting -- cost and range are different questions, see
# AMBIENT_ENERGY_FORMS above. Replaces the old flat $/m ENERGY_FORM_BASE_COST # AMBIENT_ENERGY_FORMS above.
# placeholder with a real energy-priced figure.
FUEL_PRICE_PER_MJ: dict[str, float] = { FUEL_PRICE_PER_MJ: dict[str, float] = {
"wind": 0.0, "wind": 0.0,
"gravitational": 0.0, "gravitational": 0.0,
@@ -1126,8 +1095,7 @@ class Pipeline:
return float(dep.value) return float(dep.value)
return None return None
# Step 1: the required floor (same solve as before -- now a floor # Step 1: the required floor for the search below.
# for the search below, not the final answer).
min_accel = dep_value(ctx.platform, "min_effective_accel", "range_min") min_accel = dep_value(ctx.platform, "min_effective_accel", "range_min")
specific_thrust = dep_value(ctx.actuator, "specific_thrust", "provides") specific_thrust = dep_value(ctx.actuator, "specific_thrust", "provides")
target_velocity = dep_value(ctx.platform, "target_velocity", "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 # space-medium platform paired with an actuator that declares
# neither specific_thrust nor a usable target velocity) -- # neither specific_thrust nor a usable target velocity) --
# fall back to bare floors, with the same near-zero-mass # fall back to bare floors, with the same near-zero-mass
# nominal reference used elsewhere so this doesn't silently # nominal reference used elsewhere so this doesn't
# degenerate to 0 power the way the original stub did. # degenerate to 0 power.
required_actuator = ctx.a_min if ctx.a_min > 0.0 else 10.0 required_actuator = ctx.a_min if ctx.a_min > 0.0 else 10.0
required_storage = ctx.s_min required_storage = ctx.s_min
@@ -1222,17 +1190,7 @@ class Pipeline:
bounds_by_name, units_by_name, bounds_by_name, units_by_name,
platform_mass=platform_mass, platform_mass=platform_mass,
) )
scores, weights = [], [] return score_raw(raw, bounds_by_name.values())[0]
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)
def best_at_platform(p: float, grid: int, rounds: int) -> tuple[float, float, float]: 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) 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 Domains that declare their own metric_formulas (see
_estimate_via_formulas) are estimated entirely by those _estimate_via_formulas) are estimated entirely by those
domain-authored formulas instead -- this method's hardcoded domain-authored formulas instead -- this method's hardcoded
platform/actuator/energy_storage physics model below is additive, platform/actuator/energy_storage physics model below runs for
not the only path: it's untouched and still runs unchanged for every domain that declares no formulas.
every domain that declares no formulas (every existing transport
domain today).
power_density, speed, range_fuel, cost_efficiency, and power_density, speed, range_fuel, cost_efficiency, and
cargo_capacity/cargo_capacity_kg are all computed from the 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 comment above BIOLOGICAL_OPERATOR_MASS_KG for the full formula
rationale. rationale.
safety/availability/reliability/environmental_impact are untouched safety/availability/reliability/environmental_impact are
— these are judgment calls (regulatory, economic, qualitative), judgment calls (regulatory, economic, qualitative),
not physics, and stay on the categorical lookup-table heuristics not physics, and stay on the categorical lookup-table heuristics
below (actuator's thrust_profile and energy_form and the combo's below (actuator's thrust_profile and energy_form and the combo's
infrastructure requirements). infrastructure requirements).
@@ -1373,8 +1329,7 @@ class Pipeline:
bounds_by_name = {mb.metric_name: mb for mb in metric_bounds} bounds_by_name = {mb.metric_name: mb for mb in metric_bounds}
raw: dict[str, float] = {m: 0.0 for m in metric_names} raw: dict[str, float] = {m: 0.0 for m in metric_names}
# Extract intrinsic properties from entities (unchanged — still # Extract intrinsic properties from entities.
# drives the untouched blocks below).
power_density = 0.0 # W/kg power_density = 0.0 # W/kg
energy_density = 0.0 # J/kg energy_density = 0.0 # J/kg
thrust_profile: str | None = None thrust_profile: str | None = None
@@ -1448,8 +1403,8 @@ class Pipeline:
Every formula (free-variable floor/ceiling, and each metric) is Every formula (free-variable floor/ceiling, and each metric) is
evaluated through the same safe engine.formula evaluator, given two evaluated through the same safe engine.formula evaluator, given two
kinds of names to resolve: dep(key, constraint_type="provides", kinds of names to resolve: dep(key, constraint_type="provides")
agg=None) -- a declared entity property, aggregated across the -- a declared entity property, aggregated across the
combo's entities via constraint_resolver.aggregate_dependency_value combo's entities via constraint_resolver.aggregate_dependency_value
(the exact sum-vs-max rule ConstraintResolver itself already (the exact sum-vs-max rule ConstraintResolver itself already
applies to mass/footprint) -- and any free variable already chosen 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.constraint_resolver import aggregate_dependency_value
from physcom.engine.formula import FormulaError, compile_formula, evaluate_formula from physcom.engine.formula import FormulaError, compile_formula, evaluate_formula
def dep(key: str, constraint_type: str = "provides", agg: str | None = None) -> float: def dep(key: str, constraint_type: str = "provides") -> float:
key_aggregation = None if agg is None else {key: agg} value = aggregate_dependency_value(combo, key, constraint_type)
value = aggregate_dependency_value(combo, key, constraint_type, key_aggregation)
return value if value is not None else 0.0 return value if value is not None else 0.0
functions = {"dep": dep} functions = {"dep": dep}
metric_names = [mf.metric_name for mf in domain.metric_formulas]
compiled_metrics: dict[str, object] = {} compiled_metrics: dict[str, object] = {}
for mf in domain.metric_formulas: for mf in domain.metric_formulas:
try: try:
compiled_metrics[mf.metric_name] = compile_formula(mf.formula) compiled_metrics[mf.metric_name] = compile_formula(mf.formula)
except FormulaError: except FormulaError:
compiled_metrics[mf.metric_name] = None continue
compiled_vars: list[tuple[str, object, object]] = [] compiled_vars: list[tuple[str, object, object]] = []
for fv in sorted(domain.free_variables, key=lambda v: v.sort_order): for fv in sorted(domain.free_variables, key=lambda v: v.sort_order):
@@ -1492,33 +1447,17 @@ class Pipeline:
except FormulaError: except FormulaError:
continue continue
bounds_by_name = {mb.metric_name: mb for mb in domain.metric_bounds}
def evaluate_metrics(resolved: dict[str, float]) -> dict[str, float]: 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(): for name, compiled in compiled_metrics.items():
if compiled is None:
raw[name] = 0.0
continue
try: try:
raw[name] = evaluate_formula(compiled, resolved, functions) raw[name] = evaluate_formula(compiled, resolved, functions)
except FormulaError: except FormulaError:
raw[name] = 0.0 pass
return raw return raw
def objective(resolved: dict[str, float]) -> float: def objective(resolved: dict[str, float]) -> float:
raw = evaluate_metrics(resolved) return score_raw(evaluate_metrics(resolved), domain.metric_bounds)[0]
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( resolved, _score, feasible = self._search_free_variables(
compiled_vars, {}, functions, objective compiled_vars, {}, functions, objective
@@ -1656,18 +1595,7 @@ class Pipeline:
platform_mass=p_mass, platform_mass=p_mass,
) )
normalized: dict[str, float] = {} composite, normalized = score_raw(raw, domain.metric_bounds)
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)
# Loose slider ceilings for the UI: how big this component could # Loose slider ceilings for the UI: how big this component could
# get if platform and the other component sat at their own floors # 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, "insufficient_structure": (a_mass + s_mass) > p_mass * CARGO_KG_PER_STRUCTURAL_KG,
"raw_metrics": raw, "raw_metrics": raw,
"normalized_scores": normalized, "normalized_scores": normalized,
"composite_score": composite_score(scores, weights), "composite_score": composite,
} }

View File

@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import math import math
from typing import Iterable
from physcom.models.domain import Domain, MetricBound from physcom.models.domain import Domain, MetricBound
from physcom.models.combination import Combination, Score, ScoredResult from physcom.models.combination import Combination, Score, ScoredResult
@@ -42,50 +43,37 @@ def composite_score(scores: list[float], weights: list[float]) -> float:
return result return result
def score_raw(
raw: dict[str, float], bounds: Iterable[MetricBound]
) -> tuple[float, dict[str, float]]:
"""(composite, per-metric normalized) for raw values against bounds."""
normalized: dict[str, float] = {}
weights: list[float] = []
for mb in bounds:
val = raw.get(mb.metric_name)
if val is None:
continue
n = normalize(val, mb.norm_min, mb.norm_max)
normalized[mb.metric_name] = 1.0 - n if mb.lower_is_better else n
weights.append(mb.weight)
return composite_score(list(normalized.values()), weights), normalized
class Scorer: class Scorer:
"""Scores combinations against a domain's metric bounds.""" """Scores combinations against a domain's metric bounds."""
def __init__(self, domain: Domain) -> None: def __init__(self, domain: Domain) -> None:
self.domain = domain self.domain = domain
self._bounds_by_name: dict[str, MetricBound] = {
mb.metric_name: mb for mb in domain.metric_bounds
}
def score_combination( def score_combination(
self, self, combination: Combination, raw_metrics: dict[str, float]
combination: Combination,
raw_metrics: dict[str, float],
estimation_method: str = "physics_calc",
confidence: float = 1.0,
) -> ScoredResult: ) -> ScoredResult:
"""Score a combination given raw metric values. """Score a combination given raw metric values; missing metrics count as 0.0."""
raw = {mb.metric_name: raw_metrics.get(mb.metric_name, 0.0) for mb in self.domain.metric_bounds}
raw_metrics maps metric_name -> raw estimated value. comp, normalized = score_raw(raw, self.domain.metric_bounds)
"""
scores: list[Score] = []
norm_scores: list[float] = []
weights: list[float] = []
for mb in self.domain.metric_bounds:
raw = raw_metrics.get(mb.metric_name, 0.0)
normed = normalize(raw, mb.norm_min, mb.norm_max)
if mb.lower_is_better:
normed = 1.0 - normed
scores.append(Score(
metric_name=mb.metric_name,
raw_value=raw,
normalized_score=normed,
estimation_method=estimation_method,
confidence=confidence,
))
norm_scores.append(normed)
weights.append(mb.weight)
comp = composite_score(norm_scores, weights)
return ScoredResult( return ScoredResult(
combination_id=combination.id, combination_id=combination.id,
domain_name=self.domain.name, domain_name=self.domain.name,
scores=scores, scores=[Score(metric_name=m, raw_value=raw[m], normalized_score=n) for m, n in normalized.items()],
composite_score=comp, composite_score=comp,
) )

View File

@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import asdict
from datetime import datetime, timezone from datetime import datetime, timezone
from physcom.db.repository import Repository from physcom.db.repository import Repository
@@ -70,20 +71,8 @@ def export_snapshot(repo: Repository) -> dict:
"key": dc.key, "key": dc.key,
"allowed_values": dc.allowed_values, "allowed_values": dc.allowed_values,
}) })
fvs = [] fvs = [{k: v for k, v in asdict(fv).items() if k != "id"} for fv in d.free_variables]
for fv in d.free_variables: mfs = [{k: v for k, v in asdict(mf).items() if k != "id"} for mf in d.metric_formulas]
fvs.append({
"name": fv.name,
"sort_order": fv.sort_order,
"floor_formula": fv.floor_formula,
"ceiling_formula": fv.ceiling_formula,
})
mfs = []
for mf in d.metric_formulas:
mfs.append({
"metric_name": mf.metric_name,
"formula": mf.formula,
})
domain_list.append({ domain_list.append({
"name": d.name, "name": d.name,
"description": d.description, "description": d.description,
@@ -223,19 +212,8 @@ def import_snapshot(repo: Repository, data: dict, *, clear: bool = False) -> dic
) )
for dc in d_data.get("constraints", []) for dc in d_data.get("constraints", [])
] ]
fvs = [ fvs = [FreeVariable(**fv) for fv in d_data.get("free_variables", [])]
FreeVariable( mfs = [MetricFormula(**mf) for mf in d_data.get("metric_formulas", [])]
name=fv["name"],
floor_formula=fv["floor_formula"],
ceiling_formula=fv["ceiling_formula"],
sort_order=fv.get("sort_order", 0),
)
for fv in d_data.get("free_variables", [])
]
mfs = [
MetricFormula(metric_name=mf["metric_name"], formula=mf["formula"])
for mf in d_data.get("metric_formulas", [])
]
domain = Domain( domain = Domain(
name=d_data["name"], name=d_data["name"],
description=d_data.get("description", ""), description=d_data.get("description", ""),

View File

@@ -14,29 +14,6 @@ from physcom.units import format_quantity
DEFAULT_DB = Path("data/physcom.db") DEFAULT_DB = Path("data/physcom.db")
_ENV_FILE = Path(".env")
def _load_or_generate_secret_key() -> str:
"""Return FLASK_SECRET_KEY from env, .env file, or auto-generate and persist it."""
key = os.environ.get("FLASK_SECRET_KEY", "").strip()
if key:
return key
# Try to load from .env
if _ENV_FILE.exists():
for line in _ENV_FILE.read_text().splitlines():
line = line.strip()
if line.startswith("FLASK_SECRET_KEY="):
key = line[len("FLASK_SECRET_KEY="):].strip()
if key:
return key
# Generate, persist, and return
key = secrets.token_hex(32)
with _ENV_FILE.open("a") as f:
f.write(f"FLASK_SECRET_KEY={key}\n")
return key
def get_repo() -> Repository: def get_repo() -> Repository:
@@ -56,7 +33,7 @@ def close_db(exc: BaseException | None = None) -> None:
def create_app() -> Flask: def create_app() -> Flask:
app = Flask(__name__) app = Flask(__name__)
app.secret_key = _load_or_generate_secret_key() app.secret_key = os.environ.get("FLASK_SECRET_KEY") or secrets.token_hex(32)
app.jinja_env.filters["qty"] = format_quantity app.jinja_env.filters["qty"] = format_quantity
@@ -97,4 +74,4 @@ def create_app() -> Flask:
def run() -> None: def run() -> None:
"""Entry point for `physcom-web` script.""" """Entry point for `physcom-web` script."""
app = create_app() app = create_app()
app.run(host="0.0.0.0", debug=True, port=int(os.environ.get("PORT", "5000"))) app.run(host=os.environ.get("HOST", "127.0.0.1"), debug=True, port=int(os.environ.get("PORT", "5000")))

View File

@@ -122,55 +122,50 @@ def metric_delete(domain_id: int, metric_id: int):
# ── Free variable CRUD (HTMX partials) ─────────────────────── # ── Free variable CRUD (HTMX partials) ───────────────────────
def _render(domain_id: int, partial: str):
domain = get_repo().get_domain_by_id(domain_id)
return render_template(f"domains/{partial}", domain=domain)
def _fv_from_form() -> FreeVariable:
return FreeVariable(
name=request.form["name"].strip(),
floor_formula=request.form.get("floor_formula", "").strip(),
ceiling_formula=request.form.get("ceiling_formula", "").strip(),
sort_order=request.form.get("sort_order", 0, type=int),
)
def _mf_from_form() -> MetricFormula:
return MetricFormula(
metric_name=request.form["metric_name"].strip(),
formula=request.form.get("formula", "").strip(),
)
@bp.route("/<int:domain_id>/free-vars/add", methods=["POST"]) @bp.route("/<int:domain_id>/free-vars/add", methods=["POST"])
def free_var_add(domain_id: int): def free_var_add(domain_id: int):
repo = get_repo() fv = _fv_from_form()
name = request.form["name"].strip() if not fv.name or not fv.floor_formula or not fv.ceiling_formula:
floor_formula = request.form.get("floor_formula", "").strip()
ceiling_formula = request.form.get("ceiling_formula", "").strip()
try:
sort_order = int(request.form.get("sort_order", "0"))
except ValueError:
sort_order = 0
if not name or not floor_formula or not ceiling_formula:
flash("Name, floor formula, and ceiling formula are required.", "error") flash("Name, floor formula, and ceiling formula are required.", "error")
else: else:
fv = FreeVariable( get_repo().add_free_variable(domain_id, fv)
name=name, floor_formula=floor_formula, ceiling_formula=ceiling_formula, flash(f"Free variable '{fv.name}' added.", "success")
sort_order=sort_order, return _render(domain_id, "_free_vars_table.html")
)
repo.add_free_variable(domain_id, fv)
flash(f"Free variable '{name}' added.", "success")
domain = repo.get_domain_by_id(domain_id)
return render_template("domains/_free_vars_table.html", domain=domain)
@bp.route("/<int:domain_id>/free-vars/<int:fv_id>/edit", methods=["POST"]) @bp.route("/<int:domain_id>/free-vars/<int:fv_id>/edit", methods=["POST"])
def free_var_edit(domain_id: int, fv_id: int): def free_var_edit(domain_id: int, fv_id: int):
repo = get_repo() get_repo().update_free_variable(fv_id, _fv_from_form())
try:
sort_order = int(request.form.get("sort_order", "0"))
except ValueError:
sort_order = 0
fv = FreeVariable(
name=request.form["name"].strip(),
floor_formula=request.form.get("floor_formula", "").strip(),
ceiling_formula=request.form.get("ceiling_formula", "").strip(),
sort_order=sort_order,
)
repo.update_free_variable(fv_id, fv)
flash("Free variable updated.", "success") flash("Free variable updated.", "success")
domain = repo.get_domain_by_id(domain_id) return _render(domain_id, "_free_vars_table.html")
return render_template("domains/_free_vars_table.html", domain=domain)
@bp.route("/<int:domain_id>/free-vars/<int:fv_id>/delete", methods=["POST"]) @bp.route("/<int:domain_id>/free-vars/<int:fv_id>/delete", methods=["POST"])
def free_var_delete(domain_id: int, fv_id: int): def free_var_delete(domain_id: int, fv_id: int):
repo = get_repo() get_repo().delete_free_variable(fv_id)
repo.delete_free_variable(fv_id)
flash("Free variable removed.", "success") flash("Free variable removed.", "success")
domain = repo.get_domain_by_id(domain_id) return _render(domain_id, "_free_vars_table.html")
return render_template("domains/_free_vars_table.html", domain=domain)
# ── Metric formula CRUD (HTMX partials) ────────────────────── # ── Metric formula CRUD (HTMX partials) ──────────────────────
@@ -178,35 +173,24 @@ def free_var_delete(domain_id: int, fv_id: int):
@bp.route("/<int:domain_id>/formulas/add", methods=["POST"]) @bp.route("/<int:domain_id>/formulas/add", methods=["POST"])
def formula_add(domain_id: int): def formula_add(domain_id: int):
repo = get_repo() mf = _mf_from_form()
metric_name = request.form["metric_name"].strip() if not mf.metric_name or not mf.formula:
formula = request.form.get("formula", "").strip()
if not metric_name or not formula:
flash("Metric name and formula are required.", "error") flash("Metric name and formula are required.", "error")
else: else:
repo.add_metric_formula(domain_id, MetricFormula(metric_name=metric_name, formula=formula)) get_repo().add_metric_formula(domain_id, mf)
flash(f"Formula for '{metric_name}' added.", "success") flash(f"Formula for '{mf.metric_name}' added.", "success")
domain = repo.get_domain_by_id(domain_id) return _render(domain_id, "_formulas_table.html")
return render_template("domains/_formulas_table.html", domain=domain)
@bp.route("/<int:domain_id>/formulas/<int:formula_id>/edit", methods=["POST"]) @bp.route("/<int:domain_id>/formulas/<int:formula_id>/edit", methods=["POST"])
def formula_edit(domain_id: int, formula_id: int): def formula_edit(domain_id: int, formula_id: int):
repo = get_repo() get_repo().update_metric_formula(formula_id, _mf_from_form())
mf = MetricFormula(
metric_name=request.form["metric_name"].strip(),
formula=request.form.get("formula", "").strip(),
)
repo.update_metric_formula(formula_id, mf)
flash("Formula updated.", "success") flash("Formula updated.", "success")
domain = repo.get_domain_by_id(domain_id) return _render(domain_id, "_formulas_table.html")
return render_template("domains/_formulas_table.html", domain=domain)
@bp.route("/<int:domain_id>/formulas/<int:formula_id>/delete", methods=["POST"]) @bp.route("/<int:domain_id>/formulas/<int:formula_id>/delete", methods=["POST"])
def formula_delete(domain_id: int, formula_id: int): def formula_delete(domain_id: int, formula_id: int):
repo = get_repo() get_repo().delete_metric_formula(formula_id)
repo.delete_metric_formula(formula_id)
flash("Formula removed.", "success") flash("Formula removed.", "success")
domain = repo.get_domain_by_id(domain_id) return _render(domain_id, "_formulas_table.html")
return render_template("domains/_formulas_table.html", domain=domain)