urban_commuting: mission requirements, maintenance, cruise-speed decision
Some checks failed
tests / pytest (3.11) (push) Has been cancelled
tests / pytest (3.13) (push) Has been cancelled

- ratio-log normalization (scale-invariant) replacing log1p
- domain requirements (payload, trip_range) as hard mission constraints
- platform payload_ratio, rotorcraft hover floor (min_specific_power)
- maintenance_multiple + service_life folded into cost per metre
- cruise speed searched between domain speed floor and build top speed
- default-deny "domain" requires: Wind Sail / Gravity Coast need the
  domain to declare prevailing_wind / net_descent
- LOGIC DOCS/004: cost per passenger and infrastructure cost, tabled

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-25 23:12:36 -05:00
parent af401d6bc2
commit 60c36e5d27
12 changed files with 421 additions and 178 deletions

View File

@@ -286,6 +286,11 @@ class Repository:
"INSERT OR IGNORE INTO domain_constraints (domain_id, key, value) VALUES (?, ?, ?)",
(domain.id, dc.key, val),
)
for key, val in domain.requirements.items():
self.conn.execute(
"INSERT INTO domain_requirements (domain_id, key, value) VALUES (?, ?, ?)",
(domain.id, key, val),
)
for fv in domain.free_variables:
self.add_free_variable(domain.id, fv, commit=False)
for mf in domain.metric_formulas:
@@ -356,6 +361,11 @@ class Repository:
constraints=self._load_domain_constraints(row["id"]),
free_variables=self._load_free_variables(row["id"]),
metric_formulas=self._load_metric_formulas(row["id"]),
requirements={
r["key"]: r["value"] for r in self.conn.execute(
"SELECT key, value FROM domain_requirements WHERE domain_id = ?", (row["id"],)
).fetchall()
},
)
def get_domain(self, name: str) -> Domain | None:
@@ -462,13 +472,14 @@ class Repository:
self.conn.execute("DELETE FROM combination_scores WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domain_metric_weights WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domain_constraints WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domain_requirements WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domain_free_variables WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domain_metric_formulas WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domains WHERE id = ?", (domain_id,))
self.conn.commit()
def replace_domain_constraints(self, domain: Domain) -> None:
"""Delete and re-insert domain constraints. Used by seed backfill."""
"""Delete and re-insert domain constraints and requirements. Used by seed backfill."""
if not domain.id:
existing = self.conn.execute(
"SELECT id FROM domains WHERE name = ?", (domain.name,)
@@ -477,6 +488,12 @@ class Repository:
return
domain.id = existing["id"]
self.conn.execute("DELETE FROM domain_constraints WHERE domain_id = ?", (domain.id,))
self.conn.execute("DELETE FROM domain_requirements WHERE domain_id = ?", (domain.id,))
for key, val in domain.requirements.items():
self.conn.execute(
"INSERT INTO domain_requirements (domain_id, key, value) VALUES (?, ?, ?)",
(domain.id, key, val),
)
for dc in domain.constraints:
for val in dc.allowed_values:
self.conn.execute(
@@ -988,6 +1005,7 @@ class Repository:
self.conn.execute("DELETE FROM entities")
self.conn.execute("DELETE FROM domain_metric_weights")
self.conn.execute("DELETE FROM domain_constraints")
self.conn.execute("DELETE FROM domain_requirements")
self.conn.execute("DELETE FROM domain_free_variables")
self.conn.execute("DELETE FROM domain_metric_formulas")
self.conn.execute("DELETE FROM domains")

View File

@@ -130,6 +130,13 @@ CREATE TABLE IF NOT EXISTS domain_free_variables (
UNIQUE(domain_id, name)
);
CREATE TABLE IF NOT EXISTS domain_requirements (
domain_id INTEGER NOT NULL REFERENCES domains(id),
key TEXT NOT NULL,
value REAL NOT NULL,
PRIMARY KEY(domain_id, key)
);
CREATE TABLE IF NOT EXISTS domain_metric_formulas (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain_id INTEGER NOT NULL REFERENCES domains(id),

View File

@@ -39,6 +39,8 @@ CATEGORY_SEVERITY: dict[str, str] = {
# shielding) defaulted to a non-blocking warning nothing in the catalog
# ever satisfies -- see LOGIC DOCS/002's "silent guardrail hole" pattern.
"material": "block",
# Checked against the domain's own records instead (check_domain_constraints).
"domain": "skip",
}
# For provides-vs-range_min: deficit > this ratio = hard block, else warning
@@ -311,6 +313,18 @@ class ConstraintResolver:
) -> ConstraintResult:
"""Check if a combo's entity requirements fall within domain-allowed values."""
result = ConstraintResult()
# "domain"-category requires are default-deny: the element only works
# where the domain itself declares the condition (a net-downhill route,
# a prevailing wind), so a domain with no record for the key fails it.
declared = {dc.key for dc in constraints}
for entity in combination.entities:
for dep in entity.dependencies:
if (dep.category == "domain" and dep.constraint_type == "requires"
and dep.key not in declared):
result.violations.append(
f"{entity.name} requires {dep.key}={dep.value} "
f"but the domain does not declare {dep.key}"
)
for dc in constraints:
allowed = set(dc.allowed_values)
for entity in combination.entities:

View File

@@ -10,7 +10,7 @@ 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, score_raw
from physcom.engine.scorer import Scorer, normalize, score_raw
from physcom.llm.base import LLMProvider, LLMRateLimitError
from physcom.llm.parsing import parse_rating
from physcom.models.combination import Combination, ScoredResult
@@ -71,10 +71,10 @@ INFRASTRUCTURE_AVAILABILITY: dict[tuple[str, str], float] = {
("fuel_infrastructure", "xenon_propellant"): 0.05,
}
# Crude freight-capacity proxy: kg of cargo per kg of vehicle structural
# 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.
# Fallback for platforms that don't declare their own payload_ratio
# (carried mass -- actuator + storage + payload + cargo -- per kg of
# platform structure). Real cargo ships run deadweight/lightship ratios of
# roughly 1.5-4x depending on class; 2.5 is a general-cargo midpoint.
CARGO_KG_PER_STRUCTURAL_KG: float = 2.5
# How mechanically proven/predictable an energy form is in practice — distinct
@@ -357,6 +357,21 @@ class _PhysicsContext:
e_dens: float
k_med: float | None
p_rep: float
payload_ratio: float = CARGO_KG_PER_STRUCTURAL_KG
min_specific_power: float | None = None
payload: float = 0.0
trip_range: float | None = None
service_life: float | None = None
# Lifetime maintenance as a multiple of build cost: platform, actuator, storage.
maintenance: tuple[float, float, float] = (0.0, 0.0, 0.0)
def _carried_payload(ctx: _PhysicsContext, actuator_mass: float) -> float:
"""The domain's required payload mass on board, less whatever part of
it a biological actuator already is (the rider is the commuter)."""
if ctx.actuator_energy_form in BIOLOGICAL_OPERATOR_MASS_KG:
return max(0.0, ctx.payload - actuator_mass)
return ctx.payload
@dataclass
@@ -606,18 +621,17 @@ class Pipeline:
# be blocked in this domain but valid in another. The per-domain
# block lives on combination_results.domain_block_reason (see
# count_combinations_by_status / get_all_results, which bucket on it).
if domain.constraints:
dc_result = self.resolver.check_domain_constraints(combo, domain.constraints)
if dc_result.status == "p1_fail":
self.repo.save_result(
combo.id, domain.id,
composite_score=0.0, pass_reached=1,
domain_block_reason="; ".join(dc_result.violations),
commit=False,
)
result.pass1_failed += 1
self._update_run_counters(run_id, result, current_pass=1)
return
dc_result = self.resolver.check_domain_constraints(combo, domain.constraints)
if dc_result.status == "p1_fail":
self.repo.save_result(
combo.id, domain.id,
composite_score=0.0, pass_reached=1,
domain_block_reason="; ".join(dc_result.violations),
commit=False,
)
result.pass1_failed += 1
self._update_run_counters(run_id, result, current_pass=1)
return
if cr.status == "conditional":
result.pass1_conditional += 1
@@ -856,7 +870,8 @@ class Pipeline:
self.repo.update_pipeline_run(run_id, status="running")
def _physics_context(
self, combo: Combination, bounds_by_name: dict[str, MetricBound]
self, combo: Combination, bounds_by_name: dict[str, MetricBound],
requirements: dict[str, float] | None = None,
) -> "_PhysicsContext | None":
"""Derive the entity-level physics inputs that don't depend on a
mass allocation choice -- shared by _estimate_physics (which picks
@@ -899,6 +914,15 @@ class Pipeline:
e_dens=dep_value(storage, "energy_density", "provides") or 0.0,
k_med=SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M.get(medium),
p_rep=_representative_mass(p_min, p_max),
payload_ratio=dep_value(platform, "payload_ratio", "provides") or CARGO_KG_PER_STRUCTURAL_KG,
min_specific_power=dep_value(platform, "min_specific_power", "range_min"),
payload=(requirements or {}).get("payload", 0.0),
trip_range=(requirements or {}).get("trip_range"),
service_life=dep_value(platform, "service_life", "provides"),
maintenance=tuple(
dep_value(e, "maintenance_multiple", "provides") or 0.0
for e in (platform, actuator, storage)
),
)
def _raw_physics_from_masses(
@@ -909,6 +933,7 @@ class Pipeline:
bounds_by_name: dict[str, MetricBound],
units_by_name: dict[str, str],
platform_mass: float | None = None,
cruise_iters: int = 10,
) -> dict[str, float]:
"""power_density/range_fuel/cost_efficiency/cargo_capacity for an
EXPLICIT mass allocation. `platform_mass` defaults to the
@@ -923,124 +948,147 @@ class Pipeline:
metric here does."""
p_mass = ctx.p_rep if platform_mass is None else platform_mass
out: dict[str, float] = {}
floor_total = p_mass + actuator_mass + storage_mass
carried_payload = _carried_payload(ctx, actuator_mass)
floor_total = p_mass + actuator_mass + storage_mass + carried_payload
power_density_value = (ctx.k_act * actuator_mass) / floor_total if floor_total else 0.0
if "power_density" in bounds_by_name:
out["power_density"] = power_density_value
# Deadweight/lightship cargo capacity. Real deadweight tonnage is a
# FIXED allowance sized off the vessel's own empty (lightship) mass
# -- hull + machinery, NOT fuel or cargo -- and fuel and cargo then
# SHARE that one allowance: a ship that bunkers more fuel has that
# much less room left for cargo, and vice versa. platform+actuator
# is the lightship analog here (the vehicle's own hardware);
# storage_mass is the fuel/battery competing with cargo for the
# same pool, not part of the base the pool is sized from -- get
# that backwards (basing the pool on platform+actuator+storage,
# as an earlier version of this did) and more battery looks like it
# BUYS more cargo room instead of using it up. Two ratio
# conventions coexist because heavy freight/maritime vehicles
# genuinely carry a much larger multiple of their own mass in
# cargo than light personal/delivery vehicles do (see
# CARGO_KG_PER_STRUCTURAL_KG's module comment); which one a domain
# scores is just which metric_name it declares. Floored at 0: a
# storage mass bigger than the whole allowance leaves no cargo
# room, not negative room.
# Skip the arithmetic entirely for domains that don't score either
# cargo convention and don't need it as cost_efficiency's $/(kg·m)
# denominator either -- this runs on every one of the ~11,000 grid
# points the search below tries per combo, so a domain like
# interplanetary_travel (scores neither) shouldn't pay for it.
# Spare carrying capacity: the platform structure carries
# payload_ratio x its own mass in total, and actuator, storage and
# the domain's required payload all come out of that same allowance
# -- more fuel/battery means less room for cargo, not more.
# Floored at 0. Skipped for domains that neither score cargo nor
# need it as cost_efficiency's $/(kg·m) denominator -- this runs on
# every grid point of the search in _decide_masses.
needs_cargo = (
"cargo_capacity" in bounds_by_name
or "cargo_capacity_kg" in bounds_by_name
or units_by_name.get("cost_efficiency") == "$/(kg·m)"
)
cargo_capacity_2_5x = 0.0
cargo_capacity = 0.0
if needs_cargo:
lightship_mass = p_mass + actuator_mass
cargo_capacity_2_5x = max(0.0, lightship_mass * CARGO_KG_PER_STRUCTURAL_KG - storage_mass)
cargo_capacity_0_3x = max(0.0, lightship_mass * 0.3 - storage_mass)
if "cargo_capacity" in bounds_by_name:
out["cargo_capacity"] = cargo_capacity_2_5x
if "cargo_capacity_kg" in bounds_by_name:
out["cargo_capacity_kg"] = cargo_capacity_0_3x
cargo_capacity = max(
0.0, p_mass * ctx.payload_ratio - actuator_mass - storage_mass - carried_payload
)
for name in ("cargo_capacity", "cargo_capacity_kg"):
if name in bounds_by_name:
out[name] = cargo_capacity
# Achieved steady-state cruise speed, DERIVED from this specific
# build's actual power_density, the medium's mass-proportional
# resistance, and (ground/air, see DRAG_POWER_COEFF_BY_MEDIUM) a
# mass-independent aerodynamic drag term -- not a platform-declared
# constant. A build with more power than the platform's bare
# target_velocity requires achieves a genuinely higher speed here;
# an underbuilt one achieves less -- speed is an output of the
# build, not an input to it. Computed unconditionally (not just
# when "speed" is a scored metric) because range_fuel/cost_efficiency
# below both need it too: the energy actually spent per meter
# depends on how fast this build is actually going, drag included.
# Top speed, DERIVED from this build's actual power_density, the
# medium's mass-proportional resistance and (ground/air, see
# DRAG_POWER_COEFF_BY_MEDIUM) a mass-independent aerodynamic drag
# term -- an output of the build, not a platform-declared constant.
drag_coeff = DRAG_POWER_COEFF_BY_MEDIUM.get(ctx.medium, 0.0)
achieved_speed = _solve_achievable_speed_mps(power_density_value, floor_total, ctx.k_med, drag_coeff)
effective_k_med = (
(ctx.k_med + drag_coeff * achieved_speed ** 2 / floor_total)
if ctx.k_med is not None and floor_total > 0 else ctx.k_med
)
if "speed" in bounds_by_name:
out["speed"] = achieved_speed
if "range_fuel" in bounds_by_name:
if ctx.storage_energy_form in AMBIENT_ENERGY_FORMS or ctx.k_med is None:
mb = bounds_by_name.get("range_fuel")
out["range_fuel"] = mb.norm_max if mb else 0.0
elif floor_total > 0:
out["range_fuel"] = min(
(ctx.e_dens * storage_mass) / (effective_k_med * floor_total), 1e13
)
top_speed = _solve_achievable_speed_mps(power_density_value, floor_total, ctx.k_med, drag_coeff)
# Hardware cost incl. lifetime maintenance (each entity's own
# maintenance_multiple of its build cost), amortized over the
# platform's declared service_life -- speed-independent.
amortized_per_m = 0.0
if "cost_efficiency" in bounds_by_name:
structural_cost = p_mass * STRUCTURAL_COST_PER_KG_BY_MEDIUM.get(
ctx.medium, STRUCTURAL_COST_PER_KG_BY_MEDIUM["ground"]
m_p, m_a, m_s = ctx.maintenance
upfront_cost = (
(1.0 + m_p) * (p_mass * STRUCTURAL_COST_PER_KG_BY_MEDIUM.get(
ctx.medium, STRUCTURAL_COST_PER_KG_BY_MEDIUM["ground"]))
+ (1.0 + m_a) * (actuator_mass * HARDWARE_COST_PER_KG_BY_ENERGY_FORM.get(
ctx.actuator_energy_form, 50.0))
+ (1.0 + m_s) * (storage_mass * HARDWARE_COST_PER_KG_BY_ENERGY_FORM.get(
ctx.storage_energy_form, 50.0))
)
actuator_hw_cost = actuator_mass * HARDWARE_COST_PER_KG_BY_ENERGY_FORM.get(
ctx.actuator_energy_form, 50.0
)
storage_hw_cost = storage_mass * HARDWARE_COST_PER_KG_BY_ENERGY_FORM.get(
ctx.storage_energy_form, 50.0
)
upfront_cost = structural_cost + actuator_hw_cost + storage_hw_cost
lifetime_m = LIFETIME_DISTANCE_M_BY_MEDIUM.get(
lifetime_m = ctx.service_life or LIFETIME_DISTANCE_M_BY_MEDIUM.get(
ctx.medium, LIFETIME_DISTANCE_M_BY_MEDIUM["ground"]
)
amortized_per_m = upfront_cost / lifetime_m
if ctx.k_med is not None:
fuel_price_per_mj = FUEL_PRICE_PER_MJ.get(ctx.storage_energy_form, 0.04)
energy_per_m_mj = (effective_k_med * floor_total) / 1e6
operating_per_m = energy_per_m_mj * fuel_price_per_mj
else:
# No resistance model for this medium (space -- real range
# is governed by the rocket equation, not implemented
# here, see the comment above
# SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M). Don't fabricate
# an operating cost from ground physics the way an earlier
# version of this did (`effective_k_med or ...["ground"]`)
# -- report upfront/amortized cost only, an honest partial
# answer, rather than a wrong number for an unmodeled term.
operating_per_m = 0.0
def at_speed(v: float) -> dict[str, float]:
# Energy actually spent per meter depends on the speed the build
# is actually driven at, drag included.
effective_k_med = (
(ctx.k_med + drag_coeff * v ** 2 / floor_total)
if ctx.k_med is not None and floor_total > 0 else ctx.k_med
)
m: dict[str, float] = {}
if "speed" in bounds_by_name:
m["speed"] = v
if "range_fuel" in bounds_by_name:
if ctx.storage_energy_form in AMBIENT_ENERGY_FORMS or ctx.k_med is None:
m["range_fuel"] = bounds_by_name["range_fuel"].norm_max
elif floor_total > 0:
m["range_fuel"] = min(
(ctx.e_dens * storage_mass) / (effective_k_med * floor_total), 1e13
)
if "cost_efficiency" in bounds_by_name:
if ctx.k_med is not None:
fuel_price_per_mj = FUEL_PRICE_PER_MJ.get(ctx.storage_energy_form, 0.04)
operating_per_m = (effective_k_med * floor_total) / 1e6 * fuel_price_per_mj
else:
# No resistance model for this medium (space -- real
# range is governed by the rocket equation, not
# implemented here, see the comment above
# SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M). Report
# amortized cost only, an honest partial answer, rather
# than a wrong number for an unmodeled term.
operating_per_m = 0.0
cost_per_m = amortized_per_m + operating_per_m
if units_by_name.get("cost_efficiency") == "$/(kg·m)":
m["cost_efficiency"] = cost_per_m / max(cargo_capacity, 1.0)
else:
m["cost_efficiency"] = cost_per_m
return m
cost_per_m = amortized_per_m + operating_per_m
if units_by_name.get("cost_efficiency") == "$/(kg·m)":
# Divide by whichever cargo convention this domain actually
# scores, so cost-per-cargo-kg and the cargo_capacity number
# shown alongside it always agree; default to the heavy-
# vehicle ratio if a domain scores $/(kg·m) without scoring
# either cargo metric explicitly (matches prior behavior).
cargo_basis = out.get("cargo_capacity_kg", out.get("cargo_capacity", cargo_capacity_2_5x))
out["cost_efficiency"] = cost_per_m / max(cargo_basis, 1.0)
else:
out["cost_efficiency"] = cost_per_m
# Cruise speed is a decision, not the top speed: anywhere from the
# domain's own speed floor (its norm_min -- slower is worthless to
# it) up to what this build can reach. Driving slower buys range
# and cost, so pick the speed that scores best for this domain.
speed_bound = bounds_by_name.get("speed")
v_lo = speed_bound.norm_min if speed_bound else top_speed
if ctx.k_med is None or not v_lo or v_lo <= 0 or top_speed <= v_lo:
return {**out, **at_speed(top_speed)}
return out
# Only speed/range/cost move with v; every other metric is a constant
# factor of the geometric mean, so leaving it out keeps the argmax.
# Compared in log space (sum w*log n): same argmax as the geometric
# mean, without score_raw's per-call dict/list overhead -- this runs
# ~10x per objective call.
speed_bounds = [mb for mb in bounds_by_name.values()
if mb.metric_name in ("speed", "range_fuel", "cost_efficiency")]
def score_at(v: float) -> float:
m = at_speed(v)
total = 0.0
for mb in speed_bounds:
n = normalize(m[mb.metric_name], mb.norm_min, mb.norm_max)
if mb.lower_is_better:
n = 1.0 - n
if n <= 0.0:
return -math.inf
total += mb.weight * math.log(n)
return total
# Golden-section search over log(v) -- score is unimodal in v (speed
# rises, cost/range fall, all monotonic), top speed checked explicitly
# since it's the common optimum when speed is heavily weighted.
# cruise_iters=10 is ~1% of the log span; _decide_masses's coarse
# platform scan passes fewer, it only needs a relative ranking.
lo, hi = math.log(v_lo), math.log(top_speed)
g = (math.sqrt(5) - 1) / 2
x1, x2 = hi - g * (hi - lo), lo + g * (hi - lo)
f1, f2 = score_at(math.exp(x1)), score_at(math.exp(x2))
for _ in range(cruise_iters):
if f1 < f2:
lo, x1, f1 = x1, x2, f2
x2 = lo + g * (hi - lo)
f2 = score_at(math.exp(x2))
else:
hi, x2, f2 = x2, x1, f1
x1 = hi - g * (hi - lo)
f1 = score_at(math.exp(x1))
best_v = math.exp(x1 if f1 >= f2 else x2)
if score_at(top_speed) >= max(f1, f2):
best_v = top_speed
return {**out, **at_speed(best_v)}
def _decide_masses(
self,
@@ -1064,7 +1112,7 @@ class Pipeline:
or bigger operators, or a bigger sail, not a fixed constant. That
floor also
sets the smallest platform mass that could structurally carry it
(CARGO_KG_PER_STRUCTURAL_KG again, applied to the platform
(the platform's payload_ratio again, applied to the platform
carrying its own actuator+storage instead of cargo) -- below that,
no actuator/storage choice is physically possible. Above that
lower bound, platform mass is a real THIRD search variable, not
@@ -1100,26 +1148,46 @@ class Pipeline:
specific_thrust = dep_value(ctx.actuator, "specific_thrust", "provides")
target_velocity = dep_value(ctx.platform, "target_velocity", "provides")
range_bounds = bounds_by_name.get("range_fuel")
target_range = range_bounds.norm_max if range_bounds else None
# A domain-declared trip_range is a hard mission requirement; without
# one, storage is sized toward the domain's own "good" range ceiling.
target_range = ctx.trip_range if ctx.trip_range is not None else (
range_bounds.norm_max if range_bounds else None
)
payload_start = _carried_payload(ctx, BIOLOGICAL_OPERATOR_MASS_KG.get(ctx.actuator_energy_form, 0.0))
# With a declared payload the platform no longer needs p_rep's
# "typical member of the class" guess -- the payload itself sizes it.
p_start = ctx.p_min if ctx.payload else ctx.p_rep
# `is not None`, not truthy -- dep_value() legitimately returns 0.0
# for a declared floor of zero (Spaceship declares
# min_effective_accel=0, a real "no acceleration floor" value, not
# "undeclared"). A truthy check would silently treat that the same
# as an absent requirement and fall through to the wrong branch.
# Actuator requirements as (capability C, requirement R) pairs: the
# actuator must be at least R/(C-R) of the rest of the gross mass.
# range_min floors on the platform are HARD (a rotorcraft that can't
# hover isn't a rotorcraft): enforced at every candidate build below,
# and an actuator that can never meet one (C <= R) is infeasible.
# target_velocity is a design target -- it only seeds the floor.
# `is not None`, not truthy -- Spaceship declares
# min_effective_accel=0, a real "no acceleration floor" value.
hard = []
if min_accel is not None and specific_thrust is not None:
c1, r1 = specific_thrust, min_accel
elif target_velocity and ctx.k_med:
hard.append((specific_thrust, min_accel))
if ctx.min_specific_power is not None:
hard.append((ctx.k_act, ctx.min_specific_power))
soft = []
if target_velocity and ctx.k_med:
# Resistance alone (k_med) only covers steady-state cruise --
# a real vehicle also needs reserve force for acceleration
# events (merging, passing, hills), not just holding speed.
# F=ma: an acceleration reserve in m/s^2 is dimensionally a
# specific force (N/kg) exactly like k_med (J/(kg*m) = N/kg),
# so it adds directly before converting to specific power
# (P/mass = force/mass * v).
c1, r1 = ctx.k_act, (ctx.k_med + ACCELERATION_RESERVE_M_S2) * target_velocity
else:
c1 = r1 = 0.0 # no performance requirement available -- degenerates below
# events (merging, passing, hills). F=ma: an acceleration
# reserve in m/s^2 is a specific force (N/kg) exactly like
# k_med (J/(kg*m) = N/kg), so it adds directly before
# converting to specific power (P/mass = force/mass * v).
soft.append((ctx.k_act, (ctx.k_med + ACCELERATION_RESERVE_M_S2) * target_velocity))
if any(c <= r for c, r in hard):
return max(ctx.a_min, 10.0), ctx.s_min, max(ctx.p_min, p_start), False
# Binding requirement = the largest actuator mass fraction R/C.
c1, r1 = max(
hard + [cr for cr in soft if cr[0] > cr[1]],
key=lambda cr: cr[1] / cr[0], default=(0.0, 0.0),
)
c_hard, r_hard = max(hard, key=lambda cr: cr[1] / cr[0], default=(0.0, 0.0))
if target_range and ctx.k_med:
c2, r2 = ctx.e_dens, target_range * ctx.k_med
@@ -1128,7 +1196,7 @@ class Pipeline:
if c1 and c2:
required_actuator, required_storage = _solve_two_requirement_masses(
ctx.p_rep, c1, r1, c2, r2, ctx.a_min, ctx.s_min
p_start + payload_start, c1, r1, c2, r2, ctx.a_min, ctx.s_min
)
else:
# No performance requirement available at all (e.g. a
@@ -1160,20 +1228,21 @@ class Pipeline:
a_floor = max(ctx.a_min, required_actuator)
s_floor = max(ctx.s_min, required_storage)
structural_floor = a_floor + s_floor # min mass the platform must carry
payload_floor = _carried_payload(ctx, a_floor)
structural_floor = a_floor + s_floor + payload_floor # min mass the platform must carry
ratio = ctx.payload_ratio
# Platform mass is NOT just the required-floor minimum: because
# actuator+storage are capped at platform_mass * CARGO_KG_PER_STRUCTURAL_KG
# everything carried is capped at platform_mass * payload_ratio
# (see insufficient_structure), a bigger platform also buys room for
# a bigger, higher-scoring actuator/storage build -- so platform
# mass has to be searched jointly with them, not fixed. The lower
# bound still can't go below what's needed to carry the required
# floor at all (that's a physical requirement, not a scoring
# choice); p_rep is used only as the starting point for that
# search, not the answer.
p_lo = max(ctx.p_min, ctx.p_rep, structural_floor / CARGO_KG_PER_STRUCTURAL_KG)
# choice).
p_lo = max(ctx.p_min, p_start, structural_floor / ratio)
p_lo = min(p_lo, ctx.p_max)
if p_lo * CARGO_KG_PER_STRUCTURAL_KG < structural_floor or ctx.p_max - p_lo < structural_floor:
if p_lo * ratio < structural_floor or ctx.p_max - p_lo < structural_floor:
# Even the smallest viable platform can't carry the required
# floor within the mass ceiling -- genuinely infeasible
# allocation, not a search problem. Best-effort fallback masses
@@ -1184,21 +1253,37 @@ class Pipeline:
# something else has to catch that).
return a_floor, s_floor, p_lo, False
def objective(platform_mass: float, actuator_mass: float, storage_mass: float) -> float:
def hard_actuator(p: float, a: float, s: float) -> float:
# Re-enforce the hard floor at THIS build's gross mass, not just
# the seed's: growing platform or storage raises what the
# actuator has to lift. One pass suffices -- a bigger actuator
# only ever shrinks the payload still to carry.
if not c_hard:
return a
return max(a, r_hard * (p + s + _carried_payload(ctx, a)) / (c_hard - r_hard))
def objective(platform_mass: float, actuator_mass: float, storage_mass: float, cruise_iters: int = 10) -> float:
actuator_mass = hard_actuator(platform_mass, actuator_mass, storage_mass)
carried = actuator_mass + storage_mass + _carried_payload(ctx, actuator_mass)
if carried > min(ctx.p_max - platform_mass, platform_mass * ratio):
return -1.0
raw = self._raw_physics_from_masses(
ctx, actuator_mass, storage_mass,
bounds_by_name, units_by_name,
platform_mass=platform_mass,
platform_mass=platform_mass, cruise_iters=cruise_iters,
)
if ctx.trip_range is not None and raw.get("range_fuel", ctx.trip_range) < ctx.trip_range:
return -1.0
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)
if budget < structural_floor:
def best_at_platform(p: float, grid: int, rounds: int, cruise_iters: int = 10) -> tuple[float, float, float]:
budget = min(ctx.p_max - p, p * ratio) - payload_floor
if budget < a_floor + s_floor:
return a_floor, s_floor, -1.0
return self._search_best_allocation(
a_floor, s_floor, budget, lambda a, s: objective(p, a, s), grid=grid, rounds=rounds,
a, s_, sc = self._search_best_allocation(
a_floor, s_floor, budget, lambda a, s: objective(p, a, s, cruise_iters), grid=grid, rounds=rounds,
)
return hard_actuator(p, a, s_), s_, sc
# Outer coarse-to-fine search over platform mass. A cheap/low-res
# inner (a, s) search keeps every round affordable -- a low-res
@@ -1216,7 +1301,7 @@ class Pipeline:
p = win_lo + (win_hi - win_lo) * i / grid
if p < p_floor or p > ctx.p_max:
continue
_a, _s, sc = best_at_platform(p, grid=6, rounds=3)
_a, _s, sc = best_at_platform(p, grid=6, rounds=3, cruise_iters=2)
if sc > best_score:
best_score, best_p = sc, p
span = max((win_hi - win_lo) / grid * 2, 1e-6)
@@ -1238,8 +1323,9 @@ class Pipeline:
if sc > best_score:
best_score, best_p = sc, p
actuator_mass, storage_mass, _score = best_at_platform(best_p, grid=12, rounds=6)
return actuator_mass, storage_mass, best_p, True
actuator_mass, storage_mass, final_score = best_at_platform(best_p, grid=12, rounds=6)
# -1 = every candidate broke a hard requirement (hover, trip range).
return actuator_mass, storage_mass, best_p, max(best_score, final_score) >= 0.0
@staticmethod
def _search_best_allocation(
@@ -1353,7 +1439,7 @@ class Pipeline:
# ── platform/actuator/storage-specific extraction, for
# power_density / range_fuel / cost_efficiency / cargo_capacity
# only ─────────────────────────────────────────────────────────
ctx = self._physics_context(combo, bounds_by_name)
ctx = self._physics_context(combo, bounds_by_name, domain.requirements)
feasible = True
if ctx is not None:
actuator_mass, storage_mass, platform_mass, feasible = self._decide_masses(
@@ -1574,7 +1660,7 @@ class Pipeline:
"""
bounds_by_name = {mb.metric_name: mb for mb in domain.metric_bounds}
units_by_name = {mb.metric_name: mb.unit for mb in domain.metric_bounds}
ctx = self._physics_context(combo, bounds_by_name)
ctx = self._physics_context(combo, bounds_by_name, domain.requirements)
if ctx is None or ctx.p_max is None:
return None
@@ -1603,7 +1689,7 @@ class Pipeline:
actuator_slider_max = max(a_mass, ctx.p_max - ctx.p_min - ctx.s_min)
storage_slider_max = max(s_mass, ctx.p_max - ctx.p_min - ctx.a_min)
total_mass = p_mass + a_mass + s_mass
total_mass = p_mass + a_mass + s_mass + _carried_payload(ctx, a_mass)
return {
"platform_mass": p_mass, "platform_min": ctx.p_min, "platform_max": ctx.p_max,
"actuator_mass": a_mass, "actuator_min": ctx.a_min, "actuator_slider_max": actuator_slider_max,
@@ -1617,12 +1703,10 @@ class Pipeline:
"exceeds_platform_envelope": total_mass > ctx.p_max,
# None of power_density/range_fuel/cost_efficiency penalize a
# platform mass that's too small to structurally carry its own
# actuator+storage -- they only see the total. Reuse the same
# structure-supports-N-times-its-own-mass ratio already used for
# cargo_capacity_kg (CARGO_KG_PER_STRUCTURAL_KG) rather than a
# one-off constant: a platform can't carry more actuator+storage
# mass than that, any more than it could carry that much cargo.
"insufficient_structure": (a_mass + s_mass) > p_mass * CARGO_KG_PER_STRUCTURAL_KG,
# actuator+storage+payload -- they only see the total. Same
# payload_ratio cargo_capacity uses: a platform can't carry more
# than that, any more than it could carry that much cargo.
"insufficient_structure": total_mass - p_mass > p_mass * ctx.payload_ratio,
"raw_metrics": raw,
"normalized_scores": normalized,
"composite_score": composite,

View File

@@ -14,7 +14,11 @@ def normalize(raw_value: float, norm_min: float, norm_max: float) -> float:
Values at or below norm_min -> 0.0
Values at or above norm_max -> 1.0
Values between are log-interpolated.
Values between are interpolated on log(raw / norm_min), i.e. every
range is mapped onto [1, norm_max / norm_min] first, so the curve's
shape depends only on the range's ratio, not its absolute magnitude
(log1p flattened ranges well below 1 into near-linear). A range with
no positive floor has no ratio -- linear there.
"""
if norm_max <= norm_min:
return 0.0
@@ -22,10 +26,9 @@ def normalize(raw_value: float, norm_min: float, norm_max: float) -> float:
return 0.0
if raw_value >= norm_max:
return 1.0
log_min = math.log1p(norm_min)
log_max = math.log1p(norm_max)
log_val = math.log1p(raw_value)
return (log_val - log_min) / (log_max - log_min)
if norm_min <= 0.0:
return (raw_value - norm_min) / (norm_max - norm_min)
return math.log(raw_value / norm_min) / math.log(norm_max / norm_min)
def composite_score(scores: list[float], weights: list[float]) -> float:

View File

@@ -62,4 +62,8 @@ class Domain:
constraints: list[DomainConstraint] = field(default_factory=list)
free_variables: list[FreeVariable] = field(default_factory=list)
metric_formulas: list[MetricFormula] = field(default_factory=list)
# Mission requirements every build must meet, not scored (e.g.
# {"payload": 100.0 kg, "trip_range": 50000.0 m}) -- see
# Pipeline._decide_masses.
requirements: dict[str, float] = field(default_factory=dict)
id: int | None = None

View File

@@ -22,6 +22,9 @@ GROUND_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "0.5", "m²", "range_min"),
Dependency("physical", "mass", "36000", "kg", "range_max"),
Dependency("physical", "mass", "50", "kg", "range_min"),
Dependency("physical", "payload_ratio", "1.0", "kg/kg", "provides"),
Dependency("physical", "service_life", "2e8", "m", "provides"),
Dependency("physical", "maintenance_multiple", "1.0", "x", "provides"),
Dependency("infrastructure", "road_network", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "25", "m/s", "provides"),
@@ -38,8 +41,11 @@ GROUND_PLATFORMS: list[Entity] = [
Dependency("environment", "gravity", "true", None, "provides"),
Dependency("physical", "footprint", "3", "m²", "range_max"),
Dependency("physical", "footprint", "0.3", "m²", "range_min"),
Dependency("physical", "mass", "60", "kg", "range_max"),
Dependency("physical", "mass", "150", "kg", "range_max"), # gross, rider included
Dependency("physical", "mass", "5", "kg", "range_min"),
Dependency("physical", "payload_ratio", "8", "kg/kg", "provides"),
Dependency("physical", "service_life", "3e7", "m", "provides"),
Dependency("physical", "maintenance_multiple", "1.0", "x", "provides"),
Dependency("infrastructure", "road_network", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "6", "m/s", "provides"),
@@ -58,6 +64,9 @@ GROUND_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "20", "m²", "range_min"),
Dependency("physical", "mass", "40000", "kg", "range_max"),
Dependency("physical", "mass", "10000", "kg", "range_min"),
Dependency("physical", "payload_ratio", "1.0", "kg/kg", "provides"),
Dependency("physical", "service_life", "5e9", "m", "provides"),
Dependency("physical", "maintenance_multiple", "1.5", "x", "provides"),
Dependency("infrastructure", "rail_network", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "30", "m/s", "provides"),
@@ -81,6 +90,7 @@ WATER_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "2", "m²", "range_min"),
Dependency("physical", "mass", "100000", "kg", "range_max"),
Dependency("physical", "mass", "30", "kg", "range_min"),
Dependency("physical", "payload_ratio", "2.5", "kg/kg", "provides"),
Dependency("environment", "medium", "water", None, "requires"),
Dependency("physical", "target_velocity", "8", "m/s", "provides"),
],
@@ -97,6 +107,7 @@ WATER_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "20", "m²", "range_min"),
Dependency("physical", "mass", "20000000", "kg", "range_max"),
Dependency("physical", "mass", "10000", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.3", "kg/kg", "provides"),
Dependency("environment", "medium", "water", None, "requires"),
Dependency("physical", "energy_density", "720000", "J/kg", "range_min"),
Dependency("physical", "target_velocity", "8", "m/s", "provides"),
@@ -120,6 +131,9 @@ AIR_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "10", "m²", "range_min"),
Dependency("physical", "mass", "100000", "kg", "range_max"),
Dependency("physical", "mass", "500", "kg", "range_min"),
Dependency("physical", "payload_ratio", "1.2", "kg/kg", "provides"),
Dependency("physical", "service_life", "4.3e9", "m", "provides"),
Dependency("physical", "maintenance_multiple", "4", "x", "provides"),
Dependency("infrastructure", "runway", "true", None, "requires"),
Dependency("environment", "medium", "air", None, "requires"),
Dependency("physical", "energy_density", "1440000", "J/kg", "range_min"),
@@ -139,6 +153,12 @@ AIR_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "0.5", "m²", "range_min"),
Dependency("physical", "mass", "5000", "kg", "range_max"),
Dependency("physical", "mass", "1", "kg", "range_min"),
Dependency("physical", "payload_ratio", "1.0", "kg/kg", "provides"),
Dependency("physical", "service_life", "3.6e9", "m", "provides"),
Dependency("physical", "maintenance_multiple", "8", "x", "provides"),
# Ideal hover power sqrt(disk_loading * g^3 / (2 * rho)) / figure_of_merit:
# ~25 kg/m^2 disk loading, FM 0.7 -> ~140 W per kg of gross mass, sustained.
Dependency("physical", "min_specific_power", "140", "W/kg", "range_min"),
Dependency("environment", "medium", "air", None, "requires"),
Dependency("physical", "energy_density", "720000", "J/kg", "range_min"),
Dependency("physical", "min_effective_accel", "10", "m/s²", "range_min"),
@@ -157,6 +177,9 @@ AIR_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "50", "m²", "range_min"),
Dependency("physical", "mass", "20000", "kg", "range_max"),
Dependency("physical", "mass", "200", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.5", "kg/kg", "provides"),
Dependency("physical", "service_life", "1.4e9", "m", "provides"),
Dependency("physical", "maintenance_multiple", "5", "x", "provides"),
Dependency("environment", "medium", "air", None, "requires"),
],
),
@@ -175,6 +198,7 @@ SPACE_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "500", "m²", "range_max"),
Dependency("physical", "footprint", "10", "m²", "range_min"),
Dependency("physical", "mass", "5000", "kg", "range_min"),
Dependency("physical", "payload_ratio", "1.0", "kg/kg", "provides"),
Dependency("infrastructure", "launch_facility", "true", None, "requires"),
Dependency("environment", "medium", "space", None, "requires"),
Dependency("physical", "energy_density", "7200000", "J/kg", "range_min"),
@@ -199,6 +223,7 @@ MULTI_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "5", "m²", "range_min"),
Dependency("physical", "mass", "10000", "kg", "range_max"),
Dependency("physical", "mass", "1500", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.8", "kg/kg", "provides"),
# No requires here previously -- vacuously satisfied every
# domain's medium DomainConstraint (check_domain_constraints
# only flags a violation when an entity DECLARES a requires
@@ -234,6 +259,7 @@ FICTIONAL_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "5", "m²", "range_min"),
Dependency("physical", "mass", "20000", "kg", "range_max"),
Dependency("physical", "mass", "5000", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.6", "kg/kg", "provides"),
Dependency("infrastructure", "hyperloop_tube", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "270", "m/s", "provides"), # near-sonic, per its own description
@@ -267,6 +293,7 @@ COMBUSTION_ACTUATORS: list[Entity] = [
Dependency("physical", "mass", "45", "kg", "range_min"),
Dependency("force", "thrust_profile", "high_continuous", None, "provides"),
Dependency("force", "power_density", "1000", "W/kg", "provides"),
Dependency("physical", "maintenance_multiple", "1.0", "x", "provides"),
],
),
Entity(
@@ -280,6 +307,7 @@ COMBUSTION_ACTUATORS: list[Entity] = [
Dependency("force", "thrust_profile", "extreme_continuous", None, "provides"),
Dependency("force", "power_density", "5000", "W/kg", "provides"),
Dependency("force", "specific_thrust", "50", "N/kg", "provides"),
Dependency("physical", "maintenance_multiple", "2.0", "x", "provides"),
],
),
Entity(
@@ -309,6 +337,7 @@ ELECTRIC_ACTUATORS: list[Entity] = [
Dependency("physical", "mass", "5", "kg", "range_min"),
Dependency("force", "thrust_profile", "moderate_continuous", None, "provides"),
Dependency("force", "power_density", "2000", "W/kg", "provides"),
Dependency("physical", "maintenance_multiple", "0.2", "x", "provides"),
],
),
]
@@ -370,6 +399,7 @@ RENEWABLE_ACTUATORS: list[Entity] = [
Dependency("physical", "mass", "15", "kg", "range_min"),
Dependency("force", "thrust_profile", "low_continuous", None, "provides"),
Dependency("force", "power_density", "10", "W/kg", "provides"),
Dependency("domain", "prevailing_wind", "true", None, "requires"),
],
),
]
@@ -470,6 +500,7 @@ EXOTIC_ACTUATORS: list[Entity] = [
Dependency("physical", "mass", "0", "kg", "range_min"),
Dependency("force", "thrust_profile", "low_continuous", None, "provides"),
Dependency("force", "power_density", "10", "W/kg", "provides"),
Dependency("domain", "net_descent", "true", None, "requires"),
],
),
]
@@ -560,6 +591,7 @@ ELECTRICAL_STORAGE: list[Entity] = [
Dependency("infrastructure", "fuel_infrastructure", "charging_station", None, "requires"),
Dependency("physical", "mass", "9", "kg", "range_min"),
Dependency("physical", "energy_density", "1080000", "J/kg", "provides"),
Dependency("physical", "maintenance_multiple", "1.0", "x", "provides"),
],
),
Entity(
@@ -756,18 +788,18 @@ URBAN_COMMUTING = Domain(
# this project hasn't done -- not scored anywhere for now rather than
# pretend a quick formula or an equally uninformed LLM guess settles it.
# Weights renormalized to sum to 1.0 across the remaining metrics.
# speed and cargo_capacity_kg added -- a commute's actual travel
# time and whether the vehicle can carry groceries/passengers/gear
# both matter as much as raw power_density did on their own; speed
# is a genuine build OUTPUT (see _raw_physics_from_masses), not a
# platform-declared constant.
MetricBound("power_density", weight=0.25, norm_min=1, norm_max=2000, unit="W/kg"),
MetricBound("cost_efficiency", weight=0.25, norm_min=1e-5, norm_max=2e-3, unit="$/m", lower_is_better=True),
MetricBound("speed", weight=0.25, norm_min=2, norm_max=30, unit="m/s"),
MetricBound("range_fuel", weight=0.10, norm_min=5000, norm_max=500000, unit="m"),
MetricBound("cargo_capacity_kg", weight=0.15, norm_min=1, norm_max=500, unit="kg"),
# power_density dropped: it's an input to speed (and to whether a
# build meets its platform's own hover/accel floors), not an outcome
# a commuter values -- scoring it too rewarded overpowered builds
# twice. Cargo is a mission requirement (one commuter, ~100kg with
# gear), not a more-is-better score: every build must carry it, and
# speed/cost/range are all computed with it on board.
MetricBound("cost_efficiency", weight=0.417, norm_min=1e-5, norm_max=2e-3, unit="$/m", lower_is_better=True),
MetricBound("speed", weight=0.417, norm_min=2, norm_max=30, unit="m/s"),
MetricBound("range_fuel", weight=0.166, norm_min=50000, norm_max=500000, unit="m"),
],
constraints=[DomainConstraint("medium", ["ground", "air"])],
requirements={"payload": 100.0, "trip_range": 50000.0},
)
INTERPLANETARY = Domain(

View File

@@ -78,6 +78,7 @@ def export_snapshot(repo: Repository) -> dict:
"description": d.description,
"metric_bounds": mbs,
"constraints": dcs,
"requirements": d.requirements,
"free_variables": fvs,
"metric_formulas": mfs,
})
@@ -219,6 +220,7 @@ def import_snapshot(repo: Repository, data: dict, *, clear: bool = False) -> dic
description=d_data.get("description", ""),
metric_bounds=mbs,
constraints=dcs,
requirements=d_data.get("requirements", {}),
free_variables=fvs,
metric_formulas=mfs,
)