Compare commits

...

3 Commits

Author SHA1 Message Date
60c36e5d27 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>
2026-09-25 23:12:36 -05:00
af401d6bc2 dev server uses admin login too: localhost shows the public view
Drop open_access; run() prints a one-off PHYSCOM_ADMIN_TOKEN when none is set.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-25 17:27:55 -05:00
8171fc023e public-release phases 1-3: read-only public mode, gunicorn container, demo bootstrap, CI, README
- before_request guard: visitors browse + explore; writes need PHYSCOM_ADMIN_TOKEN login
- SameSite=Lax/HttpOnly cookies, persisted secret key, debug off unless FLASK_DEBUG=1
- non-root gunicorn container with healthcheck; physcom demo --if-empty on first start
- landing page Top Concepts, write controls hidden from visitors
- CI workflow, pyproject metadata, compose Ollama parity, README rewrite
- tests/test_web_access.py: access control + GET smoke test of every page

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-25 15:40:02 -05:00
35 changed files with 929 additions and 289 deletions

View File

@@ -1,15 +0,0 @@
{
"permissions": {
"allow": [
"Bash(git *)",
"Bash(pip install *)",
"Bash(python -m pytest *)",
"Bash(python -m physcom *)",
"Bash(python -m physcom_web *)",
"Bash(python -c *)",
"WebFetch(domain:127.0.0.1)",
"WebFetch(domain:localhost)",
"Bash(curl:*)"
]
}
}

View File

@@ -8,3 +8,5 @@ data/
.claude/ .claude/
.venv/ .venv/
*.md *.md
!README.md
.env

View File

@@ -1,6 +1,13 @@
# Copy to .env — FLASK_SECRET_KEY is auto-generated on first run if omitted. # Copy to .env — FLASK_SECRET_KEY is auto-generated (and saved next to the DB) if omitted.
FLASK_SECRET_KEY= FLASK_SECRET_KEY=
# Web visitors are read-only unless logged in at /login with this token.
# Leave blank for a fully read-only public site. `python -m physcom_web`
# (the localhost dev server) is open when this is blank.
PHYSCOM_ADMIN_TOKEN=
# Set to 1 when served over HTTPS so the session cookie is Secure-only.
PHYSCOM_SECURE_COOKIES=0
# LLM provider for the optional pass 4 review (leave blank to skip it) # LLM provider for the optional pass 4 review (leave blank to skip it)
# Supported: gemini, ollama # Supported: gemini, ollama
LLM_PROVIDER= LLM_PROVIDER=

19
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: tests
on:
push:
pull_request:
jobs:
pytest:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: pip install -e ".[dev,web]"
- run: python -m pytest tests/ -q

3
.gitignore vendored
View File

@@ -178,3 +178,6 @@ cython_debug/
data/ data/
.aider* .aider*
# Local Claude Code settings
.claude/settings.local.json

View File

