optimal-wire / src /optimal_wire /geometry.py
loluwot's picture
Deploy optimal_wire
f01b9a5 verified
Raw History Blame Contribute Delete
11.2 kB
"""Snake (meander) layout with optimally rounded bends.
For gap >= 2 x width the curves come from ``phidl.geometry``
(``optimal_hairpin`` and ``optimal_90deg``), which implement the optimal
contours of Clem & Berggren. For smaller gaps the 180-degree bend comes from
the optimiser in ``gibbs.py``. This module puts the parts together.
All lengths in this module are in micrometres (the phidl / GDS default).
Layout (3 runs, straight terminals)::
terminal ============================\\
/===========================/ <- 180-degree bend
\\============================ terminal
|<-E->|<---- run_length ---->|<-E->|
``run_length`` is the part where the wires are straight and parallel. Each
bend adds the length ``E`` (see :func:`bend_extent`) outside of that part.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
import numpy as np
import phidl.geometry as pg
from phidl import Device
from . import gibbs, physics
Terminals = Literal["straight", "optimal_90"]
#: Solid film behind the bend apex, in units of the wire width (phidl default).
TURN_RATIO = 4
#: Number of points on each 180-degree curve.
HAIRPIN_POINTS = 60
#: Number of points on each 90-degree curve.
BEND90_POINTS = 30
@dataclass(frozen=True)
class SnakeSpec:
"""Geometric inputs of the snake (micrometres)."""
width: float
gap: float
run_length: float
n_runs: int
terminals: Terminals = "straight"
xi: float = 0.0 # coherence length (um); the optimised bend needs it
@property
def pitch(self) -> float:
return self.width + self.gap
@property
def shape(self) -> Literal["optimised", "contour"]:
"""The 180-degree bend that is drawn.
* gap >= 2 width: "contour" = the optimal bend of the paper (R = 1).
* gap < 2 width: "optimised" (``gibbs.py``). Where the optimiser is
not valid (see ``gibbs.is_valid``): "contour", which is then not
the best shape.
"""
if self.gap >= 2 * self.width * (1 - 1e-6):
return "contour"
return "optimised" if gibbs.is_valid(self.width, self.gap, self.xi) else "contour"
def _optimised_edge(width: float, gap: float, xi: float) -> gibbs.Edge:
return gibbs.inner_edge(gibbs.optimise(width, gap, xi))
def bend_extent(width: float, gap: float, shape: str = "contour", xi: float = 0.0) -> float:
"""Length ``E`` that one 180-degree bend adds outside the straight part.
"contour": phidl starts the curve one pitch before the slit end, the apex
is at ``x_W`` (Eq. 60) after the slit end. "optimised": the length of the
optimised edge. ``TURN_RATIO`` widths of solid film follow in the two cases.
"""
if shape == "optimised":
edge = _optimised_edge(width, gap, xi)
return -edge.points[0, 0] * width + TURN_RATIO * width
return (width + gap) + physics.hairpin_apex_x(width, gap) + TURN_RATIO * width
def optimised_hairpin(width: float, pitch: float, length: float, xi: float) -> Device:
"""180-degree bend with the inner edge from the optimiser (``gibbs.py``).
Same outline and ports as ``phidl.geometry.optimal_hairpin``.
"""
gap = pitch - width
half = (pitch + width) / 2
edge = _optimised_edge(width, gap, xi).points * width
end = TURN_RATIO * width
xpts = np.concatenate([edge[:, 0], [end, end, end - length, end - length]])
ypts = np.concatenate([edge[:, 1], [0, -half, -half, -half + width]])
D = Device("optimised_hairpin")
D.add_polygon([xpts, ypts])
D.add_polygon([xpts, -ypts])
yport = half - width / 2
D.add_port(name=1, midpoint=[end - length, yport], width=width, orientation=180)
D.add_port(name=2, midpoint=[end - length, -yport], width=width, orientation=180)
return D
def build_snake(spec: SnakeSpec) -> Device:
"""Make the snake as a phidl ``Device`` with ports 1 and 2."""
if spec.n_runs < 1:
raise ValueError("n_runs must be >= 1")
if spec.gap <= 0 or spec.width <= 0 or spec.run_length <= 0:
raise ValueError("width, gap and run_length must be > 0")
D = Device("snake")
extent = bend_extent(spec.width, spec.gap, spec.shape, spec.xi) if spec.n_runs > 1 else 0.0
half = spec.run_length / 2 + extent # phidl hairpin 'length'
first_length = half if spec.n_runs > 1 else spec.run_length
start = D.add_ref(pg.compass(size=[first_length, spec.width]))
last_port = start.ports["E"]
if spec.n_runs > 1:
if spec.shape == "optimised":
hairpin = optimised_hairpin(spec.width, spec.pitch, half, spec.xi)
else:
hairpin = pg.optimal_hairpin(
width=spec.width,
pitch=spec.pitch,
length=half,
turn_ratio=TURN_RATIO,
num_pts=HAIRPIN_POINTS,
)
# Same connection pattern as phidl.geometry.snspd.
previous = D.add_ref(hairpin)
previous.connect(1, start.ports["E"])
(bx0, by0), (bx1, by1) = previous.bbox
D.info["first_bend"] = [float(bx1 - extent), float(by0), float(bx1), float(by1)]
last_port = previous.ports[2]
alternate = True
for _ in range(spec.n_runs - 2):
ref = D.add_ref(hairpin)
if alternate:
ref.connect(2, previous.ports[2])
last_port = ref.ports[1]
else:
ref.connect(1, previous.ports[1])
last_port = ref.ports[2]
previous = ref
alternate = not alternate
if spec.n_runs > 1:
finish = D.add_ref(pg.compass(size=[half, spec.width]))
finish.connect("E", last_port)
port_in, port_out = start.ports["W"], finish.ports["W"]
else:
port_in, port_out = start.ports["W"], start.ports["E"]
if spec.terminals == "optimal_90":
bend = pg.optimal_90deg(width=spec.width, num_pts=BEND90_POINTS)
# Port choice sets the turn direction: the two leads turn away from
# the snake body (first lead up, last lead down).
first = D.add_ref(bend)
first.connect(_outward_port(port_in, up=True), port_in)
port_in = first.ports[3 - _outward_port(port_in, up=True)]
second = D.add_ref(bend)
second.connect(_outward_port(port_out, up=False), port_out)
port_out = second.ports[3 - _outward_port(port_out, up=False)]
D.add_port(port=port_in, name=1)
D.add_port(port=port_out, name=2)
return D
def _outward_port(port, up: bool) -> int:
"""Which port of ``optimal_90deg`` to connect so that the lead turns
up (``up=True``) or down, for a terminal that points left or right."""
points_left = abs(port.orientation % 360 - 180) < 1
return 2 if (points_left == up) else 1
def polygons(device: Device) -> list[np.ndarray]:
"""All polygons of the device as ``(n, 2)`` arrays (micrometres)."""
return [np.asarray(p) for p in device.get_polygons()]
def film_area(device: Device) -> float:
"""Total film area (um^2), shoelace formula."""
total = 0.0
for p in polygons(device):
x, y = p[:, 0], p[:, 1]
total += 0.5 * abs(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1)))
return total
# --------------------------------------------------------------------------
# Number of squares
# --------------------------------------------------------------------------
def hairpin_squares(width: float, gap: float) -> float:
"""Squares of one 180-degree bend (the part outside the straight runs).
The bend region is the area between the streamlines ``S = 0`` (outer
edge) and ``S = K_I W`` (inner edge) of the conformal map, Eq. (52). Its
resistance in squares is thus the potential drop along the outer edge
divided by ``K_I W``. With ``K = K_I / sqrt(1 + exp(pi x / a))`` on the
outer edge the integral from ``x = -pitch`` to infinity is analytic.
"""
a = physics.hairpin_half_width(width, gap)
u0 = np.exp(-np.pi * (width + gap) / a)
s = np.sqrt(1 + u0)
return float(-(2 * a / (np.pi * width)) * np.log((s - 1) / (s + 1)))
def bend90_arm_length(width: float) -> float:
"""Outer-edge length of each arm of phidl's ``optimal_90deg`` part."""
v0 = 10.0 ** (-1) # phidl length_adjust = 1
return 2 * width * (1 + (2 / np.pi) * np.arcsinh(1 / v0))
def bend90_squares(width: float) -> float:
"""Squares of one optimal 90-degree bend part (port to port).
The bend is the area between the outer edge and the contour
``S = -K_I a / 2`` of the map of Eq. (104), with ``a = 2 W``. On the
outer edge the map gives the distance from the corner as
``(a / pi) [acosh(q) + acos(1 / q)]`` with ``q = |1 - w|`` on one arm and
``1 / q`` on the other arm. The potential is ``-(K_I a / pi) ln|w - 1|``
(Eq. 102), thus ``squares = (4 / pi) ln(q)``.
"""
from scipy.optimize import brentq
target = np.pi * bend90_arm_length(width) / (2 * width)
q = brentq(lambda q: np.arccosh(q) + np.arccos(1 / q) - target, 1.0, 1e12)
return float((4 / np.pi) * np.log(q))
def snake_squares(spec: SnakeSpec) -> float:
"""Total number of squares between the two terminals."""
n_bends = spec.n_runs - 1
squares = spec.n_runs * spec.run_length / spec.width
if n_bends:
if spec.shape == "optimised":
per_bend = _optimised_edge(spec.width, spec.gap, spec.xi).squares
else:
per_bend = hairpin_squares(spec.width, spec.gap)
squares += n_bends * per_bend
# Two terminal stubs that go past the bends on each side.
squares += 2 * bend_extent(spec.width, spec.gap, spec.shape, spec.xi) / spec.width
if spec.terminals == "optimal_90":
squares += 2 * bend90_squares(spec.width)
return squares
# --------------------------------------------------------------------------
# Export
# --------------------------------------------------------------------------
#: Layer of the film in the exported files (layer, datatype).
FILM_LAYER = (1, 0)
def to_klayout(device: Device, cell_name: str = "snake"):
"""Convert to a ``klayout.db.Layout`` (database unit 1 nm, layer 1/0)."""
import klayout.db as kdb
layout = kdb.Layout()
layout.dbu = 0.001 # micrometres per database unit
cell = layout.create_cell(cell_name)
layer = layout.layer(*FILM_LAYER, "FILM")
for poly in polygons(device):
cell.shapes(layer).insert(kdb.DPolygon([kdb.DPoint(float(x), float(y)) for x, y in poly]))
return layout
def write_layout(device: Device, path: str) -> None:
"""Write the layout with KLayout. The file extension sets the format:
``.oas`` (OASIS), ``.gds`` (GDS-II) or ``.dxf``."""
to_klayout(device).write(path)
#: KLayout layer-properties file that gives the film layer a name and colour.
KLAYOUT_LYP = """<?xml version="1.0" encoding="utf-8"?>
<layer-properties>
<properties>
<frame-color>#2370cd</frame-color>
<fill-color>#2370cd</fill-color>
<dither-pattern>I0</dither-pattern>
<visible>true</visible>
<name>FILM (superconductor)</name>
<source>1/0@1</source>
</properties>
</layer-properties>
"""