loluwot's picture
Deploy optimal_wire
f01b9a5 verified
Raw History Blame Contribute Delete
5.07 kB
"""FastAPI server: JSON API + the static web page.
Start with ``python -m optimal_wire`` (see ``__main__.py``) or
``uvicorn optimal_wire.api:app``.
Routes
------
GET /api/config public mode on / off
GET /api/materials list templates and user-made materials
POST /api/materials/check validate a material, give derived values (not saved)
POST /api/materials make / replace a user-made material
DELETE /api/materials/{id} delete a user-made material
POST /api/design calculate a design (geometry + results)
POST /api/design/export/F same inputs, returns a layout file (F = gds, oas, dxf)
GET /api/klayout.lyp KLayout layer-properties file
GET / the web page
"""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from fastapi.staticfiles import StaticFiles
from . import __version__, geometry, materials
from .device import DesignRequest, DesignResult, _reduced_temperature, evaluate
from .materials import Material
from .operating import coherence_factor
STATIC_DIR = Path(__file__).parent / "static"
app = FastAPI(title="Optimal wire", version=__version__)
def _resolve_material(req: DesignRequest) -> Material:
if req.material_id:
try:
return materials.get_material(req.material_id)
except KeyError:
raise HTTPException(404, f"Material '{req.material_id}' not found") from None
if req.material:
return req.material
raise HTTPException(422, "Give material_id or material")
def is_public() -> bool:
"""Public mode (env ``OPTIMAL_WIRE_PUBLIC=1``): the server keeps no user
data. User-made materials then stay in the browser of each user."""
return os.environ.get("OPTIMAL_WIRE_PUBLIC", "") not in ("", "0")
@app.get("/api/config")
def config() -> dict:
return {"public": is_public(), "version": __version__}
@app.post("/api/materials/check")
def check_material(mat: Material) -> dict:
"""Validate a material and give its derived values. Nothing is saved."""
mat.is_template = False
return {**mat.model_dump(), "derived": materials.derive(mat).model_dump()}
@app.get("/api/materials")
def list_materials() -> list[dict]:
return [
{**m.model_dump(), "derived": materials.derive(m).model_dump()}
for m in materials.list_materials()
]
@app.post("/api/materials")
def create_material(mat: Material) -> Material:
if is_public():
raise HTTPException(403, "Public server: materials are kept in the browser")
return materials.save_user_material(mat)
@app.delete("/api/materials/{material_id}")
def delete_material(material_id: str) -> dict:
if is_public():
raise HTTPException(403, "Public server: materials are kept in the browser")
try:
materials.delete_user_material(material_id)
except KeyError:
raise HTTPException(404, "Not a user-made material") from None
return {"deleted": material_id}
@app.post("/api/design")
def design(req: DesignRequest) -> DesignResult:
try:
return evaluate(req, _resolve_material(req))
except ValueError as err: # for example: operating temperature above Tc
raise HTTPException(422, str(err)) from None
EXPORT_FORMATS = {"gds": "GDS-II", "oas": "OASIS (KLayout)", "dxf": "DXF"}
@app.post("/api/design/export/{fmt}")
def design_export(fmt: str, req: DesignRequest) -> Response:
"""Layout file. ``gds`` is written by phidl; ``oas`` and ``dxf`` by KLayout."""
if fmt not in EXPORT_FORMATS:
raise HTTPException(404, f"Format must be one of {sorted(EXPORT_FORMATS)}")
xi_nm = None
if req.material_id or req.material:
mat = _resolve_material(req) # same bend shape as the page
try:
t = _reduced_temperature(req, mat)
except ValueError as err:
raise HTTPException(422, str(err)) from None
xi_nm = materials.derive(mat).xi_nm * coherence_factor(t)
device = geometry.build_snake(req.spec(xi_nm))
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / f"snake.{fmt}"
if fmt == "gds":
device.write_gds(str(path))
else:
geometry.write_layout(device, str(path))
data = path.read_bytes()
name = f"snake_w{req.width_nm:g}_g{req.gap_nm:g}_n{req.n_runs}.{fmt}"
return Response(
data,
media_type="application/octet-stream",
headers={"Content-Disposition": f'attachment; filename="{name}"'},
)
@app.get("/api/klayout.lyp")
def klayout_layer_file() -> Response:
"""KLayout layer-properties file for the exported layouts."""
return Response(
geometry.KLAYOUT_LYP,
media_type="application/xml",
headers={"Content-Disposition": 'attachment; filename="optimal_wire.lyp"'},
)
# Static page last, so that /api routes have priority.
app.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")