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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
"""Device model: geometry + current crowding + material -> one result.

This is the only place where the three other modules come together, so it is
the place to add new output quantities.
"""

from __future__ import annotations

import math
from typing import Literal, Optional

import numpy as np
from pydantic import BaseModel, Field

from . import geometry, gibbs, operating, physics
from .materials import DerivedMaterial, Material, derive

LOAD_OHM = 50.0  # readout impedance used for the reset-time estimate


class DesignRequest(BaseModel):
    """User inputs of one design."""

    width_nm: float = Field(100, gt=0, le=1e5, description="Wire width W.")
    gap_nm: float = Field(200, gt=0, le=1e6, description="Spacing between wires g.")
    run_length_um: float = Field(10, gt=0, le=1e4, description="Length of each straight run.")
    n_runs: int = Field(11, ge=1, le=2000, description="Number of parallel runs.")
    terminals: Literal["straight", "optimal_90"] = "straight"
    temperature_K: Optional[float] = Field(
        None, ge=0, le=300, description="Operating temperature. None: material values as given."
    )
    bias_fraction: float = Field(0.9, gt=0, le=1, description="Bias current / device Ic.")
    series_resistance_ohm: float = Field(
        0, ge=0, le=1e5, description="Resistor in series with the 50 ohm readout."
    )
    substrate_index: float = Field(1.75, ge=1, le=5, description="Refractive index of substrate.")
    material_id: Optional[str] = None
    material: Optional[Material] = Field(
        None, description="Inline material. Used when material_id is not given."
    )

    def spec(self, xi_nm: float | None = None) -> geometry.SnakeSpec:
        """Geometry inputs.  ``xi_nm`` is necessary for the optimised bend."""
        return geometry.SnakeSpec(
            width=self.width_nm * 1e-3,
            gap=self.gap_nm * 1e-3,
            run_length=self.run_length_um,
            n_runs=self.n_runs,
            terminals=self.terminals,
            xi=(xi_nm or 0.0) * 1e-3,
        )


class BendResult(BaseModel):
    """Current crowding of one type of bend."""

    kind: str
    count: int
    crowding: float  # peak K / K_I at the inner edge (1 = none)
    min_radius_nm: Optional[float]
    reduction: float  # R = Ic(bend) / Ic(straight)
    equation: str


class OperatingResult(BaseModel):
    """Estimates at the operating temperature (``None`` = input not available)."""

    temperature_K: Optional[float]
    xi_nm: float
    lambda_nm: Optional[float]
    Lk_pH_sq: Optional[float]
    Idep_uA: Optional[float]  # depairing current of the straight wire
    Ic_over_Idep: Optional[float]  # device Ic / Idep ("constriction factor")
    width_over_xi: float
    vortex_fits: bool  # W > 4.4 xi (Likharev)
    absorptance: Optional[float]
    bias_uA: Optional[float]
    pulse_mV: Optional[float]
    reset_time_ns: Optional[float]
    load_ohm: float
    dark_count_exponent: Optional[float]
    current_step_for_10x_dcr: Optional[float]  # relative change of I
    retrapping_uA: Optional[float]
    thermal_time_ps: Optional[float]
    latching: str


class DesignResult(BaseModel):
    # geometry
    pitch_nm: float
    fill_factor: float
    optimal_gap_nm: float
    size_um: tuple[float, float]
    active_area_um2: float
    film_area_um2: float
    wire_length_um: float
    squares: float
    # crowding
    bends: list[BendResult]
    reduction: float
    limiting_bend: str
    sharp_reference: list[BendResult]
    # electrical
    material: Material
    derived: DerivedMaterial
    operating: OperatingResult
    Ic_straight_uA: Optional[float]
    Ic_origin: str
    Ic_device_uA: Optional[float]
    Ic_theory_uA: Optional[float]
    resistance_kohm: Optional[float]
    Lk_total_nH: Optional[float]
    reset_time_ns: Optional[float]
    # plot data and messages
    reduction_bound_xi: float
    first_bend_um: Optional[list[float]]
    reduction_curve: dict[str, list[Optional[float]]]
    warnings: list[str]
    polygons: list[list[list[float]]]


def _optimised(w: float, g: float, xi: float) -> BendResult:
    edge = gibbs.inner_edge(gibbs.optimise(w, g, xi))
    return BendResult(
        kind="180-degree bend, optimised",
        count=0,
        crowding=edge.peak_k,
        min_radius_nm=None,
        reduction=min(1.0, edge.reduction),
        equation="Gibbs energy, Eq. (7)-(11), all shapes",
    )


