frontend: Mol* viewer of the placed model and its density on the Rugnux live page

When the run placed a model, the Rugnux live page shows it in a Mol* viewer (molstar 5.13.0, pinned,
loaded lazily in its own chunk): cartoon, ligands and ions as ball-and-stick, the 2mFo-DFc map as a
blue mesh (1.0 sigma) and the mFo-DFc map in green/red (+/-3 sigma), each with a contour-level slider
and a show/hide switch. As in Coot, the maps are drawn within a sphere (10 A by default, adjustable,
0 = the whole box) around the centre of view, which follows the camera. Sigma levels are relative to
the whole-cell statistics the broker writes into the map headers. Reloaded for every new result;
the plugin is disposed with the component.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015CeEGgpKdfkCTJb3YNMJcu
(cherry picked from commit 08295be10c1d7a76bc7ecdf5df46fd7a3e1febac)
This commit is contained in:
leonarski_f committed 2026-10-22 20:18:50 +02:00
1 parent 15ca4b329f
commit a105c67f62
4 files changed
+1459 -14

No files matched your search

+1127 -14
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -17,6 +17,7 @@
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react-swc": "^4.2.3",
"lodash": "^4.17.23",
"molstar": "5.13.0",
"plotly.js-cartesian-dist-min": "^3.3.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
+10
View File
@@ -9,6 +9,10 @@ import RugnuxTimeline from "./RugnuxTimeline";
import RugnuxSettings from "./RugnuxSettings";
import {CutAlert, lastImageTime, ProbeAlert, RunMessage, StateChip, StepTable, VerdictAlert} from "./RugnuxParts";
import BoltIcon from "@mui/icons-material/Bolt";
import {lazy, Suspense} from "react";
// Mol* is large: loaded only when there is a model to show.
const RugnuxStructureViewer = lazy(() => import("./RugnuxStructureViewer"));
// The summary rows rugnux writes; the ones a crystallographer looks at first get a stronger tile, and
// space group and cell share a row.
@@ -151,6 +155,12 @@ function RugnuxPage({measuring}: { measuring: boolean }) {
</Stack>
</Section>
</Box>
{s.placed_model && s.state !== 'Running' &&
<Section title="Placed model and electron density">
<Suspense fallback={<Typography color="text.secondary">Loading viewer...</Typography>}>
<RugnuxStructureViewer resultKey={`${s.elapsed_s}`}/>
</Suspense>
</Section>}
</Stack>
);
@@ -0,0 +1,321 @@
import {useEffect, useRef, useState} from "react";
import {Alert, Box, Checkbox, FormControlLabel, Slider, Stack, Typography} from "@mui/material";
import {PluginContext} from "molstar/lib/mol-plugin/context";
import {DefaultPluginSpec} from "molstar/lib/mol-plugin/spec";
import {StateTransforms} from "molstar/lib/mol-plugin-state/transforms";
import {createVolumeRepresentationParams} from "molstar/lib/mol-plugin-state/helpers/volume-representation-params";
import {setSubtreeVisibility} from "molstar/lib/mol-plugin/behavior/static/state";
import {Volume} from "molstar/lib/mol-model/volume";
import {Color} from "molstar/lib/mol-util/color";
import {Mat4, Vec3} from "molstar/lib/mol-math/linear-algebra";
import {Sphere3D} from "molstar/lib/mol-math/geometry";
import {authHeaders, noteResponse} from "../auth";
// The model rugnux live placed, with its 2mFo-DFc and mFo-DFc maps, in a Mol* viewer (headless plugin: the
// render core and state tree, no Mol* UI). Mol* is only loaded with this component (React.lazy in
// RugnuxPage). The broker serves the maps cut to the box around the model, with the whole cell's mean and
// RMS in their headers, so the contour levels in sigma are the usual crystallographic ones.
//
// As in Coot, the maps are drawn only within a radius of the centre of view, which follows the camera (a click
// on an atom centres it): over the whole model the mesh at 1 sigma is a solid block.
const COLOR_2FOFC = 0x3b6fd6;
const COLOR_FOFC_POS = 0x2ca02c;
const COLOR_FOFC_NEG = 0xd62728;
interface MapLayer {
volume: string;
reprs: string[]; // one for 2mFo-DFc, +/- for mFo-DFc
}
async function fetchBytes(path: string, signal: AbortSignal): Promise<ArrayBuffer | undefined> {
const res = await fetch(path, {headers: authHeaders(), signal});
noteResponse(res);
if (res.status === 404)
return undefined;
if (!res.ok)
throw new Error(`${path}: HTTP ${res.status}`);
return res.arrayBuffer();
}
// What is drawn of a map: the inside of a sphere of `radius` A around `centre`; radius 0 draws all of it.
function sphereClip(centre: Vec3, radius: number) {
return {
variant: 'pixel' as const,
objects: radius > 0 ? [{
type: 'sphere' as const,
invert: true, // keep the inside
position: Vec3.clone(centre),
rotation: {axis: Vec3.create(1, 0, 0), angle: 0},
scale: Vec3.create(2 * radius, 2 * radius, 2 * radius), // the diameter
transform: Mat4.identity(),
}] : [],
};
}
async function addIsosurface(plugin: PluginContext, volume: string, sigma: number, color: number,
clip: ReturnType<typeof sphereClip>) {
const cell = plugin.state.data.select(volume)[0];
const repr = plugin.build().to(volume).apply(StateTransforms.Representation.VolumeRepresentation3D,
createVolumeRepresentationParams(plugin, cell?.obj?.data, {
type: 'isosurface',
typeParams: {isoValue: Volume.IsoValue.relative(sigma), visuals: ['wireframe'], clip},
color: 'uniform',
colorParams: {value: Color(color)},
}));
await repr.commit();
return repr.ref;
}
async function loadMap(plugin: PluginContext, bytes: ArrayBuffer, label: string, sigmas: number[],
colors: number[], clip: ReturnType<typeof sphereClip>): Promise<MapLayer> {
const data = await plugin.builders.data.rawData({data: new Uint8Array(bytes), label});
const parsed = await plugin.dataFormats.get('ccp4')!.parse(plugin, data);
const volume: string = parsed.volume.ref;
const reprs: string[] = [];
for (let i = 0; i < sigmas.length; i++)
reprs.push(await addIsosurface(plugin, volume, sigmas[i], colors[i], clip));
return {volume, reprs};
}
async function setSigma(plugin: PluginContext, layer: MapLayer | undefined, sigmas: number[]) {
if (!layer)
return;
const b = plugin.build();
layer.reprs.forEach((ref, i) =>
b.to(ref).update((old: { type: { params: { isoValue: Volume.IsoValue } } }) => {
old.type.params.isoValue = Volume.IsoValue.relative(sigmas[i]);
}));
await b.commit();
}
async function setClip(plugin: PluginContext, layers: (MapLayer | undefined)[], clip: ReturnType<typeof sphereClip>) {
const b = plugin.build();
for (const layer of layers)
layer?.reprs.forEach(ref =>
b.to(ref).update((old: { type: { params: { clip: unknown } } }) => {
old.type.params.clip = clip;
}));
await b.commit();
}
function setVisible(plugin: PluginContext, layer: MapLayer | undefined, visible: boolean) {
if (layer)
setSubtreeVisibility(plugin.state.data, layer.volume, !visible); // the flag is "hidden"
}
// resultKey: changes when a new result is there to load.
function RugnuxStructureViewer({resultKey}: { resultKey: string }) {
const containerRef = useRef<HTMLDivElement>(null);
const [plugin, setPlugin] = useState<PluginContext>();
const [error, setError] = useState<string>();
const [loading, setLoading] = useState(false);
const maps = useRef<{ twofofc?: MapLayer, fofc?: MapLayer }>({});
const [hasFofc, setHasFofc] = useState(false);
const [sigma2, setSigma2] = useState(1.0);
const [sigma1, setSigma1] = useState(3.0);
const [show2, setShow2] = useState(true);
const [show1, setShow1] = useState(true);
const [radius, setRadius] = useState(10);
// The levels as they are when a map is loaded, without making the loading depend on them.
const levels = useRef({sigma2, sigma1, show2, show1, radius});
levels.current = {sigma2, sigma1, show2, show1, radius};
const centre = useRef(Vec3.zero());
// The plugin, once per mount. A canvas of its own every time: dispose() loses the WebGL context of the
// canvas it ran on, so a second plugin on the same one (React StrictMode mounts twice) would start dead.
useEffect(() => {
const container = containerRef.current;
if (!container)
return;
let disposed = false;
let instance: PluginContext | undefined;
const canvas = document.createElement('canvas');
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.style.display = 'block';
container.appendChild(canvas);
(async () => {
try {
const p = new PluginContext(DefaultPluginSpec());
await p.init();
if (!await p.initViewerAsync(canvas, container)) {
p.dispose();
throw new Error("WebGL is not available");
}
if (disposed) {
p.dispose();
return;
}
// The camera is moved by this component alone: by default Mol* resets it whenever the scene's
// bounds change, i.e. as each map arrives, which undoes the zoom on the centre of view.
p.canvas3d?.setProps({renderer: {backgroundColor: Color(0xffffff)}, camera: {manualReset: true}});
instance = p;
setPlugin(p);
} catch (e) {
if (!disposed)
setError(e instanceof Error ? e.message : String(e));
}
})();
const resize = new ResizeObserver(() => instance?.handleResize());
resize.observe(container);
return () => {
disposed = true;
resize.disconnect();
instance?.dispose();
canvas.remove();
setPlugin(undefined);
};
}, []);
// The model and its maps, again for every new result.
useEffect(() => {
if (!plugin)
return;
const abort = new AbortController();
(async () => {
setLoading(true);
setError(undefined);
try {
await plugin.clear();
maps.current = {};
setHasFofc(false);
const [cif, map2, map1] = await Promise.all([
fetchBytes("/rugnux/model.cif", abort.signal),
fetchBytes("/rugnux/map.ccp4?type=2fofc", abort.signal),
fetchBytes("/rugnux/map.ccp4?type=fofc", abort.signal)]);
if (abort.signal.aborted)
return;
if (!cif) {
setError("No placed model");
return;
}
const data = await plugin.builders.data.rawData({data: new TextDecoder().decode(cif), label: "model"});
const trajectory = await plugin.builders.structure.parseTrajectory(data, 'mmcif');
const model = await plugin.builders.structure.createModel(trajectory);
const structure = await plugin.builders.structure.createStructure(model);
const polymer = await plugin.builders.structure.tryCreateComponentStatic(structure, 'polymer');
if (polymer)
await plugin.builders.structure.representation.addRepresentation(polymer,
{type: 'cartoon', color: 'chain-id'});
for (const kind of ['ligand', 'ion'] as const) {
const c = await plugin.builders.structure.tryCreateComponentStatic(structure, kind);
if (c)
await plugin.builders.structure.representation.addRepresentation(c,
{type: 'ball-and-stick', color: 'element-symbol'});
}
// The centre of view on the model, zoomed in to about the maps' sphere, before the maps: they
// are drawn around it.
plugin.managers.camera.reset(undefined, 0);
const target = plugin.canvas3d?.camera.state.target;
if (target)
Vec3.copy(centre.current, target);
const l = levels.current;
plugin.managers.camera.focusSphere(Sphere3D.create(Vec3.clone(centre.current), Math.max(l.radius, 10) + 4),
{durationMs: 0});
const clip = sphereClip(centre.current, l.radius);
if (map2) {
maps.current.twofofc = await loadMap(plugin, map2, "2mFo-DFc", [l.sigma2], [COLOR_2FOFC], clip);
setVisible(plugin, maps.current.twofofc, l.show2);
}
if (map1) {
maps.current.fofc = await loadMap(plugin, map1, "mFo-DFc", [l.sigma1, -l.sigma1],
[COLOR_FOFC_POS, COLOR_FOFC_NEG], clip);
setVisible(plugin, maps.current.fofc, l.show1);
setHasFofc(true);
}
} catch (e) {
if (!abort.signal.aborted)
setError(e instanceof Error ? e.message : String(e));
} finally {
if (!abort.signal.aborted)
setLoading(false);
}
})();
return () => abort.abort();
}, [plugin, resultKey]);
// The maps follow the centre of view - it moves on a pan or a click on an atom, not on a rotation or zoom.
useEffect(() => {
const camera = plugin?.canvas3d?.camera;
if (!plugin || !camera)
return;
let timer: ReturnType<typeof setTimeout> | undefined;
const sub = camera.stateChanged.subscribe(() => {
if (Vec3.distance(camera.state.target, centre.current) < 0.5 || timer !== undefined)
return;
timer = setTimeout(() => {
timer = undefined;
Vec3.copy(centre.current, camera.state.target);
setClip(plugin, [maps.current.twofofc, maps.current.fofc],
sphereClip(centre.current, levels.current.radius)).catch(() => undefined);
}, 150);
});
return () => {
sub.unsubscribe();
if (timer !== undefined)
clearTimeout(timer);
};
}, [plugin]);
useEffect(() => {
if (plugin)
setClip(plugin, [maps.current.twofofc, maps.current.fofc], sphereClip(centre.current, radius))
.catch(() => undefined);
}, [plugin, radius]);
useEffect(() => {
if (plugin)
setSigma(plugin, maps.current.twofofc, [sigma2]).catch(() => undefined);
}, [plugin, sigma2]);
useEffect(() => {
if (plugin)
setSigma(plugin, maps.current.fofc, [sigma1, -sigma1]).catch(() => undefined);
}, [plugin, sigma1]);
useEffect(() => {
if (plugin)
setVisible(plugin, maps.current.twofofc, show2);
}, [plugin, show2]);
useEffect(() => {
if (plugin)
setVisible(plugin, maps.current.fofc, show1);
}, [plugin, show1]);
return (
<Stack spacing={1}>
<Box sx={{position: "relative", height: {xs: 360, md: 520}, borderRadius: 1, overflow: "hidden",
border: "1px solid", borderColor: "divider"}}>
<Box ref={containerRef} sx={{position: "absolute", inset: 0}}/>
{loading && <Typography sx={{position: "absolute", top: 8, left: 12, color: "text.secondary"}}>
Loading model and maps...</Typography>}
</Box>
{error && <Alert severity="warning">{error}</Alert>}
<Stack direction={{xs: "column", md: "row"}} spacing={3} alignItems={{md: "center"}}>
<Stack direction="row" spacing={2} alignItems="center" sx={{flex: 1}}>
<FormControlLabel control={<Checkbox checked={show2} onChange={e => setShow2(e.target.checked)}/>}
label={<Typography sx={{color: "#3b6fd6", fontWeight: 700, whiteSpace: "nowrap"}}>
2mFo-DFc {sigma2.toFixed(1)} σ</Typography>}/>
<Slider value={sigma2} min={0.3} max={4} step={0.1} size="small"
onChange={(_, v) => setSigma2(v as number)} aria-label="2mFo-DFc contour level"/>
</Stack>
{hasFofc && <Stack direction="row" spacing={2} alignItems="center" sx={{flex: 1}}>
<FormControlLabel control={<Checkbox checked={show1} onChange={e => setShow1(e.target.checked)}/>}
label={<Typography sx={{color: "#2ca02c", fontWeight: 700, whiteSpace: "nowrap"}}>
mFo-DFc ±{sigma1.toFixed(1)} σ</Typography>}/>
<Slider value={sigma1} min={1.5} max={6} step={0.1} size="small"
onChange={(_, v) => setSigma1(v as number)} aria-label="mFo-DFc contour level"/>
</Stack>}
</Stack>
<Stack direction="row" spacing={2} alignItems="center" sx={{maxWidth: 520}}>
<Typography sx={{whiteSpace: "nowrap"}}>
Maps within {radius > 0 ? `${radius} Å` : "the whole box"}</Typography>
<Slider value={radius} min={0} max={30} step={1} size="small"
onChange={(_, v) => setRadius(v as number)} aria-label="Map radius"/>
</Stack>
<Typography variant="body2" color="text.secondary">
Left drag rotates, right drag pans, wheel zooms, a click on an atom centres it; the maps are drawn
around the centre of view (radius 0: the whole box, the model plus 5 Å).
</Typography>
</Stack>
);
}
export default RugnuxStructureViewer;