const state = { catalog: null, datasetFilter: "all", datasetQuery: "", modelFilter: "all", modelQuery: "", route: "home", neuralPredictor: null, predictionRunning: false, }; const staticMode = document.documentElement.dataset.magnetStatic === "true"; const el = (id) => document.getElementById(id); const escapeHtml = (value) => String(value).replace(/[&<>'"]/g, (character) => ({ "&": "&", "<": "<", ">": ">", "'": "'", '"': """, })[character]); const labels = { "migration-required": "Being prepared", "publication-blocked": "Publication blocked", planned: "Planned", available: "Available", raw: "Raw", processed: "Training ready", "steady-state-loss": "Steady-state loss", "transient-sequence": "Transient sequence", unvalidated: "Not yet validated", "parity-validated": "Numerically checked", baseline: "Baseline", preparing: "Preparing release", published: "Published", "review-required": "Under review", }; const routes = new Set(["home", "data", "models", "predict", "documentation"]); const legacyRoutes = { data: "data", models: "models", predict: "predict", learn: "documentation", home: "home" }; const pageTitles = { home: "Princeton MagNet", data: "Data · Princeton MagNet", models: "Models · Princeton MagNet", predict: "Predict · Princeton MagNet", documentation: "Documentation · Princeton MagNet", }; function routeFromHash() { const rawHash = window.location.hash.slice(1); const rawRoute = rawHash.startsWith("/") ? rawHash.slice(1) : rawHash; const token = rawRoute.split("/")[0]; const route = token ? (legacyRoutes[token] || token) : "home"; if (!routes.has(route)) { window.history.replaceState(null, "", "#/"); return "home"; } if (rawHash && !rawHash.startsWith("/")) { window.history.replaceState(null, "", route === "home" ? "#/" : `#/${route}`); } return route; } function showRoute({ focus = true } = {}) { const route = routeFromHash(); state.route = route; document.querySelectorAll("[data-view]").forEach((view) => { view.hidden = view.dataset.view !== route; }); document.querySelectorAll("nav [data-route]").forEach((link) => { if (link.dataset.route === route) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current"); }); document.title = pageTitles[route]; window.scrollTo({ top: 0, behavior: "auto" }); const view = document.querySelector(`[data-view="${route}"]`); if (focus) { const heading = view.querySelector("h1"); heading.setAttribute("tabindex", "-1"); heading.focus({ preventScroll: true }); } if (route === "predict" && state.catalog) requestAnimationFrame(updateWaveform); } function humanize(value) { return labels[value] || String(value ?? "—").replaceAll("-", " "); } function formatBytes(bytes) { if (!Number.isFinite(bytes)) return "Not reported"; const units = ["B", "KB", "MB", "GB", "TB"]; let value = bytes; let unit = 0; while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit += 1; } return `${value >= 10 || unit === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`; } function isPublished(item) { const release = item.release; return Boolean( release && release.status === "published" && release.repo_id && release.revision && Array.isArray(release.files) && release.files.length && item.license !== "review-required" ); } function huggingFaceRepoUrl(release) { const prefix = release.repo_type === "dataset" ? "datasets/" : ""; const releasePath = release.path_prefix ? `/${release.path_prefix.split("/").map(encodeURIComponent).join("/")}` : ""; return `https://huggingface.co/${prefix}${release.repo_id}/tree/${encodeURIComponent(release.revision)}${releasePath}`; } function huggingFaceFileUrl(release, file) { const prefix = release.repo_type === "dataset" ? "datasets/" : ""; const path = file.path.split("/").map(encodeURIComponent).join("/"); return `https://huggingface.co/${prefix}${release.repo_id}/resolve/${encodeURIComponent(release.revision)}/${path}?download=true`; } function searchText(item) { return [ item.id, item.title, item.summary, item.task, item.stage, item.format, item.framework, item.license, ...(item.materials || []), ...(item.tags || []), ].filter(Boolean).join(" ").toLocaleLowerCase(); } function libraryActions(item, kind) { const release = item.release || {}; const onlineAction = kind === "model" && item.inference_available && (staticMode || item.id === "igse-v1") ? 'Try online' : ""; if (!isPublished(item)) { return `
${escapeHtml(release.status === "planned" ? "Planned for Hugging Face" : "Publishing pending")}${escapeHtml(release.repo_id || "Repository not assigned")}${onlineAction}
`; } const fileLinks = release.files.map((file) => `
  • ${escapeHtml(file.label || file.path)} ${escapeHtml(formatBytes(file.size_bytes))}
  • `).join(""); let command; if (kind !== "dataset" || item.stage === "raw") { const patterns = release.path_prefix ? `, allow_patterns=\"${release.path_prefix}/**\"` : ""; command = `snapshot_download(repo_id=\"${release.repo_id}\", repo_type=\"${release.repo_type}\", revision=\"${release.revision}\"${patterns})`; } else { const names = item.task === "steady-state-loss" ? ["steady-state-scalar", "steady-state-sequence"] : ["transient-sequences"]; command = names.map((name) => `load_dataset(\"${release.repo_id}\", name=\"${name}\", split=\"full\", revision=\"${release.revision}\")`).join("; "); } return `
    View on Hugging Face ${onlineAction}
    Download files (${release.files.length})
    ${escapeHtml(command)}
    `; } function card(item, kind) { const materials = Array.isArray(item.materials) ? item.materials : []; const materialCount = materials.length; const details = kind === "dataset" ? [["Task", humanize(item.task)], ["Stage", humanize(item.stage)], ["Format", item.format], ["License", humanize(item.license)]] : [["Version", item.version], ["Task", humanize(item.task)], ["Framework", item.framework], ["Materials", materialCount], ["Validation", humanize(item.certification)], ["License", humanize(item.license)]]; const tags = (item.tags || []).slice(0, 4).map((tag) => `${escapeHtml(humanize(tag))}`).join(""); const materialList = kind === "dataset" ? `
    Available materials (${materialCount})

    ${materials.map(escapeHtml).join(", ")}

    ` : ""; return `

    ${escapeHtml(item.title)}

    ${escapeHtml(humanize(item.status))}

    ${escapeHtml(item.summary || "MagNet library release.")}

    ${materialList}
    ${tags}
    ${details.map(([key, value]) => `
    ${escapeHtml(key)}
    ${escapeHtml(value ?? "—")}
    `).join("")}
    Release size
    ${escapeHtml(formatBytes(item.release?.total_size_bytes))}
    ${libraryActions(item, kind)}
    `; } function renderDatasets() { const query = state.datasetQuery.toLocaleLowerCase(); const items = state.catalog.datasets.filter((item) => { const filterMatch = state.datasetFilter === "all" || item.task === state.datasetFilter || item.stage === state.datasetFilter || (state.datasetFilter === "published" && isPublished(item)); return filterMatch && (!query || searchText(item).includes(query)); }); el("dataset-result-count").textContent = `${items.length} ${items.length === 1 ? "dataset" : "datasets"}`; el("dataset-grid").innerHTML = items.map((item) => card(item, "dataset")).join("") || '

    No datasets match these filters.

    '; } function renderModels() { const query = state.modelQuery.toLocaleLowerCase(); const items = state.catalog.models.filter((item) => { const filterMatch = state.modelFilter === "all" || item.task === state.modelFilter || (state.modelFilter === "published" && isPublished(item)) || (state.modelFilter === "inference" && item.inference_available); return filterMatch && (!query || searchText(item).includes(query)); }); el("model-result-count").textContent = `${items.length} ${items.length === 1 ? "model" : "models"}`; el("model-grid").innerHTML = items.map((item) => card(item, "model")).join("") || '

    No models match these filters.

    '; } function waveform(kind, peakMilliTesla, dutyRatio = 0.5, count = 200) { const peak = peakMilliTesla / 1000; const riseDuty = Math.min(0.99, Math.max(0.01, dutyRatio)); return Array.from({ length: count }, (_, index) => { const phase = index / count; if (kind === "triangle") { if (phase < riseDuty) return -peak + 2 * peak * phase / riseDuty; return peak - 2 * peak * (phase - riseDuty) / (1 - riseDuty); } return peak * Math.sin(2 * Math.PI * phase); }); } function drawWaveform(values) { const canvas = el("waveform-chart"); const cssWidth = Math.max(canvas.clientWidth, 320); const cssHeight = cssWidth * (260 / 760); const scale = window.devicePixelRatio || 1; canvas.width = Math.round(cssWidth * scale); canvas.height = Math.round(cssHeight * scale); const context = canvas.getContext("2d"); context.setTransform(scale, 0, 0, scale, 0, 0); const width = cssWidth; const height = cssHeight; const padding = Math.min(34, width * 0.08); context.clearRect(0, 0, width, height); context.strokeStyle = "#d8d8d4"; context.lineWidth = 1; context.beginPath(); context.moveTo(padding, height / 2); context.lineTo(width - padding, height / 2); context.stroke(); context.strokeStyle = "#e77500"; context.lineWidth = 3; context.lineJoin = "round"; const maxAbs = Math.max(...values.map(Math.abs), 1e-9); context.beginPath(); values.forEach((value, index) => { const x = padding + index / (values.length - 1) * (width - 2 * padding); const y = height / 2 - value / maxAbs * (height / 2 - padding); if (index) context.lineTo(x, y); else context.moveTo(x, y); }); context.stroke(); context.fillStyle = "#5f5f5f"; context.font = "13px system-ui"; context.fillText(`+${(maxAbs * 1000).toFixed(0)} mT`, padding, 18); context.fillText(`−${(maxAbs * 1000).toFixed(0)} mT`, padding, height - 8); } function currentWaveform() { const kind = el("waveform").value; const duty = Number(el("duty").value); const values = waveform(kind, Number(el("flux").value), duty, 128); if (kind !== "triangle") return values; const shift = Math.trunc((duty <= 0.5 ? 0.5 - duty / 2 : -duty / 2) * 128); return values.map((_, index) => values[((index - shift) % 128 + 128) % 128]); } function syncPredictionMaterials() { const selectedMaterial = el("material").value; const baseline = state.catalog.models.find((item) => item.id === "igse-v1"); const neural = state.catalog.models.find((item) => item.id === "legacy-transformer-v1"); const supported = state.catalog.materials.filter((item) => (item.igse && baseline?.materials?.includes(item.id)) || neural?.materials?.includes(item.id)); el("material").innerHTML = supported.map((item) => ``).join(""); if (supported.some((item) => item.id === selectedMaterial)) el("material").value = selectedMaterial; el("predict-button").disabled = !supported.length; resetPrediction(); if (!supported.length) { el("neural-prediction-note").textContent = "No material has an online iGSE or Transformer prediction."; } updateWaveform(); } function resetPrediction() { el("igse-loss-result").textContent = "—"; el("neural-loss-result").textContent = "—"; el("igse-prediction-note").textContent = "Uses waveform, frequency, and material; ignores temperature and DC bias."; el("neural-prediction-note").textContent = "Experimental legacy model. First run downloads the browser runtime and material model."; el("bh-loop-section").hidden = true; el("bh-loop-path").setAttribute("d", ""); } function formatLoss(loss) { if (!Number.isFinite(loss)) throw new Error("Model returned a non-finite volumetric loss."); return `${(loss / 1000).toLocaleString(undefined, { maximumFractionDigits: 1 })} kW/m³`; } function drawBhLoop(b, h) { if (!Array.isArray(b) || !Array.isArray(h) || b.length !== 128 || h.length !== b.length || !b.every(Number.isFinite) || !h.every(Number.isFinite)) { throw new Error("Transformer returned an invalid 128-point B–H loop."); } const maxH = Math.max(...h.map(Math.abs), 1e-9); const maxB = Math.max(...b.map(Math.abs), 1e-9); const left = 74; const right = 728; const top = 40; const bottom = 300; const centerX = (left + right) / 2; const centerY = (top + bottom) / 2; const path = h.map((field, index) => { const x = centerX + field / maxH * (right - left) / 2; const y = centerY - b[index] / maxB * (bottom - top) / 2; return `${index ? "L" : "M"}${x.toFixed(2)} ${y.toFixed(2)}`; }).join(" "); el("bh-loop-path").setAttribute("d", path); el("bh-loop-start").setAttribute("cx", (centerX + h[0] / maxH * (right - left) / 2).toFixed(2)); el("bh-loop-start").setAttribute("cy", (centerY - b[0] / maxB * (bottom - top) / 2).toFixed(2)); const fieldLabel = maxH >= 10 ? maxH.toFixed(1) : maxH.toPrecision(2); const fluxLabel = (maxB * 1000).toFixed(0); el("bh-h-negative").textContent = `−${fieldLabel}`; el("bh-h-positive").textContent = `+${fieldLabel}`; el("bh-b-positive").textContent = `+${fluxLabel}`; el("bh-b-negative").textContent = `−${fluxLabel}`; el("bh-loop-section").hidden = false; } function updateDutyVisibility() { const triangular = el("waveform").value === "triangle"; el("duty-control").hidden = !triangular; } function updateWaveform() { drawWaveform(currentWaveform()); const waveformName = el("waveform").selectedOptions[0].textContent; const dutySummary = el("waveform").value === "triangle" ? `, ${Math.round(Number(el("duty").value) * 100)}% rising / ${Math.round((1 - Number(el("duty").value)) * 100)}% falling` : ""; const phaseSummary = el("waveform").value === "triangle" ? " Phase-aligned for the legacy model." : ""; el("waveform-summary").textContent = `${waveformName} waveform, ${el("flux").value} mT peak${dutySummary}. Both methods receive the same 128 B samples.${phaseSummary}`; } function errorMessage(detail) { if (typeof detail === "string") return detail; if (Array.isArray(detail)) return detail.map((item) => item.msg || JSON.stringify(item)).join("; "); if (detail && typeof detail === "object") return detail.msg || JSON.stringify(detail); return "Prediction failed."; } async function predict(event) { event.preventDefault(); if (state.predictionRunning) return; state.predictionRunning = true; const values = currentWaveform(); updateWaveform(); resetPrediction(); el("igse-loss-result").textContent = "Calculating…"; el("neural-loss-result").textContent = "Waiting…"; el("predict-button").disabled = true; const controls = Array.from(el("prediction-form").querySelectorAll("input, select")); controls.forEach((control) => { control.disabled = true; }); const request = { model_id: "igse-v1", material_id: el("material").value, frequency_hz: Number(el("frequency").value) * 1000, temperature_c: Number(el("temperature").value), b_waveform_t: values, }; try { const baseline = state.catalog.models.find((item) => item.id === "igse-v1"); if (!baseline?.materials?.includes(request.material_id) || !state.catalog.materials.find((item) => item.id === request.material_id)?.igse) { throw new Error("No iGSE coefficients are available for this material."); } let result; if (staticMode) { if (!window.MagNetStaticPredictor?.predictLoss) { throw new Error("iGSE browser predictor unavailable. Please refresh the page."); } result = await window.MagNetStaticPredictor.predictLoss(request, state.catalog); } else { const response = await fetch("/api/v1/predict/loss", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(request), }); result = await response.json(); if (!response.ok) throw new Error(errorMessage(result.detail)); } el("igse-loss-result").textContent = formatLoss(result.loss_w_per_m3); el("igse-prediction-note").textContent = [ ...(result.warnings || []), "iGSE does not model temperature or DC bias.", ].join(" "); } catch (error) { el("igse-loss-result").textContent = "Unavailable"; el("igse-prediction-note").textContent = error.message; } try { el("neural-loss-result").textContent = "Loading model…"; const neural = state.catalog.models.find((item) => item.id === "legacy-transformer-v1"); if (!neural?.materials?.includes(request.material_id)) { throw new Error("No Transformer checkpoint is available for this material."); } if (!staticMode || !window.MagNetNeuralPredictor) { throw new Error("Transformer browser inference is available in the static MagNet Space, not this server deployment."); } const material = encodeURIComponent(request.material_id); const modelBase = `./assets/neural/${material}/`; const normResponse = await fetch(`${modelBase}norm.json`); if (!normResponse.ok) throw new Error(`Neural model normalization unavailable (${normResponse.status}).`); const norm = await normResponse.json(); if (!state.neuralPredictor) { state.neuralPredictor = new window.MagNetNeuralPredictor({ workerUrl: "./assets/neural-worker.js", ortScriptUrl: "./assets/ort.wasm.min.js", wasmBaseUrl: "./assets/", }); } const duty = el("waveform").value === "triangle" ? Number(el("duty").value) : 0.5; const domainCheck = window.MagNetNeuralDomain ? window.MagNetNeuralDomain.check(request.material_id, [ request.frequency_hz, Number(el("flux").value) / 1000, Number(el("bias").value), request.temperature_c, duty, ]).catch((error) => ({ error: error.message })) : Promise.resolve({ error: "domain checker unavailable" }); const result = await state.neuralPredictor.predict({ materialId: request.material_id, b_waveform_t: values, frequency_hz: request.frequency_hz, temperature_c: request.temperature_c, bias_a_per_m: Number(el("bias").value), norm, encoderUrl: `${modelBase}encoder.onnx`, decoderUrl: `${modelBase}decoder.onnx`, }, { onProgress(progress) { el("neural-loss-result").textContent = progress.stage === "loading" ? "Loading model…" : progress.stage === "decoding" ? `Calculating ${Math.min(progress.completedSteps, 128)}/128…` : "Finishing…"; }, }); drawBhLoop(values, result.h_waveform_a_per_m); el("neural-loss-result").textContent = formatLoss(result.loss_w_per_m3); const domain = await domainCheck; const notes = [...(result.warnings || [])]; if (domain?.error) notes.push("Operating-domain check unavailable; use caution."); else if ((typeof domain === "boolean" ? domain : domain?.inDomain) === false) { notes.push("Outside the legacy model's measured operating domain; this is an extrapolation."); } notes.push("Legacy neural model; numerical port parity checked, independent accuracy not certified. Calculated in your browser."); el("neural-prediction-note").textContent = notes.join(" "); } catch (error) { el("neural-loss-result").textContent = "Unavailable"; el("neural-prediction-note").textContent = error.message; el("bh-loop-section").hidden = true; el("bh-loop-path").setAttribute("d", ""); } finally { state.predictionRunning = false; el("predict-button").disabled = !el("material").options.length; controls.forEach((control) => { control.disabled = false; }); } } async function init() { const response = await fetch(staticMode ? "./catalog.json" : "/api/v1/catalog"); if (!response.ok) throw new Error(`Catalog request failed (${response.status}).`); state.catalog = await response.json(); el("material-count").textContent = state.catalog.materials.length; el("dataset-count").textContent = state.catalog.datasets.length; el("model-count").textContent = state.catalog.models.length; renderDatasets(); renderModels(); updateDutyVisibility(); syncPredictionMaterials(); } function configureStaticLinks() { if (!staticMode) return; const guide = document.querySelector("[data-api-reference]"); guide.href = "https://huggingface.co/datasets/minjiechen/MagNet"; guide.target = "_blank"; guide.rel = "noopener"; guide.querySelector("strong").textContent = "Dataset guide"; guide.querySelector("span").textContent = "Published data and download instructions ↗"; const footer = document.querySelector("[data-api-footer]"); footer.href = "#/documentation"; footer.textContent = "Documentation"; } document.querySelectorAll("[data-dataset-filter]").forEach((button) => button.addEventListener("click", () => { document.querySelectorAll("[data-dataset-filter]").forEach((peer) => { const active = peer === button; peer.classList.toggle("active", active); peer.setAttribute("aria-pressed", String(active)); }); state.datasetFilter = button.dataset.datasetFilter; renderDatasets(); })); document.querySelectorAll("[data-model-filter]").forEach((button) => button.addEventListener("click", () => { document.querySelectorAll("[data-model-filter]").forEach((peer) => { const active = peer === button; peer.classList.toggle("active", active); peer.setAttribute("aria-pressed", String(active)); }); state.modelFilter = button.dataset.modelFilter; renderModels(); })); el("dataset-search").addEventListener("input", () => { state.datasetQuery = el("dataset-search").value.trim(); renderDatasets(); }); el("model-search").addEventListener("input", () => { state.modelQuery = el("model-search").value.trim(); renderModels(); }); [["frequency", "frequency-output"], ["flux", "flux-output"], ["temperature", "temperature-output"]].forEach(([input, output]) => el(input).addEventListener("input", () => { el(output).value = el(input).value; resetPrediction(); if (input === "flux") updateWaveform(); })); el("material").addEventListener("change", resetPrediction); el("waveform").addEventListener("change", () => { resetPrediction(); updateWaveform(); }); el("waveform").addEventListener("change", updateDutyVisibility); el("duty").addEventListener("input", () => { el("duty-output").value = `${Math.round(Number(el("duty").value) * 100)}%`; resetPrediction(); updateWaveform(); }); el("bias").addEventListener("input", () => { el("bias-output").value = el("bias").value; resetPrediction(); }); el("prediction-form").addEventListener("submit", predict); window.addEventListener("resize", () => { if (state.catalog && state.route === "predict") updateWaveform(); }); window.addEventListener("hashchange", () => showRoute({ focus: true })); document.querySelector(".skip-link").addEventListener("click", (event) => { event.preventDefault(); const heading = document.querySelector(`[data-view="${state.route}"] h1`); heading.setAttribute("tabindex", "-1"); heading.focus(); }); configureStaticLinks(); showRoute({ focus: !["", "#/", "#home"].includes(window.location.hash) }); init().catch((error) => { el("dataset-grid").innerHTML = `

    Catalog unavailable: ${escapeHtml(error.message)}

    `; el("model-grid").innerHTML = `

    Catalog unavailable: ${escapeHtml(error.message)}

    `; el("predict-button").disabled = true; });