def _contour(w: float, g: float, xi: float) -> BendResult:
    optimal = g >= 2 * w * (1 - 1e-6)
    return BendResult(
        kind="180-degree optimal bend" if optimal else "180-degree bend, streamline contour",
        count=0,
        crowding=physics.hairpin_crowding(w, g),
        min_radius_nm=physics.hairpin_min_radius(w, g),
        reduction=physics.reduction_rounded_hairpin(w, g, xi),
        equation="Eq. (58)" if optimal else "Eq. (62), (63)",
    )


#: Bend shape (``SnakeSpec.shape``) -> model.
BEND_MODELS = {"optimised": _optimised, "contour": _contour}


def bend_results(req: DesignRequest, xi_nm: float) -> list[BendResult]:
    """Current crowding of the bends that are in the design."""
    w, g = req.width_nm, req.gap_nm
    out = []
    if req.n_runs > 1:
        bend = BEND_MODELS[req.spec(xi_nm).shape](w, g, xi_nm)
        bend.count = req.n_runs - 1
        out.append(bend)
    if req.terminals == "optimal_90":
        out.append(
            BendResult(
                kind="90-degree optimal bend",
                count=2,
                crowding=1.0,
                min_radius_nm=physics.OPTIMAL_90_MIN_RADIUS_FACTOR * w,
                reduction=physics.reduction_optimal_90(w, xi_nm),
                equation="Eq. (111)",
            )
        )
    return out


def _sharp_turn(w: float, g: float, xi: float) -> tuple[float, str]:
    """R of the sharp rectangular turn, and its origin.

    In the range of ``gibbs.py`` the same model as for the optimised bend is
    used, so that the two can be compared.  Else: the paper's Eq. (100).
    """
    if gibbs.XI_RANGE[0] <= xi / w <= gibbs.XI_RANGE[1] and g / w >= gibbs.RATIO_RANGE[0]:
        return gibbs.reduction_sharp_turn(
            w, g, xi
        ), "Gibbs energy, same model (Eq. 100 for xi << W)"
    return physics.reduction_sharp_rect_hairpin(w, g, xi), "Eq. (100)"


def sharp_reference(req: DesignRequest, xi_nm: float) -> list[BendResult]:
    """R of sharp corners with the same width and gap, for comparison."""
    w, g = req.width_nm, req.gap_nm
    sharp, origin = _sharp_turn(w, g, xi_nm)
    return [
        BendResult(
            kind="Sharp rectangular 180-degree turn",
            count=0,
            crowding=math.inf,
            min_radius_nm=0.0,
            reduction=sharp,
            equation=origin,
        ),
        BendResult(
            kind="Sharp 90-degree corner",
            count=0,
            crowding=math.inf,
            min_radius_nm=0.0,
            reduction=physics.reduction_sharp_90(w, xi_nm),
            equation="Eq. (108)",
        ),
    ]


def reduction_curve(width_nm: float, xi_nm: float, n: int = 60) -> dict[str, list]:
    """R against gap / width: optimised bend, sharp turn, and the estimate
    of the largest R of all shapes."""
    ratio = np.linspace(0.1, 3.0, n)
    return {
        "gap_over_width": ratio.tolist(),
        "optimised": gibbs.reduction_curve(ratio.tolist(), xi_nm / width_nm),
        "sharp": [_sharp_turn(width_nm, r * width_nm, xi_nm)[0] for r in ratio],
        "bound_xi": [gibbs.reduction_bound(width_nm, r * width_nm, xi_nm) for r in ratio],
    }