@@ -12,10 +12,10 @@ PhysCom (Physical Combinatorics) — innovation discovery engine that generates
- **Tests (all)**: `python -m pytest tests/ -q` (~130 tests, ~2 min). Run after every change. - **Tests (all)**: `python -m pytest tests/ -q` (~130 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` (localhost, public read-only view; log in at `/login` with `PHYSCOM_ADMIN_TOKEN` or the one-off token it prints; debug only with `FLASK_DEBUG=1`)
- **CLI**: `python -m physcom` (or `physcom` if installed) - **CLI**: `python -m physcom` (or `physcom` if installed)
- **Docker**: `docker compose up web` / `docker compose run cli physcom seed` - **Docker**: `docker compose up web` / `docker compose run cli physcom seed`
- **Seed data**: loaded automatically on first DB init (SQLite, `physcom.db` or `$PHYSCOM_DB`) - **Demo data**: `python -m physcom demo` seeds + runs passes 1-3 for every domain (~20s). The Docker image does this on first start (`--if-empty`). DB is `data/physcom.db` or `$PHYSCOM_DB`.
## Architecture ## Architecture
@@ -35,7 +35,7 @@ src/physcom/ # Core library (no web dependency)
seed/transport_example.py # 11 platforms × 15 actuators × 18 energy storages, 5 domains seed/transport_example.py # 11 platforms × 15 actuators × 18 energy storages, 5 domains
src/physcom_web/ # Flask web UI src/physcom_web/ # Flask web UI
app.py # App factory, get_repo(), DB path resolution app.py # App factory, get_repo(), DB path, read-only public mode + /login
routes/pipeline.py # Background thread pipeline execution, HTMX status/cancel endpoints routes/pipeline.py # Background thread pipeline execution, HTMX status/cancel endpoints
routes/results.py # Results browse, detail view, human review submission routes/results.py # Results browse, detail view, human review submission
routes/entities.py # Entity CRUD routes/entities.py # Entity CRUD
@@ -58,6 +58,7 @@ tests/ # pytest, uses seeded_repo fixture from conftest.py
- **`save_combination`** loads existing status/block_reason on dedup (important for resume). - **`save_combination`** loads existing status/block_reason on dedup (important for resume).
- **`ensure_metric`** backfills unit if the row already exists with an empty unit. - **`ensure_metric`** backfills unit if the row already exists with an empty unit.
- **MetricBound** carries `unit` — flows through seed → ensure_metric → metrics table → get_combination_scores → template display. - **MetricBound** carries `unit` — flows through seed → ensure_metric → metrics table → get_combination_scores → template display.
- **Read-only public mode**: `create_app()` locks every non-GET (except `results.explore`) and the admin/pipeline/new pages behind a session login with `PHYSCOM_ADMIN_TOKEN`. The dev server uses the same rules (it prints a one-off token if none is set). Templates use `is_admin()`; `body.readonly` hides every `form[method=post]` via CSS — a new write form needs no template guard, but a new public POST must be added to `PUBLIC_POST_ENDPOINTS`.
- **HTMX polling**: `_run_status.html` partial polls every 2s while run is pending/running; stops polling when terminal. - **HTMX polling**: `_run_status.html` partial polls every 2s while run is pending/running; stops polling when terminal.
## Data flow (pipeline passes) ## Data flow (pipeline passes)

View File

@@ -2,14 +2,22 @@ FROM python:3.13-slim AS base
WORKDIR /app WORKDIR /app
COPY pyproject.toml . COPY pyproject.toml README.md ./
COPY src/ src/ COPY src/ src/
RUN pip install --no-cache-dir ".[web,gemini]" RUN pip install --no-cache-dir ".[web,gemini]" \
&& useradd --create-home --uid 1000 physcom \
&& mkdir -p /app/data && chown physcom:physcom /app/data
USER physcom
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"] HEALTHCHECK --interval=30s --timeout=5s --start-period=60s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/', timeout=4)"
# First start on an empty volume builds the demo data (~20s: seed + passes
# 1-3 for every domain). One gunicorn worker: pipeline runs are background
# threads inside the web process.
CMD ["sh", "-c", "physcom demo --if-empty && exec gunicorn --workers 1 --threads 8 --timeout 120 --bind 0.0.0.0:5000 'physcom_web.app:create_app()'"]

View File

@@ -55,6 +55,25 @@ Skipped until something forces them:
--- ---
## Suggested order ## Progress (2026-09-25)
1.1 → 1.5 → 1.2 → 1.3 → 1.4 → 1.6 → 1.7 → 1.8 → 2.3 → 2.1 → 2.4 → 2.5 → 2.6 → 3.1 → 3.3 → 2.2 (screenshots need the final UI) → 3.4 → 3.2. | Item | Status |
|------|--------|
| 1.1 gunicorn, debug off | Done. Dev server debug only with `FLASK_DEBUG=1`. |
| 1.2 read-only public mode | Done. Deviation: an unset token means *nobody* can write under gunicorn, instead of "localhost can write", because behind a reverse proxy every request looks like localhost. The dev server uses the same login; without a token it prints a one-off one. |
| 1.3 cookie hardening | Done. `Secure` is opt-in via `PHYSCOM_SECURE_COOKIES=1` so plain-HTTP local Docker can still log in. |
| 1.4 explore | Done. Verified it never writes; it costs about 45 ms per call (measured over 168 combos). Non-finite inputs are now rejected. No app-level rate limit: add one at the proxy if needed. |
| 1.5 secret key | Done differently: instead of refusing to start, an unset key is generated once and saved next to the DB. |
| 1.6 container | Done: non-root, healthcheck. Base image **not** digest-pinned (no Docker available here to resolve one). **Container build is untested**, since Docker isn't installed on this machine. |
| 1.7 untrack local config | Done. Checked the history: no secrets. The repo was already public. |
| 1.8 tests | Done: `tests/test_web_access.py`. |
| 2.1 LICENSE | **Open. Your decision** (and your employer's). |
| 2.2 README | Done, apart from **screenshots**, which need a browser. |
| 2.3 CI | Done: `.github/workflows/test.yml` (Gitea Actions reads it). Unverified until a runner picks it up. |
| 2.4 metadata | Done. `license` is left unset until 2.1. |
| 2.5 compose parity | Done: Ollama vars, admin token, Postgres placeholder removed. |
| 2.6 route smoke tests | Done (in 1.8's file). |
| 3.1 demo data | Done differently: `physcom demo --if-empty` builds it on first start (about 20 s) instead of committing a snapshot that goes stale whenever the physics changes. |
| 3.2 host | **Open. Your call**: the README "Deploying publicly" section covers any host. |
| 3.3 pass-4 reviews | **Open.** Ollama wasn't running here. Run pass 4 locally, then snapshot export → import. |
| 3.4 landing page | Done: "Top Concepts" table, and the Run Pipeline button is hidden from visitors. |

View File

@@ -0,0 +1,32 @@
# Cost per passenger: tabled, not rejected
## Context
`cost_efficiency` in urban_commuting is $ per vehicle-metre. A domain can set a `payload` requirement (one commuter, ~100 kg). Every build must carry that payload, and speed, cost and range are all computed with it on board. Anything the platform can carry beyond that shows up as `cargo_capacity`, but it earns no credit in the score.
As a result, high-capacity platforms lose **by construction**. A 60-passenger tram costs about $2.6/km per vehicle, which is above urban_commuting's 2e-3 $/m ceiling. That cost normalizes to 0, and the geometric mean then zeroes the whole combo. Hyperloop and Rail rank near the bottom for the same reason. This doesn't show that mass transit is physically worse. The metric only charges the vehicle and never credits the people it moves.
The obvious fix is cost per passenger-metre, with passengers = carrying capacity ÷ the domain's payload. That is how buses and rail win in reality.
## Why it isn't done yet
**1. Without a counterweight, the optimizer games it.** An earlier experiment divided cost by payload kg, a unit a domain can already declare. The optimizer built 35 t trucks and road vehicles pushing 23 t of people. Any metric that rewards size will be maximized up to each platform's mass ceiling, so dividing by passengers alone brings back the same failure.
**2. Capacity isn't occupancy.** A vehicle only benefits from its seats when they're filled. Realistic figures are about 1.3 people in a 5-seat car and about 20–40% of a train's capacity. That **load factor** is operational, not intrinsic. It belongs to the service model, such as a private car versus a scheduled line, and not to the physics of the platform. By LOGIC DOCS/002, a platform could declare only an intrinsic category (`private` versus `shared`), and the domain would supply the load factor per category. The domain requirements added for payload and trip_range could hold it, but that adds a second level of data keyed on a category.
**3. Door-to-door speed.** Transit riders walk to the stop, wait, and stop at every station, so their effective speed is well below the vehicle's cruise speed. Without an access or wait penalty, the per-passenger cost win is free, and every platform is pushed to its largest allowed size. Modeling that penalty needs something like a stop spacing or headway per service model, which is another operational parameter.
**4. The factors interact.** Load factor scales down the cost gain, and the access penalty scales down the speed gain. Both have to be present before the ranking means anything. Adding either one alone gives a misleading intermediate ranking.
**5. Infrastructure cost is missing.** The cost model covers only the vehicle: build cost, maintenance, and energy. No platform pays for the track, road, runway or guideway it needs. Rail and hyperloop get dedicated infrastructure for free. So do road vehicles, but roads are shared by far more traffic. Right now a 10 t railcar carrying one commuter costs about $0.13/km, because its structure is cheap per kg and its service life is long (5 million km). The track that makes that possible is never charged. The fix has the same shape as the passenger division: infrastructure cost only makes sense divided across the traffic that uses it. That depends on utilization (vehicles per day on a line), which is an operational parameter, not a physical one. Charging the full infrastructure cost to a single vehicle would bury rail. Charging nothing flatters it. So infrastructure cost is tabled alongside cost per passenger, and they should be designed together.
## Decision
Tabled. The fix is sound, but it adds at least three layers: a service-model category on platforms, a per-domain load factor for each category, and an access-speed penalty. None of them is physical, which is what this project models well, and a simpler way to handle "shared vehicles amortize over riders" may exist.
Until then, read the results with this in mind: urban_commuting currently ranks **private** vehicles fairly against each other. Its scores for rail and hyperloop reflect the missing passenger division, not their physics.
## Revisit when
- A second domain also needs occupancy (freight load factor, shared cargo) and the mechanism can serve both, or
- Someone finds a formulation that avoids the size-gaming exploit without operational parameters. One candidate is scoring cost at a *fixed* domain payload and treating spare capacity as a separate, capped metric.

View File

@@ -1,72 +1,68 @@
# Applied Combinatorics # Physical Combinatorics
### Innovation via Attribute Mixing ### Innovation via Attribute Mixing
This is an experimental repo which uses lists of physical attributes and recombines them to form new objects. These objects are then reviewed for comprehensibility and viability. [![tests](https://git.asimonson.com/andrew/physicalCombinatorics/actions/workflows/test.yml/badge.svg)](https://git.asimonson.com/andrew/physicalCombinatorics/actions)
Example: An experiment that takes lists of real physical attributes, recombines them into every possible object, and then sorts vaguely reasonable concepts from nonsense.
Let's identify some methods of getting from here to there: Let's identify some ways of getting from here to there:
- Car - Car
- Airplane - Airplane
- Train - Train
- Bicycle - Bicycle
- Walking with your legs - Walking with your legs
- Wheelchair
- Scooter
- Spaceship - Spaceship
- Teleportation or beaming technology
To build object 'car' you must select a power source. Power sources include: To build a car you must choose what pushes it and what it runs on:
- Gas/Internal Combustion Engine - Gas engine, electric motor, human pedalling, a solar sail, cannonfire recoil...
- Lithium Ion Batteries - Gasoline, lithium ion batteries, hydrogen, coal, sunlight, gunpowder...
- Hydrogen Combustion Engine
- Human pedalling
- Modular Nuclear Reactor
- Coal/steam locomotion
- the Sun via Solar Sail
- Cannonfire Recoil
- Pushed by a friend
Putting together lists 1 and 2 we can create 81 mostly novel forms of transportation, such as trains powered by solar sails or walking powered by tiny cannon recoil. Obviously some of these concepts are not as viable as others. While being pushed by a friend might work for those in a wheelchair, it is too slow for those in a car. Speed is therefore a target metric. Let's list some target metrics: Multiply those lists together and you get thousands of mostly novel forms of transportation: trains driven by solar sails, walking powered by tiny cannon recoil. Obviously some are more viable than others. Being pushed by a friend might work for a wheelchair, but it's far too slow for a car. So each concept is measured against target metrics (power density, cost, speed, range, cargo), weighted by what matters in a given **domain** (urban commuting cares about cost and speed; interplanetary travel cares about range).
- Speed The shortlist may include concepts that sound bizarre but are technically plausible. Bicycles, motorcycles and e-bikes all had their turn. Why not hydrogen-bikes?
- Cost efficiency
- Availability
- Safety
- Range (by fuel)
- Range (by platform degredation or maintenance)
Using these metrics this experiment intends to sift vaguely reasonable concepts from nonsense. Its shortlist may include concepts that sound bizarre but may be technically plausible. Bicycles, motorcycles, and e-bikes all had their turn. Why not hydrogen-bikes? The seed data is 11 platforms × 15 actuators × 18 energy storages = **2,970 combinations**, scored across 5 domains.
## How it works
Every combination goes through five passes:
1. **Constraints.** Each entity declares only its own physical envelope: what it `requires`, `provides` and `excludes`, plus numeric floors and ceilings on shared quantities like mass and footprint. The resolver cross-checks those generically across every pair. A nuclear reactor is blocked from a bicycle because its mass floor collides with the bicycle's mass ceiling, not because anyone wrote "nuclear + bicycle = no". Most of the combinatorial explosion dies here. ([why](LOGIC%20DOCS/002-guardrails-via-intrinsic-properties.md))
2. **Physics estimation.** A deterministic engine sizes each surviving combination from its entities' declared properties. It optimizes the platform/actuator/storage mass split, solves for drag-limited speed, and derives power density, range, cost and cargo. Domains can also define their own metrics as formulas.
3. **Scoring.** Raw values are log-normalized against each domain's bounds and combined with a weighted geometric mean. The geometric mean is deliberately harsh: one near-zero metric sinks the whole concept, which filters out things that are technically possible but pointless.
4. **LLM review (optional).** Top combinations get a plausibility verdict and a LOW/MEDIUM/HIGH rating from Gemini or a local Ollama model.
5. **Human review.** Annotate or approve results in the web UI.
Design reasoning lives in [`LOGIC DOCS/`](LOGIC%20DOCS/).
## Setup ## Setup
### Docker (recommended) ### Docker (recommended)
```bash ```bash
cp .env.example .env # set PHYSCOM_ADMIN_TOKEN to be able to edit
docker compose up web docker compose up web
``` ```
Then open [http://localhost:5000](http://localhost:5000). Open [http://localhost:5000](http://localhost:5000). On first start with an empty volume, the container seeds the transport example and scores every domain (about 20 seconds). Visitors are read-only; log in at `/login` with `PHYSCOM_ADMIN_TOKEN` to edit entities, run the pipeline or use the admin page.
Seed the database with the transport example: CLI inside the container:
```bash ```bash
docker compose run cli seed transport docker compose run --rm cli results urban_commuting --top 10
``` ```
### Local development ### Local development
```bash ```bash
pip install -e ".[dev,web]" pip install -e ".[dev,web]"
python -m physcom init python -m physcom demo # seed + run passes 1-3 for every domain
python -m physcom seed transport python -m physcom_web # localhost dev server, prints an admin login token
python -m physcom_web
``` ```
Then open [http://localhost:5000](http://localhost:5000). Then open [http://localhost:5000](http://localhost:5000). You see the public read-only view; log in at `/login` with the printed token (or your `PHYSCOM_ADMIN_TOKEN`) to edit. Set `FLASK_DEBUG=1` for the Werkzeug debugger (never on a reachable host).
Run tests: Run tests:
@@ -74,9 +70,9 @@ Run tests:
python -m pytest tests/ -q python -m pytest tests/ -q
``` ```
### LLM integration (optional) ### LLM review (optional)
Pass 2 (physics estimation) is always the deterministic estimator — no LLM. Pass 2 (physics estimation) is always the deterministic estimator, with no LLM involved.
An LLM is only used for the optional pass 4 plausibility review. An LLM is only used for the optional pass 4 plausibility review.
Gemini: Gemini:
@@ -98,15 +94,32 @@ export LLM_PROVIDER=ollama
physcom run urban_commuting --passes 1,2,3,4 physcom run urban_commuting --passes 1,2,3,4
``` ```
Copy `.env.example` to `.env` and fill in your key for persistent configuration. Copy `.env.example` to `.env` to keep these settings.
--- ## Deploying publicly
a few notes: the thin atmosphere and the sun are obvious dependencies to the solar sail power source. Dependencies would include things such as scale of force (nuclear reactor vs pedalling obviously has an important force differential) and geographic requirements (walking requires ground and gravity). The project should include on every entity a list of dependencies. The viability tester will need to pull in all of these dependencies to ensure they do not contradict. The container is built to sit behind a TLS-terminating reverse proxy (Caddy, nginx, or a platform like Fly.io or Railway):
Additionally, metrics are expected to be extremely close to full points or none at all. The speed of a person pushing a car is effectively zero in its domain whereas a rocket powered car would easily reach the limits of speed in the domain. The resulting multiplication between metrics to get the viability score will be heavily logarithmic. This is expected and is intended to be a filter to eliminate technically plausible but completely pointless in practice concepts. - It serves with gunicorn (one worker, eight threads), runs as a non-root user and has a healthcheck.
Metric weights are therefore dependent on domain, which will also need to be defined. - Anonymous visitors can browse every result and use the mass-allocation explorer, and nothing else. Every write needs a login with `PHYSCOM_ADMIN_TOKEN`. If the token is unset, nobody can write.
- Set `PHYSCOM_SECURE_COOKIES=1` once it's served over HTTPS.
- Mount a persistent volume at `/app/data`. SQLite plus a single writer is plenty for a read-mostly demo.
- To publish LLM reviews without exposing an API key: run pass 4 locally against Ollama, export from `/admin` (or `physcom snapshot export`), and import that snapshot on the server.
First pass viability is physics such as force output, possibly generalized by LLM, last passes can include LLM and human review of social factors. Minimal Caddy example:
Attributes themselves are real (quality proven) and are thusly not garbage in the 'garbage in garbage out' risk - that risk is measured in how much nonsense the dimensional explosion generates that makes it past heuristic filters. ```
physcom.example.com {
reverse_proxy localhost:5000
}
```
## Project layout
```
src/physcom/ core engine: models, SQLite repository, constraint resolver,
physics estimator, scorer, pipeline, LLM providers, CLI
src/physcom_web/ Flask + HTMX web UI
tests/ pytest suite
LOGIC DOCS/ design decisions and the reasoning behind them
```

View File

@@ -1,3 +1,12 @@
x-env: &env
PHYSCOM_DB: /app/data/physcom.db
LLM_PROVIDER: ${LLM_PROVIDER:-}
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
GEMINI_MODEL: ${GEMINI_MODEL:-gemini-2.0-flash}
OLLAMA_MODEL: ${OLLAMA_MODEL:-qwen2.5:7b}
# Ollama running on the host machine, not in this container.
OLLAMA_HOST: ${OLLAMA_HOST:-http://host.docker.internal:11434}
services: services:
web: web:
build: . build: .
@@ -6,37 +15,24 @@ services:
volumes: volumes:
- physcom-data:/app/data - physcom-data:/app/data
environment: environment:
- PHYSCOM_DB=/app/data/physcom.db <<: *env
- FLASK_SECRET_KEY=${FLASK_SECRET_KEY:-} FLASK_SECRET_KEY: ${FLASK_SECRET_KEY:-}
- LLM_PROVIDER=${LLM_PROVIDER:-} # Visitors are read-only; log in at /login with this token to edit or run.
- GEMINI_API_KEY=${GEMINI_API_KEY:-} PHYSCOM_ADMIN_TOKEN: ${PHYSCOM_ADMIN_TOKEN:-}
- GEMINI_MODEL=${GEMINI_MODEL:-gemini-2.0-flash} PHYSCOM_SECURE_COOKIES: ${PHYSCOM_SECURE_COOKIES:-0}
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped restart: unless-stopped
expose:
- 5000
cli: cli:
build: . build: .
volumes: volumes:
- physcom-data:/app/data - physcom-data:/app/data
environment: environment: *env
- PHYSCOM_DB=/app/data/physcom.db extra_hosts:
- LLM_PROVIDER=${LLM_PROVIDER:-} - "host.docker.internal:host-gateway"
- GEMINI_API_KEY=${GEMINI_API_KEY:-} entrypoint: ["physcom"]
- GEMINI_MODEL=${GEMINI_MODEL:-gemini-2.0-flash}
entrypoint: ["python", "-m", "physcom"]
profiles: [cli] profiles: [cli]
# Future: replace SQLite with a dedicated DB service
# db:
# image: postgres:16
# volumes:
# - pgdata:/var/lib/postgresql/data
# environment:
# - POSTGRES_DB=physcom
# - POSTGRES_USER=physcom
# - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
volumes: volumes:
physcom-data: physcom-data:
# pgdata:

View File

@@ -6,7 +6,14 @@ build-backend = "setuptools.build_meta"
name = "physcom" name = "physcom"
version = "0.1.0" version = "0.1.0"
description = "Physical Combinatorics — innovation via attribute mixing" description = "Physical Combinatorics — innovation via attribute mixing"
requires-python = ">=3.10" readme = "README.md"
requires-python = ">=3.11"
authors = [{ name = "Andrew Simonson", email = "asimonson1125@gmail.com" }]
classifiers = [
"Programming Language :: Python :: 3",
"Framework :: Flask",
"Topic :: Scientific/Engineering :: Physics",
]
dependencies = [ dependencies = [
"click>=8.1", "click>=8.1",
] ]
@@ -17,11 +24,15 @@ dev = [
] ]
web = [ web = [
"flask>=3.0", "flask>=3.0",
"gunicorn>=22.0",
] ]
gemini = [ gemini = [
"google-genai>=1.0", "google-genai>=1.0",
] ]
[project.urls]
Repository = "https://git.asimonson.com/andrew/physicalCombinatorics"
[project.scripts] [project.scripts]
physcom = "physcom.cli:main" physcom = "physcom.cli:main"
physcom-web = "physcom_web.app:run" physcom-web = "physcom_web.app:run"

View File

@@ -19,7 +19,7 @@ def _get_repo(db_path: str | None = None) -> Repository:
@click.group() @click.group()
@click.option("--db", default=None, help="Path to SQLite database") @click.option("--db", default=None, envvar="PHYSCOM_DB", help="Path to SQLite database (or $PHYSCOM_DB)")
@click.pass_context @click.pass_context
def main(ctx, db): def main(ctx, db):
"""Physical Combinatorics — innovation via attribute mixing.""" """Physical Combinatorics — innovation via attribute mixing."""
@@ -49,6 +49,31 @@ def seed(ctx, seed_name):
click.echo(f"Unknown seed: {seed_name}. Available: transport") click.echo(f"Unknown seed: {seed_name}. Available: transport")
@main.command()
@click.option("--if-empty", is_flag=True, help="Do nothing if the DB already has entities")
@click.pass_context
def demo(ctx, if_empty):
"""Seed the transport example and run passes 1-3 for every domain."""
repo = _get_repo(ctx.obj["db"])
if if_empty and repo.list_entities():
click.echo("DB already has data; skipping demo build.")
return
from physcom.engine.constraint_resolver import ConstraintResolver
from physcom.engine.scorer import Scorer
from physcom.engine.pipeline import Pipeline
from physcom.seed.transport_example import load_transport_seed
load_transport_seed(repo)
dims = ["platform", "actuator", "energy_storage"]
for domain in repo.list_domains():
result = Pipeline(repo, ConstraintResolver(), Scorer(domain)).run(
domain, dims, score_threshold=0.1, passes=[1, 2, 3],
)
click.echo(f" {domain.name}: {result.pass3_above_threshold} of "
f"{result.total_generated} combos above threshold")
@main.group() @main.group()
def entity(): def entity():
"""Manage entities.""" """Manage entities."""

View File

@@ -286,6 +286,11 @@ class Repository:
"INSERT OR IGNORE INTO domain_constraints (domain_id, key, value) VALUES (?, ?, ?)", "INSERT OR IGNORE INTO domain_constraints (domain_id, key, value) VALUES (?, ?, ?)",
(domain.id, dc.key, val), (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: for fv in domain.free_variables:
self.add_free_variable(domain.id, fv, commit=False) self.add_free_variable(domain.id, fv, commit=False)
for mf in domain.metric_formulas: for mf in domain.metric_formulas:
@@ -356,6 +361,11 @@ class Repository:
constraints=self._load_domain_constraints(row["id"]), constraints=self._load_domain_constraints(row["id"]),
free_variables=self._load_free_variables(row["id"]), free_variables=self._load_free_variables(row["id"]),
metric_formulas=self._load_metric_formulas(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: 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 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_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_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_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 domain_metric_formulas WHERE domain_id = ?", (domain_id,))
self.conn.execute("DELETE FROM domains WHERE id = ?", (domain_id,)) self.conn.execute("DELETE FROM domains WHERE id = ?", (domain_id,))
self.conn.commit() self.conn.commit()
def replace_domain_constraints(self, domain: Domain) -> None: 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: if not domain.id:
existing = self.conn.execute( existing = self.conn.execute(
"SELECT id FROM domains WHERE name = ?", (domain.name,) "SELECT id FROM domains WHERE name = ?", (domain.name,)
@@ -477,6 +488,12 @@ class Repository:
return return
domain.id = existing["id"] domain.id = existing["id"]
self.conn.execute("DELETE FROM domain_constraints 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,))
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 dc in domain.constraints:
for val in dc.allowed_values: for val in dc.allowed_values:
self.conn.execute( self.conn.execute(
@@ -988,6 +1005,7 @@ class Repository:
self.conn.execute("DELETE FROM entities") self.conn.execute("DELETE FROM entities")
self.conn.execute("DELETE FROM domain_metric_weights") self.conn.execute("DELETE FROM domain_metric_weights")
self.conn.execute("DELETE FROM domain_constraints") 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_free_variables")
self.conn.execute("DELETE FROM domain_metric_formulas") self.conn.execute("DELETE FROM domain_metric_formulas")
self.conn.execute("DELETE FROM domains") self.conn.execute("DELETE FROM domains")

View File

@@ -130,6 +130,13 @@ CREATE TABLE IF NOT EXISTS domain_free_variables (
UNIQUE(domain_id, name) 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 ( CREATE TABLE IF NOT EXISTS domain_metric_formulas (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
domain_id INTEGER NOT NULL REFERENCES domains(id), 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 # shielding) defaulted to a non-blocking warning nothing in the catalog
# ever satisfies -- see LOGIC DOCS/002's "silent guardrail hole" pattern. # ever satisfies -- see LOGIC DOCS/002's "silent guardrail hole" pattern.
"material": "block", "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 # For provides-vs-range_min: deficit > this ratio = hard block, else warning
@@ -311,6 +313,18 @@ class ConstraintResolver:
) -> ConstraintResult: ) -> ConstraintResult:
"""Check if a combo's entity requirements fall within domain-allowed values.""" """Check if a combo's entity requirements fall within domain-allowed values."""
result = ConstraintResult() 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: for dc in constraints:
allowed = set(dc.allowed_values) allowed = set(dc.allowed_values)
for entity in combination.entities: for entity in combination.entities:

View File

@@ -10,7 +10,7 @@ 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, score_raw from physcom.engine.scorer import Scorer, normalize, 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
@@ -71,10 +71,10 @@ INFRASTRUCTURE_AVAILABILITY: dict[tuple[str, str], float] = {
("fuel_infrastructure", "xenon_propellant"): 0.05, ("fuel_infrastructure", "xenon_propellant"): 0.05,
} }
# Crude freight-capacity proxy: kg of cargo per kg of vehicle structural # Fallback for platforms that don't declare their own payload_ratio
# mass. Real cargo ships run deadweight/lightship ratios of # (carried mass -- actuator + storage + payload + cargo -- per kg of
# roughly 1.5-4x depending on class; 2.5 is a reasonable general-cargo # platform structure). Real cargo ships run deadweight/lightship ratios of
# midpoint for this domain-agnostic proxy. # roughly 1.5-4x depending on class; 2.5 is a general-cargo midpoint.
CARGO_KG_PER_STRUCTURAL_KG: float = 2.5 CARGO_KG_PER_STRUCTURAL_KG: float = 2.5
# How mechanically proven/predictable an energy form is in practice — distinct # How mechanically proven/predictable an energy form is in practice — distinct
@@ -357,6 +357,21 @@ class _PhysicsContext:
e_dens: float e_dens: float
k_med: float | None k_med: float | None
p_rep: float 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 @dataclass
@@ -606,18 +621,17 @@ class Pipeline:
# be blocked in this domain but valid in another. The per-domain # be blocked in this domain but valid in another. The per-domain
# block lives on combination_results.domain_block_reason (see # block lives on combination_results.domain_block_reason (see
# count_combinations_by_status / get_all_results, which bucket on it). # count_combinations_by_status / get_all_results, which bucket on it).
if domain.constraints: dc_result = self.resolver.check_domain_constraints(combo, domain.constraints)
dc_result = self.resolver.check_domain_constraints(combo, domain.constraints) if dc_result.status == "p1_fail":
if dc_result.status == "p1_fail": self.repo.save_result(
self.repo.save_result( combo.id, domain.id,
combo.id, domain.id, composite_score=0.0, pass_reached=1,
composite_score=0.0, pass_reached=1, domain_block_reason="; ".join(dc_result.violations),
domain_block_reason="; ".join(dc_result.violations), commit=False,
commit=False, )
) result.pass1_failed += 1
result.pass1_failed += 1 self._update_run_counters(run_id, result, current_pass=1)
self._update_run_counters(run_id, result, current_pass=1) return
return
if cr.status == "conditional": if cr.status == "conditional":
result.pass1_conditional += 1 result.pass1_conditional += 1
@@ -856,7 +870,8 @@ class Pipeline:
self.repo.update_pipeline_run(run_id, status="running") self.repo.update_pipeline_run(run_id, status="running")
def _physics_context( 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": ) -> "_PhysicsContext | None":
"""Derive the entity-level physics inputs that don't depend on a """Derive the entity-level physics inputs that don't depend on a
mass allocation choice -- shared by _estimate_physics (which picks 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, e_dens=dep_value(storage, "energy_density", "provides") or 0.0,
k_med=SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M.get(medium), k_med=SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M.get(medium),
p_rep=_representative_mass(p_min, p_max), 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( def _raw_physics_from_masses(
@@ -909,6 +933,7 @@ class Pipeline:
bounds_by_name: dict[str, MetricBound], bounds_by_name: dict[str, MetricBound],
units_by_name: dict[str, str], units_by_name: dict[str, str],
platform_mass: float | None = None, platform_mass: float | None = None,
cruise_iters: int = 10,
) -> dict[str, float]: ) -> dict[str, float]:
"""power_density/range_fuel/cost_efficiency/cargo_capacity for an """power_density/range_fuel/cost_efficiency/cargo_capacity for an
EXPLICIT mass allocation. `platform_mass` defaults to the EXPLICIT mass allocation. `platform_mass` defaults to the
@@ -923,124 +948,147 @@ class Pipeline:
metric here does.""" metric here does."""
p_mass = ctx.p_rep if platform_mass is None else platform_mass p_mass = ctx.p_rep if platform_mass is None else platform_mass
out: dict[str, float] = {} 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 power_density_value = (ctx.k_act * actuator_mass) / floor_total if floor_total else 0.0
if "power_density" in bounds_by_name: if "power_density" in bounds_by_name:
out["power_density"] = power_density_value out["power_density"] = power_density_value
# Deadweight/lightship cargo capacity. Real deadweight tonnage is a # Spare carrying capacity: the platform structure carries
# FIXED allowance sized off the vessel's own empty (lightship) mass # payload_ratio x its own mass in total, and actuator, storage and
# -- hull + machinery, NOT fuel or cargo -- and fuel and cargo then # the domain's required payload all come out of that same allowance
# SHARE that one allowance: a ship that bunkers more fuel has that # -- more fuel/battery means less room for cargo, not more.
# much less room left for cargo, and vice versa. platform+actuator # Floored at 0. Skipped for domains that neither score cargo nor
# is the lightship analog here (the vehicle's own hardware); # need it as cost_efficiency's $/(kg·m) denominator -- this runs on
# storage_mass is the fuel/battery competing with cargo for the # every grid point of the search in _decide_masses.
# 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.
needs_cargo = ( needs_cargo = (
"cargo_capacity" in bounds_by_name "cargo_capacity" in bounds_by_name
or "cargo_capacity_kg" in bounds_by_name or "cargo_capacity_kg" in bounds_by_name
or units_by_name.get("cost_efficiency") == "$/(kg·m)" or units_by_name.get("cost_efficiency") == "$/(kg·m)"
) )
cargo_capacity_2_5x = 0.0 cargo_capacity = 0.0
if needs_cargo: if needs_cargo:
lightship_mass = p_mass + actuator_mass cargo_capacity = max(
cargo_capacity_2_5x = max(0.0, lightship_mass * CARGO_KG_PER_STRUCTURAL_KG - storage_mass) 0.0, p_mass * ctx.payload_ratio - actuator_mass - storage_mass - carried_payload
cargo_capacity_0_3x = max(0.0, lightship_mass * 0.3 - storage_mass) )
if "cargo_capacity" in bounds_by_name: for name in ("cargo_capacity", "cargo_capacity_kg"):
out["cargo_capacity"] = cargo_capacity_2_5x if name in bounds_by_name:
if "cargo_capacity_kg" in bounds_by_name: out[name] = cargo_capacity
out["cargo_capacity_kg"] = cargo_capacity_0_3x
# Achieved steady-state cruise speed, DERIVED from this specific # Top speed, DERIVED from this build's actual power_density, the
# build's actual power_density, the medium's mass-proportional # medium's mass-proportional resistance and (ground/air, see
# resistance, and (ground/air, see DRAG_POWER_COEFF_BY_MEDIUM) a # DRAG_POWER_COEFF_BY_MEDIUM) a mass-independent aerodynamic drag
# mass-independent aerodynamic drag term -- not a platform-declared # term -- an output of the build, not a platform-declared constant.
# 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.
drag_coeff = DRAG_POWER_COEFF_BY_MEDIUM.get(ctx.medium, 0.0) 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) top_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
)
# 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: if "cost_efficiency" in bounds_by_name:
structural_cost = p_mass * STRUCTURAL_COST_PER_KG_BY_MEDIUM.get( m_p, m_a, m_s = ctx.maintenance
ctx.medium, STRUCTURAL_COST_PER_KG_BY_MEDIUM["ground"] 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( lifetime_m = ctx.service_life or LIFETIME_DISTANCE_M_BY_MEDIUM.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(
ctx.medium, LIFETIME_DISTANCE_M_BY_MEDIUM["ground"] ctx.medium, LIFETIME_DISTANCE_M_BY_MEDIUM["ground"]
) )
amortized_per_m = upfront_cost / lifetime_m amortized_per_m = upfront_cost / lifetime_m
if ctx.k_med is not None: def at_speed(v: float) -> dict[str, float]:
fuel_price_per_mj = FUEL_PRICE_PER_MJ.get(ctx.storage_energy_form, 0.04) # Energy actually spent per meter depends on the speed the build
energy_per_m_mj = (effective_k_med * floor_total) / 1e6 # is actually driven at, drag included.
operating_per_m = energy_per_m_mj * fuel_price_per_mj effective_k_med = (
else: (ctx.k_med + drag_coeff * v ** 2 / floor_total)
# No resistance model for this medium (space -- real range if ctx.k_med is not None and floor_total > 0 else ctx.k_med
# is governed by the rocket equation, not implemented )
# here, see the comment above m: dict[str, float] = {}
# SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M). Don't fabricate if "speed" in bounds_by_name:
# an operating cost from ground physics the way an earlier m["speed"] = v
# version of this did (`effective_k_med or ...["ground"]`) if "range_fuel" in bounds_by_name:
# -- report upfront/amortized cost only, an honest partial if ctx.storage_energy_form in AMBIENT_ENERGY_FORMS or ctx.k_med is None:
# answer, rather than a wrong number for an unmodeled term. m["range_fuel"] = bounds_by_name["range_fuel"].norm_max
operating_per_m = 0.0 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 # Cruise speed is a decision, not the top speed: anywhere from the
if units_by_name.get("cost_efficiency") == "$/(kg·m)": # domain's own speed floor (its norm_min -- slower is worthless to
# Divide by whichever cargo convention this domain actually # it) up to what this build can reach. Driving slower buys range
# scores, so cost-per-cargo-kg and the cargo_capacity number # and cost, so pick the speed that scores best for this domain.
# shown alongside it always agree; default to the heavy- speed_bound = bounds_by_name.get("speed")
# vehicle ratio if a domain scores $/(kg·m) without scoring v_lo = speed_bound.norm_min if speed_bound else top_speed
# either cargo metric explicitly (matches prior behavior). if ctx.k_med is None or not v_lo or v_lo <= 0 or top_speed <= v_lo:
cargo_basis = out.get("cargo_capacity_kg", out.get("cargo_capacity", cargo_capacity_2_5x)) return {**out, **at_speed(top_speed)}
out["cost_efficiency"] = cost_per_m / max(cargo_basis, 1.0)
else:
out["cost_efficiency"] = cost_per_m
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( def _decide_masses(
self, self,
@@ -1064,7 +1112,7 @@ class Pipeline:
or bigger operators, or a bigger sail, not a fixed constant. That or bigger operators, or a bigger sail, not a fixed constant. That
floor also floor also
sets the smallest platform mass that could structurally carry it 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, carrying its own actuator+storage instead of cargo) -- below that,
no actuator/storage choice is physically possible. Above that no actuator/storage choice is physically possible. Above that
lower bound, platform mass is a real THIRD search variable, not 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") 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")
range_bounds = bounds_by_name.get("range_fuel") 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 # Actuator requirements as (capability C, requirement R) pairs: the
# for a declared floor of zero (Spaceship declares # actuator must be at least R/(C-R) of the rest of the gross mass.
# min_effective_accel=0, a real "no acceleration floor" value, not # range_min floors on the platform are HARD (a rotorcraft that can't
# "undeclared"). A truthy check would silently treat that the same # hover isn't a rotorcraft): enforced at every candidate build below,
# as an absent requirement and fall through to the wrong branch. # 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: if min_accel is not None and specific_thrust is not None:
c1, r1 = specific_thrust, min_accel hard.append((specific_thrust, min_accel))
elif target_velocity and ctx.k_med: 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 -- # Resistance alone (k_med) only covers steady-state cruise --
# a real vehicle also needs reserve force for acceleration # a real vehicle also needs reserve force for acceleration
# events (merging, passing, hills), not just holding speed. # events (merging, passing, hills). F=ma: an acceleration
# F=ma: an acceleration reserve in m/s^2 is dimensionally a # reserve in m/s^2 is a specific force (N/kg) exactly like
# specific force (N/kg) exactly like k_med (J/(kg*m) = N/kg), # k_med (J/(kg*m) = N/kg), so it adds directly before
# so it adds directly before converting to specific power # converting to specific power (P/mass = force/mass * v).
# (P/mass = force/mass * v). soft.append((ctx.k_act, (ctx.k_med + ACCELERATION_RESERVE_M_S2) * target_velocity))
c1, r1 = ctx.k_act, (ctx.k_med + ACCELERATION_RESERVE_M_S2) * target_velocity if any(c <= r for c, r in hard):
else: return max(ctx.a_min, 10.0), ctx.s_min, max(ctx.p_min, p_start), False
c1 = r1 = 0.0 # no performance requirement available -- degenerates below # 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: if target_range and ctx.k_med:
c2, r2 = ctx.e_dens, target_range * ctx.k_med c2, r2 = ctx.e_dens, target_range * ctx.k_med
@@ -1128,7 +1196,7 @@ class Pipeline:
if c1 and c2: if c1 and c2:
required_actuator, required_storage = _solve_two_requirement_masses( 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: else:
# No performance requirement available at all (e.g. a # No performance requirement available at all (e.g. a
@@ -1160,20 +1228,21 @@ class Pipeline:
a_floor = max(ctx.a_min, required_actuator) a_floor = max(ctx.a_min, required_actuator)
s_floor = max(ctx.s_min, required_storage) 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 # 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 # (see insufficient_structure), a bigger platform also buys room for
# a bigger, higher-scoring actuator/storage build -- so platform # a bigger, higher-scoring actuator/storage build -- so platform
# mass has to be searched jointly with them, not fixed. The lower # 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 # bound still can't go below what's needed to carry the required
# floor at all (that's a physical requirement, not a scoring # floor at all (that's a physical requirement, not a scoring
# choice); p_rep is used only as the starting point for that # choice).
# search, not the answer. p_lo = max(ctx.p_min, p_start, structural_floor / ratio)
p_lo = max(ctx.p_min, ctx.p_rep, structural_floor / CARGO_KG_PER_STRUCTURAL_KG)
p_lo = min(p_lo, ctx.p_max) 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 # Even the smallest viable platform can't carry the required
# floor within the mass ceiling -- genuinely infeasible # floor within the mass ceiling -- genuinely infeasible
# allocation, not a search problem. Best-effort fallback masses # allocation, not a search problem. Best-effort fallback masses
@@ -1184,21 +1253,37 @@ class Pipeline:
# something else has to catch that). # something else has to catch that).
return a_floor, s_floor, p_lo, False 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( raw = self._raw_physics_from_masses(
ctx, actuator_mass, storage_mass, ctx, actuator_mass, storage_mass,
bounds_by_name, units_by_name, 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] return score_raw(raw, bounds_by_name.values())[0]
def best_at_platform(p: float, grid: int, rounds: int) -> tuple[float, float, float]: 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 * CARGO_KG_PER_STRUCTURAL_KG) budget = min(ctx.p_max - p, p * ratio) - payload_floor
if budget < structural_floor: if budget < a_floor + s_floor:
return a_floor, s_floor, -1.0 return a_floor, s_floor, -1.0
return self._search_best_allocation( a, s_, sc = self._search_best_allocation(
a_floor, s_floor, budget, lambda a, s: objective(p, a, s), grid=grid, rounds=rounds, 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 # Outer coarse-to-fine search over platform mass. A cheap/low-res
# inner (a, s) search keeps every round affordable -- a 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 p = win_lo + (win_hi - win_lo) * i / grid
if p < p_floor or p > ctx.p_max: if p < p_floor or p > ctx.p_max:
continue 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: if sc > best_score:
best_score, best_p = sc, p best_score, best_p = sc, p
span = max((win_hi - win_lo) / grid * 2, 1e-6) span = max((win_hi - win_lo) / grid * 2, 1e-6)
@@ -1238,8 +1323,9 @@ class Pipeline:
if sc > best_score: if sc > best_score:
best_score, best_p = sc, p best_score, best_p = sc, p
actuator_mass, storage_mass, _score = best_at_platform(best_p, grid=12, rounds=6) actuator_mass, storage_mass, final_score = best_at_platform(best_p, grid=12, rounds=6)
return actuator_mass, storage_mass, best_p, True # -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 @staticmethod
def _search_best_allocation( def _search_best_allocation(
@@ -1353,7 +1439,7 @@ class Pipeline:
# ── platform/actuator/storage-specific extraction, for # ── platform/actuator/storage-specific extraction, for
# power_density / range_fuel / cost_efficiency / cargo_capacity # power_density / range_fuel / cost_efficiency / cargo_capacity
# only ───────────────────────────────────────────────────────── # only ─────────────────────────────────────────────────────────
ctx = self._physics_context(combo, bounds_by_name) ctx = self._physics_context(combo, bounds_by_name, domain.requirements)
feasible = True feasible = True
if ctx is not None: if ctx is not None:
actuator_mass, storage_mass, platform_mass, feasible = self._decide_masses( 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} 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} 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: if ctx is None or ctx.p_max is None:
return None return None
@@ -1603,7 +1689,7 @@ class Pipeline:
actuator_slider_max = max(a_mass, ctx.p_max - ctx.p_min - ctx.s_min) 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) 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 { return {
"platform_mass": p_mass, "platform_min": ctx.p_min, "platform_max": ctx.p_max, "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, "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, "exceeds_platform_envelope": total_mass > ctx.p_max,
# None of power_density/range_fuel/cost_efficiency penalize a # None of power_density/range_fuel/cost_efficiency penalize a
# platform mass that's too small to structurally carry its own # platform mass that's too small to structurally carry its own
# actuator+storage -- they only see the total. Reuse the same # actuator+storage+payload -- they only see the total. Same
# structure-supports-N-times-its-own-mass ratio already used for # payload_ratio cargo_capacity uses: a platform can't carry more
# cargo_capacity_kg (CARGO_KG_PER_STRUCTURAL_KG) rather than a # than that, any more than it could carry that much cargo.
# one-off constant: a platform can't carry more actuator+storage "insufficient_structure": total_mass - p_mass > p_mass * ctx.payload_ratio,
# 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,
"raw_metrics": raw, "raw_metrics": raw,
"normalized_scores": normalized, "normalized_scores": normalized,
"composite_score": composite, "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 below norm_min -> 0.0
Values at or above norm_max -> 1.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: if norm_max <= norm_min:
return 0.0 return 0.0
@@ -22,10 +26,9 @@ def normalize(raw_value: float, norm_min: float, norm_max: float) -> float:
return 0.0 return 0.0
if raw_value >= norm_max: if raw_value >= norm_max:
return 1.0 return 1.0
log_min = math.log1p(norm_min) if norm_min <= 0.0:
log_max = math.log1p(norm_max) return (raw_value - norm_min) / (norm_max - norm_min)
log_val = math.log1p(raw_value) return math.log(raw_value / norm_min) / math.log(norm_max / norm_min)
return (log_val - log_min) / (log_max - log_min)
def composite_score(scores: list[float], weights: list[float]) -> float: 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) constraints: list[DomainConstraint] = field(default_factory=list)
free_variables: list[FreeVariable] = field(default_factory=list) free_variables: list[FreeVariable] = field(default_factory=list)
metric_formulas: list[MetricFormula] = 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 id: int | None = None

View File

@@ -22,6 +22,9 @@ GROUND_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "0.5", "m²", "range_min"), Dependency("physical", "footprint", "0.5", "m²", "range_min"),
Dependency("physical", "mass", "36000", "kg", "range_max"), Dependency("physical", "mass", "36000", "kg", "range_max"),
Dependency("physical", "mass", "50", "kg", "range_min"), 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("infrastructure", "road_network", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"), Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "25", "m/s", "provides"), Dependency("physical", "target_velocity", "25", "m/s", "provides"),
@@ -38,8 +41,11 @@ GROUND_PLATFORMS: list[Entity] = [
Dependency("environment", "gravity", "true", None, "provides"), Dependency("environment", "gravity", "true", None, "provides"),
Dependency("physical", "footprint", "3", "m²", "range_max"), Dependency("physical", "footprint", "3", "m²", "range_max"),
Dependency("physical", "footprint", "0.3", "m²", "range_min"), 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", "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("infrastructure", "road_network", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"), Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "6", "m/s", "provides"), 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", "footprint", "20", "m²", "range_min"),
Dependency("physical", "mass", "40000", "kg", "range_max"), Dependency("physical", "mass", "40000", "kg", "range_max"),
Dependency("physical", "mass", "10000", "kg", "range_min"), 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("infrastructure", "rail_network", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"), Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "30", "m/s", "provides"), 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", "footprint", "2", "m²", "range_min"),
Dependency("physical", "mass", "100000", "kg", "range_max"), Dependency("physical", "mass", "100000", "kg", "range_max"),
Dependency("physical", "mass", "30", "kg", "range_min"), Dependency("physical", "mass", "30", "kg", "range_min"),
Dependency("physical", "payload_ratio", "2.5", "kg/kg", "provides"),
Dependency("environment", "medium", "water", None, "requires"), Dependency("environment", "medium", "water", None, "requires"),
Dependency("physical", "target_velocity", "8", "m/s", "provides"), 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", "footprint", "20", "m²", "range_min"),
Dependency("physical", "mass", "20000000", "kg", "range_max"), Dependency("physical", "mass", "20000000", "kg", "range_max"),
Dependency("physical", "mass", "10000", "kg", "range_min"), Dependency("physical", "mass", "10000", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.3", "kg/kg", "provides"),
Dependency("environment", "medium", "water", None, "requires"), Dependency("environment", "medium", "water", None, "requires"),
Dependency("physical", "energy_density", "720000", "J/kg", "range_min"), Dependency("physical", "energy_density", "720000", "J/kg", "range_min"),
Dependency("physical", "target_velocity", "8", "m/s", "provides"), 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", "footprint", "10", "m²", "range_min"),
Dependency("physical", "mass", "100000", "kg", "range_max"), Dependency("physical", "mass", "100000", "kg", "range_max"),
Dependency("physical", "mass", "500", "kg", "range_min"), 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("infrastructure", "runway", "true", None, "requires"),
Dependency("environment", "medium", "air", None, "requires"), Dependency("environment", "medium", "air", None, "requires"),
Dependency("physical", "energy_density", "1440000", "J/kg", "range_min"), 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", "footprint", "0.5", "m²", "range_min"),
Dependency("physical", "mass", "5000", "kg", "range_max"), Dependency("physical", "mass", "5000", "kg", "range_max"),
Dependency("physical", "mass", "1", "kg", "range_min"), 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("environment", "medium", "air", None, "requires"),
Dependency("physical", "energy_density", "720000", "J/kg", "range_min"), Dependency("physical", "energy_density", "720000", "J/kg", "range_min"),
Dependency("physical", "min_effective_accel", "10", "m/s²", "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", "footprint", "50", "m²", "range_min"),
Dependency("physical", "mass", "20000", "kg", "range_max"), Dependency("physical", "mass", "20000", "kg", "range_max"),
Dependency("physical", "mass", "200", "kg", "range_min"), 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"), Dependency("environment", "medium", "air", None, "requires"),
], ],
), ),
@@ -175,6 +198,7 @@ SPACE_PLATFORMS: list[Entity] = [
Dependency("physical", "footprint", "500", "m²", "range_max"), Dependency("physical", "footprint", "500", "m²", "range_max"),
Dependency("physical", "footprint", "10", "m²", "range_min"), Dependency("physical", "footprint", "10", "m²", "range_min"),
Dependency("physical", "mass", "5000", "kg", "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("infrastructure", "launch_facility", "true", None, "requires"),
Dependency("environment", "medium", "space", None, "requires"), Dependency("environment", "medium", "space", None, "requires"),
Dependency("physical", "energy_density", "7200000", "J/kg", "range_min"), 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", "footprint", "5", "m²", "range_min"),
Dependency("physical", "mass", "10000", "kg", "range_max"), Dependency("physical", "mass", "10000", "kg", "range_max"),
Dependency("physical", "mass", "1500", "kg", "range_min"), Dependency("physical", "mass", "1500", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.8", "kg/kg", "provides"),
# No requires here previously -- vacuously satisfied every # No requires here previously -- vacuously satisfied every
# domain's medium DomainConstraint (check_domain_constraints # domain's medium DomainConstraint (check_domain_constraints
# only flags a violation when an entity DECLARES a requires # 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", "footprint", "5", "m²", "range_min"),
Dependency("physical", "mass", "20000", "kg", "range_max"), Dependency("physical", "mass", "20000", "kg", "range_max"),
Dependency("physical", "mass", "5000", "kg", "range_min"), Dependency("physical", "mass", "5000", "kg", "range_min"),
Dependency("physical", "payload_ratio", "0.6", "kg/kg", "provides"),
Dependency("infrastructure", "hyperloop_tube", "true", None, "requires"), Dependency("infrastructure", "hyperloop_tube", "true", None, "requires"),
Dependency("environment", "medium", "ground", None, "requires"), Dependency("environment", "medium", "ground", None, "requires"),
Dependency("physical", "target_velocity", "270", "m/s", "provides"), # near-sonic, per its own description 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("physical", "mass", "45", "kg", "range_min"),
Dependency("force", "thrust_profile", "high_continuous", None, "provides"), Dependency("force", "thrust_profile", "high_continuous", None, "provides"),
Dependency("force", "power_density", "1000", "W/kg", "provides"), Dependency("force", "power_density", "1000", "W/kg", "provides"),
Dependency("physical", "maintenance_multiple", "1.0", "x", "provides"),
], ],
), ),
Entity( Entity(
@@ -280,6 +307,7 @@ COMBUSTION_ACTUATORS: list[Entity] = [
Dependency("force", "thrust_profile", "extreme_continuous", None, "provides"), Dependency("force", "thrust_profile", "extreme_continuous", None, "provides"),
Dependency("force", "power_density", "5000", "W/kg", "provides"), Dependency("force", "power_density", "5000", "W/kg", "provides"),
Dependency("force", "specific_thrust", "50", "N/kg", "provides"), Dependency("force", "specific_thrust", "50", "N/kg", "provides"),
Dependency("physical", "maintenance_multiple", "2.0", "x", "provides"),
], ],
), ),
Entity( Entity(
@@ -309,6 +337,7 @@ ELECTRIC_ACTUATORS: list[Entity] = [
Dependency("physical", "mass", "5", "kg", "range_min"), Dependency("physical", "mass", "5", "kg", "range_min"),
Dependency("force", "thrust_profile", "moderate_continuous", None, "provides"), Dependency("force", "thrust_profile", "moderate_continuous", None, "provides"),
Dependency("force", "power_density", "2000", "W/kg", "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("physical", "mass", "15", "kg", "range_min"),
Dependency("force", "thrust_profile", "low_continuous", None, "provides"), Dependency("force", "thrust_profile", "low_continuous", None, "provides"),
Dependency("force", "power_density", "10", "W/kg", "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("physical", "mass", "0", "kg", "range_min"),
Dependency("force", "thrust_profile", "low_continuous", None, "provides"), Dependency("force", "thrust_profile", "low_continuous", None, "provides"),
Dependency("force", "power_density", "10", "W/kg", "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("infrastructure", "fuel_infrastructure", "charging_station", None, "requires"),
Dependency("physical", "mass", "9", "kg", "range_min"), Dependency("physical", "mass", "9", "kg", "range_min"),
Dependency("physical", "energy_density", "1080000", "J/kg", "provides"), Dependency("physical", "energy_density", "1080000", "J/kg", "provides"),
Dependency("physical", "maintenance_multiple", "1.0", "x", "provides"),
], ],
), ),
Entity( Entity(
@@ -756,18 +788,18 @@ URBAN_COMMUTING = Domain(
# this project hasn't done -- not scored anywhere for now rather than # this project hasn't done -- not scored anywhere for now rather than
# pretend a quick formula or an equally uninformed LLM guess settles it. # pretend a quick formula or an equally uninformed LLM guess settles it.
# Weights renormalized to sum to 1.0 across the remaining metrics. # Weights renormalized to sum to 1.0 across the remaining metrics.
# speed and cargo_capacity_kg added -- a commute's actual travel # power_density dropped: it's an input to speed (and to whether a
# time and whether the vehicle can carry groceries/passengers/gear # build meets its platform's own hover/accel floors), not an outcome
# both matter as much as raw power_density did on their own; speed # a commuter values -- scoring it too rewarded overpowered builds
# is a genuine build OUTPUT (see _raw_physics_from_masses), not a # twice. Cargo is a mission requirement (one commuter, ~100kg with
# platform-declared constant. # gear), not a more-is-better score: every build must carry it, and
MetricBound("power_density", weight=0.25, norm_min=1, norm_max=2000, unit="W/kg"), # speed/cost/range are all computed with it on board.
MetricBound("cost_efficiency", weight=0.25, norm_min=1e-5, norm_max=2e-3, unit="$/m", lower_is_better=True), MetricBound("cost_efficiency", weight=0.417, 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("speed", weight=0.417, norm_min=2, norm_max=30, unit="m/s"),
MetricBound("range_fuel", weight=0.10, norm_min=5000, norm_max=500000, unit="m"), MetricBound("range_fuel", weight=0.166, norm_min=50000, norm_max=500000, unit="m"),
MetricBound("cargo_capacity_kg", weight=0.15, norm_min=1, norm_max=500, unit="kg"),
], ],
constraints=[DomainConstraint("medium", ["ground", "air"])], constraints=[DomainConstraint("medium", ["ground", "air"])],
requirements={"payload": 100.0, "trip_range": 50000.0},
) )
INTERPLANETARY = Domain( INTERPLANETARY = Domain(

View File

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

View File

@@ -2,11 +2,12 @@
from __future__ import annotations from __future__ import annotations
import hmac
import os import os
import secrets import secrets
from pathlib import Path from pathlib import Path
from flask import Flask, g from flask import Flask, abort, g, redirect, render_template, request, session, url_for
from physcom.db.schema import init_db from physcom.db.schema import init_db
from physcom.db.repository import Repository from physcom.db.repository import Repository
@@ -15,12 +16,41 @@ from physcom.units import format_quantity
DEFAULT_DB = Path("data/physcom.db") DEFAULT_DB = Path("data/physcom.db")
# Everything a read-only visitor may not reach. Writes (any non-GET) are
# locked separately, except the purely exploratory results.explore.
ADMIN_GET_ENDPOINTS = {"pipeline.pipeline_form", "entities.entity_new", "domains.domain_new"}
PUBLIC_POST_ENDPOINTS = {"results.explore", "login"}
def db_path() -> Path:
return Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB)))
def _secret_key() -> str:
"""FLASK_SECRET_KEY, else a key persisted next to the DB so admin
sessions survive restarts."""
key = os.environ.get("FLASK_SECRET_KEY")
if key:
return key
path = db_path().parent / ".secret_key"
try:
return path.read_text().strip()
except FileNotFoundError:
key = secrets.token_hex(32)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(key)
return key
def is_admin() -> bool:
from flask import current_app
return session.get("admin", False)
def get_repo() -> Repository: def get_repo() -> Repository:
"""Return a Repository scoped to the current request.""" """Return a Repository scoped to the current request."""
if "repo" not in g: if "repo" not in g:
db_path = Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB))) conn = init_db(db_path())
conn = init_db(db_path)
g.repo = Repository(conn) g.repo = Repository(conn)
return g.repo return g.repo
@@ -32,8 +62,52 @@ def close_db(exc: BaseException | None = None) -> None:
def create_app() -> Flask: def create_app() -> Flask:
"""Read-only to visitors; writes need a login with PHYSCOM_ADMIN_TOKEN
(no token set = no one can write)."""
app = Flask(__name__) app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY") or secrets.token_hex(32) app.secret_key = _secret_key()
admin_token = os.environ.get("PHYSCOM_ADMIN_TOKEN", "")
app.config.update(
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=os.environ.get("PHYSCOM_SECURE_COOKIES") == "1",
)
app.jinja_env.globals["is_admin"] = is_admin
@app.before_request
def require_admin():
if is_admin() or request.endpoint in (None, "static"):
return None
blueprint = request.endpoint.split(".")[0]
if request.method in ("GET", "HEAD"):
if blueprint == "admin" or request.endpoint in ADMIN_GET_ENDPOINTS:
return redirect(url_for("login", next=request.path))
return None
if request.endpoint not in PUBLIC_POST_ENDPOINTS:
abort(403)
return None
@app.route("/login", methods=["GET", "POST"])
def login():
error = None
if request.method == "POST":
given = request.form.get("token", "")
if admin_token and hmac.compare_digest(given, admin_token):
session.clear()
session["admin"] = True
session.permanent = True
target = request.args.get("next", "")
# Only same-site relative paths, never "//evil.com".
if not target.startswith("/") or target.startswith("//"):
target = url_for("index")
return redirect(target)
error = "Wrong token." if admin_token else "Admin login is disabled (PHYSCOM_ADMIN_TOKEN not set)."
return render_template("login.html", error=error), (401 if error else 200)
@app.route("/logout", methods=["POST"])
def logout():
session.clear()
return redirect(url_for("index"))
app.jinja_env.filters["qty"] = format_quantity app.jinja_env.filters["qty"] = format_quantity
@@ -54,7 +128,6 @@ def create_app() -> Flask:
@app.route("/") @app.route("/")
def index(): def index():
from flask import render_template
repo = get_repo() repo = get_repo()
entities = repo.list_entities() entities = repo.list_entities()
dims = {e.dimension for e in entities} dims = {e.dimension for e in entities}
@@ -66,12 +139,26 @@ def create_app() -> Flask:
"domains": len(domains), "domains": len(domains),
"combinations": sum(status_counts.values()), "combinations": sum(status_counts.values()),
} }
return render_template("home.html", stats=stats) top_concepts = []
for d in domains:
top = repo.get_top_results(d.name, limit=1)
if top and top[0]["composite_score"]:
top_concepts.append((d, top[0]))
return render_template("home.html", stats=stats, top_concepts=top_concepts)
return app return app
def run() -> None: def run() -> None:
"""Entry point for `physcom-web` script.""" """Entry point for `physcom-web` script. Same access rules as production,
so localhost shows the public view; without PHYSCOM_ADMIN_TOKEN a one-off
token is generated and printed for /login."""
if not os.environ.get("PHYSCOM_ADMIN_TOKEN"):
os.environ["PHYSCOM_ADMIN_TOKEN"] = secrets.token_urlsafe(16)
print(f" * Admin login token (this run only): {os.environ['PHYSCOM_ADMIN_TOKEN']}")
app = create_app() app = create_app()
app.run(host=os.environ.get("HOST", "127.0.0.1"), debug=True, port=int(os.environ.get("PORT", "5000"))) app.run(
host=os.environ.get("HOST", "127.0.0.1"),
debug=os.environ.get("FLASK_DEBUG") == "1",
port=int(os.environ.get("PORT", "5000")),
)

View File

@@ -3,9 +3,7 @@
from __future__ import annotations from __future__ import annotations
import json import json
import os
import threading import threading
from pathlib import Path
from flask import Blueprint, flash, redirect, render_template, request, url_for from flask import Blueprint, flash, redirect, render_template, request, url_for
@@ -138,8 +136,8 @@ def pipeline_run():
run_id = repo.create_pipeline_run(domain.id, config) run_id = repo.create_pipeline_run(domain.id, config)
# Resolve DB path for the background thread # Resolve DB path for the background thread
from physcom_web.app import DEFAULT_DB from physcom_web.app import db_path as _db_path
db_path = str(Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB)))) db_path = str(_db_path())
# Start background thread # Start background thread
t = threading.Thread( t = threading.Thread(

View File

@@ -2,6 +2,8 @@
from __future__ import annotations from __future__ import annotations
import math
from flask import Blueprint, flash, redirect, render_template, request, url_for from flask import Blueprint, flash, redirect, render_template, request, url_for
from physcom.engine.constraint_resolver import ConstraintResolver from physcom.engine.constraint_resolver import ConstraintResolver
@@ -104,9 +106,10 @@ def explore(domain_name: str, combo_id: int):
if raw is None: if raw is None:
return None return None
try: try:
return float(raw) value = float(raw)
except ValueError: except ValueError:
return None return None
return value if math.isfinite(value) else None
explore_result = _run_evaluate( explore_result = _run_evaluate(
repo, domain, combo, repo, domain, combo,

View File

@@ -704,3 +704,14 @@ select option {
/* ── Google Fonts import ─────────────────────────────────── */ /* ── Google Fonts import ─────────────────────────────────── */
@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');
/* Read-only public mode: hide every write control (the server rejects them anyway). */
body.readonly form[method="post"]:not(.public) { display: none; }
.nav-logout { display: inline; margin: 0; }
.nav-logout button {
background: none; border: none; cursor: pointer;
color: var(--text-secondary); font: inherit; font-size: 0.88rem; font-weight: 500;
padding: 0.4rem 0.75rem; border-radius: var(--radius);
}
.nav-logout button:hover { color: var(--text-primary); background: var(--bg-elevated); }

View File

@@ -8,7 +8,7 @@
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="https://unpkg.com/htmx.org@2.0.4"></script> <script src="https://unpkg.com/htmx.org@2.0.4"></script>
</head> </head>
<body> <body{% if not is_admin() %} class="readonly"{% endif %}>
<nav> <nav>
<a href="{{ url_for('index') }}" class="nav-brand"> <a href="{{ url_for('index') }}" class="nav-brand">
<img src="{{ url_for('static', filename='logo.svg') }}" alt=""> <img src="{{ url_for('static', filename='logo.svg') }}" alt="">
@@ -17,9 +17,12 @@
<ul> <ul>
<li><a href="{{ url_for('entities.entity_list') }}">Entities</a></li> <li><a href="{{ url_for('entities.entity_list') }}">Entities</a></li>
<li><a href="{{ url_for('domains.domain_list') }}">Domains</a></li> <li><a href="{{ url_for('domains.domain_list') }}">Domains</a></li>
<li><a href="{{ url_for('pipeline.pipeline_form') }}">Pipeline</a></li>
<li><a href="{{ url_for('results.results_index') }}">Results</a></li> <li><a href="{{ url_for('results.results_index') }}">Results</a></li>
{% if is_admin() %}
<li><a href="{{ url_for('pipeline.pipeline_form') }}">Pipeline</a></li>
<li><a href="{{ url_for('admin.admin_index') }}">Admin</a></li> <li><a href="{{ url_for('admin.admin_index') }}">Admin</a></li>
<li><form method="post" action="{{ url_for('logout') }}" class="nav-logout"><button type="submit">Log out</button></form></li>
{% endif %}
</ul> </ul>
</nav> </nav>

View File

@@ -4,7 +4,7 @@
{% block content %} {% block content %}
<div class="page-header"> <div class="page-header">
<h1>Domains</h1> <h1>Domains</h1>
<a href="{{ url_for('domains.domain_new') }}" class="btn btn-primary">New Domain</a> {% if is_admin() %}<a href="{{ url_for('domains.domain_new') }}" class="btn btn-primary">New Domain</a>{% endif %}
</div> </div>
{% if not domains %} {% if not domains %}

View File

@@ -4,7 +4,7 @@
{% block content %} {% block content %}
<div class="page-header"> <div class="page-header">
<h1>Entities</h1> <h1>Entities</h1>
<a href="{{ url_for('entities.entity_new') }}" class="btn btn-primary">+ Add Entity</a> {% if is_admin() %}<a href="{{ url_for('entities.entity_new') }}" class="btn btn-primary">+ Add Entity</a>{% endif %}
</div> </div>
{% if not grouped %} {% if not grouped %}

View File

@@ -14,11 +14,41 @@
entity combinations against real-world physics. entity combinations against real-world physics.
</p> </p>
<div class="hero-actions"> <div class="hero-actions">
{% if is_admin() %}
<a href="{{ url_for('pipeline.pipeline_form') }}" class="btn btn-primary">Run Pipeline</a> <a href="{{ url_for('pipeline.pipeline_form') }}" class="btn btn-primary">Run Pipeline</a>
<a href="{{ url_for('results.results_index') }}" class="btn">View Results</a> {% endif %}
<a href="{{ url_for('results.results_index') }}" class="btn{% if not is_admin() %} btn-primary{% endif %}">View Results</a>
</div> </div>
</div> </div>
{% if top_concepts %}
<!-- Best concept per domain -->
<h2 class="section-heading">Top Concepts</h2>
<p class="section-desc">
The highest-scoring surviving combination in each domain, out of
{{ stats.combinations }} generated.
</p>
<div class="card">
<table>
<thead><tr><th>Domain</th><th>Concept</th><th>Score</th><th></th></tr></thead>
<tbody>
{% for domain, r in top_concepts %}
<tr>
<td>{{ domain.name }}</td>
<td>{{ r.combination.entities|map(attribute='name')|join(' + ') }}</td>
<td class="score-cell">{{ "%.4f"|format(r.composite_score) }}</td>
<td>
<a href="{{ url_for('results.result_detail', domain_name=domain.name, combo_id=r.combination.id) }}"
class="btn btn-sm">View</a>
<a href="{{ url_for('results.results_domain', domain_name=domain.name) }}" class="btn btn-sm">All</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
<!-- How It Works --> <!-- How It Works -->
<h2 class="section-heading">How It Works</h2> <h2 class="section-heading">How It Works</h2>
<p class="section-desc"> <p class="section-desc">

View File

@@ -0,0 +1,16 @@
{% extends "base.html" %}
{% block title %}Admin login — PhysCom{% endblock %}
{% block content %}
<h1>Admin login</h1>
<div class="card">
{% if error %}<div class="flash flash-error">{{ error }}</div>{% endif %}
<form method="post" class="public">
<div class="form-group">
<label for="token">Admin token</label>
<input type="password" id="token" name="token" required autofocus autocomplete="current-password">
</div>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
</div>
{% endblock %}

View File

@@ -58,7 +58,7 @@
{% if status_filter or rating_filter %} {% if status_filter or rating_filter %}
<p class="empty">No results matching that filter in this domain.</p> <p class="empty">No results matching that filter in this domain.</p>
{% else %} {% else %}
<p class="empty">No results for this domain yet. <a href="{{ url_for('pipeline.pipeline_form') }}">Run the pipeline</a> first.</p> <p class="empty">No results for this domain yet.{% if is_admin() %} <a href="{{ url_for('pipeline.pipeline_form') }}">Run the pipeline</a> first.{% endif %}</p>
{% endif %} {% endif %}
{% else %} {% else %}
<table> <table>

View File

@@ -388,3 +388,17 @@ def test_agreement_key_reaches_valid_status(bicycle, human_pedalling, food_calor
result = resolver.resolve(Combination(entities=[bicycle, human_pedalling, food_calories])) result = resolver.resolve(Combination(entities=[bicycle, human_pedalling, food_calories]))
assert result.status == "valid" assert result.status == "valid"
assert not any("medium" in w for w in result.warnings) assert not any("medium" in w for w in result.warnings)
def test_domain_requirement_is_default_deny():
"""A "domain"-category requires fails unless the domain declares that key."""
resolver = ConstraintResolver()
sail = Entity(name="Wind Sail", dimension="actuator", dependencies=[
Dependency("domain", "prevailing_wind", "true", None, "requires"),
])
combo = Combination(entities=[sail])
medium_only = [DomainConstraint("medium", ["ground"])]
assert resolver.check_domain_constraints(combo, medium_only).status == "p1_fail"
windy = medium_only + [DomainConstraint("prevailing_wind", ["true"])]
assert resolver.check_domain_constraints(combo, windy).status != "p1_fail"
assert resolver.resolve(combo).warnings == []

View File

@@ -75,3 +75,32 @@ def test_blocked_combos_not_scored(seeded_repo):
# block, not a bug (see Pipeline._decide_masses' `feasible` return). # block, not a bug (see Pipeline._decide_masses' `feasible` return).
assert result.pass2_estimated < result.total_generated assert result.pass2_estimated < result.total_generated
assert result.pass2_estimated <= result.pass1_valid + result.pass1_conditional assert result.pass2_estimated <= result.pass1_valid + result.pass1_conditional
def test_hover_floor_and_mission_payload_are_hard(seeded_repo):
"""Rotorcraft must keep >= its min_specific_power at the build the
optimizer actually picks (payload included), and an actuator that can
never reach it is infeasible rather than silently floored."""
from physcom.models.combination import Combination
from physcom.engine.pipeline import _carried_payload
domain = seeded_repo.get_domain("urban_commuting")
assert domain.requirements == {"payload": 100.0, "trip_range": 50000.0}
bounds = {mb.metric_name: mb for mb in domain.metric_bounds}
units = {mb.metric_name: mb.unit for mb in domain.metric_bounds}
pipeline = Pipeline(seeded_repo, ConstraintResolver(), Scorer(domain))
rotor = seeded_repo.get_entity_by_name("platform", "Rotorcraft")
fuel = seeded_repo.get_entity_by_name("energy_storage", "Liquid Fuel")
piston = seeded_repo.get_entity_by_name("actuator", "Piston Engine")
ctx = pipeline._physics_context(Combination(entities=[rotor, piston, fuel]), bounds, domain.requirements)
a, s, p, feasible = pipeline._decide_masses(ctx, bounds, units)
gross = p + a + s + _carried_payload(ctx, a)
assert feasible
assert ctx.k_act * a / gross >= 140.0 - 1e-6
raw = pipeline._raw_physics_from_masses(ctx, a, s, bounds, units, platform_mass=p)
assert raw["range_fuel"] >= 50000.0
steam = seeded_repo.get_entity_by_name("actuator", "Steam Engine")
ctx = pipeline._physics_context(Combination(entities=[rotor, steam, fuel]), bounds, domain.requirements)
assert pipeline._decide_masses(ctx, bounds, units)[3] is False

View File

@@ -37,9 +37,13 @@ class TestNormalize:
assert normalize(50.0, 100.0, 50.0) == 0.0 assert normalize(50.0, 100.0, 50.0) == 0.0
def test_zero_min(self): def test_zero_min(self):
"""norm_min=0 should work (log1p(0)=0).""" """norm_min=0 has no ratio to log -- falls back to linear."""
result = normalize(0.5, 0.0, 1.0) assert normalize(0.5, 0.0, 1.0) == 0.5
assert 0.0 < result < 1.0
def test_scale_invariant(self):
"""Same ratio within the range -> same score, whatever the magnitude."""
assert abs(normalize(1e-4, 1e-5, 1e-3) - normalize(10.0, 1.0, 100.0)) < 1e-12
assert abs(normalize(10.0, 1.0, 100.0) - 0.5) < 1e-12
class TestCompositeScore: class TestCompositeScore:
@@ -110,5 +114,5 @@ class TestScorer:
cost_expensive = next(s for s in result_expensive.scores if s.metric_name == "cost_efficiency") cost_expensive = next(s for s in result_expensive.scores if s.metric_name == "cost_efficiency")
assert cost_cheap.normalized_score > cost_expensive.normalized_score assert cost_cheap.normalized_score > cost_expensive.normalized_score
assert cost_cheap.normalized_score > 0.9 # near the best assert cost_cheap.normalized_score > 0.85 # 2x the floor of a 200x range
assert cost_expensive.normalized_score < 0.1 # near the worst assert cost_expensive.normalized_score < 0.1 # near the worst

160
tests/test_web_access.py Normal file
View File

@@ -0,0 +1,160 @@
"""Web UI: read-only public mode, admin login, and a GET smoke test of every page."""
from __future__ import annotations
import pytest
from physcom.db.repository import Repository
from physcom.db.schema import init_db
from physcom.engine.constraint_resolver import ConstraintResolver
from physcom.engine.pipeline import Pipeline
from physcom.engine.scorer import Scorer
from physcom.seed.transport_example import load_transport_seed
TOKEN = "test-admin-token"
@pytest.fixture(scope="module")
def db_file(tmp_path_factory):
path = tmp_path_factory.mktemp("web") / "physcom.db"
repo = Repository(init_db(path))
load_transport_seed(repo)
domain = repo.get_domain("urban_commuting")
Pipeline(repo, ConstraintResolver(), Scorer(domain)).run(
domain, ["platform", "actuator", "energy_storage"],
score_threshold=0.01, passes=[1, 2, 3],
)
ids = {
"entity_id": repo.list_entities()[0].id,
"domain_id": domain.id,
"combo_id": next(
r["combination"].id for r in repo.get_all_results("urban_commuting")
if r["pass_reached"] >= 3
),
}
repo.conn.close()
return path, ids
def _app(monkeypatch, db_file, token: str | None):
from physcom_web.app import create_app
monkeypatch.setenv("PHYSCOM_DB", str(db_file[0]))
monkeypatch.setenv("FLASK_SECRET_KEY", "test")
if token:
monkeypatch.setenv("PHYSCOM_ADMIN_TOKEN", token)
else:
monkeypatch.delenv("PHYSCOM_ADMIN_TOKEN", raising=False)
return create_app()
@pytest.fixture
def visitor(monkeypatch, db_file):
return _app(monkeypatch, db_file, TOKEN).test_client()
@pytest.fixture
def admin(monkeypatch, db_file):
client = _app(monkeypatch, db_file, TOKEN).test_client()
assert client.post("/login", data={"token": TOKEN}).status_code == 302
return client
def _public_pages(ids):
return [
"/", "/entities/", f"/entities/{ids['entity_id']}",
"/domains/", f"/domains/{ids['domain_id']}",
"/results/", "/results/urban_commuting",
f"/results/urban_commuting/{ids['combo_id']}",
"/login",
]
def _admin_pages():
return ["/admin/", "/pipeline/", "/entities/new", "/domains/new", "/admin/snapshot/export"]
def test_visitor_can_browse(visitor, db_file):
for url in _public_pages(db_file[1]):
assert visitor.get(url).status_code == 200, url
def test_visitor_cannot_reach_admin_pages(visitor):
for url in _admin_pages():
resp = visitor.get(url)
assert resp.status_code == 302 and "/login" in resp.location, url
def test_visitor_cannot_write(visitor, db_file):
ids = db_file[1]
for url in [
"/admin/wipe", "/admin/reseed", "/pipeline/run",
f"/entities/{ids['entity_id']}/delete", f"/domains/{ids['domain_id']}/delete",
"/results/urban_commuting/reset",
f"/results/urban_commuting/{ids['combo_id']}/review",
]:
assert visitor.post(url).status_code == 403, url
def test_visitor_can_explore(visitor, db_file):
url = f"/results/urban_commuting/{db_file[1]['combo_id']}/explore"
assert visitor.post(url, data={"platform_mass": "inf"}).status_code == 200
def test_home_lists_top_concept(visitor):
html = visitor.get("/").get_data(as_text=True)
assert "Top Concepts" in html and "urban_commuting" in html
def test_visitor_pages_hide_write_controls(visitor):
html = visitor.get("/").get_data(as_text=True)
assert 'class="readonly"' in html
assert "/admin/" not in html and "/pipeline/" not in html
def test_wrong_token_rejected(visitor):
assert visitor.post("/login", data={"token": "nope"}).status_code == 401
assert visitor.get("/admin/").status_code == 302
def test_no_token_means_no_login(monkeypatch, db_file):
client = _app(monkeypatch, db_file, None).test_client()
assert client.post("/login", data={"token": ""}).status_code == 401
assert client.post("/admin/wipe").status_code == 403
def test_login_redirect_stays_on_site(visitor):
resp = visitor.post("/login?next=//evil.example", data={"token": TOKEN})
assert resp.location == "/"
resp = visitor.post("/login?next=/admin/", data={"token": TOKEN})
assert resp.location == "/admin/"
def test_admin_can_reach_everything(admin, db_file):
for url in _public_pages(db_file[1]) + _admin_pages():
assert admin.get(url).status_code == 200, url
html = admin.get("/").get_data(as_text=True)
assert 'class="readonly"' not in html
def test_debug_off_by_default(monkeypatch, db_file):
import physcom_web.app as web
seen = {}
monkeypatch.delenv("FLASK_DEBUG", raising=False)
monkeypatch.delenv("PHYSCOM_ADMIN_TOKEN", raising=False)
monkeypatch.setenv("PHYSCOM_DB", str(db_file[0]))
monkeypatch.setattr("flask.Flask.run", lambda self, **kw: seen.update(kw, app=self))
web.run()
assert seen["debug"] is False and seen["host"] == "127.0.0.1"
# Dev server shows the public view too; the printed token logs in.
client = seen["app"].test_client()
assert client.get("/admin/").status_code == 302
token = web.os.environ["PHYSCOM_ADMIN_TOKEN"]
assert client.post("/login", data={"token": token}).status_code == 302
assert client.get("/admin/").status_code == 200
def test_cli_demo_if_empty_skips_populated_db(db_file):
from click.testing import CliRunner
from physcom.cli import main
result = CliRunner().invoke(main, ["--db", str(db_file[0]), "demo", "--if-empty"])
assert result.exit_code == 0 and "skipping" in result.output