- 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>
324 lines
11 KiB
Python
324 lines
11 KiB
Python
"""Database snapshot export/import — JSON-based, uses natural keys."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import asdict
|
|
from datetime import datetime, timezone
|
|
|
|
from physcom.db.repository import Repository
|
|
from physcom.models.entity import Entity, Dependency
|
|
from physcom.models.domain import Domain, DomainConstraint, FreeVariable, MetricBound, MetricFormula
|
|
from physcom.models.combination import Combination
|
|
|
|
|
|
def export_snapshot(repo: Repository) -> dict:
|
|
"""Export the full database state to a portable dict (natural keys, no numeric IDs)."""
|
|
dimensions = repo.list_dimensions()
|
|
entities = repo.list_entities()
|
|
domains = repo.list_domains()
|
|
combinations = repo.list_combinations()
|
|
|
|
# Build entity id → (dimension, name) lookup
|
|
eid_to_ref: dict[int, list[str]] = {
|
|
e.id: [e.dimension, e.name] for e in entities
|
|
}
|
|
|
|
# Build metric id → name lookup
|
|
metric_rows = repo.conn.execute("SELECT id, name FROM metrics").fetchall()
|
|
mid_to_name: dict[int, str] = {r["id"]: r["name"] for r in metric_rows}
|
|
|
|
# Export dimensions
|
|
dim_list = [
|
|
{"name": d["name"], "description": d.get("description") or ""}
|
|
for d in dimensions
|
|
]
|
|
|
|
# Export entities with dependencies
|
|
entity_list = []
|
|
for e in entities:
|
|
deps = []
|
|
for dep in e.dependencies:
|
|
deps.append({
|
|
"category": dep.category,
|
|
"key": dep.key,
|
|
"value": dep.value,
|
|
"unit": dep.unit,
|
|
"constraint_type": dep.constraint_type,
|
|
})
|
|
entity_list.append({
|
|
"name": e.name,
|
|
"dimension": e.dimension,
|
|
"description": e.description,
|
|
"dependencies": deps,
|
|
})
|
|
|
|
# Export domains with metric_bounds and constraints
|
|
domain_list = []
|
|
for d in domains:
|
|
mbs = []
|
|
for mb in d.metric_bounds:
|
|
mbs.append({
|
|
"metric_name": mb.metric_name,
|
|
"weight": mb.weight,
|
|
"norm_min": mb.norm_min,
|
|
"norm_max": mb.norm_max,
|
|
"unit": mb.unit,
|
|
"lower_is_better": mb.lower_is_better,
|
|
})
|
|
dcs = []
|
|
for dc in d.constraints:
|
|
dcs.append({
|
|
"key": dc.key,
|
|
"allowed_values": dc.allowed_values,
|
|
})
|
|
fvs = [{k: v for k, v in asdict(fv).items() if k != "id"} for fv in d.free_variables]
|
|
mfs = [{k: v for k, v in asdict(mf).items() if k != "id"} for mf in d.metric_formulas]
|
|
domain_list.append({
|
|
"name": d.name,
|
|
"description": d.description,
|
|
"metric_bounds": mbs,
|
|
"constraints": dcs,
|
|
"requirements": d.requirements,
|
|
"free_variables": fvs,
|
|
"metric_formulas": mfs,
|
|
})
|
|
|
|
# Export combinations
|
|
combo_list = []
|
|
for c in combinations:
|
|
entity_refs = [eid_to_ref[e.id] for e in c.entities if e.id in eid_to_ref]
|
|
combo_list.append({
|
|
"entity_refs": entity_refs,
|
|
"status": c.status,
|
|
"block_reason": c.block_reason,
|
|
})
|
|
|
|
# Export results and scores (per combo per domain)
|
|
result_list = []
|
|
score_list = []
|
|
domain_id_to_name: dict[int, str] = {d.id: d.name for d in domains}
|
|
|
|
for c in combinations:
|
|
for res in repo.get_results_for_combination(c.id):
|
|
domain_name = domain_id_to_name.get(res["domain_id"])
|
|
if not domain_name:
|
|
continue
|
|
entity_refs = [eid_to_ref[e.id] for e in c.entities if e.id in eid_to_ref]
|
|
result_list.append({
|
|
"entity_refs": entity_refs,
|
|
"domain": domain_name,
|
|
"composite_score": res["composite_score"],
|
|
"novelty_flag": res.get("novelty_flag"),
|
|
"llm_review": res.get("llm_review"),
|
|
"human_notes": res.get("human_notes"),
|
|
"pass_reached": res["pass_reached"],
|
|
"domain_block_reason": res.get("domain_block_reason"),
|
|
})
|
|
|
|
for sc in repo.get_combination_scores(c.id, res["domain_id"]):
|
|
score_list.append({
|
|
"entity_refs": entity_refs,
|
|
"domain": domain_name,
|
|
"metric": mid_to_name.get(sc["metric_id"], ""),
|
|
"raw_value": sc["raw_value"],
|
|
"normalized_score": sc["normalized_score"],
|
|
"estimation_method": sc.get("estimation_method"),
|
|
"confidence": sc.get("confidence"),
|
|
})
|
|
|
|
return {
|
|
"version": 1,
|
|
"exported_at": datetime.now(timezone.utc).isoformat(),
|
|
"dimensions": dim_list,
|
|
"entities": entity_list,
|
|
"domains": domain_list,
|
|
"combinations": combo_list,
|
|
"results": result_list,
|
|
"scores": score_list,
|
|
}
|
|
|
|
|
|
def import_snapshot(repo: Repository, data: dict, *, clear: bool = False) -> dict:
|
|
"""Import a snapshot dict into the database.
|
|
|
|
Args:
|
|
repo: Target repository.
|
|
data: Snapshot dict (as produced by export_snapshot).
|
|
clear: If True, wipe all existing data before importing.
|
|
|
|
Returns:
|
|
Counts dict with keys: dimensions, entities, domains, combinations, results, scores.
|
|
"""
|
|
if clear:
|
|
repo.clear_all()
|
|
|
|
counts = {
|
|
"dimensions": 0,
|
|
"entities": 0,
|
|
"domains": 0,
|
|
"combinations": 0,
|
|
"results": 0,
|
|
"scores": 0,
|
|
}
|
|
|
|
# 1. Dimensions
|
|
for d in data.get("dimensions", []):
|
|
repo.ensure_dimension(d["name"], d.get("description", ""))
|
|
counts["dimensions"] += 1
|
|
|
|
# 2. Entities (with dependencies)
|
|
for e_data in data.get("entities", []):
|
|
deps = [
|
|
Dependency(
|
|
category=dep["category"],
|
|
key=dep["key"],
|
|
value=dep["value"],
|
|
unit=dep.get("unit"),
|
|
constraint_type=dep.get("constraint_type", "requires"),
|
|
)
|
|
for dep in e_data.get("dependencies", [])
|
|
]
|
|
existing = repo.get_entity_by_name(e_data["dimension"], e_data["name"])
|
|
if existing:
|
|
repo.replace_entity_dependencies(existing.id, deps)
|
|
else:
|
|
entity = Entity(
|
|
name=e_data["name"],
|
|
dimension=e_data["dimension"],
|
|
description=e_data.get("description", ""),
|
|
dependencies=deps,
|
|
)
|
|
repo.add_entity(entity)
|
|
counts["entities"] += 1
|
|
|
|
# 3. Domains (with metric_bounds and constraints)
|
|
for d_data in data.get("domains", []):
|
|
existing = repo.get_domain(d_data["name"])
|
|
if not existing:
|
|
mbs = [
|
|
MetricBound(
|
|
metric_name=mb["metric_name"],
|
|
weight=mb["weight"],
|
|
norm_min=mb["norm_min"],
|
|
norm_max=mb["norm_max"],
|
|
unit=mb.get("unit", ""),
|
|
lower_is_better=mb.get("lower_is_better", False),
|
|
)
|
|
for mb in d_data.get("metric_bounds", [])
|
|
]
|
|
dcs = [
|
|
DomainConstraint(
|
|
key=dc["key"],
|
|
allowed_values=dc.get("allowed_values", []),
|
|
)
|
|
for dc in d_data.get("constraints", [])
|
|
]
|
|
fvs = [FreeVariable(**fv) for fv in d_data.get("free_variables", [])]
|
|
mfs = [MetricFormula(**mf) for mf in d_data.get("metric_formulas", [])]
|
|
domain = Domain(
|
|
name=d_data["name"],
|
|
description=d_data.get("description", ""),
|
|
metric_bounds=mbs,
|
|
constraints=dcs,
|
|
requirements=d_data.get("requirements", {}),
|
|
free_variables=fvs,
|
|
metric_formulas=mfs,
|
|
)
|
|
repo.add_domain(domain)
|
|
counts["domains"] += 1
|
|
|
|
# Build lookup: (dimension, name) → entity id
|
|
all_entities = repo.list_entities()
|
|
ref_to_eid: dict[tuple[str, str], int] = {
|
|
(e.dimension, e.name): e.id for e in all_entities
|
|
}
|
|
|
|
# Build lookup: domain name → id
|
|
all_domains = repo.list_domains()
|
|
domain_name_to_id: dict[str, int] = {d.name: d.id for d in all_domains}
|
|
|
|
# Build lookup: metric name → id
|
|
metric_rows = repo.conn.execute("SELECT id, name FROM metrics").fetchall()
|
|
metric_name_to_id: dict[str, int] = {r["name"]: r["id"] for r in metric_rows}
|
|
|
|
# 4. Combinations
|
|
for c_data in data.get("combinations", []):
|
|
entity_refs = c_data.get("entity_refs", [])
|
|
entity_objs = []
|
|
skip = False
|
|
for ref in entity_refs:
|
|
eid = ref_to_eid.get((ref[0], ref[1]))
|
|
if eid is None:
|
|
skip = True
|
|
break
|
|
entity_objs.append(Entity(id=eid, name=ref[1], dimension=ref[0]))
|
|
if skip:
|
|
continue
|
|
combo = Combination(
|
|
entities=entity_objs,
|
|
status=c_data.get("status", "pending"),
|
|
block_reason=c_data.get("block_reason"),
|
|
)
|
|
repo.save_combination(combo)
|
|
counts["combinations"] += 1
|
|
|
|
# 5. Results
|
|
for r_data in data.get("results", []):
|
|
entity_refs = r_data.get("entity_refs", [])
|
|
entity_objs = []
|
|
skip = False
|
|
for ref in entity_refs:
|
|
eid = ref_to_eid.get((ref[0], ref[1]))
|
|
if eid is None:
|
|
skip = True
|
|
break
|
|
entity_objs.append(Entity(id=eid, name=ref[1], dimension=ref[0]))
|
|
if skip:
|
|
continue
|
|
combo = Combination(entities=entity_objs)
|
|
combo = repo.save_combination(combo)
|
|
domain_id = domain_name_to_id.get(r_data["domain"])
|
|
if combo.id is None or domain_id is None:
|
|
continue
|
|
repo.save_result(
|
|
combo.id,
|
|
domain_id,
|
|
composite_score=r_data.get("composite_score", 0.0),
|
|
pass_reached=r_data.get("pass_reached", 0),
|
|
novelty_flag=r_data.get("novelty_flag"),
|
|
llm_review=r_data.get("llm_review"),
|
|
human_notes=r_data.get("human_notes"),
|
|
domain_block_reason=r_data.get("domain_block_reason"),
|
|
)
|
|
counts["results"] += 1
|
|
|
|
# 6. Scores
|
|
for s_data in data.get("scores", []):
|
|
entity_refs = s_data.get("entity_refs", [])
|
|
entity_objs = []
|
|
skip = False
|
|
for ref in entity_refs:
|
|
eid = ref_to_eid.get((ref[0], ref[1]))
|
|
if eid is None:
|
|
skip = True
|
|
break
|
|
entity_objs.append(Entity(id=eid, name=ref[1], dimension=ref[0]))
|
|
if skip:
|
|
continue
|
|
combo = Combination(entities=entity_objs)
|
|
combo = repo.save_combination(combo)
|
|
domain_id = domain_name_to_id.get(s_data["domain"])
|
|
metric_id = metric_name_to_id.get(s_data.get("metric", ""))
|
|
if combo.id is None or domain_id is None or metric_id is None:
|
|
continue
|
|
repo.save_scores(combo.id, domain_id, [{
|
|
"metric_id": metric_id,
|
|
"raw_value": s_data.get("raw_value"),
|
|
"normalized_score": s_data.get("normalized_score"),
|
|
"estimation_method": s_data.get("estimation_method"),
|
|
"confidence": s_data.get("confidence"),
|
|
}])
|
|
counts["scores"] += 1
|
|
|
|
return counts
|