def _warnings(
    req: DesignRequest,
    mat: Material,
    derived: DerivedMaterial,
    xi: float,
    lambda_nm: Optional[float],
) -> list[str]:
    """Cautions.  ``xi`` and ``lambda_nm`` are the values at the operating temperature."""
    w, g = req.width_nm, req.gap_nm
    out = []
    if req.n_runs > 1 and g < 2 * w * (1 - 1e-9):
        out.append(
            f"Spacing is smaller than 2 x width ({2 * w:g} nm). A bend without current "
            "crowding is not possible at constant pitch."
        )
        if req.spec(xi).shape != "optimised":
            out.append(
                "The optimiser is not valid for these inputs (it needs 0.005 <= xi/W <= 0.15 "
                "and 0.05 <= g/W <= 1.98). The streamline contour of phidl is used. "
                "It is not the best shape."
            )
    if w < 5 * xi:
        out.append(f"Width is only {w / xi:.1f} x xi. The model is accurate for xi << width.")
    if req.n_runs > 1 and g < 10 * xi:
        out.append("Spacing is not much larger than xi. The model is less accurate.")
    pearl_um = 2 * lambda_nm**2 / mat.thickness_nm * 1e-3 if lambda_nm else None
    if pearl_um and w * 1e-3 > 0.1 * pearl_um:
        out.append(
            "Width is not much smaller than the Pearl length "
            f"({pearl_um:.1f} um). The uniform-current model is less accurate."
        )
    if w <= operating.LIKHAREV_FACTOR * xi:
        out.append(
            f"Width is smaller than 4.4 x xi = {operating.LIKHAREV_FACTOR * xi:.0f} nm: a vortex "
            "does not fit in the wire. The vortex-entry model for R and the dark-count "
            "exponent do not apply."
        )
    if derived.lambda_nm is None and mat.jc_MA_cm2 is None:
        out.append(
            "No lambda, Lk, (Rs and Tc), or jc for this material: "
            "the critical current cannot be calculated. R is still correct."
        )
    return out


def _reduced_temperature(req: DesignRequest, mat: Material) -> float:
    """t = T / Tc; 0 when no temperature is given."""
    if req.temperature_K is None:
        return 0.0
    if not mat.Tc_K:
        raise ValueError("This material has no Tc: an operating temperature cannot be used")
    if req.temperature_K >= mat.Tc_K:
        raise ValueError(
            f"Operating temperature {req.temperature_K:g} K is not lower than Tc = {mat.Tc_K:g} K"
        )
    return req.temperature_K / mat.Tc_K


def _operating(
    req: DesignRequest,
    mat: Material,
    t: float,
    xi_nm: float,
    lambda_nm: Optional[float],
    lk_pH_sq: Optional[float],
    squares: float,
    ic_device_uA: Optional[float],
) -> OperatingResult:
    """Detector estimates.  Each one is ``None`` if an input is not available."""
    w = req.width_nm * 1e-9
    d = mat.thickness_nm * 1e-9
    temp = req.temperature_K
    diffusion = mat.D_cm2_s * 1e-4 if mat.D_cm2_s else None
    load = LOAD_OHM + req.series_resistance_ohm

    idep = None
    if mat.Rs_ohm_sq and mat.Tc_K and diffusion:
        idep = operating.depairing_current(mat.Rs_ohm_sq, mat.Tc_K, diffusion, w, t) * 1e6
    bias = ic_device_uA * req.bias_fraction if ic_device_uA else None
    nu = None
    if lambda_nm and temp:
        nu = operating.dark_count_exponent(lambda_nm * 1e-9, d, temp)
    retrap = tau_th = None
    latching = "not available (no thermal conductance, Rs or Tc)"
    if mat.hc_W_m2K and mat.Rs_ohm_sq and mat.Tc_K and temp is not None:
        retrap = operating.retrapping_current(mat.Rs_ohm_sq, mat.Tc_K, w, mat.hc_W_m2K, temp) * 1e6
        if diffusion:
            tau_th = (
                operating.thermal_time(mat.Rs_ohm_sq, mat.Tc_K, d, diffusion, mat.hc_W_m2K) * 1e12
            )
        if bias is None:
            latching = "not available (no critical current)"
        elif bias <= retrap:
            latching = "not possible: bias is below the retrapping current"
        else:
            latching = "possible: bias is above the retrapping current"
    elif temp is None:
        latching = "not available (no operating temperature)"
    lk_total = lk_pH_sq * squares * 1e-3 if lk_pH_sq else None  # nH

    return OperatingResult(
        temperature_K=temp,
        xi_nm=xi_nm,
        lambda_nm=lambda_nm,
        Lk_pH_sq=lk_pH_sq,
        Idep_uA=idep,
        Ic_over_Idep=ic_device_uA / idep if ic_device_uA and idep else None,
        width_over_xi=req.width_nm / xi_nm,
        vortex_fits=req.width_nm > operating.LIKHAREV_FACTOR * xi_nm,
        absorptance=(
            operating.absorptance(
                mat.Rs_ohm_sq, req.width_nm / (req.width_nm + req.gap_nm), req.substrate_index
            )
            if mat.Rs_ohm_sq
            else None
        ),
        bias_uA=bias,
        pulse_mV=bias * LOAD_OHM * 1e-3 if bias else None,
        reset_time_ns=lk_total / load if lk_total else None,
        load_ohm=load,
        dark_count_exponent=nu,
        current_step_for_10x_dcr=math.log(10) / nu if nu else None,
        retrapping_uA=retrap,
        thermal_time_ps=tau_th,
        latching=latching,
    )


