File size: 5,072 Bytes
f01b9a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""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")