optimal-wire / src /optimal_wire /materials.py
loluwot's picture
Deploy optimal_wire
f01b9a5 verified
Raw History Blame Contribute Delete
7.15 kB
"""Superconducting film materials: templates and user-made records.
A material is one JSON file. Templates (values from the literature) are in
``optimal_wire/data/materials``. Materials made in the web page are written
to the user directory (default ``./user_materials``, set with the environment
variable ``OPTIMAL_WIRE_USER_MATERIALS``).
To add a template: add a JSON file with the fields of :class:`Material` to
``data/materials``. No code change is necessary.
"""
from __future__ import annotations
import json
import math
import os
import re
from pathlib import Path
from typing import Optional
from pydantic import BaseModel, Field, model_validator
from .physics import HBAR, KB, MU0
TEMPLATE_DIR = Path(__file__).parent / "data" / "materials"
BCS_GAP_RATIO = 1.764 # Delta(0) / (kB Tc), weak-coupling BCS
#: Template that the page selects at the start (first in the list).
DEFAULT_MATERIAL_ID = "nbn-mit-incalza2026-4p6nm"
def user_dir() -> Path:
"""Directory for user-made materials (made if it does not exist)."""
path = Path(os.environ.get("OPTIMAL_WIRE_USER_MATERIALS", "user_materials"))
path.mkdir(parents=True, exist_ok=True)
return path
class Material(BaseModel):
"""Measured properties of one superconducting thin film.
``thickness_nm`` is always necessary, and also ``xi_nm`` or
(``D_cm2_s`` and ``Tc_K``). The coherence length, the kinetic inductance
and the penetration depth can be given directly or are calculated from
other fields (see :func:`derive`).
"""
id: str = Field("", description="Unique key. Made from the name if empty.")
name: str = Field(..., min_length=1, max_length=80)
material: str = Field("", description="Compound, for example NbN.")
thickness_nm: float = Field(..., gt=0, description="Film thickness d.")
xi_nm: Optional[float] = Field(None, gt=0, description="GL coherence length.")
D_cm2_s: Optional[float] = Field(None, gt=0, description="Electron diffusion coefficient.")
Tc_K: Optional[float] = Field(None, gt=0, description="Critical temperature.")
Rs_ohm_sq: Optional[float] = Field(None, gt=0, description="Normal sheet resistance.")
Lk_pH_sq: Optional[float] = Field(None, gt=0, description="Kinetic sheet inductance.")
lambda_nm: Optional[float] = Field(None, gt=0, description="Magnetic penetration depth.")
jc_MA_cm2: Optional[float] = Field(
None, gt=0, description="Measured critical current density of a straight wire."
)
jc_temperature_K: Optional[float] = Field(
None, ge=0, description="Temperature of the jc measurement."
)
hc_W_m2K: Optional[float] = Field(
None, gt=0, description="Thermal conductance film to substrate (W / m^2 K)."
)
source: str = Field("", description="Citation or origin of the values.")
url: str = ""
notes: str = ""
is_template: bool = False
@model_validator(mode="after")
def _xi_must_be_available(self) -> "Material":
if self.xi_nm is None and not (self.D_cm2_s and self.Tc_K):
raise ValueError("Give xi_nm, or D_cm2_s and Tc_K (xi is then calculated)")
return self
class DerivedMaterial(BaseModel):
"""Material values used by the device model, with their origin."""
xi_nm: float
xi_origin: str
Lk_pH_sq: Optional[float]
Lk_origin: str
lambda_nm: Optional[float]
lambda_origin: str
pearl_length_um: Optional[float]
def derive(mat: Material) -> DerivedMaterial:
"""Fill in xi, kinetic inductance and penetration depth when not measured.
Order of preference:
* ``xi``: measured value; else the dirty-limit relation
``xi^2 = phi0 / (2 pi Bc2(0))`` with ``Bc2(0) = 0.69 Tc (4 kB / pi e D)``,
which is ``xi^2 = pi hbar D / (5.52 kB Tc)``.
* ``Lk``: measured value; else ``mu0 lambda^2 / d``; else the dirty-limit
BCS relation at T = 0, ``Lk = hbar Rs / (pi Delta)`` with
``Delta = 1.764 kB Tc``.
* ``lambda``: measured value; else ``sqrt(Lk d / mu0)``.
"""
d = mat.thickness_nm * 1e-9
if mat.xi_nm:
xi_nm, xi_origin = mat.xi_nm, "measured"
else:
xi_m = math.sqrt(math.pi * HBAR * mat.D_cm2_s * 1e-4 / (4 * 0.69 * 2 * KB * mat.Tc_K))
xi_nm, xi_origin = xi_m * 1e9, "from D and Tc: sqrt(pi hbar D / (5.52 kB Tc))"
lk = mat.Lk_pH_sq * 1e-12 if mat.Lk_pH_sq else None
lam = mat.lambda_nm * 1e-9 if mat.lambda_nm else None
lk_origin = "measured" if lk else "not available"
lam_origin = "measured" if lam else "not available"
if lk is None and lam is not None:
lk = MU0 * lam**2 / d
lk_origin = "from lambda: mu0 lambda^2 / d"
if lk is None and mat.Rs_ohm_sq and mat.Tc_K:
gap = BCS_GAP_RATIO * KB * mat.Tc_K
lk = HBAR * mat.Rs_ohm_sq / (math.pi * gap)
lk_origin = "from Rs and Tc: hbar Rs / (pi 1.764 kB Tc)"
if lam is None and lk is not None:
lam = math.sqrt(lk * d / MU0)
lam_origin = "from Lk: sqrt(Lk d / mu0)"
return DerivedMaterial(
xi_nm=xi_nm,
xi_origin=xi_origin,
Lk_pH_sq=lk * 1e12 if lk else None,
Lk_origin=lk_origin,
lambda_nm=lam * 1e9 if lam else None,
lambda_origin=lam_origin,
pearl_length_um=(2 * lam**2 / d) * 1e6 if lam else None,
)
# --------------------------------------------------------------------------
# Storage
# --------------------------------------------------------------------------
def _slug(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "material"
def _load_dir(path: Path, is_template: bool) -> list[Material]:
out = []
for file in sorted(path.glob("*.json")):
mat = Material(**json.loads(file.read_text()))
mat.id = mat.id or file.stem
mat.is_template = is_template
out.append(mat)
return out
def list_materials() -> list[Material]:
"""All templates (the default one first), then all user-made materials."""
templates = _load_dir(TEMPLATE_DIR, True)
templates.sort(key=lambda m: m.id != DEFAULT_MATERIAL_ID) # stable: default first
if os.environ.get("OPTIMAL_WIRE_PUBLIC", "") not in ("", "0"):
return templates # public server: no user data on the server
return templates + _load_dir(user_dir(), False)
def get_material(material_id: str) -> Material:
for mat in list_materials():
if mat.id == material_id:
return mat
raise KeyError(material_id)
def save_user_material(mat: Material) -> Material:
"""Write a user-made material to disk. Template ids cannot be replaced."""
mat.is_template = False
mat.id = "user-" + _slug(mat.id.removeprefix("user-") or mat.name)
(user_dir() / f"{mat.id}.json").write_text(
json.dumps(mat.model_dump(exclude={"is_template"}), indent=2)
)
return mat
def delete_user_material(material_id: str) -> None:
"""Delete a user-made material. Templates are read-only."""
file = user_dir() / f"{_slug(material_id)}.json"
if not material_id.startswith("user-") or not file.exists():
raise KeyError(material_id)
file.unlink()