From d2b5a482f9554c843b0ae41ec540c8caf11b749c Mon Sep 17 00:00:00 2001 From: Winter-Soren Date: Sun, 15 Nov 2026 01:17:11 +0530 Subject: [PATCH 1/2] feat(pharma): redesign drug discovery job page Pipeline stepper, KPI row, full-bleed protein viewer with floating controls, best ligand and score convergence cards, compact candidate cards with ADMET rules, collapsible pipeline log. Scope the ligand SVG dark-theme style so it no longer recolours charts, and parse zone-less backend timestamps as UTC. --- .../pharma/components/admet-panel.tsx | 80 +-- .../pharma/components/candidate-card.tsx | 161 +++-- .../pharma/components/ligand-viewer.tsx | 116 +--- .../pharma/components/pharma-live-canvas.tsx | 648 +++++++++--------- .../pharma/components/protein-viewer.tsx | 75 +- 5 files changed, 521 insertions(+), 559 deletions(-) diff --git a/frontend/src/features/pharma/components/admet-panel.tsx b/frontend/src/features/pharma/components/admet-panel.tsx index 4d3d99c1..f8c8b054 100644 --- a/frontend/src/features/pharma/components/admet-panel.tsx +++ b/frontend/src/features/pharma/components/admet-panel.tsx @@ -3,62 +3,54 @@ import type { ADMETResult } from "@/features/pharma/types"; export function ADMETPanel({ admet }: { admet: ADMETResult }) { const metrics = [ - { label: "MW", value: admet.molecular_weight.toFixed(1), unit: "Da", ok: admet.molecular_weight <= 500 }, - { label: "LogP", value: admet.logp.toFixed(2), unit: "", ok: admet.logp <= 5 }, - { label: "TPSA", value: admet.tpsa.toFixed(1), unit: "Ų", ok: admet.tpsa <= 140 }, - { label: "HBD", value: String(admet.hbd), unit: "", ok: admet.hbd <= 5 }, - { label: "HBA", value: String(admet.hba), unit: "", ok: admet.hba <= 10 }, - { label: "QED", value: admet.qed_score.toFixed(3), unit: "", ok: admet.qed_score >= 0.4 }, - { label: "SA", value: admet.synthetic_accessibility.toFixed(2), unit: "", ok: admet.synthetic_accessibility <= 4 }, + { label: "MW", value: admet.molecular_weight.toFixed(1), unit: "Da", rule: "≤ 500", ok: admet.molecular_weight <= 500 }, + { label: "LogP", value: admet.logp.toFixed(2), unit: "", rule: "≤ 5", ok: admet.logp <= 5 }, + { label: "TPSA", value: admet.tpsa.toFixed(1), unit: "Ų", rule: "≤ 140", ok: admet.tpsa <= 140 }, + { label: "HBD", value: String(admet.hbd), unit: "", rule: "≤ 5", ok: admet.hbd <= 5 }, + { label: "HBA", value: String(admet.hba), unit: "", rule: "≤ 10", ok: admet.hba <= 10 }, + { label: "QED", value: admet.qed_score.toFixed(2), unit: "", rule: "≥ 0.4", ok: admet.qed_score >= 0.4 }, + { label: "SA", value: admet.synthetic_accessibility.toFixed(1), unit: "", rule: "≤ 4", ok: admet.synthetic_accessibility <= 4 }, ]; return ( -
-
-

- ADMET Profile -

+
+
+

ADMET

- {admet.passes ? : } - {admet.passes ? "Passes" : "Fails"} + {admet.passes ? : } + {admet.passes ? "Drug-like" : "Fails filters"} + {admet.herg_risk && ( + + hERG risk + + )}
-
- {metrics.map(({ label, value, unit, ok }) => ( -
-

{label}

-

+

+ {metrics.map(({ label, value, unit, rule, ok }) => ( +
+
+ {label} + {rule} +
+
{value} - {unit && {unit}} -

+ {unit && {unit}} +
))} -
+ {admet.failure_reasons.length > 0 && ( -
- {admet.failure_reasons.map((r, i) => ( -

- - {r} -

+
    + {admet.failure_reasons.map((reason) => ( +
  • · {reason}
  • ))} -
+ )} -
+
); } diff --git a/frontend/src/features/pharma/components/candidate-card.tsx b/frontend/src/features/pharma/components/candidate-card.tsx index f0223ea4..b8f763db 100644 --- a/frontend/src/features/pharma/components/candidate-card.tsx +++ b/frontend/src/features/pharma/components/candidate-card.tsx @@ -1,79 +1,112 @@ +"use client"; + +import { useState } from "react"; +import { Check, Copy, GitMerge } from "lucide-react"; import type { PharmaCandidate } from "@/features/pharma/types"; import { ADMETPanel } from "./admet-panel"; -import { GitMerge } from "lucide-react"; +import { LigandViewer } from "./ligand-viewer"; + +function CopySmiles({ smiles }: { smiles: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} + +function Metric({ label, value, hint }: { label: string; value: string; hint?: string }) { + return ( +
+

{label}

+

{value}

+
+ ); +} export function CandidateCard({ candidate }: { candidate: PharmaCandidate }) { const { smiles, vqc_score, docking_pose, scaffold_history, rank } = candidate; + const [lo, hi] = vqc_score.confidence_interval; return ( -
- {/* Header row */} -
-
-

- Rank #{rank} -

-

- {smiles} -

-
-
-

Binding Affinity

-

- {vqc_score.binding_affinity_kcal.toFixed(2)} -

-

kcal/mol

-

- [{vqc_score.confidence_interval[0].toFixed(1)}, {vqc_score.confidence_interval[1].toFixed(1)}] -

-
+
+
+ + #{rank} + +
- {/* Docking metrics */} -
-
-

QUBO Energy

-

- {docking_pose.total_qubo_energy.toFixed(3)} -

-
-
-

QAOA Approx. Ratio

-

- {(docking_pose.qaoa_approximation_ratio * 100).toFixed(1)}% -

-
-
-

DC-QAOA α

-

- {docking_pose.dc_qaoa_alpha.toFixed(2)} -

-
-
- - - - {scaffold_history.length > 0 && ( -
-
- -

- Scaffold Hops ({scaffold_history.length}) +

+
+
+

Binding affinity

+

+ {vqc_score.binding_affinity_kcal.toFixed(2)} + kcal/mol +

+

+ 95% CI {lo.toFixed(2)} to {hi.toFixed(2)}

-
- {scaffold_history.map((hop, i) => ( -
- #{hop.iteration + 1} - {hop.input_smiles} - → - {hop.output_smiles} - ({hop.reason_for_hop}) -
- ))} +
+ + +
- )} -
+ + + + + + {scaffold_history.length > 0 && ( +
+ + + {scaffold_history.length} scaffold hop{scaffold_history.length === 1 ? "" : "s"} + show + +
    + {scaffold_history.map((hop) => ( +
  1. + #{hop.iteration + 1} + + {hop.input_smiles} + → + {hop.output_smiles} + + {hop.reason_for_hop} +
  2. + ))} +
+
+ )} +
+
); } diff --git a/frontend/src/features/pharma/components/ligand-viewer.tsx b/frontend/src/features/pharma/components/ligand-viewer.tsx index dcb4e09d..4aad8049 100644 --- a/frontend/src/features/pharma/components/ligand-viewer.tsx +++ b/frontend/src/features/pharma/components/ligand-viewer.tsx @@ -1,111 +1,67 @@ "use client"; import { useEffect, useRef, useState } from "react"; -import { Loader2, Hexagon } from "lucide-react"; +import { Loader2 } from "lucide-react"; interface Props { smiles: string; - label?: string; width?: number; height?: number; + className?: string; } -// Injected into the SVG so bonds/atoms are visible on dark backgrounds -// regardless of whether openchemlib uses inline attrs or CSS style attributes +// Injected into the SVG so bonds/atoms read on dark backgrounds whatever openchemlib emits. +// Scoped to .ocl-ligand: an inline `; -export function LigandViewer({ smiles, label, width = 260, height = 180 }: Props) { +/** Chrome-less 2D structure drawing; the parent supplies the frame and label. */ +export function LigandViewer({ smiles, width = 260, height = 180, className = "" }: Props) { const containerRef = useRef(null); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); + const [state, setState] = useState<"loading" | "ready" | "error">("loading"); useEffect(() => { if (!smiles || !containerRef.current) return; - let cancelled = false; - setLoading(true); - setError(null); - + setState("loading"); import("openchemlib") .then((OCL) => { if (cancelled || !containerRef.current) return; - try { - const mol = OCL.Molecule.fromSmiles(smiles); - - const svgStr = mol.toSVG(width, height, undefined, { - autoCrop: true, - autoCropMargin: 12, - suppressChiralText: true, - noStereoProblem: true, - }); - - // Inject the dark-theme style block right after the opening ]*>)/, `$1${DARK_THEME_STYLE}`); - - containerRef.current.innerHTML = patched; - setLoading(false); - } catch { - if (!cancelled) { - setError("Invalid SMILES"); - setLoading(false); - } - } + const svg = OCL.Molecule.fromSmiles(smiles).toSVG(width, height, undefined, { + autoCrop: true, + autoCropMargin: 12, + suppressChiralText: true, + noStereoProblem: true, + }); + containerRef.current.innerHTML = svg.replace(/(]*>)/, `$1${DARK_THEME_STYLE}`); + setState("ready"); }) - .catch(() => { - if (!cancelled) { - setError("Failed to load chemistry engine"); - setLoading(false); - } - }); - - return () => { cancelled = true; }; + .catch(() => !cancelled && setState("error")); + return () => { + cancelled = true; + }; }, [smiles, width, height]); return ( -
-
- - - Ligand Structure - - {label && ( - - {label} - - )} -
- +
+ {state === "loading" && } + {state === "error" &&

Structure unavailable

}
- {loading && ( -
- -

Rendering…

-
- )} - {error && ( -

{error}

- )} -
-
- - {!loading && !error && ( -
-

- {smiles} -

-
- )} + ref={containerRef} + className={state === "ready" ? "ocl-ligand [&_svg]:h-auto [&_svg]:max-w-full" : "hidden"} + />
); } diff --git a/frontend/src/features/pharma/components/pharma-live-canvas.tsx b/frontend/src/features/pharma/components/pharma-live-canvas.tsx index 5cee9220..e080e0e0 100644 --- a/frontend/src/features/pharma/components/pharma-live-canvas.tsx +++ b/frontend/src/features/pharma/components/pharma-live-canvas.tsx @@ -3,28 +3,22 @@ import { PublishToNearButton } from "@/features/agentkit"; import dynamic from "next/dynamic"; import { useEffect, useRef, useState } from "react"; +import { Ban, Check, CheckCircle2, ChevronDown, Loader2 } from "lucide-react"; import { - Activity, - Ban, - CheckCircle2, - FlaskConical, - Loader2, - Star, -} from "lucide-react"; -import { - LineChart, - Line, + Area, + AreaChart, + CartesianGrid, + ResponsiveContainer, + Tooltip, XAxis, YAxis, - Tooltip, - ResponsiveContainer, } from "recharts"; -import { motion, AnimatePresence } from "motion/react"; +import { motion } from "motion/react"; import { usePharmaJobLive } from "../hooks/use-pharma-job-live"; import { LigandViewer } from "./ligand-viewer"; import { CandidateCard } from "./candidate-card"; import { PharmaPeersDrawer } from "./pharma-peers-drawer"; -import { LOG_META, STAGE_ICONS } from "../lib/pharma-stage-config"; +import { LOG_META, STAGE_ICONS, STAGE_ORDER } from "../lib/pharma-stage-config"; import type { PharmaJob, PipelineLogEntry, PipelineLogLevel } from "../types"; import type { ScorePoint } from "../types-live"; @@ -33,15 +27,16 @@ const ProteinViewer = dynamic( { ssr: false }, ); -const STATUS_COLORS: Record = { - queued: "text-amber-400 bg-amber-400/10 border-amber-400/25", - running: "text-sky-400 bg-sky-400/10 border-sky-400/25", - completed: "text-emerald-400 bg-emerald-400/10 border-emerald-400/25", - failed: "text-red-400 bg-red-400/10 border-red-400/25", - cancelled: "text-white/30 bg-white/5 border-white/10", +const STATUS_STYLE: Record = { + queued: "bg-amber-400/10 text-amber-300", + running: "bg-sky-400/10 text-sky-300", + completed: "bg-emerald-400/10 text-emerald-300", + failed: "bg-rose-400/10 text-rose-300", + cancelled: "bg-white/5 text-white/40", }; const QUANTUM_LEVELS = new Set(["vqe"]); +const PIPELINE = STAGE_ORDER.filter((s) => s !== "completed"); interface Props { job: PharmaJob; @@ -79,13 +74,10 @@ function deriveMetricsFromLogs(logLines: PipelineLogEntry[]): DerivedMetrics { const m = line.message.match(/Iteration \d+\/(\d+)/); if (m) maxIter = Math.max(maxIter, parseInt(m[1], 10)); } - - // Extract the current candidate SMILES from the Stage 3 fragmenting log if (line.level === "stage" && line.message.includes("fragment decomposition:")) { const m = line.message.match(/fragment decomposition:\s*(\S+)/); if (m) currentCandidateSmiles = m[1]; } - if (line.level === "score") { const scoreM = line.message.match(/([-\d.]+)\s*kcal/); const smilesM = line.message.match(/SMILES:(\S+)/); @@ -98,142 +90,201 @@ function deriveMetricsFromLogs(logLines: PipelineLogEntry[]): DerivedMetrics { scoreHistory.push({ iteration: iterCount, score: v, ts: line.ts }); } } - - if (line.level === "admet" && line.message.toLowerCase().includes("pass")) { - admetPasses++; - } + if (line.level === "admet" && line.message.toLowerCase().includes("pass")) admetPasses++; } return { currentStage, iterCount, maxIter, bestScore, bestSmiles, currentCandidateSmiles, scoreHistory, admetPasses }; } -function StatCard({ label, value, color }: { label: string; value: string; color: string }) { +// Backend timestamps are UTC but may lack a zone suffix; without one JS parses them as local time. +function parseUtc(ts: string): number { + return new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(ts) ? ts : `${ts}Z`).getTime(); +} + +function formatDuration(totalSec: number): string { + const s = Math.max(0, Math.round(totalSec)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + if (h > 0) return `${h}h ${m}m`; + if (m > 0) return `${m}m ${String(sec).padStart(2, "0")}s`; + return `${sec}s`; +} + +function Panel({ + title, + aside, + children, + className = "", +}: { + title: string; + aside?: React.ReactNode; + children: React.ReactNode; + className?: string; +}) { return ( - -

{label}

-

{value}

-
+
+
+

{title}

+ {aside &&
{aside}
} +
+ {children} +
); } -function LiveLogRow({ entry }: { entry: PipelineLogEntry }) { +function Kpi({ label, value, unit, sub, tone = "text-white" }: { + label: string; + value: string; + unit?: string; + sub?: string; + tone?: string; +}) { + return ( +
+

{label}

+ + {value} + {unit && {unit}} + + {sub &&

{sub}

} +
+ ); +} + +function PipelineStepper({ stage, done, iter, maxIter }: { + stage: string | null; + done: boolean; + iter: number; + maxIter: number; +}) { + const current = stage ? PIPELINE.indexOf(stage) : -1; + const pct = maxIter > 0 ? Math.min((iter / maxIter) * 100, 100) : done ? 100 : 0; + return ( +
+
    + {PIPELINE.map((key, i) => { + const meta = STAGE_ICONS[key]; + const state = done || i < current ? "done" : i === current ? "active" : "todo"; + return ( +
  1. + + {state === "done" ? : state === "active" ? : i + 1} + + + {meta?.label ?? key} + + {i < PIPELINE.length - 1 && ( +
  2. + ); + })} +
+ {maxIter > 0 && ( +
+
+ +
+ + iteration {iter}/{maxIter} + +
+ )} +
+ ); +} + +function LogRow({ entry }: { entry: PipelineLogEntry }) { const meta = LOG_META[entry.level] ?? LOG_META.info; - const Icon = meta.icon; - const time = new Date(entry.ts).toLocaleTimeString("en-US", { + const time = new Date(parseUtc(entry.ts)).toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit", }); - const displayMsg = entry.level === "score" - ? entry.message.replace(/\s*SMILES:\S+/, "").trim() - : entry.message; - + const message = entry.level === "score" ? entry.message.replace(/\s*SMILES:\S+/, "").trim() : entry.message; return ( - - {time} - - {meta.label} - - - {displayMsg} - - ); -} - -function IterProgress({ current, max }: { current: number; max: number }) { - const pct = Math.min((current / max) * 100, 100); - return ( -
- - Iter {current}/{max} - -
- -
- {pct.toFixed(0)}% -
+
  • + {time} + {meta.label} + {message} +
  • ); } export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { const { job_id: jobId, target_pdb_id: targetPdbId, mode, status } = job; - const isRunning = status === "queued" || status === "running"; + const isRunning = status === "queued" || status === "running"; const isCompleted = status === "completed"; const { data: liveData } = usePharmaJobLive(jobId, isRunning); const allLogLines = job.log_lines ?? []; const bioLogLines = allLogLines.filter((l) => !QUANTUM_LEVELS.has(l.level)); - const derived = deriveMetricsFromLogs(allLogLines); + const derived = deriveMetricsFromLogs(allLogLines); + const topCandidate = job.result?.candidates[0]; - const effectiveStage = liveData?.current_stage ?? derived.currentStage; - const effectiveIter = liveData?.iteration_count ?? derived.iterCount; - const effectiveScore = isCompleted - ? (job.result?.candidates[0]?.vqc_score?.binding_affinity_kcal ?? liveData?.best_score ?? derived.bestScore) + const effectiveStage = liveData?.current_stage ?? derived.currentStage; + const effectiveIter = liveData?.iteration_count ?? derived.iterCount; + const effectiveScore = isCompleted + ? (topCandidate?.vqc_score?.binding_affinity_kcal ?? liveData?.best_score ?? derived.bestScore) : (liveData?.best_score ?? derived.bestScore); - const effectiveAdmet = liveData?.admet_passes ?? derived.admetPasses; - const effectiveHistory = (liveData?.score_history?.length ?? 0) > 0 - ? liveData!.score_history - : derived.scoreHistory; - const effectiveSmiles = isCompleted - ? (job.result?.candidates[0]?.smiles ?? liveData?.best_smiles ?? derived.bestSmiles ?? derived.currentCandidateSmiles) + const effectiveAdmet = liveData?.admet_passes ?? derived.admetPasses; + const effectiveHistory = (liveData?.score_history?.length ?? 0) > 0 ? liveData!.score_history : derived.scoreHistory; + const effectiveSmiles = isCompleted + ? (topCandidate?.smiles ?? liveData?.best_smiles ?? derived.bestSmiles ?? derived.currentCandidateSmiles) : (liveData?.best_smiles ?? derived.bestSmiles ?? derived.currentCandidateSmiles); + const maxIter = derived.maxIter; - const stageRef = useRef(null); + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- NGL ships no types + const stageRef = useRef(null); const prevSmilesRef = useRef(null); - const prevScoreRef = useRef(null); - const prevStageRef = useRef(null); - const logScrollRef = useRef(null); + const prevScoreRef = useRef(null); + const prevStageRef = useRef(null); + const logScrollRef = useRef(null); const [discoveredSmiles, setDiscoveredSmiles] = useState([]); - const discoveredScrollRef = useRef(null); + const [logOpen, setLogOpen] = useState(isRunning); - // Elapsed-time timer (ticks every second while running) - const [elapsedSec, setElapsedSec] = useState(0); + const [elapsedSec, setElapsedSec] = useState(0); useEffect(() => { if (!isRunning) return; - const start = new Date(job.submitted_at).getTime(); + const start = parseUtc(job.submitted_at); const tick = () => setElapsedSec(Math.floor((Date.now() - start) / 1000)); tick(); const id = setInterval(tick, 1000); return () => clearInterval(id); }, [isRunning, job.submitted_at]); - const elapsedDisplay = (() => { - const h = Math.floor(elapsedSec / 3600); - const m = Math.floor((elapsedSec % 3600) / 60); - const s = elapsedSec % 60; - return h > 0 - ? `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` - : `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; - })(); - - // NGL: swap ligand when best smiles changes + // NGL: dock the current best ligand into the protein scene useEffect(() => { const stage = stageRef.current; const smiles = effectiveSmiles; if (!stage || !smiles || smiles === prevSmilesRef.current) return; prevSmilesRef.current = smiles; stage.compList - .filter((c: any) => c.name === "live-ligand") - .forEach((c: any) => stage.removeComponent(c)); + .filter((c: { name: string }) => c.name === "live-ligand") + .forEach((c: unknown) => stage.removeComponent(c)); stage .loadFile(`smiles://${smiles}`, { name: "live-ligand" }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any .then((comp: any) => { if (!comp) return; comp.addRepresentation("ball+stick", { colorScheme: "element", quality: "high" }); @@ -242,14 +293,16 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { .catch(() => {}); }, [effectiveSmiles]); - // NGL: pocket pulse on new best score + // NGL: pulse the pocket surface on a new best score useEffect(() => { const stage = stageRef.current; if (!stage || effectiveScore === null || effectiveScore === prevScoreRef.current) return; prevScoreRef.current = effectiveScore; + // eslint-disable-next-line @typescript-eslint/no-explicit-any stage.compList.forEach((comp: any) => { comp.reprList - .filter((r: any) => r.type === "surface") + .filter((r: { type: string }) => r.type === "surface") + // eslint-disable-next-line @typescript-eslint/no-explicit-any .forEach((r: any) => { r.setParameters({ opacity: 0.5 }); setTimeout(() => r.setParameters({ opacity: 0.18 }), 700); @@ -257,7 +310,6 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { }); }, [effectiveScore]); - // NGL: camera refocus on stage change useEffect(() => { const stage = stageRef.current; if (!stage || !effectiveStage || effectiveStage === prevStageRef.current) return; @@ -265,243 +317,191 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { stage.autoView(800); }, [effectiveStage]); - // Auto-scroll log to bottom on new events useEffect(() => { const el = logScrollRef.current; if (el) el.scrollTop = el.scrollHeight; - }, [bioLogLines.length]); + }, [bioLogLines.length, logOpen]); - // Accumulate discovered SMILES on ADMET pass - useEffect(() => { - const smiles = effectiveSmiles; - if (!smiles || effectiveAdmet === 0) return; - setDiscoveredSmiles((prev) => { - if (prev.includes(smiles)) return prev; - return [...prev, smiles].slice(-20); - }); - }, [effectiveAdmet, effectiveSmiles]); - - // On completion, add final candidates - useEffect(() => { - if (!isCompleted || !job.result) return; - setDiscoveredSmiles((prev) => { - const fresh = job.result!.candidates.map((c) => c.smiles).filter((s) => !prev.includes(s)); - return [...prev, ...fresh].slice(-20); - }); - }, [isCompleted, job.result]); - - useEffect(() => { - const el = discoveredScrollRef.current; - if (el) el.scrollLeft = el.scrollWidth; - }, [discoveredSmiles.length]); + // Remember each ligand that passed ADMET (state adjusted during render, not in an effect). + if (effectiveSmiles && effectiveAdmet > 0 && !discoveredSmiles.includes(effectiveSmiles)) { + setDiscoveredSmiles([...discoveredSmiles, effectiveSmiles].slice(-12)); + } - const stageMeta = effectiveStage ? STAGE_ICONS[effectiveStage] : null; - const ActiveStageIcon = isCompleted ? CheckCircle2 : (stageMeta?.icon ?? Activity); - const stageColor = isCompleted ? "text-emerald-400" : (stageMeta?.color ?? "text-white/30"); - const maxIter = derived.maxIter; + const stageMeta = effectiveStage ? STAGE_ICONS[effectiveStage] : null; + const runtime = isCompleted && job.result ? job.result.total_runtime_seconds : elapsedSec; + const candidates = job.result?.candidates ?? []; return ( -
    - - {/* Top bar */} -
    - - - {targetPdbId} — {mode} - - - {isRunning && } - {isCompleted && } - {status} - - {isRunning && ( - - - - - - live - - )} - {jobId} -
    - -
    - {isCompleted && } - {isRunning && ( -
    - - - - +
    + {/* Header */} +
    +
    +
    +

    Drug discovery · {mode}

    +
    +

    {targetPdbId.toUpperCase()}

    + + {isRunning && } + {isCompleted && } + {status} - {elapsedDisplay} - - -
    - )} -
    - - {/* Main split */} -
    - - {/* LEFT: 3D protein viewer */} -
    -
    - - - {isCompleted ? "Completed" : (stageMeta?.label ?? "Protein Structure")} - - {targetPdbId.toUpperCase()} -
    -
    - { stageRef.current = stage; }} /> +
    +

    {jobId}

    - {/* Live stage / score overlay on the 3D canvas */} -
    - {isRunning ? ( - <> - - - {stageMeta?.label ?? "Initialising…"} - - {maxIter > 0 && ( - iter {effectiveIter}/{maxIter} - )} - {effectiveScore !== null && ( - - {effectiveScore.toFixed(2)} kcal/mol - - )} - - ) : isCompleted ? ( - <> - - Pipeline complete - {effectiveScore !== null && ( - - best {effectiveScore.toFixed(2)} kcal/mol - - )} - - ) : ( - No active pipeline +
    + + {isCompleted && } + {isRunning && ( + )}
    +
    + +
    + + +
    + + 0 ? String(effectiveIter) : "—"} + unit={maxIter > 0 ? `/ ${maxIter}` : undefined} + sub={isCompleted ? undefined : (stageMeta?.label ?? "Starting")} + /> + 0 ? String(effectiveAdmet) : "—"} + sub={isCompleted ? `${candidates.filter((c) => c.admet.passes).length} pass ADMET` : "passed ADMET so far"} + /> + 0 ? formatDuration(runtime) : "—"} + sub={job.result ? `${Math.round(job.result.cache_hit_rate * 100)}% VQE cache hits` : undefined} + /> +
    - {/* RIGHT: dashboard + live log */} -
    - - {/* Stat cards */} -
    - - 0 ? (maxIter > 0 ? `${effectiveIter}/${maxIter}` : String(effectiveIter)) : "—"} color="text-violet-300" /> - - 0 ? String(effectiveAdmet) : "—"} color="text-teal-300" /> +
    +
    + { stageRef.current = stage; }} />
    - {/* Iteration progress bar */} - {maxIter > 0 && } - - {/* Live biology event feed */} -
    -
    - Live Biology Feed - - {isRunning && } - {bioLogLines.length} event{bioLogLines.length !== 1 ? "s" : ""} - -
    -
    - {bioLogLines.length === 0 ? ( -
    - {isRunning ? ( - Waiting for pipeline to start… - ) : "No events"} -
    - ) : ( - - {bioLogLines.map((entry, i) => ( - +
    + +
    + {effectiveSmiles ? ( + + ) : ( +

    + {isRunning ? "Waiting for the first scored ligand…" : "No ligand"} +

    + )} +
    + {isRunning && discoveredSmiles.length > 1 && ( +
    + {discoveredSmiles.slice(0, -1).reverse().map((s) => ( +
    + +
    ))} - - )} -
    -
    - - {/* Score chart + best ligand side-by-side */} -
    -
    -

    Score / Iter

    - {effectiveHistory.length > 0 ? ( - - - - - [`${(v as number).toFixed(2)} kcal/mol`, "Score"]} labelFormatter={(l: unknown) => `Iter ${l}`} /> - - - - ) : ( -
    - {isRunning ? waiting… : "—"}
    )} -
    -
    -

    - {effectiveScore != null ? "Best Ligand" : "Current Candidate"} -

    - {effectiveSmiles ? ( - - ) : ( -
    - {isRunning ? : "—"} -
    - )} -
    + + + +
    + {effectiveHistory.length > 0 ? ( + + + + + + + + + + + + [`${(v as number).toFixed(2)} kcal/mol`, "Score"]} + labelFormatter={(l: unknown) => `Iteration ${l}`} + /> + + + + ) : ( +
    + {isRunning ? "Scores appear after the first docking round" : "No scores recorded"} +
    + )} +
    +
    +
    - {/* Discovered SMILES strip */} - {discoveredSmiles.length > 0 && ( -
    -

    Discovered ({discoveredSmiles.length})

    -
    - - {discoveredSmiles.map((smiles) => ( - - - - ))} - -
    + {candidates.length > 0 && ( +
    +
    +

    Top candidates

    + + {candidates.length} ranked by binding affinity · {job.result!.iterations_used} iterations +
    - )} +
    + {candidates.map((c) => ( + + ))} +
    +
    + )} - {/* Completed: candidate cards */} - {isCompleted && job.result && job.result.candidates.length > 0 && ( -
    -
    - -

    - Top Candidates ({job.result.candidates.length}) +

    + + {logOpen && ( +
    + {bioLogLines.length === 0 ? ( +

    + {isRunning && } + {isRunning ? "Waiting for the pipeline to start…" : "No events"}

    - - {job.result.total_runtime_seconds.toFixed(1)}s · {job.result.iterations_used} iters - -
    -
    - {job.result.candidates.map((c) => ( - - ))} -
    + ) : ( +
      + {bioLogLines.map((entry, i) => ( + + ))} +
    + )}
    )} -
    +
    ); diff --git a/frontend/src/features/pharma/components/protein-viewer.tsx b/frontend/src/features/pharma/components/protein-viewer.tsx index 6b222d97..b1e7c691 100644 --- a/frontend/src/features/pharma/components/protein-viewer.tsx +++ b/frontend/src/features/pharma/components/protein-viewer.tsx @@ -1,7 +1,7 @@ "use client"; import { useEffect, useRef, useState } from "react"; -import { Loader2, RotateCcw, Maximize2, Layers } from "lucide-react"; +import { Loader2, RotateCcw } from "lucide-react"; type RepStyle = "cartoon" | "surface" | "ball+stick"; @@ -140,29 +140,23 @@ export function ProteinViewer({ pdbId, height = 380, onStageReady }: Props) { } return ( -
    - {/* Header bar */} -
    - - - 3D Protein Structure - - - {pdbId.toUpperCase()} - +
    +
    - {/* Rep toggles */} -
    +
    + + PDB {pdbId.toUpperCase()} + +
    {REP_LABELS.map(({ key, label }) => (
    - {/* Viewer canvas */} -
    -
    - - {loading && ( -
    - -

    - Loading {pdbId.toUpperCase()} from RCSB… -

    -
    - )} - - {error && ( -
    -

    {error}

    -
    - )} -
    - - {/* Footer hint */} - {!loading && !error && ( -
    -

    - Drag to rotate · Scroll to zoom · Right-drag to translate · - Ligand shown as ball+stick · Binding pocket surface (electrostatic) -

    + {loading && ( +
    + +

    Loading {pdbId.toUpperCase()} from RCSB…

    )} + {error && ( +
    +

    {error}

    +
    + )} + {!loading && !error && ( +

    + Drag to rotate · scroll to zoom · pocket surface coloured by charge +

    + )}
    ); } From ac883491eac7238c5e17455c6f06f9532ef26896 Mon Sep 17 00:00:00 2001 From: Winter-Soren Date: Sun, 15 Nov 2026 03:04:38 +0530 Subject: [PATCH 2/2] feat(pharma): scientific job page with figures, tables and methods Rebuild the drug discovery job page as a lab report: pipeline trace, readouts, Figure 1 (receptor, lead ligand, dG convergence with CI, MW x cLogP chemical space), Table 1 of scored ligands, and a per-compound dossier (ADMET radar and table, HOMO/LUMO diagram, VQE error vs exact, fragment table with peers, QAOA register and angles, scaffold lineage). Per-ligand data is parsed from the run log. Failed and cancelled jobs use the same page; the duplicate legacy view and old card components are removed. --- .../pharma/components/admet-panel.tsx | 56 -- .../pharma/components/candidate-card.tsx | 112 ---- .../pharma/components/candidate-dossier.tsx | 264 ++++++++ .../pharma/components/pharma-job-detail.tsx | 335 +--------- .../pharma/components/pharma-live-canvas.tsx | 608 ++++++++---------- .../pharma/components/science-figures.tsx | 344 ++++++++++ .../src/features/pharma/lib/pharma-science.ts | 99 +++ frontend/src/features/pharma/types.ts | 8 + 8 files changed, 983 insertions(+), 843 deletions(-) delete mode 100644 frontend/src/features/pharma/components/admet-panel.tsx delete mode 100644 frontend/src/features/pharma/components/candidate-card.tsx create mode 100644 frontend/src/features/pharma/components/candidate-dossier.tsx create mode 100644 frontend/src/features/pharma/components/science-figures.tsx create mode 100644 frontend/src/features/pharma/lib/pharma-science.ts diff --git a/frontend/src/features/pharma/components/admet-panel.tsx b/frontend/src/features/pharma/components/admet-panel.tsx deleted file mode 100644 index f8c8b054..00000000 --- a/frontend/src/features/pharma/components/admet-panel.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { CheckCircle2, XCircle } from "lucide-react"; -import type { ADMETResult } from "@/features/pharma/types"; - -export function ADMETPanel({ admet }: { admet: ADMETResult }) { - const metrics = [ - { label: "MW", value: admet.molecular_weight.toFixed(1), unit: "Da", rule: "≤ 500", ok: admet.molecular_weight <= 500 }, - { label: "LogP", value: admet.logp.toFixed(2), unit: "", rule: "≤ 5", ok: admet.logp <= 5 }, - { label: "TPSA", value: admet.tpsa.toFixed(1), unit: "Ų", rule: "≤ 140", ok: admet.tpsa <= 140 }, - { label: "HBD", value: String(admet.hbd), unit: "", rule: "≤ 5", ok: admet.hbd <= 5 }, - { label: "HBA", value: String(admet.hba), unit: "", rule: "≤ 10", ok: admet.hba <= 10 }, - { label: "QED", value: admet.qed_score.toFixed(2), unit: "", rule: "≥ 0.4", ok: admet.qed_score >= 0.4 }, - { label: "SA", value: admet.synthetic_accessibility.toFixed(1), unit: "", rule: "≤ 4", ok: admet.synthetic_accessibility <= 4 }, - ]; - - return ( -
    -
    -

    ADMET

    - - {admet.passes ? : } - {admet.passes ? "Drug-like" : "Fails filters"} - - {admet.herg_risk && ( - - hERG risk - - )} -
    -
    - {metrics.map(({ label, value, unit, rule, ok }) => ( -
    -
    - {label} - {rule} -
    -
    - {value} - {unit && {unit}} -
    -
    - ))} -
    - {admet.failure_reasons.length > 0 && ( -
      - {admet.failure_reasons.map((reason) => ( -
    • · {reason}
    • - ))} -
    - )} -
    - ); -} diff --git a/frontend/src/features/pharma/components/candidate-card.tsx b/frontend/src/features/pharma/components/candidate-card.tsx deleted file mode 100644 index b8f763db..00000000 --- a/frontend/src/features/pharma/components/candidate-card.tsx +++ /dev/null @@ -1,112 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { Check, Copy, GitMerge } from "lucide-react"; -import type { PharmaCandidate } from "@/features/pharma/types"; -import { ADMETPanel } from "./admet-panel"; -import { LigandViewer } from "./ligand-viewer"; - -function CopySmiles({ smiles }: { smiles: string }) { - const [copied, setCopied] = useState(false); - return ( - - ); -} - -function Metric({ label, value, hint }: { label: string; value: string; hint?: string }) { - return ( -
    -

    {label}

    -

    {value}

    -
    - ); -} - -export function CandidateCard({ candidate }: { candidate: PharmaCandidate }) { - const { smiles, vqc_score, docking_pose, scaffold_history, rank } = candidate; - const [lo, hi] = vqc_score.confidence_interval; - - return ( -
    -
    - - #{rank} - - -
    - -
    -
    -
    -

    Binding affinity

    -

    - {vqc_score.binding_affinity_kcal.toFixed(2)} - kcal/mol -

    -

    - 95% CI {lo.toFixed(2)} to {hi.toFixed(2)} -

    -
    -
    - - - -
    -
    - - - - - - {scaffold_history.length > 0 && ( -
    - - - {scaffold_history.length} scaffold hop{scaffold_history.length === 1 ? "" : "s"} - show - -
      - {scaffold_history.map((hop) => ( -
    1. - #{hop.iteration + 1} - - {hop.input_smiles} - → - {hop.output_smiles} - - {hop.reason_for_hop} -
    2. - ))} -
    -
    - )} -
    -
    - ); -} diff --git a/frontend/src/features/pharma/components/candidate-dossier.tsx b/frontend/src/features/pharma/components/candidate-dossier.tsx new file mode 100644 index 00000000..21949f5d --- /dev/null +++ b/frontend/src/features/pharma/components/candidate-dossier.tsx @@ -0,0 +1,264 @@ +"use client"; + +import { useState } from "react"; +import { Check, Copy } from "lucide-react"; +import type { PharmaCandidate, VQEDescriptor } from "../types"; +import { CHEMICAL_ACCURACY_HA } from "../lib/pharma-science"; +import { LigandViewer } from "./ligand-viewer"; +import { Figure, OrbitalDiagram, PropertyRadar, VqeErrorPlot } from "./science-figures"; + +const TH = "px-3 py-1.5 text-left text-[10px] font-medium uppercase tracking-wider text-white/35"; +const TD = "px-3 py-1.5 font-mono text-[11px] tabular-nums text-white/75"; + +function CopySmiles({ smiles }: { smiles: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} + +function Ok({ ok }: { ok: boolean }) { + return {ok ? "✓" : "✕"}; +} + +/** Qubit register as |b₀b₁…⟩ with set bits highlighted. */ +function Bitstring({ bits }: { bits: number[] }) { + return ( + + | + {bits.map((b, i) => ( + {b} + ))} + ⟩ + + ); +} + +export function CandidateDossier({ + candidate, + fragmentNames, + fragmentPeers, +}: { + candidate: PharmaCandidate; + fragmentNames: Map; + fragmentPeers: Record; +}) { + const { smiles, vqc_score: vqc, docking_pose: pose, admet, descriptors, scaffold_history: hops, rank } = candidate; + const [lo, hi] = vqc.confidence_interval; + const name = (d: VQEDescriptor) => fragmentNames.get(d.ground_state_energy_hartree.toFixed(6)) ?? d.fragment_id; + const nameById = (id: string) => { + const d = descriptors.find((x) => x.fragment_id === id); + return d ? name(d) : id; + }; + + const admetRows = [ + { p: "Molecular weight", v: admet.molecular_weight.toFixed(1), u: "Da", rule: "≤ 500", ok: admet.molecular_weight <= 500 }, + { p: "cLogP (Crippen)", v: admet.logp.toFixed(2), u: "", rule: "≤ 5", ok: admet.logp <= 5 }, + { p: "TPSA", v: admet.tpsa.toFixed(1), u: "Ų", rule: "≤ 140", ok: admet.tpsa <= 140 }, + { p: "H-bond donors", v: String(admet.hbd), u: "", rule: "≤ 5", ok: admet.hbd <= 5 }, + { p: "H-bond acceptors", v: String(admet.hba), u: "", rule: "≤ 10", ok: admet.hba <= 10 }, + { p: "Synthetic accessibility", v: admet.synthetic_accessibility.toFixed(2), u: "", rule: "≤ 4", ok: admet.synthetic_accessibility <= 4 }, + { p: "QED", v: admet.qed_score.toFixed(3), u: "", rule: "≥ 0.4", ok: admet.qed_score >= 0.4 }, + { p: "hERG liability", v: admet.herg_risk ? "flagged" : "none", u: "", rule: "cLogP>4.5 ∧ MW>400", ok: !admet.herg_risk }, + ]; + + return ( +
    + {/* Identity strip */} +
    +
    + Cpd {rank} + +
    +
    +
    +
    +

    ΔGbind (VQC)

    +

    + {vqc.binding_affinity_kcal.toFixed(2)} + kcal/mol +

    +

    95% CI [{lo.toFixed(2)}, {hi.toFixed(2)}] · σ²shot {vqc.quantum_shot_variance.toExponential(2)}

    +
    +
    +
    EQUBO
    +
    rQAOA
    +
    Lipinski
    +
    {pose.total_qubo_energy.toFixed(2)}
    +
    {pose.qaoa_approximation_ratio.toFixed(3)}
    +
    {admet.lipinski_violations} viol.
    +
    + + {admet.passes ? "✓ ADMET PASS" : "✕ ADMET FAIL"} + +
    + + {admet.failure_reasons.length > 0 && ( +

    Rejected: {admet.failure_reasons.join("; ")}

    + )} +
    +
    + +
    +
    +
    + + + + + + + + + + + {admetRows.map((r) => ( + + + + + + + ))} + +
    PropertyValueRule +
    {r.p}{r.v}{r.u && {r.u}}{r.rule}
    +
    +
    + +
    + +
    +
    + +
    +
    +
    + +
    +
    + +
    +
    + + + + + + + + + + + + + + + + {descriptors.map((d) => { + const err = d.exact_energy_hartree != null ? Math.abs(d.ground_state_energy_hartree - d.exact_energy_hartree) : null; + return ( + + + + + + + + + + + + ); + })} + +
    FragmentE₀ VQEΔE (mHa)Gap (eV)η (eV)QubitsGatesIter × startsPeer
    {name(d)}{d.ground_state_energy_hartree.toFixed(6)} CHEMICAL_ACCURACY_HA ? "text-rose-300" : ""}`}>{err != null ? (err * 1000).toFixed(4) : "—"}{d.homo_lumo_gap_ev.toFixed(2)}{d.chemical_hardness_ev.toFixed(2)}{d.qubit_count}{d.gate_count.toLocaleString()}{d.vqe_iterations} × {d.vqe_starts}{d.cached && c}{fragmentPeers[d.fragment_id] ?? "—"}
    +
    +
    +
    + +
    +
    +
    + + + + + + + + + + + + + {pose.fragment_placements.map((p) => ( + + + + + + + + + ))} + +
    FragmentRegisterSiteEint (kcal/mol)ClashBond
    {nameById(p.fragment_id)}{p.grid_site_index}{p.interaction_energy_kcal.toFixed(2)} 0 ? "text-amber-300" : "text-white/40"}`}>{(p.clash_penalty ?? 0).toFixed(2)} 0 ? "text-amber-300" : "text-white/40"}`}>{(p.bond_geometry_penalty ?? 0).toFixed(2)}
    +
    +
    +
    EQUBO
    {pose.total_qubo_energy.toFixed(4)}
    +
    r (approx. ratio)
    {pose.qaoa_approximation_ratio.toFixed(4)}
    +
    β
    [{pose.qaoa_params_beta.map((b) => b.toFixed(3)).join(", ")}]
    +
    γ
    [{pose.qaoa_params_gamma.map((g) => g.toFixed(3)).join(", ")}]
    +
    DC-QAOA α
    {pose.dc_qaoa_alpha.toFixed(2)}
    +
    RMSD
    {pose.rmsd_angstrom != null ? `${pose.rmsd_angstrom.toFixed(2)} Å` : "n/a (no reference pose)"}
    +
    +
    +
    + + {hops.length > 0 && ( +
    +
      +
    1. +

      seed

      + +

      {hops[0].input_smiles}

      +
    2. + {hops.map((h) => ( +
    3. +
      + → + {h.reason_for_hop} +
      +
      +

      iter {h.iteration + 1}

      + +

      {h.output_smiles}

      +
      +
    4. + ))} +
    +
    + )} +
    + ); +} diff --git a/frontend/src/features/pharma/components/pharma-job-detail.tsx b/frontend/src/features/pharma/components/pharma-job-detail.tsx index 53bba463..8f8ef688 100644 --- a/frontend/src/features/pharma/components/pharma-job-detail.tsx +++ b/frontend/src/features/pharma/components/pharma-job-detail.tsx @@ -1,158 +1,19 @@ "use client"; import dynamic from "next/dynamic"; -import { useEffect, useRef } from "react"; -import { - Activity, - Ban, - FlaskConical, - Loader2, - Star, -} from "lucide-react"; +import { Loader2 } from "lucide-react"; import { usePharmaJob } from "@/features/pharma/hooks/use-pharma-job"; import { useCancelPharma } from "@/features/pharma/hooks/use-cancel-pharma"; -import { CandidateCard } from "./candidate-card"; -import { PageHeader } from "@/shared/components/layout/page-header"; -import type { PipelineLogEntry, PipelineLogLevel } from "../types"; -import { - LOG_META, - STAGE_ICONS, - STAGE_ORDER, - type LogMeta, -} from "../lib/pharma-stage-config"; -import { LigandViewer } from "./ligand-viewer"; // NGL uses window + WebGL — must be client-only, no SSR -const ProteinViewer = dynamic( - () => import("./protein-viewer").then((m) => ({ default: m.ProteinViewer })), - { ssr: false }, -); - const PharmaLiveCanvas = dynamic( () => import("./pharma-live-canvas").then((m) => ({ default: m.PharmaLiveCanvas })), { ssr: false }, ); -// ── Status colours ──────────────────────────────────────────────────────────── - -const STATUS_COLORS: Record = { - queued: "text-amber-400 bg-amber-400/10 border-amber-400/25", - running: "text-sky-400 bg-sky-400/10 border-sky-400/25", - completed: "text-emerald-400 bg-emerald-400/10 border-emerald-400/25", - failed: "text-red-400 bg-red-400/10 border-red-400/25", - cancelled: "text-white/30 bg-white/5 border-white/10", -}; - -// ── Log-level visual config imported from pharma-stage-config ─────────────── - - - - -// Quantum-internal levels hidden from the biology feed -const QUANTUM_LEVELS = new Set(["vqe"]); - -// ── Sub-components ──────────────────────────────────────────────────────────── - -function LogLine({ entry }: { entry: PipelineLogEntry }) { - const meta = LOG_META[entry.level] ?? LOG_META.info; - const Icon = meta.icon; - const time = new Date(entry.ts).toLocaleTimeString("en-US", { - hour12: false, - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }); - - return ( -
    - {time} - - {meta.label} - - - - {entry.message} - -
    - ); -} - -function StageStrip({ logLines }: { logLines: PipelineLogEntry[] }) { - const seenStages = new Set(logLines.map((l) => l.stage).filter(Boolean)); - const lastStage = logLines.length > 0 ? logLines[logLines.length - 1].stage : null; - - return ( -
    - {STAGE_ORDER.map((stage, idx) => { - const meta = STAGE_ICONS[stage]; - if (!meta) return null; - const Icon = meta.icon; - const done = seenStages.has(stage); - const active = lastStage === stage; - return ( -
    -
    - {active && } - - {meta.label} -
    - {idx < STAGE_ORDER.length - 1 && ( -
    - )} -
    - ); - })} -
    - ); -} - -// ── Live metrics extracted from biology log lines ───────────────────────────── - -function extractLiveMetrics(logLines: PipelineLogEntry[]) { - let currentStage: string | null = null; - let iterCount = 0; - let bestScore: number | null = null; - let candidatesFound = 0; - - for (const line of logLines) { - if (line.stage) currentStage = line.stage; - if (line.level === "iter") iterCount++; - if (line.level === "score") { - const m = line.message.match(/([-\d.]+)/); - if (m) { - const v = parseFloat(m[1]); - if (bestScore === null || v < bestScore) bestScore = v; - } - } - if (line.level === "admet" && line.message.toLowerCase().includes("pass")) { - candidatesFound++; - } - } - - return { currentStage, iterCount, bestScore, candidatesFound }; -} - -// ── Main component ──────────────────────────────────────────────────────────── - export function PharmaJobDetail({ jobId }: { jobId: string }) { const { data: job, isLoading, error } = usePharmaJob(jobId); const { mutate: cancelJob, isPending: isCancelling } = useCancelPharma(jobId); - const consoleRef = useRef(null); - - useEffect(() => { - const el = consoleRef.current; - if (el) el.scrollTop = el.scrollHeight; - }, [job?.log_lines?.length]); if (isLoading) { return ( @@ -165,200 +26,10 @@ export function PharmaJobDetail({ jobId }: { jobId: string }) { if (error || !job) { return (
    -

    - {error instanceof Error ? error.message : "Job not found"} -

    +

    {error instanceof Error ? error.message : "Job not found"}

    ); } - const isRunning = job.status === "queued" || job.status === "running"; - - if (isRunning || job.status === "completed") { - return ( - cancelJob()} - isCancelling={isCancelling} - /> - ); - } - const allLogLines = job.log_lines ?? []; - // Strip quantum-internal levels — show only biology events - const bioLogLines = allLogLines.filter((l) => !QUANTUM_LEVELS.has(l.level)); - const metrics = extractLiveMetrics(bioLogLines); - const stageMeta = metrics.currentStage ? STAGE_ICONS[metrics.currentStage] : null; - const ActiveStageIcon = stageMeta?.icon ?? Activity; - - return ( -
    - - -
    - {/* ── Top bar: status + controls ──────────────────────────────────── */} -
    - - {isRunning && } - {job.status} - - -
    - - {job.target_pdb_id} - {job.mode} - - {job.result && ( - <> -
    - - {job.result.candidates.length} candidates · {job.result.total_runtime_seconds.toFixed(1)}s · {job.result.iterations_used} iters - - - )} - - {job.completed_at && ( - - {new Date(job.completed_at).toLocaleString()} - - )} - - {isRunning && ( - - )} -
    - - {/* ── Error banner ────────────────────────────────────────────────── */} - {job.error && ( -
    -

    {job.error}

    -
    - )} - - {/* ── Live biology hero panel ──────────────────────────────────────── */} - {(bioLogLines.length > 0 || isRunning) && ( -
    - - {/* Hero header */} -
    -
    - -
    -
    - - Live Docking Pipeline - - {metrics.currentStage && ( - - {stageMeta?.label ?? metrics.currentStage} - - )} -
    - {isRunning && ( - - - - - - live - - )} - - {bioLogLines.length} event{bioLogLines.length !== 1 ? "s" : ""} - -
    - - {/* Live metrics strip */} -
    -
    -

    Stage

    -

    - {stageMeta?.label ?? (metrics.currentStage ?? "—")} -

    -
    -
    -

    Iterations

    -

    - {metrics.iterCount > 0 ? metrics.iterCount : "—"} -

    -
    -
    -

    Best Dock Score

    -

    - {metrics.bestScore !== null ? metrics.bestScore.toFixed(2) : "—"} -

    -
    -
    -

    ADMET Passes

    -

    - {metrics.candidatesFound > 0 ? metrics.candidatesFound : "—"} -

    -
    -
    - - {/* Stage progress strip */} - {bioLogLines.length > 0 && ( -
    - -
    - )} - - {/* Biology event feed */} -
    - {bioLogLines.length === 0 && isRunning ? ( -
    - - Waiting for pipeline to start… -
    - ) : ( - bioLogLines.map((entry, i) => ) - )} -
    - - {isRunning && ( -
    - - Refreshing every 3 s -
    - )} -
    - )} - - {/* ── Candidates ──────────────────────────────────────────────────── */} - {job.result && job.result.candidates.length > 0 && ( -
    -
    - -

    - Top Candidates ({job.result.candidates.length}) -

    -
    - {job.result.candidates.map((c) => ( - - ))} -
    - )} -
    -
    - ); + return cancelJob()} isCancelling={isCancelling} />; } diff --git a/frontend/src/features/pharma/components/pharma-live-canvas.tsx b/frontend/src/features/pharma/components/pharma-live-canvas.tsx index e080e0e0..59853d8e 100644 --- a/frontend/src/features/pharma/components/pharma-live-canvas.tsx +++ b/frontend/src/features/pharma/components/pharma-live-canvas.tsx @@ -2,25 +2,16 @@ import { PublishToNearButton } from "@/features/agentkit"; import dynamic from "next/dynamic"; -import { useEffect, useRef, useState } from "react"; -import { Ban, Check, CheckCircle2, ChevronDown, Loader2 } from "lucide-react"; -import { - Area, - AreaChart, - CartesianGrid, - ResponsiveContainer, - Tooltip, - XAxis, - YAxis, -} from "recharts"; -import { motion } from "motion/react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { Ban, Check, ChevronDown, Loader2 } from "lucide-react"; import { usePharmaJobLive } from "../hooks/use-pharma-job-live"; import { LigandViewer } from "./ligand-viewer"; -import { CandidateCard } from "./candidate-card"; +import { CandidateDossier } from "./candidate-dossier"; import { PharmaPeersDrawer } from "./pharma-peers-drawer"; +import { ChemicalSpacePlot, ConvergencePlot, Figure } from "./science-figures"; import { LOG_META, STAGE_ICONS, STAGE_ORDER } from "../lib/pharma-stage-config"; +import { fragmentSmilesByEnergy, parseScienceLog } from "../lib/pharma-science"; import type { PharmaJob, PipelineLogEntry, PipelineLogLevel } from "../types"; -import type { ScorePoint } from "../types-live"; const ProteinViewer = dynamic( () => import("./protein-viewer").then((m) => ({ default: m.ProteinViewer })), @@ -28,74 +19,33 @@ const ProteinViewer = dynamic( ); const STATUS_STYLE: Record = { - queued: "bg-amber-400/10 text-amber-300", - running: "bg-sky-400/10 text-sky-300", - completed: "bg-emerald-400/10 text-emerald-300", - failed: "bg-rose-400/10 text-rose-300", - cancelled: "bg-white/5 text-white/40", + queued: "border-amber-400/40 text-amber-300", + running: "border-sky-400/40 text-sky-300", + completed: "border-emerald-400/40 text-emerald-300", + failed: "border-rose-400/40 text-rose-300", + cancelled: "border-white/15 text-white/40", }; const QUANTUM_LEVELS = new Set(["vqe"]); const PIPELINE = STAGE_ORDER.filter((s) => s !== "completed"); +const STAGE_METHOD: Record = { + init: "load target", + filtering: "Ro5 seed check", + generating: "QWGAN pool", + fragmenting: "BRICS cuts", + vqe_computing: "VQE ground state", + docking: "DC-QAOA QUBO", + scoring: "VQC ΔG + ADMET", + refining: "scaffold hop", +}; + interface Props { job: PharmaJob; onCancel: () => void; isCancelling: boolean; } -interface DerivedMetrics { - currentStage: string | null; - iterCount: number; - maxIter: number; - bestScore: number | null; - bestSmiles: string | null; - currentCandidateSmiles: string | null; - scoreHistory: ScorePoint[]; - admetPasses: number; -} - -function deriveMetricsFromLogs(logLines: PipelineLogEntry[]): DerivedMetrics { - let currentStage: string | null = null; - let iterCount = 0; - let maxIter = 0; - let bestScore: number | null = null; - let bestSmiles: string | null = null; - let currentCandidateSmiles: string | null = null; - const scoreHistory: ScorePoint[] = []; - let admetPasses = 0; - - for (const line of logLines) { - if (QUANTUM_LEVELS.has(line.level)) continue; - if (line.stage) currentStage = line.stage; - - if (line.level === "iter") { - iterCount++; - const m = line.message.match(/Iteration \d+\/(\d+)/); - if (m) maxIter = Math.max(maxIter, parseInt(m[1], 10)); - } - if (line.level === "stage" && line.message.includes("fragment decomposition:")) { - const m = line.message.match(/fragment decomposition:\s*(\S+)/); - if (m) currentCandidateSmiles = m[1]; - } - if (line.level === "score") { - const scoreM = line.message.match(/([-\d.]+)\s*kcal/); - const smilesM = line.message.match(/SMILES:(\S+)/); - if (scoreM) { - const v = parseFloat(scoreM[1]); - if (bestScore === null || v < bestScore) { - bestScore = v; - if (smilesM) bestSmiles = smilesM[1]; - } - scoreHistory.push({ iteration: iterCount, score: v, ts: line.ts }); - } - } - if (line.level === "admet" && line.message.toLowerCase().includes("pass")) admetPasses++; - } - - return { currentStage, iterCount, maxIter, bestScore, bestSmiles, currentCandidateSmiles, scoreHistory, admetPasses }; -} - // Backend timestamps are UTC but may lack a zone suffix; without one JS parses them as local time. function parseUtc(ts: string): number { return new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(ts) ? ts : `${ts}Z`).getTime(); @@ -111,101 +61,60 @@ function formatDuration(totalSec: number): string { return `${sec}s`; } -function Panel({ - title, - aside, - children, - className = "", -}: { - title: string; - aside?: React.ReactNode; - children: React.ReactNode; - className?: string; -}) { - return ( -
    -
    -

    {title}

    - {aside &&
    {aside}
    } -
    - {children} -
    - ); +function lastStage(lines: PipelineLogEntry[]): string | null { + for (let i = lines.length - 1; i >= 0; i--) if (lines[i].stage) return lines[i].stage; + return null; } -function Kpi({ label, value, unit, sub, tone = "text-white" }: { - label: string; - value: string; - unit?: string; - sub?: string; - tone?: string; -}) { +function Readout({ label, value, unit, sub, tone = "text-white" }: { label: React.ReactNode; value: string; unit?: string; sub?: string; tone?: string }) { return ( -
    -

    {label}

    - +
    +

    {label}

    +

    {value} - {unit && {unit}} - - {sub &&

    {sub}

    } + {unit && {unit}} +

    + {sub &&

    {sub}

    }
    ); } -function PipelineStepper({ stage, done, iter, maxIter }: { - stage: string | null; - done: boolean; - iter: number; - maxIter: number; -}) { +function PipelineTrace({ stage, done, iter, maxIter }: { stage: string | null; done: boolean; iter: number; maxIter: number }) { const current = stage ? PIPELINE.indexOf(stage) : -1; - const pct = maxIter > 0 ? Math.min((iter / maxIter) * 100, 100) : done ? 100 : 0; return ( -
    -
      +
      +
        {PIPELINE.map((key, i) => { - const meta = STAGE_ICONS[key]; const state = done || i < current ? "done" : i === current ? "active" : "todo"; return ( -
      1. - - {state === "done" ? : state === "active" ? : i + 1} - - - {meta?.label ?? key} - - {i < PIPELINE.length - 1 && ( -
      2. +
        + + {state === "done" ? : state === "active" ? : `S${i}`} + + {STAGE_ICONS[key]?.label ?? key} +
        +

        {STAGE_METHOD[key]}

        + {state === "active" && }
      3. ); })}
      {maxIter > 0 && ( -
      -
      - +
      + iter +
      + {Array.from({ length: maxIter }, (_, i) => { + const finished = done ? i < iter : i < iter - 1; + const active = !done && i === iter - 1; + return ; + })}
      - - iteration {iter}/{maxIter} - + {iter}/{maxIter}
      )}
      @@ -214,18 +123,13 @@ function PipelineStepper({ stage, done, iter, maxIter }: { function LogRow({ entry }: { entry: PipelineLogEntry }) { const meta = LOG_META[entry.level] ?? LOG_META.info; - const time = new Date(parseUtc(entry.ts)).toLocaleTimeString("en-US", { - hour12: false, - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }); + const time = new Date(parseUtc(entry.ts)).toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }); const message = entry.level === "score" ? entry.message.replace(/\s*SMILES:\S+/, "").trim() : entry.message; return ( -
    1. +
    2. {time} - {meta.label} - {message} + {meta.label} + {message}
    3. ); } @@ -234,34 +138,33 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { const { job_id: jobId, target_pdb_id: targetPdbId, mode, status } = job; const isRunning = status === "queued" || status === "running"; const isCompleted = status === "completed"; - const { data: liveData } = usePharmaJobLive(jobId, isRunning); - const allLogLines = job.log_lines ?? []; + const allLogLines = useMemo(() => job.log_lines ?? [], [job.log_lines]); + const science = useMemo(() => parseScienceLog(allLogLines), [allLogLines]); + const fragmentNames = useMemo(() => fragmentSmilesByEnergy(science.vqe), [science.vqe]); + const candidates = job.result?.candidates ?? []; + const [selected, setSelected] = useState(0); + const candidate = candidates[Math.min(selected, candidates.length - 1)]; + + const molecules = science.molecules; + const bestMol = molecules.reduce<(typeof molecules)[number] | null>((b, m) => (!b || m.dg < b.dg ? m : b), null); + const stage = liveData?.current_stage ?? lastStage(allLogLines); + const iter = liveData?.iteration_count ?? molecules.at(-1)?.iteration ?? 0; + const maxIter = science.maxIterations; + const bestDg = isCompleted ? (candidates[0]?.vqc_score.binding_affinity_kcal ?? bestMol?.dg ?? null) : (liveData?.best_score ?? bestMol?.dg ?? null); + const bestSmiles = isCompleted ? (candidates[0]?.smiles ?? bestMol?.smiles) : (liveData?.best_smiles ?? bestMol?.smiles); + const passes = molecules.filter((m) => m.admet?.pass).length; + const peers = new Set(science.vqe.map((v) => v.peer)); const bioLogLines = allLogLines.filter((l) => !QUANTUM_LEVELS.has(l.level)); - const derived = deriveMetricsFromLogs(allLogLines); - const topCandidate = job.result?.candidates[0]; - - const effectiveStage = liveData?.current_stage ?? derived.currentStage; - const effectiveIter = liveData?.iteration_count ?? derived.iterCount; - const effectiveScore = isCompleted - ? (topCandidate?.vqc_score?.binding_affinity_kcal ?? liveData?.best_score ?? derived.bestScore) - : (liveData?.best_score ?? derived.bestScore); - const effectiveAdmet = liveData?.admet_passes ?? derived.admetPasses; - const effectiveHistory = (liveData?.score_history?.length ?? 0) > 0 ? liveData!.score_history : derived.scoreHistory; - const effectiveSmiles = isCompleted - ? (topCandidate?.smiles ?? liveData?.best_smiles ?? derived.bestSmiles ?? derived.currentCandidateSmiles) - : (liveData?.best_smiles ?? derived.bestSmiles ?? derived.currentCandidateSmiles); - const maxIter = derived.maxIter; + const [logOpen, setLogOpen] = useState(isRunning); + const [quantumLog, setQuantumLog] = useState(true); + const shownLog = quantumLog ? allLogLines : bioLogLines; // eslint-disable-next-line @typescript-eslint/no-explicit-any -- NGL ships no types const stageRef = useRef(null); const prevSmilesRef = useRef(null); - const prevScoreRef = useRef(null); - const prevStageRef = useRef(null); const logScrollRef = useRef(null); - const [discoveredSmiles, setDiscoveredSmiles] = useState([]); - const [logOpen, setLogOpen] = useState(isRunning); const [elapsedSec, setElapsedSec] = useState(0); useEffect(() => { @@ -273,17 +176,14 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { return () => clearInterval(id); }, [isRunning, job.submitted_at]); - // NGL: dock the current best ligand into the protein scene + // NGL: put the current best ligand into the protein scene useEffect(() => { - const stage = stageRef.current; - const smiles = effectiveSmiles; - if (!stage || !smiles || smiles === prevSmilesRef.current) return; - prevSmilesRef.current = smiles; - stage.compList - .filter((c: { name: string }) => c.name === "live-ligand") - .forEach((c: unknown) => stage.removeComponent(c)); - stage - .loadFile(`smiles://${smiles}`, { name: "live-ligand" }) + const ngl = stageRef.current; + if (!ngl || !bestSmiles || bestSmiles === prevSmilesRef.current) return; + prevSmilesRef.current = bestSmiles; + ngl.compList.filter((c: { name: string }) => c.name === "live-ligand").forEach((c: unknown) => ngl.removeComponent(c)); + ngl + .loadFile(`smiles://${bestSmiles}`, { name: "live-ligand" }) // eslint-disable-next-line @typescript-eslint/no-explicit-any .then((comp: any) => { if (!comp) return; @@ -291,63 +191,35 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { comp.autoView(400); }) .catch(() => {}); - }, [effectiveSmiles]); - - // NGL: pulse the pocket surface on a new best score - useEffect(() => { - const stage = stageRef.current; - if (!stage || effectiveScore === null || effectiveScore === prevScoreRef.current) return; - prevScoreRef.current = effectiveScore; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - stage.compList.forEach((comp: any) => { - comp.reprList - .filter((r: { type: string }) => r.type === "surface") - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .forEach((r: any) => { - r.setParameters({ opacity: 0.5 }); - setTimeout(() => r.setParameters({ opacity: 0.18 }), 700); - }); - }); - }, [effectiveScore]); - - useEffect(() => { - const stage = stageRef.current; - if (!stage || !effectiveStage || effectiveStage === prevStageRef.current) return; - prevStageRef.current = effectiveStage; - stage.autoView(800); - }, [effectiveStage]); + }, [bestSmiles]); useEffect(() => { const el = logScrollRef.current; if (el) el.scrollTop = el.scrollHeight; - }, [bioLogLines.length, logOpen]); - - // Remember each ligand that passed ADMET (state adjusted during render, not in an effect). - if (effectiveSmiles && effectiveAdmet > 0 && !discoveredSmiles.includes(effectiveSmiles)) { - setDiscoveredSmiles([...discoveredSmiles, effectiveSmiles].slice(-12)); - } + }, [shownLog.length, logOpen]); - const stageMeta = effectiveStage ? STAGE_ICONS[effectiveStage] : null; const runtime = isCompleted && job.result ? job.result.total_runtime_seconds : elapsedSec; - const candidates = job.result?.candidates ?? []; + const lead = candidates[0]; + const qubits = [...new Set(lead?.descriptors.map((d) => d.qubit_count) ?? [])].join("/"); return ( -
      - {/* Header */} -
      -
      +
      +
      +
      -

      Drug discovery · {mode}

      -
      -

      {targetPdbId.toUpperCase()}

      - +

      In-silico screen · {mode} · PDB

      +
      +

      {targetPdbId.toUpperCase()}

      + {isRunning && } - {isCompleted && } - {status} + {status}
      -

      {jobId}

      +
      +
      run
      {jobId}
      +
      submitted (UTC)
      {new Date(parseUtc(job.submitted_at)).toISOString().replace("T", " ").slice(0, 19)}
      +
      {isCompleted && } @@ -356,10 +228,10 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) { type="button" onClick={onCancel} disabled={isCancelling} - className="inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-[12px] font-medium text-rose-300 ring-1 ring-rose-400/30 transition-colors hover:bg-rose-400/10 disabled:opacity-50" + className="inline-flex h-8 items-center gap-1.5 px-3 text-[12px] font-medium text-rose-300 ring-1 ring-rose-400/30 transition-colors hover:bg-rose-400/10 disabled:opacity-50" > {isCancelling ? : } - {isCancelling ? "Cancelling…" : "Cancel"} + {isCancelling ? "Cancelling…" : "Abort run"} )}
      @@ -367,134 +239,184 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) {
      - + {job.error && ( +
      + RUN {status.toUpperCase()} + {job.error} +
      + )} -
      - - 0 ? String(effectiveIter) : "—"} - unit={maxIter > 0 ? `/ ${maxIter}` : undefined} - sub={isCompleted ? undefined : (stageMeta?.label ?? "Starting")} - /> - 0 ? String(effectiveAdmet) : "—"} - sub={isCompleted ? `${candidates.filter((c) => c.admet.passes).length} pass ADMET` : "passed ADMET so far"} - /> - 0 ? formatDuration(runtime) : "—"} - sub={job.result ? `${Math.round(job.result.cache_hit_rate * 100)}% VQE cache hits` : undefined} - /> -
      + -
      -
      - { stageRef.current = stage; }} /> -
      +
      + min ΔGbind} value={bestDg != null ? bestDg.toFixed(2) : "—"} unit={bestDg != null ? "kcal/mol" : undefined} sub="VQC · lower binds tighter" tone="text-emerald-300" /> + + 0 ? String(iter) : "—"} unit={maxIter ? `/ ${maxIter}` : undefined} sub={science.hops.length ? `${science.hops.length} scaffold hop${science.hops.length === 1 ? "" : "s"}` : "no hops"} /> + + + 0 ? formatDuration(runtime) : "—"} sub={!isCompleted && stage ? (STAGE_ICONS[stage]?.label ?? stage) : undefined} /> +
      -
      - -
      - {effectiveSmiles ? ( - - ) : ( -

      - {isRunning ? "Waiting for the first scored ligand…" : "No ligand"} -

      - )} -
      - {isRunning && discoveredSmiles.length > 1 && ( -
      - {discoveredSmiles.slice(0, -1).reverse().map((s) => ( -
      - -
      - ))} -
      +

      Figure 1 · Target and optimisation trajectory

      +
      +
      + { stageRef.current = s; }} /> +
      +
      {bestSmiles} : undefined} + > +
      + {bestSmiles ? ( + + ) : ( +

      {isRunning ? "Waiting for the first scored ligand…" : "No ligand"}

      )} - - - -
      - {effectiveHistory.length > 0 ? ( - - - - - - - - - - - - [`${(v as number).toFixed(2)} kcal/mol`, "Score"]} - labelFormatter={(l: unknown) => `Iteration ${l}`} - /> - - - - ) : ( -
      - {isRunning ? "Scores appear after the first docking round" : "No scores recorded"} -
      - )} -
      -
      -
      +
      + +
      + +
      +
      + +
      - {candidates.length > 0 && ( -
      -
      -

      Top candidates

      - - {candidates.length} ranked by binding affinity · {job.result!.iterations_used} iterations - + {molecules.length > 0 && ( +
      +
      +

      Table 1 · Scored ligands

      + read from the run log, in scoring order +
      +
      + + + + + + + + + + + + + + + + + + {molecules.map((m, i) => ( + + + + + + + + + + + + + + ))} + +
      #IterStructureSMILESΔG (kcal/mol)95% CIMWcLogPQEDSAADMET
      {i + 1}{m.iteration}
      {m.smiles}{m.dg.toFixed(2)}[{m.ciLo.toFixed(2)}, {m.ciHi.toFixed(2)}]{m.admet?.mw.toFixed(1) ?? "—"}{m.admet?.logp.toFixed(2) ?? "—"}{m.admet?.qed.toFixed(3) ?? "—"}{m.admet?.sa.toFixed(2) ?? "—"} + {m.admet ? {m.admet.pass ? "✓ pass" : "✕ fail"} : pending} +
      -
      - {candidates.map((c) => ( - - ))} +
      + )} + + {candidate && ( +
      +
      +

      Figure 2 · Candidate dossier

      + {candidates.length > 1 && ( +
      + {candidates.map((c, i) => ( + + ))} +
      + )}
      +
      )} -
      - + {lead && job.result && ( +
      +

      Methods

      +

      + Target {targetPdbId.toUpperCase()} was screened in {mode} mode for{" "} + {job.result.iterations_used} of {maxIter || job.result.iterations_used} iteration{job.result.iterations_used === 1 ? "" : "s"}. Each ligand was cut into BRICS + fragments, and VQE found each fragment's ground state in a {qubits}-qubit active space ({lead.descriptors[0]?.gate_count.toLocaleString()} gates,{" "} + {lead.descriptors[0]?.vqe_iterations} optimiser steps). {science.vqe.length} VQE solves ran on {peers.size} mesh peer{peers.size === 1 ? "" : "s"}, and each + energy was checked against exact diagonalisation of the same active space. Fragment placement on the binding-site grid was solved as a QUBO with DC-QAOA + (p = {lead.docking_pose.qaoa_params_beta.length}, α = {lead.docking_pose.dc_qaoa_alpha}), taking the most probable bitstring. A variational quantum + classifier predicted binding affinity with a 95% confidence interval. Ligands had to pass Lipinski's rule of five, TPSA ≤ 140 Ų, SA ≤ 4 and QED ≥ 0.4. + Ligands that failed went to the scaffold hopper ({science.hops.length} hop{science.hops.length === 1 ? "" : "s"}). Wall time was{" "} + {formatDuration(job.result.total_runtime_seconds)}. +

      +
      + )} + +
      +
      + + {logOpen && ( + + )} +
      {logOpen && ( -
      - {bioLogLines.length === 0 ? ( -

      +

      + {shownLog.length === 0 ? ( +

      {isRunning && } {isRunning ? "Waiting for the pipeline to start…" : "No events"}

      ) : (
        - {bioLogLines.map((entry, i) => ( + {shownLog.map((entry, i) => ( ))}
      diff --git a/frontend/src/features/pharma/components/science-figures.tsx b/frontend/src/features/pharma/components/science-figures.tsx new file mode 100644 index 00000000..7d2fca01 --- /dev/null +++ b/frontend/src/features/pharma/components/science-figures.tsx @@ -0,0 +1,344 @@ +"use client"; + +import { + CartesianGrid, + ComposedChart, + ErrorBar, + Line, + PolarAngleAxis, + PolarGrid, + PolarRadiusAxis, + Radar, + RadarChart, + ReferenceArea, + ReferenceLine, + ResponsiveContainer, + Scatter, + ScatterChart, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import type { ADMETResult, VQEDescriptor } from "../types"; +import type { ScorePoint } from "../types-live"; +import { admetLoad, CHEMICAL_ACCURACY_HA, type EvaluatedMolecule } from "../lib/pharma-science"; + +// Validated with the dataviz palette script on #07090d (lightness, chroma, CVD, contrast all pass). +const C = { + dg: "#10b981", + homo: "#0284c7", + lumo: "#d97706", + pass: "#10b981", + fail: "#e11d48", + ink: "rgba(255,255,255,0.78)", + muted: "rgba(255,255,255,0.38)", + grid: "rgba(255,255,255,0.06)", + surface: "#07090d", +}; + +const AXIS_TICK = { fontSize: 10, fill: C.muted, fontFamily: "var(--font-mono, ui-monospace)" }; +const TOOLTIP_STYLE = { + background: "#0d1017", + border: "1px solid rgba(255,255,255,0.1)", + borderRadius: 6, + fontSize: 11, + fontFamily: "ui-monospace, monospace", +}; + +/** Journal-style figure: bold panel letter, title, plot, caption. */ +export function Figure({ + panel, + title, + caption, + aside, + children, + className = "", +}: { + panel: string; + title: string; + caption?: React.ReactNode; + aside?: React.ReactNode; + children: React.ReactNode; + className?: string; +}) { + return ( +
      +
      + {panel} +

      {title}

      + {aside &&
      {aside}
      } +
      +
      {children}
      + {caption && ( +
      + {caption} +
      + )} +
      + ); +} + +function Empty({ children }: { children: React.ReactNode }) { + return
      {children}
      ; +} + +// ── ΔG convergence ──────────────────────────────────────────────────────────── + +/** ΔG per evaluated ligand with its 95% CI, plus the running minimum. */ +export function ConvergencePlot({ molecules, fallback }: { molecules: EvaluatedMolecule[]; fallback: ScorePoint[] }) { + const source = molecules.length + ? molecules.map((m) => ({ dg: m.dg, err: [m.dg - m.ciLo, m.ciHi - m.dg] as [number, number], it: m.iteration })) + : fallback.map((p) => ({ dg: p.score, err: [0, 0] as [number, number], it: p.iteration })); + if (!source.length) return ΔG appears after the first VQC scoring round; + + const rows = source.map((r, i) => ({ n: i + 1, ...r, best: Math.min(...source.slice(0, i + 1).map((s) => s.dg)) })); + + return ( +
      + + + + r.n)} + tick={AXIS_TICK} + tickLine={false} + axisLine={{ stroke: C.grid }} + label={{ value: "evaluation #", position: "insideBottom", offset: -8, fontSize: 10, fill: C.muted }} + /> + + + `evaluation ${n}`} + formatter={(v: unknown, name: unknown) => [`${(v as number).toFixed(2)} kcal/mol`, name === "best" ? "running min" : "ΔG"]} + /> + + + + + + +
      + ); +} + +// ── Chemical space ──────────────────────────────────────────────────────────── + +/** MW × cLogP of every scored ligand, with the Lipinski box and the optimisation path. */ +export function ChemicalSpacePlot({ molecules }: { molecules: EvaluatedMolecule[] }) { + const pts = molecules + .filter((m) => m.admet) + .map((m, i) => ({ x: m.admet!.mw, y: m.admet!.logp, pass: m.admet!.pass, smiles: m.smiles, n: i + 1, qed: m.admet!.qed })); + if (!pts.length) return Ligand properties appear after the first ADMET pass; + + const xMax = Math.max(600, ...pts.map((p) => p.x + 60)); + const yMin = Math.min(-2, ...pts.map((p) => Math.floor(p.y - 0.5))); + const yMax = Math.max(6, ...pts.map((p) => Math.ceil(p.y + 0.5))); + + return ( +
      + + + + + + + { + const p = payload?.[0]?.payload as (typeof pts)[number] | undefined; + if (!p) return null; + return ( +
      +

      #{p.n} {p.smiles}

      +

      MW {p.x.toFixed(1)} · cLogP {p.y.toFixed(2)} · QED {p.qed.toFixed(3)}

      +

      {p.pass ? "✓ ADMET pass" : "✕ ADMET fail"}

      +
      + ); + }} + /> + { + const { cx = 0, cy = 0, payload } = props; + const pass = payload?.pass; + return pass ? ( + + ) : ( + + + + + ); + }} + /> +
      +
      +
      + ); +} + +// ── Property radar ──────────────────────────────────────────────────────────── + +/** Each ADMET property as a fraction of its limit; the dashed ring is the limit itself. */ +export function PropertyRadar({ admet }: { admet: ADMETResult }) { + const data = admetLoad(admet).map((d) => ({ ...d, plot: Math.min(d.value, 1.5), limit: 1 })); + return ( +
      + + + + + + + + + name === "limit" ? [null, null] : [`${item.payload?.raw} (${Math.round((item.payload?.value ?? 0) * 100)}% of limit)`, item.payload?.key] + } + labelFormatter={() => ""} + /> + + +
      + ); +} + +// ── Frontier orbitals ───────────────────────────────────────────────────────── + +/** HOMO/LUMO levels per fragment on a shared eV axis, with the gap annotated. */ +export function OrbitalDiagram({ descriptors, names }: { descriptors: VQEDescriptor[]; names: (d: VQEDescriptor) => string }) { + if (!descriptors.length) return No VQE descriptors; + const W = 360; + const H = 230; + const pad = { l: 42, r: 10, t: 14, b: 34 }; + const lo = Math.floor(Math.min(...descriptors.map((d) => d.homo_energy_ev)) / 5) * 5 - 5; + const hi = Math.ceil(Math.max(...descriptors.map((d) => d.lumo_energy_ev)) / 5) * 5 + 5; + const y = (ev: number) => pad.t + ((hi - ev) / (hi - lo)) * (H - pad.t - pad.b); + const col = (W - pad.l - pad.r) / descriptors.length; + const ticks: number[] = []; + for (let t = lo; t <= hi; t += 5) ticks.push(t); + + return ( + + {ticks.map((t) => ( + + + {t} + + ))} + E (eV) + {descriptors.map((d, i) => { + const cx = pad.l + col * i + col / 2; + const half = Math.min(col * 0.32, 34); + const yh = y(d.homo_energy_ev); + const yl = y(d.lumo_energy_ev); + return ( + + {`${names(d)}\nHOMO ${d.homo_energy_ev.toFixed(2)} eV · LUMO ${d.lumo_energy_ev.toFixed(2)} eV\ngap ${d.homo_lumo_gap_ev.toFixed(2)} eV · η ${d.chemical_hardness_ev.toFixed(2)} eV`} + + + + {/* paired electrons in the HOMO */} + ↑↓ + + {d.homo_lumo_gap_ev.toFixed(1)} + {truncate(names(d), 12)} + + ); + })} + + + + + + + + LUMO + + HOMO + gap in eV + + + ); +} + +// ── VQE error vs exact diagonalisation ─────────────────────────────────────── + +/** |E_VQE − E_exact| per fragment on a log scale, against the 1 kcal/mol line. */ +export function VqeErrorPlot({ descriptors, names }: { descriptors: VQEDescriptor[]; names: (d: VQEDescriptor) => string }) { + const rows = descriptors + .filter((d) => d.exact_energy_hartree != null) + .map((d) => ({ d, err: Math.abs(d.ground_state_energy_hartree - d.exact_energy_hartree!) })); + if (!rows.length) return No exact reference energies for this run; + + const W = 360; + const rowH = 26; + const pad = { l: 92, r: 14, t: 10, b: 30 }; + const H = pad.t + pad.b + rows.length * rowH; + const decades = [-7, -6, -5, -4, -3, -2, -1]; + const lx = (ha: number) => pad.l + ((Math.log10(Math.max(ha, 1e-7)) + 7) / 6) * (W - pad.l - pad.r); + + return ( + + {decades.map((p) => ( + + + + 10{p} + + + ))} + + 1 kcal/mol + {rows.map(({ d, err }, i) => { + const cy = pad.t + i * rowH + rowH / 2; + const ok = err <= CHEMICAL_ACCURACY_HA; + return ( + + {`${names(d)}: |ΔE| = ${(err * 1000).toFixed(4)} mHa (${ok ? "within" : "outside"} chemical accuracy)`} + {truncate(names(d), 13)} + + + + ); + })} + |E_VQE − E_exact| (Ha) + + ); +} + +function truncate(s: string, n: number) { + return s.length > n ? `${s.slice(0, n - 1)}…` : s; +} diff --git a/frontend/src/features/pharma/lib/pharma-science.ts b/frontend/src/features/pharma/lib/pharma-science.ts new file mode 100644 index 00000000..0fcff623 --- /dev/null +++ b/frontend/src/features/pharma/lib/pharma-science.ts @@ -0,0 +1,99 @@ +import type { ADMETResult, PipelineLogEntry } from "../types"; + +/** 1 kcal/mol in hartree: the usual "chemical accuracy" bar for VQE energies. */ +export const CHEMICAL_ACCURACY_HA = 0.0016; + +/** ADMET limits, mirroring backend ADMETFilter defaults (pharma/stages/stage_6.py). */ +export const ADMET_RULES = { + mw: { label: "MW", max: 500, unit: "Da" }, + logp: { label: "cLogP", max: 5, unit: "" }, + tpsa: { label: "TPSA", max: 140, unit: "Ų" }, + hbd: { label: "HBD", max: 5, unit: "" }, + hba: { label: "HBA", max: 10, unit: "" }, + sa: { label: "SA", max: 4, unit: "" }, + qed: { label: "QED", min: 0.4, unit: "" }, +} as const; + +/** Each property as a fraction of its limit; > 1 breaks the rule (QED is inverted so the same holds). */ +export function admetLoad(a: ADMETResult) { + return [ + { key: "MW", value: a.molecular_weight / 500, raw: a.molecular_weight.toFixed(1) }, + { key: "cLogP", value: Math.max(a.logp, 0) / 5, raw: a.logp.toFixed(2) }, + { key: "TPSA", value: a.tpsa / 140, raw: a.tpsa.toFixed(1) }, + { key: "HBD", value: a.hbd / 5, raw: String(a.hbd) }, + { key: "HBA", value: a.hba / 10, raw: String(a.hba) }, + { key: "SA", value: a.synthetic_accessibility / 4, raw: a.synthetic_accessibility.toFixed(2) }, + { key: "1−QED", value: (1 - a.qed_score) / 0.6, raw: a.qed_score.toFixed(3) }, + ]; +} + +export interface EvaluatedMolecule { + iteration: number; + smiles: string; + dg: number; + ciLo: number; + ciHi: number; + admet?: { pass: boolean; mw: number; logp: number; qed: number; sa: number }; +} + +export interface VqeFragmentRun { + iteration: number; + smiles: string; + energy: number; + exact: number | null; + gapEv: number; + qubits: number; + peer: string; +} + +export interface ScaffoldHop { + iteration: number; + to: string; + reason: string; +} + +const RE_ITER = /Iteration (\d+)\/(\d+)/; +const RE_SCORE = /Binding affinity: ([-\d.]+) kcal\/mol\s+confidence \[([-\d.]+), ([-\d.]+)\]\s+SMILES:(\S+)/; +const RE_ADMET = /ADMET (PASS|FAIL) — MW=([\d.]+)\s+LogP=([-\d.]+)\s+QED=([\d.]+)\s+SA=([\d.]+)/; +const RE_VQE = /^\s*(\S+): E=([-\d.]+) Ha \(exact ([-\d.]+|n\/a)\), gap=([\d.]+) eV, (\d+) qubits, computed on (\S+)/; +const RE_HOP = /Hop → (\S+)\s+reason: (.+)$/; + +/** Rebuilds the per-iteration science record from the orchestrator's log lines (formats in pharma/orchestrator.py). */ +export function parseScienceLog(lines: PipelineLogEntry[]) { + let iteration = 0; + let maxIterations = 0; + const molecules: EvaluatedMolecule[] = []; + const vqe: VqeFragmentRun[] = []; + const hops: ScaffoldHop[] = []; + + for (const { message } of lines) { + let m: RegExpMatchArray | null; + if ((m = message.match(RE_ITER))) { + iteration = parseInt(m[1], 10); + maxIterations = parseInt(m[2], 10); + } else if ((m = message.match(RE_SCORE))) { + molecules.push({ iteration, smiles: m[4], dg: +m[1], ciLo: +m[2], ciHi: +m[3] }); + } else if ((m = message.match(RE_ADMET))) { + const last = molecules[molecules.length - 1]; + if (last && !last.admet) last.admet = { pass: m[1] === "PASS", mw: +m[2], logp: +m[3], qed: +m[4], sa: +m[5] }; + } else if ((m = message.match(RE_VQE))) { + vqe.push({ + iteration, + smiles: m[1], + energy: +m[2], + exact: m[3] === "n/a" ? null : +m[3], + gapEv: +m[4], + qubits: +m[5], + peer: m[6], + }); + } else if ((m = message.match(RE_HOP))) { + hops.push({ iteration, to: m[1], reason: m[2].trim() }); + } + } + return { molecules, vqe, hops, maxIterations }; +} + +/** Fragment SMILES keyed by ground-state energy (6 dp), the only field shared by descriptors and log lines. */ +export function fragmentSmilesByEnergy(vqe: VqeFragmentRun[]): Map { + return new Map(vqe.map((v) => [v.energy.toFixed(6), v.smiles])); +} diff --git a/frontend/src/features/pharma/types.ts b/frontend/src/features/pharma/types.ts index 2e3b2754..4e0413af 100644 --- a/frontend/src/features/pharma/types.ts +++ b/frontend/src/features/pharma/types.ts @@ -42,13 +42,17 @@ export interface VQCScore { export interface QUBOPlacement { fragment_id: string; grid_site_index: number; + binary_variable_assignment: number[]; interaction_energy_kcal: number; + clash_penalty: number; + bond_geometry_penalty: number; } export interface DockingPose { ligand_smiles: string; fragment_placements: QUBOPlacement[]; total_qubo_energy: number; + rmsd_angstrom: number | null; qaoa_approximation_ratio: number; dc_qaoa_alpha: number; qaoa_params_beta: number[]; @@ -60,6 +64,7 @@ export interface ScaffoldIteration { input_smiles: string; output_smiles: string; reason_for_hop: string; + replacement_fragment_smiles: string; } export interface VQEDescriptor { @@ -68,6 +73,9 @@ export interface VQEDescriptor { lumo_energy_ev: number; homo_lumo_gap_ev: number; chemical_hardness_ev: number; + ground_state_energy_hartree: number; + exact_energy_hartree: number | null; + vqe_starts: number; qubit_count: number; gate_count: number; vqe_iterations: number;