// Optimal wire - web page logic. No build step and no dependencies.
// The server does all physics and geometry; this file only shows the results.
const $ = (id) => document.getElementById(id);
const SVG = "http://www.w3.org/2000/svg";
const INPUTS = [
"width_nm", "gap_nm", "run_length_um", "n_runs", "terminals", "material_id",
"temperature_K", "bias_fraction", "series_resistance_ohm", "substrate_index",
];
let materials = [];
let publicMode = false; // true: user-made materials are kept in this browser only
const LOCAL_KEY = "optimal_wire_materials";
const localMaterials = () => JSON.parse(localStorage.getItem(LOCAL_KEY) || "[]");
const storeLocal = (list) => localStorage.setItem(LOCAL_KEY, JSON.stringify(list));
let result = null;
let view = null; // layout viewBox {x, y, w, h}
// ---------------------------------------------------------------- helpers
const fmt = (v, digits = 3) =>
v === null || v === undefined || !isFinite(v) ? "-" : Number(v.toPrecision(digits)).toLocaleString("en-US");
function el(tag, attrs = {}, text) {
const node = document.createElementNS(SVG, tag);
for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
if (text !== undefined) node.textContent = text;
return node;
}
async function api(path, options) {
const response = await fetch(path, options);
if (!response.ok) {
let detail = response.statusText;
try {
const body = await response.json();
detail = Array.isArray(body.detail)
? body.detail.map((d) => `${d.loc.slice(1).join(".")}: ${d.msg}`).join("; ")
: body.detail;
} catch { /* keep statusText */ }
throw new Error(detail);
}
return response;
}
const post = (path, body) =>
api(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
function request() {
return {
width_nm: +$("width_nm").value,
gap_nm: +$("gap_nm").value,
run_length_um: +$("run_length_um").value,
n_runs: Math.round(+$("n_runs").value),
terminals: $("terminals").value,
...materialRef(),
temperature_K: $("temperature_K").value === "" ? null : +$("temperature_K").value,
bias_fraction: +$("bias_fraction").value,
series_resistance_ohm: +$("series_resistance_ohm").value,
substrate_index: +$("substrate_index").value,
};
}
// A browser-kept material is sent in full; a server material by its id.
function materialRef() {
const id = $("material_id").value;
const m = materials.find((x) => x.id === id);
if (m && m.local) {
const { derived, local, is_template, ...material } = m;
return { material };
}
return { material_id: id };
}
// -------------------------------------------------------------- materials
async function loadMaterials(selectId) {
materials = await (await api("api/materials")).json();
if (publicMode) materials = materials.concat(localMaterials().map((m) => ({ ...m, local: true })));
const select = $("material_id");
const keep = selectId || select.value;
select.replaceChildren();
for (const [label, flag] of [["Templates (literature)", true], [publicMode ? "User-made (in this browser)" : "User-made", false]]) {
const items = materials.filter((m) => m.is_template === flag);
if (!items.length) continue;
const group = document.createElement("optgroup");
group.label = label;
for (const m of items) group.append(new Option(m.name, m.id));
select.append(group);
}
if (materials.some((m) => m.id === keep)) select.value = keep;
showMaterial();
}
function showMaterial() {
const m = materials.find((x) => x.id === $("material_id").value);
if (!m) return;
const d = m.derived;
const rows = [
["Compound", m.material || "-"],
["Thickness d", `${fmt(m.thickness_nm)} nm`],
["Coherence length ξ", `${fmt(d.xi_nm)} nm${m.xi_nm ? "" : " (calc.)"}`],
["Diffusion coefficient D", m.D_cm2_s ? `${fmt(m.D_cm2_s)} cm²/s` : "-"],
["Tc", m.Tc_K ? `${fmt(m.Tc_K)} K` : "-"],
["Sheet resistance Rs", m.Rs_ohm_sq ? `${fmt(m.Rs_ohm_sq)} Ω/sq` : "-"],
["Lk", d.Lk_pH_sq ? `${fmt(d.Lk_pH_sq)} pH/sq${m.Lk_pH_sq ? "" : " (calc.)"}` : "-"],
["λ", d.lambda_nm ? `${fmt(d.lambda_nm)} nm${m.lambda_nm ? "" : " (calc.)"}` : "-"],
["Measured jc", m.jc_MA_cm2 ? `${fmt(m.jc_MA_cm2)} MA/cm²${m.jc_temperature_K != null ? ` (${fmt(m.jc_temperature_K)} K)` : ""}` : "-"],
["Thermal conductance", m.hc_W_m2K ? `${fmt(m.hc_W_m2K)} W/m\u00b2K` : "-"],
];
$("material_props").innerHTML = rows.map(([k, v]) => `
${k}${v}`).join("");
const src = $("material_source");
src.replaceChildren();
if (m.source) src.append(m.source + " ");
if (m.url) {
const a = document.createElement("a");
a.href = m.url; a.target = "_blank"; a.rel = "noopener"; a.textContent = "[link]";
src.append(a);
}
if (m.notes) src.append(" " + m.notes);
$("delete_material").hidden = m.is_template;
}
function openForm(prefill) {
const form = $("material_form");
form.reset();
if (prefill) {
for (const field of form.elements) {
if (field.name && prefill[field.name] != null) field.value = prefill[field.name];
}
form.elements.name.value = prefill.name + " (copy)";
}
form.hidden = false;
form.elements.name.focus();
}
async function saveMaterial(event) {
event.preventDefault();
const body = {};
for (const field of event.target.elements) {
if (!field.name || field.value === "") continue;
body[field.name] = field.type === "number" ? +field.value : field.value;
}
try {
let saved;
if (publicMode) {
// The server validates and gives the derived values; the browser keeps the material.
saved = await (await post("api/materials/check", body)).json();
saved.id = "local-" + saved.name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
storeLocal(localMaterials().filter((m) => m.id !== saved.id).concat([saved]));
} else {
saved = await (await post("api/materials", body)).json();
}
event.target.hidden = true;
await loadMaterials(saved.id);
update();
} catch (err) {
showError("Material was not saved: " + err.message);
}
}
// ----------------------------------------------------------------- update
function showError(message) {
$("error").textContent = message;
$("error").hidden = !message;
}
let pending = 0;
async function update() {
const ticket = ++pending;
const req = request();
$("gap_hint").textContent =
`Fully optimal 180-degree bend: g ≥ 2W = ${fmt(2 * req.width_nm)} nm (fill factor ≤ 1/3).`;
try {
const data = await (await post("api/design", req)).json();
if (ticket !== pending) return; // a newer request is in progress
const keepView = result && sameShape(result.request, req);
result = { ...data, request: req };
showError("");
render(keepView);
} catch (err) {
if (ticket === pending) showError("Calculation not possible: " + err.message);
}
}
const sameShape = (a, b) =>
["width_nm", "gap_nm", "run_length_um", "n_runs", "terminals"].every((k) => a[k] === b[k]);
function render(keepView) {
const r = result;
$("warnings").replaceChildren(...r.warnings.map((w) => Object.assign(document.createElement("li"), { textContent: w })));
renderTiles(r);
renderLayout(r, keepView);
renderBends(r);
renderOperating(r);
renderChart(r);
renderDetails(r);
}
function renderTiles(r) {
const peak = Math.max(1, ...r.bends.map((b) => b.crowding));
const tiles = [
["Critical-current factor R", fmt(r.reduction), "", r.reduction < 1 ? `${fmt((1 - r.reduction) * 100, 2)} % decrease` : "No decrease"],
["Peak current crowding", fmt(peak), "×", "K at inner edge / K in straight wire"],
["Ic of device", fmt(r.Ic_device_uA), "µA", `Straight wire: ${fmt(r.Ic_straight_uA)} µA`],
["Kinetic inductance", fmt(r.Lk_total_nH), "nH", `${fmt(r.squares, 4)} squares`],
["Reset time Lk / R", fmt(r.reset_time_ns), "ns", `R = ${fmt(r.operating.load_ohm)} \u03a9`],
["Fill factor", fmt(r.fill_factor), "", `Pitch ${fmt(r.pitch_nm)} nm`],
["Upper bound of R", fmt(r.reduction_bound_xi), "", "All inner-edge shapes, constant pitch"],
];
$("tiles").innerHTML = tiles
.map(([k, v, u, s]) => ``)
.join("");
}
// ----------------------------------------------------------------- layout
function fullView(r) {
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const poly of r.polygons) for (const [x, y] of poly) {
x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, -y); y1 = Math.max(y1, -y);
}
const pad = 0.05 * Math.max(x1 - x0, y1 - y0);
return { x: x0 - pad, y: y0 - pad, w: x1 - x0 + 2 * pad, h: y1 - y0 + 2 * pad, x0, y0, x1, y1 };
}
function setView(v) {
view = v;
$("layout").setAttribute("viewBox", `${v.x} ${v.y} ${v.w} ${v.h}`);
}
function renderLayout(r, keepView) {
const svg = $("layout");
svg.replaceChildren(
...r.polygons.map((poly) => el("polygon", { points: poly.map(([x, y]) => `${x},${-y}`).join(" ") }))
);
if (!keepView || !view) setView(fullView(r));
}
function zoomToBend() {
// The server gives the box of the first 180-degree bend (micrometres, y up).
const box = result.first_bend_um;
if (!box) return setView(fullView(result));
const [x0, y0, x1, y1] = box;
const w = (x1 - x0) * 1.15, h = Math.max((y1 - y0) * 2.2, w * 0.38);
setView({ x: x1 - w * 0.97, y: -(y0 + y1) / 2 - h / 2, w, h });
}
function initPanZoom() {
const svg = $("layout");
const toUser = (event) => {
const p = new DOMPoint(event.clientX, event.clientY).matrixTransform(svg.getScreenCTM().inverse());
return [p.x, p.y];
};
svg.addEventListener("wheel", (event) => {
event.preventDefault();
const [x, y] = toUser(event);
const k = event.deltaY > 0 ? 1.25 : 0.8;
setView({ x: x - (x - view.x) * k, y: y - (y - view.y) * k, w: view.w * k, h: view.h * k });
}, { passive: false });
let drag = null;
svg.addEventListener("pointerdown", (event) => {
drag = toUser(event);
svg.setPointerCapture(event.pointerId);
});
svg.addEventListener("pointermove", (event) => {
if (!drag) return;
const [x, y] = toUser(event);
setView({ ...view, x: view.x - (x - drag[0]), y: view.y - (y - drag[1]) });
});
svg.addEventListener("pointerup", () => { drag = null; });
}
// ------------------------------------------------------------------ tables
function renderBends(r) {
const row = (b, ref) => `
| ${b.kind}${ref ? " (for comparison, not in layout)" : ""} |
${ref ? "-" : b.count} |
${b.crowding === null || !isFinite(b.crowding) ? "diverges" : fmt(b.crowding)} |
${fmt(b.min_radius_nm)} |
${fmt(b.reduction)} |
${b.equation} |
`;
$("bend_table").innerHTML =
`| Bend | Quantity | Peak K / K straight |
Curvature radius (nm) | R | Paper |
` +
(r.bends.length ? "" : `| No bends: one straight wire. |
`) +
r.bends.map((b) => row(b, false)).join("") +
r.sharp_reference.map((b) => row(b, true)).join("");
}
function renderOperating(r) {
const o = r.operating;
const pct = (v) => (v === null ? "-" : `${fmt(v * 100)} %`);
const rows = [
["Temperature", o.temperature_K === null ? "not given" : `${fmt(o.temperature_K)} K`,
"\u03be, \u03bb, Lk and the currents are changed to this temperature"],
["Depairing current of the wire", `${fmt(o.Idep_uA)} \u00b5A`, "Kupriyanov-Lukichev, from D, Rs, Tc"],
["Device Ic / depairing current", fmt(o.Ic_over_Idep), "Higher is better for saturated efficiency"],
["Width / \u03be", fmt(o.width_over_xi),
o.vortex_fits ? "More than 4.4: a vortex fits in the wire" : "Less than 4.4: no vortex fits in the wire"],
["Absorptance of the film", pct(o.absorptance), "Field parallel to the wires; no cavity"],
["Bias current", `${fmt(o.bias_uA)} \u00b5A`, "Bias fraction \u00d7 device Ic"],
["Pulse height at the 50 \u03a9 input", `${fmt(o.pulse_mV)} mV`, "Bias current \u00d7 50 \u03a9, before the amplifier"],
["Reset time Lk / R", `${fmt(o.reset_time_ns)} ns`, `R = ${fmt(o.load_ohm)} \u03a9`],
["Dark-count exponent \u03bd", fmt(o.dark_count_exponent), "DCR \u221d (I / Ic)^\u03bd, vortex entry, straight wire"],
["Current change for 10\u00d7 dark counts", pct(o.current_step_for_10x_dcr), "ln(10) / \u03bd"],
["Retrapping current", `${fmt(o.retrapping_uA)} \u00b5A`, "From the thermal conductance to the substrate"],
["Electron cooling time", `${fmt(o.thermal_time_ps)} ps`, "Lower limit (no phonon heat capacity)"],
["Latching", o.latching, "Indication only: compare reset time and cooling time"],
];
$("operating_table").innerHTML = rows
.map(([k, v, note]) => `| ${k} | ${v} | ${note} |
`)
.join("");
}
function renderDetails(r) {
const d = r.derived;
const rows = [
["Limiting location", r.limiting_bend],
["Ic of straight wire", `${fmt(r.Ic_straight_uA)} µA`, r.Ic_origin],
["Ic of device = R × Ic straight", `${fmt(r.Ic_device_uA)} µA`],
["Vortex-entry Ic, Eq. (14)", `${fmt(r.Ic_theory_uA)} µA`, "Theory limit for a straight wire"],
["Number of squares", fmt(r.squares, 5)],
["Equivalent wire length", `${fmt(r.wire_length_um, 4)} µm`, "squares × width"],
["Normal resistance", `${fmt(r.resistance_kohm)} kΩ`],
["Kinetic inductance", `${fmt(r.Lk_total_nH)} nH`],
["Coherence length \u03be", `${fmt(r.operating.xi_nm)} nm`, `At T = 0: ${fmt(d.xi_nm)} nm (${d.xi_origin})`],
["Penetration depth \u03bb", `${fmt(r.operating.lambda_nm)} nm`, `At T = 0: ${fmt(d.lambda_nm)} nm (${d.lambda_origin})`],
["Lk per square", `${fmt(r.operating.Lk_pH_sq)} pH`, `At T = 0: ${fmt(d.Lk_pH_sq)} pH (${d.Lk_origin})`],
["Pearl length 2\u03bb\u00b2/d", `${fmt(r.operating.lambda_nm ? 2 * r.operating.lambda_nm ** 2 / r.material.thickness_nm / 1000 : null)} \u00b5m`],
["Layout size", `${fmt(r.size_um[0], 4)} × ${fmt(r.size_um[1], 4)} µm`],
["Active area (straight part)", `${fmt(r.active_area_um2, 4)} µm²`],
["Film area", `${fmt(r.film_area_um2, 4)} µm²`],
["Spacing for fully optimal bend", `${fmt(r.optimal_gap_nm)} nm`, "g = 2W"],
];
$("detail_table").innerHTML = rows
.map(([k, v, note]) => `| ${k} | ${v} | ${note || ""} |
`)
.join("");
}
// ------------------------------------------------------------------- chart
// Series in fixed order: colour belongs to the bend type.
const SERIES = [
{ key: "optimised", cls: 1, label: "Optimised bend" },
{ key: "sharp", cls: 2, label: "Sharp rectangular" },
];
function renderChart(r) {
const svg = $("chart");
const W = svg.clientWidth || 700, H = 280;
const m = { l: 44, r: 150, t: 12, b: 38 };
svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
$("tooltip").hidden = true; // values of the old model must not stay on the screen
const raw = r.reduction_curve;
const xs = raw.gap_over_width;
const data = raw; // one list of values per series; null = no value
const bound = raw.bound_xi;
const shown = SERIES.filter((s) => data[s.key].some((v) => v !== null));
const X = (v) => m.l + (v / 3) * (W - m.l - m.r);
const Y = (v) => H - m.b - v * (H - m.t - m.b);
const nodes = [];
for (let t = 0; t <= 1.0001; t += 0.25) {
nodes.push(el("line", { class: "grid", x1: m.l, x2: W - m.r, y1: Y(t), y2: Y(t) }));
nodes.push(el("text", { x: m.l - 6, y: Y(t) + 4, "text-anchor": "end" }, t.toFixed(2)));
}
for (let t = 0; t <= 3; t += 0.5) {
nodes.push(el("text", { x: X(t), y: H - m.b + 16, "text-anchor": "middle" }, t.toFixed(1)));
}
nodes.push(el("line", { class: "axis", x1: m.l, x2: W - m.r, y1: Y(0), y2: Y(0) }));
nodes.push(el("text", { x: (m.l + W - m.r) / 2, y: H - 4, "text-anchor": "middle" }, "Spacing / width (g / W)"));
const path = (ys) => {
let d = "", pen = false;
xs.forEach((x, i) => {
if (ys[i] === null) { pen = false; return; }
d += `${pen ? "L" : "M"}${X(x).toFixed(1)},${Y(ys[i]).toFixed(1)}`;
pen = true;
});
return d;
};
for (const s of [...shown].reverse()) nodes.push(el("path", { class: `l${s.cls}`, d: path(data[s.key]) }));
// The dotted line is drawn last: a series with the same values would hide it.
nodes.push(el("path", { class: "lb", d: path(bound) }));
// Direct labels at the line ends (ink colour; the legend gives the colours).
const last = xs.length - 1;
const labels = shown.map((s) => ({ s, y: Y(data[s.key][last]) + 4 })).sort((p, q) => p.y - q.y);
for (let i = 1; i < labels.length; i++) labels[i].y = Math.max(labels[i].y, labels[i - 1].y + 14);
for (const { s, y } of labels) nodes.push(el("text", { class: "lbl", x: W - m.r + 8, y }, s.label));
// Marker for the given spacing.
const ratio = r.request.gap_nm / r.request.width_nm;
if (ratio <= 3) {
nodes.push(el("line", { class: "marker", x1: X(ratio), x2: X(ratio), y1: Y(0), y2: Y(1) }));
nodes.push(el("text", { class: "lbl", x: X(ratio) + 5, y: Y(0) - 6 }, `g/W = ${fmt(ratio)}`));
}
const cross = el("line", { class: "cross", y1: Y(0), y2: Y(1), visibility: "hidden" });
const dots = shown.map((s) => el("circle", { class: `d${s.cls}`, r: 5, visibility: "hidden" }));
nodes.push(cross, ...dots);
svg.replaceChildren(...nodes);
const tip = $("tooltip");
svg.onpointermove = (event) => {
const box = svg.getBoundingClientRect();
const px = ((event.clientX - box.left) / box.width) * W;
const v = ((px - m.l) / (W - m.l - m.r)) * 3;
let i = 0;
xs.forEach((x, j) => { if (Math.abs(x - v) < Math.abs(xs[i] - v)) i = j; });
cross.setAttribute("visibility", "visible");
cross.setAttribute("x1", X(xs[i])); cross.setAttribute("x2", X(xs[i]));
shown.forEach((s, k) => {
const val = data[s.key][i];
dots[k].setAttribute("visibility", val === null ? "hidden" : "visible");
if (val !== null) { dots[k].setAttribute("cx", X(xs[i])); dots[k].setAttribute("cy", Y(val)); }
});
tip.hidden = false;
tip.innerHTML = `g / W = ${fmt(xs[i])} (g = ${fmt(xs[i] * r.request.width_nm)} nm)` +
shown.map((s) => `
${s.label}: R = ${fmt(data[s.key][i])}`).join("") +
`
Upper bound: ${fmt(bound[i])}`;
const left = (X(xs[i]) / W) * box.width;
tip.style.left = `${left > box.width - 260 ? left - 240 : left + 12}px`;
tip.style.top = "10px";
};
svg.onpointerleave = () => {
tip.hidden = true;
for (const n of [cross, ...dots]) n.setAttribute("visibility", "hidden");
};
}
// ------------------------------------------------------------------ export
async function downloadLayout() {
try {
const format = $("export_format").value;
const response = await post(`api/design/export/${format}`, request());
const blob = await response.blob();
const name = /filename="(.+?)"/.exec(response.headers.get("Content-Disposition") || "")?.[1] || `snake.${format}`;
const a = Object.assign(document.createElement("a"), { href: URL.createObjectURL(blob), download: name });
a.click();
URL.revokeObjectURL(a.href);
} catch (err) {
showError("Layout download not possible: " + err.message);
}
}
// -------------------------------------------------------------------- init
let timer = null;
const schedule = () => { clearTimeout(timer); timer = setTimeout(update, 200); };
for (const id of INPUTS) $(id).addEventListener("input", schedule);
$("material_id").addEventListener("input", showMaterial);
$("new_material").addEventListener("click", () => openForm(null));
$("copy_material").addEventListener("click", () => openForm(materials.find((m) => m.id === $("material_id").value)));
$("cancel_material").addEventListener("click", () => { $("material_form").hidden = true; });
$("material_form").addEventListener("submit", saveMaterial);
$("delete_material").addEventListener("click", async () => {
const id = $("material_id").value;
if (!confirm(`Delete material "${id}"?`)) return;
if (publicMode) storeLocal(localMaterials().filter((m) => m.id !== id));
else await api(`api/materials/${encodeURIComponent(id)}`, { method: "DELETE" });
await loadMaterials();
update();
});
$("zoom_reset").addEventListener("click", () => setView(fullView(result)));
$("zoom_bend").addEventListener("click", zoomToBend);
$("download_layout").addEventListener("click", downloadLayout);
window.addEventListener("resize", () => result && renderChart(result));
initPanZoom();
publicMode = (await (await api("api/config")).json()).public;
await loadMaterials();
update();