datacenter-twin 2.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- datacenter_twin/__init__.py +3 -0
- datacenter_twin/__main__.py +3 -0
- datacenter_twin/api.py +161 -0
- datacenter_twin/browser.py +69 -0
- datacenter_twin/calculations.py +72 -0
- datacenter_twin/catalog.py +67 -0
- datacenter_twin/cli.py +143 -0
- datacenter_twin/continuity.py +796 -0
- datacenter_twin/contracts.py +232 -0
- datacenter_twin/demo.py +233 -0
- datacenter_twin/emt.py +229 -0
- datacenter_twin/engine.py +126 -0
- datacenter_twin/output.py +63 -0
- datacenter_twin/reporting.py +380 -0
- datacenter_twin/research/__init__.py +150 -0
- datacenter_twin/research/__main__.py +43 -0
- datacenter_twin/research/common.py +95 -0
- datacenter_twin/research/datacenter_init_from_pf_qss.py +67 -0
- datacenter_twin/research/datacenter_port_model.py +159 -0
- datacenter_twin/research/gfl_init_from_pf_qss_newton.py +69 -0
- datacenter_twin/research/gfl_port_model.py +98 -0
- datacenter_twin/research/gfm_init_from_pf_qss_newton.py +74 -0
- datacenter_twin/research/gfm_port_model.py +79 -0
- datacenter_twin/research/grid_network.py +653 -0
- datacenter_twin/research/model_comparison.py +234 -0
- datacenter_twin/research/model_validation.py +254 -0
- datacenter_twin/research/sdcib.py +519 -0
- datacenter_twin/research/sdcib_core.py +320 -0
- datacenter_twin/research/sm_init_from_pf_fsolve.py +87 -0
- datacenter_twin/research/sm_port_model.py +53 -0
- datacenter_twin/research/types.py +78 -0
- datacenter_twin/resources/azure-retail-snapshot.json +27 -0
- datacenter_twin/resources/catalog.json +176 -0
- datacenter_twin/resources/reference-site-v2.json +42 -0
- datacenter_twin/sensitivity.py +180 -0
- datacenter_twin/spectrum.py +44 -0
- datacenter_twin/topology.py +306 -0
- datacenter_twin-2.0.1.dist-info/METADATA +115 -0
- datacenter_twin-2.0.1.dist-info/RECORD +44 -0
- datacenter_twin-2.0.1.dist-info/WHEEL +5 -0
- datacenter_twin-2.0.1.dist-info/entry_points.txt +2 -0
- datacenter_twin-2.0.1.dist-info/licenses/LICENSE +202 -0
- datacenter_twin-2.0.1.dist-info/licenses/NOTICE +37 -0
- datacenter_twin-2.0.1.dist-info/top_level.txt +1 -0
datacenter_twin/api.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Loopback-only application surface for pure simulation and bundled evidence."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from fastapi import FastAPI, Request
|
|
9
|
+
from fastapi.responses import JSONResponse, Response
|
|
10
|
+
from starlette.concurrency import run_in_threadpool
|
|
11
|
+
from starlette.middleware.base import RequestResponseEndpoint
|
|
12
|
+
from starlette.middleware.cors import CORSMiddleware
|
|
13
|
+
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
|
14
|
+
from starlette.staticfiles import StaticFiles
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .browser import scenario_report, scenario_sweep
|
|
18
|
+
from .catalog import load_catalog, normalize_quote
|
|
19
|
+
from .continuity import simulate_continuity
|
|
20
|
+
from .contracts import MAX_SCENARIO_BYTES, InputError, Scenario, parse_json_document
|
|
21
|
+
from .demo import PRESETS, demo_scenario
|
|
22
|
+
from .engine import simulate
|
|
23
|
+
from .topology import SiteScenario
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _web_directory() -> Path:
|
|
27
|
+
"""Keep bundled evidence reachable in deeply nested Windows environments."""
|
|
28
|
+
directory = os.path.normpath((Path(__file__).parent / "web").absolute())
|
|
29
|
+
if os.name == "nt" and not directory.startswith("\\\\?\\"):
|
|
30
|
+
# Evidence filenames include full input hashes. Prefix the trusted,
|
|
31
|
+
# normalized installation root, never a path received from a client.
|
|
32
|
+
if directory.startswith("\\\\"):
|
|
33
|
+
directory = "\\\\?\\UNC\\" + directory[2:]
|
|
34
|
+
else:
|
|
35
|
+
directory = "\\\\?\\" + directory
|
|
36
|
+
return Path(directory)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def create_app() -> FastAPI:
|
|
40
|
+
app = FastAPI(
|
|
41
|
+
title="Datacenter Twin Lab",
|
|
42
|
+
version=__version__,
|
|
43
|
+
docs_url=None,
|
|
44
|
+
redoc_url=None,
|
|
45
|
+
description="Local synthetic calculations. No physical controls or persisted mutations.",
|
|
46
|
+
)
|
|
47
|
+
app.add_middleware(
|
|
48
|
+
TrustedHostMiddleware,
|
|
49
|
+
allowed_hosts=["localhost", "127.0.0.1", "[::1]", "testserver"],
|
|
50
|
+
)
|
|
51
|
+
app.add_middleware(
|
|
52
|
+
CORSMiddleware,
|
|
53
|
+
allow_origins=["http://127.0.0.1:5173", "http://localhost:5173"],
|
|
54
|
+
allow_methods=["GET", "POST"],
|
|
55
|
+
allow_headers=["Content-Type"],
|
|
56
|
+
)
|
|
57
|
+
slots = asyncio.Semaphore(2)
|
|
58
|
+
|
|
59
|
+
@app.middleware("http")
|
|
60
|
+
async def headers(request: Request, call_next: RequestResponseEndpoint) -> Response:
|
|
61
|
+
response = await call_next(request)
|
|
62
|
+
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
63
|
+
response.headers["Referrer-Policy"] = "no-referrer"
|
|
64
|
+
response.headers["Content-Security-Policy"] = (
|
|
65
|
+
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
|
66
|
+
"img-src 'self' data:; connect-src 'self'; "
|
|
67
|
+
"frame-ancestors 'none'; base-uri 'none'"
|
|
68
|
+
)
|
|
69
|
+
if request.url.path.startswith("/api/"):
|
|
70
|
+
response.headers["Cache-Control"] = "no-store"
|
|
71
|
+
return response
|
|
72
|
+
|
|
73
|
+
@app.exception_handler(InputError)
|
|
74
|
+
async def input_error(_request: Request, exc: Exception) -> JSONResponse:
|
|
75
|
+
return JSONResponse(status_code=422, content={"error": str(exc)})
|
|
76
|
+
|
|
77
|
+
async def payload(request: Request) -> Any:
|
|
78
|
+
if (
|
|
79
|
+
request.headers.get("content-type", "").split(";")[0].strip().lower()
|
|
80
|
+
!= "application/json"
|
|
81
|
+
):
|
|
82
|
+
raise InputError(
|
|
83
|
+
"Send application/json with the complete scenario returned by /api/v1/demo"
|
|
84
|
+
)
|
|
85
|
+
chunks, size = [], 0
|
|
86
|
+
async for chunk in request.stream():
|
|
87
|
+
size += len(chunk)
|
|
88
|
+
if size > MAX_SCENARIO_BYTES:
|
|
89
|
+
raise InputError("Scenario request exceeds the 4 MiB input limit")
|
|
90
|
+
chunks.append(chunk)
|
|
91
|
+
return parse_json_document(b"".join(chunks))
|
|
92
|
+
|
|
93
|
+
@app.get("/api/v1/health")
|
|
94
|
+
def health() -> dict[str, str]:
|
|
95
|
+
return {
|
|
96
|
+
"status": "ok",
|
|
97
|
+
"version": __version__,
|
|
98
|
+
"mode": "SIMULATED",
|
|
99
|
+
"scope": "local_stateless",
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
@app.get("/api/v1/presets")
|
|
103
|
+
def presets() -> list[dict[str, str]]:
|
|
104
|
+
return [{"id": key, "name": name} for key, name in PRESETS.items()]
|
|
105
|
+
|
|
106
|
+
@app.get("/api/v1/demo")
|
|
107
|
+
def demo(preset: str = "utility_loss") -> dict[str, Any]:
|
|
108
|
+
return demo_scenario(preset).to_dict()
|
|
109
|
+
|
|
110
|
+
@app.post(
|
|
111
|
+
"/api/v1/simulations",
|
|
112
|
+
summary="Calculate a schema-v2 scenario without persisting or actuating anything",
|
|
113
|
+
)
|
|
114
|
+
async def run(request: Request) -> dict[str, Any]:
|
|
115
|
+
scenario = SiteScenario.from_dict(await payload(request))
|
|
116
|
+
async with slots:
|
|
117
|
+
result = await run_in_threadpool(simulate_continuity, scenario)
|
|
118
|
+
return result.to_dict()
|
|
119
|
+
|
|
120
|
+
@app.post("/api/v1/planning", summary="Evaluate an existing schema-v1 PUE scenario")
|
|
121
|
+
async def planning(request: Request) -> dict[str, Any]:
|
|
122
|
+
return simulate(Scenario.from_dict(await payload(request)))
|
|
123
|
+
|
|
124
|
+
@app.get("/api/v1/catalog")
|
|
125
|
+
def catalog() -> dict[str, Any]:
|
|
126
|
+
return load_catalog()
|
|
127
|
+
|
|
128
|
+
@app.post("/api/v1/reports", summary="Render a reproducible report from a validated scenario")
|
|
129
|
+
async def report(request: Request) -> dict[str, Any]:
|
|
130
|
+
data = await payload(request)
|
|
131
|
+
async with slots:
|
|
132
|
+
return await run_in_threadpool(scenario_report, data)
|
|
133
|
+
|
|
134
|
+
@app.post("/api/v1/sweeps", summary="Run a bounded one-parameter sensitivity sweep")
|
|
135
|
+
async def sweep(request: Request) -> dict[str, Any]:
|
|
136
|
+
data = await payload(request)
|
|
137
|
+
async with slots:
|
|
138
|
+
return await run_in_threadpool(scenario_sweep, data)
|
|
139
|
+
|
|
140
|
+
@app.post(
|
|
141
|
+
"/api/v1/quotes/normalize",
|
|
142
|
+
summary="Normalize an assumed rate using the selected offering's declared billing unit",
|
|
143
|
+
)
|
|
144
|
+
async def quote(request: Request) -> dict[str, Any]:
|
|
145
|
+
return normalize_quote(await payload(request))
|
|
146
|
+
|
|
147
|
+
web = _web_directory()
|
|
148
|
+
if (web / "index.html").is_file():
|
|
149
|
+
app.mount("/", StaticFiles(directory=web, html=True), name="dashboard")
|
|
150
|
+
else:
|
|
151
|
+
|
|
152
|
+
@app.get("/")
|
|
153
|
+
def build_required() -> JSONResponse:
|
|
154
|
+
return JSONResponse(
|
|
155
|
+
status_code=503,
|
|
156
|
+
content={
|
|
157
|
+
"error": ("Dashboard is not built. Run npm ci and npm run build in apps/web.")
|
|
158
|
+
},
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
return app
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""JSON-only adapter for the original engine running inside a browser worker.
|
|
2
|
+
|
|
3
|
+
No networking, filesystem writes, dynamic Python execution, or shared service.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from typing import Any
|
|
8
|
+
from urllib.parse import parse_qs, urlsplit
|
|
9
|
+
|
|
10
|
+
from .catalog import load_catalog, normalize_quote
|
|
11
|
+
from .continuity import simulate_continuity
|
|
12
|
+
from .contracts import MAX_SCENARIO_BYTES, InputError, Scenario, parse_json_document
|
|
13
|
+
from .demo import PRESETS, demo_scenario
|
|
14
|
+
from .engine import simulate as simulate_planning
|
|
15
|
+
from .reporting import render_html, render_markdown
|
|
16
|
+
from .sensitivity import sweep_continuity
|
|
17
|
+
from .topology import SiteScenario
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def scenario_report(payload: dict[str, Any]) -> dict[str, Any]:
|
|
21
|
+
if not isinstance(payload, dict) or set(payload) != {"scenario", "format"}:
|
|
22
|
+
raise InputError("Report requires scenario and format")
|
|
23
|
+
if payload["format"] not in ("markdown", "html"):
|
|
24
|
+
raise InputError("Report format must be markdown or html")
|
|
25
|
+
run = simulate_continuity(SiteScenario.from_dict(payload["scenario"])).to_dict()
|
|
26
|
+
renderer = render_html if payload["format"] == "html" else render_markdown
|
|
27
|
+
return {"format": payload["format"], "text": renderer(run), "run_id": run["run_id"]}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def scenario_sweep(payload: dict[str, Any]) -> dict[str, Any]:
|
|
31
|
+
if not isinstance(payload, dict) or set(payload) != {"scenario", "parameter", "values"}:
|
|
32
|
+
raise InputError("Sweep requires scenario, parameter, and values")
|
|
33
|
+
return sweep_continuity(
|
|
34
|
+
SiteScenario.from_dict(payload["scenario"]), payload["parameter"], payload["values"]
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def dispatch_json(path: str, body: str = "null") -> str:
|
|
39
|
+
"""Dispatch a fixed set of operations; user input is JSON, never Python code."""
|
|
40
|
+
if len(body.encode("utf-8")) > MAX_SCENARIO_BYTES:
|
|
41
|
+
raise InputError("Request exceeds the 4 MiB input limit")
|
|
42
|
+
route = urlsplit(path)
|
|
43
|
+
result: object
|
|
44
|
+
if route.path == "presets":
|
|
45
|
+
result = [{"id": key, "name": name} for key, name in PRESETS.items()]
|
|
46
|
+
elif route.path == "demo":
|
|
47
|
+
preset = parse_qs(route.query).get("preset", ["utility_loss"])[0]
|
|
48
|
+
result = demo_scenario(preset).to_dict()
|
|
49
|
+
elif route.path == "catalog":
|
|
50
|
+
result = load_catalog()
|
|
51
|
+
elif route.path in ("simulations", "quotes/normalize", "reports", "sweeps", "planning", "emt"):
|
|
52
|
+
payload = parse_json_document(body.encode("utf-8"))
|
|
53
|
+
if route.path == "emt":
|
|
54
|
+
from .emt import simulate_emt
|
|
55
|
+
|
|
56
|
+
result = simulate_emt(payload)
|
|
57
|
+
elif route.path == "simulations":
|
|
58
|
+
result = simulate_continuity(SiteScenario.from_dict(payload)).to_dict()
|
|
59
|
+
elif route.path == "planning":
|
|
60
|
+
result = simulate_planning(Scenario.from_dict(payload))
|
|
61
|
+
elif route.path == "quotes/normalize":
|
|
62
|
+
result = normalize_quote(payload)
|
|
63
|
+
elif route.path == "reports":
|
|
64
|
+
result = scenario_report(payload)
|
|
65
|
+
else:
|
|
66
|
+
result = scenario_sweep(payload)
|
|
67
|
+
else:
|
|
68
|
+
raise InputError("Unsupported browser operation")
|
|
69
|
+
return json.dumps(result, ensure_ascii=True, allow_nan=False, separators=(",", ":"))
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Small arithmetic primitives for future domain modules; no vendor prices."""
|
|
2
|
+
|
|
3
|
+
from decimal import Decimal, localcontext
|
|
4
|
+
from typing import Literal, TypedDict
|
|
5
|
+
|
|
6
|
+
from .contracts import InputError, number
|
|
7
|
+
from .engine import ARITHMETIC
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NodeCharge(TypedDict):
|
|
11
|
+
cost: Decimal | None
|
|
12
|
+
provisioned_gpu_hour_rate: Decimal | None
|
|
13
|
+
billing_unit: Literal["node_hour"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def node_charge(
|
|
17
|
+
billed_node_hours: object, node_hour_price: object, gpus_per_node: int
|
|
18
|
+
) -> NodeCharge:
|
|
19
|
+
hours = number(billed_node_hours, "billed_node_hours")
|
|
20
|
+
if type(gpus_per_node) is not int or gpus_per_node <= 0:
|
|
21
|
+
raise InputError("gpus_per_node: expected a positive integer")
|
|
22
|
+
rate = None if node_hour_price is None else number(node_hour_price, "node_hour_price")
|
|
23
|
+
with localcontext(ARITHMETIC):
|
|
24
|
+
return {
|
|
25
|
+
"cost": None if rate is None else hours * rate,
|
|
26
|
+
"provisioned_gpu_hour_rate": None if rate is None else rate / gpus_per_node,
|
|
27
|
+
"billing_unit": "node_hour",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def token_charge(
|
|
32
|
+
input_tokens: object,
|
|
33
|
+
output_tokens: object,
|
|
34
|
+
input_price_per_million: object,
|
|
35
|
+
output_price_per_million: object,
|
|
36
|
+
) -> Decimal | None:
|
|
37
|
+
inputs, outputs = number(input_tokens, "input_tokens"), number(output_tokens, "output_tokens")
|
|
38
|
+
for value in (inputs, outputs):
|
|
39
|
+
if value != value.to_integral_value():
|
|
40
|
+
raise InputError("Token counts must be whole numbers")
|
|
41
|
+
rates = [
|
|
42
|
+
None if value is None else number(value, label)
|
|
43
|
+
for value, label in (
|
|
44
|
+
(input_price_per_million, "input_price_per_million"),
|
|
45
|
+
(output_price_per_million, "output_price_per_million"),
|
|
46
|
+
)
|
|
47
|
+
]
|
|
48
|
+
input_rate, output_rate = rates
|
|
49
|
+
if input_rate is None or output_rate is None:
|
|
50
|
+
return None
|
|
51
|
+
with localcontext(ARITHMETIC):
|
|
52
|
+
return (inputs * input_rate + outputs * output_rate) / Decimal(1000000)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def battery_runtime_hours(deliverable_energy_kwh: object, load_kw: object) -> Decimal | None:
|
|
56
|
+
"""Energy is already deliverable at the load boundary; no efficiency inferred."""
|
|
57
|
+
energy, load = (
|
|
58
|
+
number(deliverable_energy_kwh, "deliverable_energy_kwh"),
|
|
59
|
+
number(load_kw, "load_kw"),
|
|
60
|
+
)
|
|
61
|
+
with localcontext(ARITHMETIC):
|
|
62
|
+
return None if load == 0 else energy / load
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def steady_heat_kw(
|
|
66
|
+
mass_flow_kg_s: object, specific_heat_kj_kg_k: object, delta_temperature_k: object
|
|
67
|
+
) -> Decimal:
|
|
68
|
+
flow = number(mass_flow_kg_s, "mass_flow_kg_s")
|
|
69
|
+
heat = number(specific_heat_kj_kg_k, "specific_heat_kj_kg_k", positive=True)
|
|
70
|
+
delta = number(delta_temperature_k, "delta_temperature_k")
|
|
71
|
+
with localcontext(ARITHMETIC):
|
|
72
|
+
return flow * heat * delta
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Source-backed options and explicit, illustrative billing normalization."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from decimal import Decimal, localcontext
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .contracts import InputError, _keys, _text, decimal_text, number
|
|
9
|
+
from .engine import ARITHMETIC
|
|
10
|
+
from .topology import bounded_integer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_catalog() -> dict[str, Any]:
|
|
14
|
+
resource = files("datacenter_twin").joinpath("resources/catalog.json")
|
|
15
|
+
result: dict[str, Any] = json.loads(resource.read_text(encoding="utf-8"))
|
|
16
|
+
return result
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def normalize_quote(data: dict[str, Any]) -> dict[str, Any]:
|
|
20
|
+
"""Hours are already billed node-hours per node, not an inferred invoice duration."""
|
|
21
|
+
_keys(data, {"offer_id", "node_count", "billed_hours", "assumed_rate"}, "quote")
|
|
22
|
+
offer_id = _text(data["offer_id"], "offer_id")
|
|
23
|
+
offer = next((o for o in load_catalog()["cloud_offers"] if o["id"] == offer_id), None)
|
|
24
|
+
if offer is None:
|
|
25
|
+
raise InputError("offer_id: unknown catalogue offer")
|
|
26
|
+
count = bounded_integer(data["node_count"], "node_count", 1, 100000)
|
|
27
|
+
hours = number(data["billed_hours"], "billed_hours")
|
|
28
|
+
rate = None if data["assumed_rate"] is None else number(data["assumed_rate"], "assumed_rate")
|
|
29
|
+
with localcontext(ARITHMETIC):
|
|
30
|
+
node_hours = count * hours
|
|
31
|
+
billing_multiplier = offer["gpu_count"] if offer["billing_unit"] == "gpu_hour" else 1
|
|
32
|
+
units = node_hours * billing_multiplier
|
|
33
|
+
total = None if rate is None else units * rate
|
|
34
|
+
node_rate = None if rate is None else rate * billing_multiplier
|
|
35
|
+
gpu_rate = None if node_rate is None else node_rate / offer["gpu_count"]
|
|
36
|
+
inputs = {
|
|
37
|
+
"offer_id": offer_id,
|
|
38
|
+
"node_count": count,
|
|
39
|
+
"billed_hours": decimal_text(hours),
|
|
40
|
+
"assumed_rate": None if rate is None else decimal_text(rate),
|
|
41
|
+
}
|
|
42
|
+
limitations = [
|
|
43
|
+
"User-entered rate is an assumption, not a fetched vendor quote.",
|
|
44
|
+
(
|
|
45
|
+
"Already-billed hours exclude invoice granularity, minimums,"
|
|
46
|
+
" taxes and ancillary charges."
|
|
47
|
+
),
|
|
48
|
+
(
|
|
49
|
+
"No workload throughput, utilization, region availability or "
|
|
50
|
+
"performance equivalence is inferred."
|
|
51
|
+
),
|
|
52
|
+
]
|
|
53
|
+
return {
|
|
54
|
+
"offer": offer,
|
|
55
|
+
"inputs": inputs,
|
|
56
|
+
"billing_unit": offer["billing_unit"],
|
|
57
|
+
"billed_units": decimal_text(units),
|
|
58
|
+
"billed_node_hours": decimal_text(node_hours),
|
|
59
|
+
"normalized_node_hour_rate": (None if node_rate is None else decimal_text(node_rate)),
|
|
60
|
+
"provisioned_gpu_hour_rate": (None if gpu_rate is None else decimal_text(gpu_rate)),
|
|
61
|
+
"cost": None if total is None else format(total.quantize(Decimal("0.01")), "f"),
|
|
62
|
+
"currency": offer["currency"],
|
|
63
|
+
"price_status": "unknown" if rate is None else "user_assumption",
|
|
64
|
+
"source_ids": offer["source_ids"],
|
|
65
|
+
"calibrated": False,
|
|
66
|
+
"limitations": limitations,
|
|
67
|
+
}
|
datacenter_twin/cli.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Offline CLI for synthetic scenario evaluation and comparison."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .contracts import InputError, load_json_document, load_scenario
|
|
11
|
+
from .demo import PRESETS
|
|
12
|
+
from .engine import compare, simulate
|
|
13
|
+
from .output import write_result
|
|
14
|
+
from .reporting import render_html, render_markdown
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str] | None = None) -> int:
|
|
18
|
+
parser = argparse.ArgumentParser(
|
|
19
|
+
description="Datacenter Twin Lab: synthetic planning, preliminary"
|
|
20
|
+
)
|
|
21
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
22
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
23
|
+
run = commands.add_parser("run", help="Evaluate a local JSON scenario")
|
|
24
|
+
run.add_argument("scenario", type=Path)
|
|
25
|
+
comparison = commands.add_parser(
|
|
26
|
+
"compare", help="Compare scenarios with identical IT load intervals"
|
|
27
|
+
)
|
|
28
|
+
comparison.add_argument("baseline", type=Path)
|
|
29
|
+
comparison.add_argument("alternative", type=Path)
|
|
30
|
+
continuity = commands.add_parser(
|
|
31
|
+
"simulate", help="Run a schema-v2 electrical continuity scenario"
|
|
32
|
+
)
|
|
33
|
+
source = continuity.add_mutually_exclusive_group()
|
|
34
|
+
source.add_argument("--scenario", type=Path)
|
|
35
|
+
source.add_argument("--preset", default="utility_loss", choices=tuple(PRESETS))
|
|
36
|
+
continuity.add_argument("--format", choices=["json", "markdown", "html"], default="json")
|
|
37
|
+
sweep = commands.add_parser(
|
|
38
|
+
"sweep", help="Sweep one field of a schema-v2 electrical continuity scenario"
|
|
39
|
+
)
|
|
40
|
+
sweep_source = sweep.add_mutually_exclusive_group()
|
|
41
|
+
sweep_source.add_argument("--scenario", type=Path)
|
|
42
|
+
sweep_source.add_argument("--preset", default="generator_failure", choices=tuple(PRESETS))
|
|
43
|
+
sweep.add_argument(
|
|
44
|
+
"--parameter",
|
|
45
|
+
required=True,
|
|
46
|
+
choices=[
|
|
47
|
+
"battery_initial_kwh",
|
|
48
|
+
"it_demand_kw",
|
|
49
|
+
"generator_start_delay_s",
|
|
50
|
+
"distribution_efficiency",
|
|
51
|
+
],
|
|
52
|
+
)
|
|
53
|
+
sweep.add_argument(
|
|
54
|
+
"--values",
|
|
55
|
+
nargs="+",
|
|
56
|
+
required=True,
|
|
57
|
+
help="One to twenty decimal values in caller order",
|
|
58
|
+
)
|
|
59
|
+
sweep.add_argument("--format", choices=["json", "markdown", "html"], default="json")
|
|
60
|
+
serve = commands.add_parser("serve", help="Serve the local API and built dashboard on loopback")
|
|
61
|
+
serve.add_argument("--port", type=int, default=8000)
|
|
62
|
+
for command in (run, comparison, continuity, sweep):
|
|
63
|
+
command.add_argument(
|
|
64
|
+
"--output", type=Path, help="Write the selected result format to this path"
|
|
65
|
+
)
|
|
66
|
+
command.add_argument("--force", action="store_true", help="Replace an existing result file")
|
|
67
|
+
args = parser.parse_args(argv)
|
|
68
|
+
if args.command == "serve":
|
|
69
|
+
if not 1 <= args.port <= 65535:
|
|
70
|
+
parser.error("--port must be from 1 to 65535")
|
|
71
|
+
try:
|
|
72
|
+
import uvicorn
|
|
73
|
+
|
|
74
|
+
from .api import create_app
|
|
75
|
+
except ImportError:
|
|
76
|
+
parser.error('Install the API extra: python -m pip install -e ".[api]"')
|
|
77
|
+
uvicorn.run(create_app(), host="127.0.0.1", port=args.port, access_log=False)
|
|
78
|
+
return 0
|
|
79
|
+
if args.force and not args.output:
|
|
80
|
+
parser.error("--force requires --output")
|
|
81
|
+
try:
|
|
82
|
+
if args.command == "run":
|
|
83
|
+
input_paths = [args.scenario]
|
|
84
|
+
result = simulate(load_scenario(args.scenario))
|
|
85
|
+
elif args.command == "compare":
|
|
86
|
+
input_paths = [args.baseline, args.alternative]
|
|
87
|
+
result = compare(load_scenario(args.baseline), load_scenario(args.alternative))
|
|
88
|
+
elif args.command == "simulate":
|
|
89
|
+
from .continuity import simulate_continuity
|
|
90
|
+
from .demo import demo_scenario
|
|
91
|
+
from .topology import SiteScenario
|
|
92
|
+
|
|
93
|
+
input_paths = [args.scenario] if args.scenario else []
|
|
94
|
+
scenario = (
|
|
95
|
+
SiteScenario.from_dict(load_json_document(args.scenario))
|
|
96
|
+
if args.scenario
|
|
97
|
+
else demo_scenario(args.preset)
|
|
98
|
+
)
|
|
99
|
+
result = simulate_continuity(scenario).to_dict()
|
|
100
|
+
if args.format == "markdown":
|
|
101
|
+
content = render_markdown(result)
|
|
102
|
+
elif args.format == "html":
|
|
103
|
+
content = render_html(result)
|
|
104
|
+
else:
|
|
105
|
+
payload = {
|
|
106
|
+
"generated_at_utc": datetime.now(UTC).isoformat(),
|
|
107
|
+
"result": result,
|
|
108
|
+
}
|
|
109
|
+
content = json.dumps(payload, indent=2, ensure_ascii=True, allow_nan=False) + "\n"
|
|
110
|
+
else:
|
|
111
|
+
from .demo import demo_scenario
|
|
112
|
+
from .sensitivity import sweep_continuity
|
|
113
|
+
from .topology import SiteScenario
|
|
114
|
+
|
|
115
|
+
input_paths = [args.scenario] if args.scenario else []
|
|
116
|
+
scenario = (
|
|
117
|
+
SiteScenario.from_dict(load_json_document(args.scenario))
|
|
118
|
+
if args.scenario
|
|
119
|
+
else demo_scenario(args.preset)
|
|
120
|
+
)
|
|
121
|
+
result = sweep_continuity(scenario, args.parameter, args.values)
|
|
122
|
+
if args.format == "markdown":
|
|
123
|
+
content = render_markdown(result)
|
|
124
|
+
elif args.format == "html":
|
|
125
|
+
content = render_html(result)
|
|
126
|
+
else:
|
|
127
|
+
payload = {
|
|
128
|
+
"generated_at_utc": datetime.now(UTC).isoformat(),
|
|
129
|
+
"result": result,
|
|
130
|
+
}
|
|
131
|
+
content = json.dumps(payload, indent=2, ensure_ascii=True, allow_nan=False) + "\n"
|
|
132
|
+
if args.command in ("run", "compare"):
|
|
133
|
+
payload = {"generated_at_utc": datetime.now(UTC).isoformat(), "result": result}
|
|
134
|
+
content = json.dumps(payload, indent=2, ensure_ascii=True, allow_nan=False) + "\n"
|
|
135
|
+
if args.output:
|
|
136
|
+
write_result(args.output, content, protected_paths=input_paths, force=args.force)
|
|
137
|
+
sys.stdout.write((f"Saved synthetic planning result: {args.output}") + "\n")
|
|
138
|
+
else:
|
|
139
|
+
sys.stdout.write(content)
|
|
140
|
+
except (InputError, OSError, ValueError) as exc:
|
|
141
|
+
sys.stderr.write((f"Error: {exc}") + "\n")
|
|
142
|
+
return 2
|
|
143
|
+
return 0
|