def evaluate(req: DesignRequest, mat: Material) -> DesignResult:
    """Calculate all outputs for one design and one material.

    With ``req.temperature_K`` the material values are changed to that
    temperature first (laws in ``operating.py``); R, the bend shape, Ic, the
    inductance and the reset time then use the changed values.
    """
    derived = derive(mat)
    t = _reduced_temperature(req, mat)
    xi_nm = derived.xi_nm * operating.coherence_factor(t)
    lk_factor = operating.inductance_factor(t)
    lambda_nm = derived.lambda_nm * math.sqrt(lk_factor) if derived.lambda_nm else None
    lk_pH_sq = derived.Lk_pH_sq * lk_factor if derived.Lk_pH_sq else None

    spec = req.spec(xi_nm)
    device = geometry.build_snake(spec)
    (x0, y0), (x1, y1) = device.bbox
    squares = geometry.snake_squares(spec)

    bends = bend_results(req, xi_nm)
    limiting = min(bends, key=lambda b: b.reduction, default=None)
    reduction = limiting.reduction if limiting else 1.0

    # Critical current of the straight wire.
    ic_theory = None
    if lambda_nm:
        kc = physics.critical_sheet_current(xi_nm * 1e-9, lambda_nm * 1e-9, mat.thickness_nm * 1e-9)
        ic_theory = kc * req.width_nm * 1e-9 * 1e6  # uA
    if mat.jc_MA_cm2:
        # MA/cm^2 = 1e10 A/m^2
        ic_straight = mat.jc_MA_cm2 * 1e10 * req.width_nm * 1e-9 * mat.thickness_nm * 1e-9 * 1e6
        ic_origin = "measured jc x width x thickness"
        same = mat.jc_temperature_K is not None and req.temperature_K == mat.jc_temperature_K
        if same:
            ic_origin += f" (measured at {mat.jc_temperature_K:g} K)"
        elif req.temperature_K is not None and mat.jc_temperature_K is not None and mat.Tc_K:
            t_meas = mat.jc_temperature_K / mat.Tc_K
            ic_straight *= operating.current_factor(t) / operating.current_factor(t_meas)
            ic_origin += (
                f", changed from {mat.jc_temperature_K:g} K to {req.temperature_K:g} K "
                "with (1 - t^2)^(3/2)"
            )
        elif req.temperature_K is not None:
            ic_origin += " (temperature of the measurement not known: not changed)"
    else:
        ic_straight = ic_theory
        ic_origin = "Eq. (14): phi0 W / (e pi mu0 xi Lambda)" if ic_theory else "not available"

    ic_device = ic_straight * reduction if ic_straight else None
    op = _operating(req, mat, t, xi_nm, lambda_nm, lk_pH_sq, squares, ic_device)
    lk_total = lk_pH_sq * squares * 1e-3 if lk_pH_sq else None  # nH
    warnings = _warnings(req, mat, derived, xi_nm, lambda_nm)

    return DesignResult(
        pitch_nm=req.width_nm + req.gap_nm,
        fill_factor=req.width_nm / (req.width_nm + req.gap_nm),
        optimal_gap_nm=2 * req.width_nm,
        size_um=(x1 - x0, y1 - y0),
        active_area_um2=spec.run_length * (spec.n_runs * spec.pitch - spec.gap),
        film_area_um2=geometry.film_area(device),
        wire_length_um=squares * spec.width,
        squares=squares,
        bends=bends,
        reduction=reduction,
        limiting_bend=limiting.kind if limiting and reduction < 1 else "none (straight wire)",
        sharp_reference=sharp_reference(req, xi_nm),
        material=mat,
        derived=derived,
        operating=op,
        Ic_straight_uA=ic_straight,
        Ic_origin=ic_origin,
        Ic_device_uA=ic_device,
        Ic_theory_uA=ic_theory,
        resistance_kohm=mat.Rs_ohm_sq * squares * 1e-3 if mat.Rs_ohm_sq else None,
        Lk_total_nH=lk_total,
        reset_time_ns=op.reset_time_ns,
        reduction_bound_xi=gibbs.reduction_bound(req.width_nm, req.gap_nm, xi_nm),
        first_bend_um=device.info.get("first_bend"),
        reduction_curve=reduction_curve(req.width_nm, xi_nm),
        warnings=warnings,
        polygons=[np.round(p, 5).tolist() for p in geometry.polygons(device)],
    )