Skip to content
Merged
286 changes: 205 additions & 81 deletions quantui/app.py

Large diffs are not rendered by default.

37 changes: 34 additions & 3 deletions quantui/app_runflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ def _set_run_output(app: Any, outputs: tuple) -> None:

def on_run_clicked(app: Any, btn: Any) -> None:
"""Reset result panes and start the background run thread."""
# One run at a time. The button is disabled while a run is in flight,
# but a double-click (or a click queued before the disable reached the
# browser) still lands here; two runs would share the cancel flag, the
# live log and the checkpoint directory (audit APP-4).
if getattr(app, "_calc_running", False):
return
# Pre-run guard: catch a basis with no parameters for an
# element (e.g. 6-31G on Pt) or a charge/multiplicity inconsistent with the
# electron count, and explain it here — on the main thread, before anything
Expand Down Expand Up @@ -220,7 +226,10 @@ def on_run_clicked(app: Any, btn: Any) -> None:
submit_slurm_run(app)
return

threading.Thread(target=app._do_run, daemon=True).start()
# Claim the run on this (main) thread, before the worker starts: the
# worker used to set the flag itself, leaving a window for a second run.
app._begin_run_lock()
threading.Thread(target=app._run_in_thread, daemon=True).start()


_FREQ_PREOPT_DESC_DEFAULT = "Geometry optimization before calculation (QM, slower)"
Expand Down Expand Up @@ -1134,8 +1143,29 @@ def _update_freq_perturb_seed_ui(app: Any, path_str: str) -> None:
box.layout.display = "none"


def seed_with_run_charge(seed_mol: Any, base_mol: Any) -> Any:
"""*seed_mol*'s geometry with *base_mol*'s charge and multiplicity.

A seed is a saved result's geometry, and its ``trajectory.json`` carries
the charge and multiplicity of *that* run. The run being set up decides
the electronic state: the classic "cation at the neutral's optimized
geometry" must not silently recompute the neutral (audit APP-3).
"""
from quantui.molecule import Molecule

return Molecule(
list(seed_mol.atoms),
[list(map(float, c)) for c in seed_mol.coordinates],
charge=int(base_mol.charge),
multiplicity=int(base_mol.multiplicity),
)


def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> Any:
"""Apply seed geometry (geo-opt final frame or freq mode perturbation)."""
"""Apply seed geometry (geo-opt final frame or freq mode perturbation).

The returned molecule keeps *base_mol*'s charge and multiplicity.
"""
from quantui.backends.dispatch import load_seed_molecule, seed_path_from_app
from quantui.freq_calc import (
VIB_MODE_DISPLAY_AMPLITUDE_ANGSTROM,
Expand All @@ -1157,6 +1187,7 @@ def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) ->
mode_number,
fraction=fraction,
)
mol = seed_with_run_charge(mol, base_mol)
if log is not None:
freq_raw = meta.get("frequency_cm1")
freq_val = float(freq_raw) if isinstance(freq_raw, (int, float)) else None
Expand All @@ -1170,7 +1201,7 @@ def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) ->
)
return mol

mol = load_seed_molecule(seed_path)
mol = seed_with_run_charge(load_seed_molecule(seed_path), base_mol)
if log is not None:
log.write(
f"\nSeed geometry loaded from: {Path(seed_path).name}\n"
Expand Down
38 changes: 17 additions & 21 deletions quantui/app_visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from quantui.orbital_visualization import _GENERIC_CAPTURE_JS, _png_capture_controls
from quantui.symmetry import html_irrep
from quantui.viz_assets import orient_js, orient_view
from quantui.viz_assets import script_json as _script_json

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -3116,11 +3117,10 @@ def iso_bridge_update(app: Any, **opts: Any) -> None:
bridge = getattr(app, "_iso_js_bridge", None)
if bridge is None:
return
import json

from IPython.display import Javascript, display

payload = json.dumps(opts)
payload = _script_json(opts)
# Retry-until-present mirrors _vib_bridge_set_mode: at the moment a slider
# fires, the viewer may still be loading its async 3Dmol bundle.
js = (
Expand Down Expand Up @@ -3446,7 +3446,6 @@ def _frame_stepper_controls(
(e.g. per-frame energy arrays). ``loop`` makes Play cycle forever, else it
runs once and stops on the last frame.
"""
import json

btn = _STEPPER_BTN_STYLE
start = (n - 1) if start_index is None else start_index
Expand Down Expand Up @@ -3483,8 +3482,8 @@ def _frame_stepper_controls(
.replace("__IV__", str(interval_ms))
.replace("__LOOP__", "1" if loop else "0")
.replace("__START__", str(start))
.replace("__AB_START__", json.dumps(ab_at_start or ""))
.replace("__AB_OTHER__", json.dumps(ab_other or ""))
.replace("__AB_START__", _script_json(ab_at_start or ""))
.replace("__AB_OTHER__", _script_json(ab_other or ""))
.replace("__EXTRA__", extra_decls)
.replace("__LABEL_BODY__", label_js)
)
Expand Down Expand Up @@ -3520,7 +3519,6 @@ def build_reorg_geometry_viewer_html(
the isosurface viewer's capture bridge but with a uid-scoped
capture function — see ``_GENERIC_CAPTURE_JS``. Empty omits the button.
"""
import json
import re

from quantui.viz_assets import make_view
Expand Down Expand Up @@ -3549,7 +3547,7 @@ def build_reorg_geometry_viewer_html(
return _theme.frame_viewer_html(view_html, width=width)
uid = m.group(1)

slugs = json.dumps(
slugs = _script_json(
[
g.get("label", f"geometry_{i + 1}").split(" — ")[0]
for i, g in enumerate(geometries)
Expand All @@ -3561,7 +3559,7 @@ def build_reorg_geometry_viewer_html(
capture_js = (
_GENERIC_CAPTURE_JS.replace("__UID__", uid)
.replace("__CAPFN__", capture_fn)
.replace("__BG__", json.dumps(bgcolor))
.replace("__BG__", _script_json(bgcolor))
)
bridge_js = (
_REORG_PNG_BRIDGE_JS.replace("__UID__", uid)
Expand All @@ -3583,10 +3581,10 @@ def build_reorg_geometry_viewer_html(
if len(geometries) < 2:
return _theme.frame_viewer_html(view_html, width=width)

labels = json.dumps(
labels = _script_json(
[g.get("label", f"Geometry {i + 1}") for i, g in enumerate(geometries)]
)
notes = json.dumps([g.get("note", "") for g in geometries])
notes = _script_json([g.get("note", "") for g in geometries])
controls = _frame_stepper_controls(
uid,
len(geometries),
Expand Down Expand Up @@ -3826,7 +3824,6 @@ def build_trajectory_viewer_html(
displayed in it — nothing trajectory-specific needed). Empty omits the
button.
"""
import json
import re

from quantui.viz_assets import make_view
Expand All @@ -3850,7 +3847,7 @@ def build_trajectory_viewer_html(
capture_js = (
_GENERIC_CAPTURE_JS.replace("__UID__", uid)
.replace("__CAPFN__", capture_fn)
.replace("__BG__", json.dumps(bgcolor))
.replace("__BG__", _script_json(bgcolor))
)
view_html = (
view_html
Expand All @@ -3864,9 +3861,9 @@ def build_trajectory_viewer_html(
return _theme.frame_viewer_html(view_html, width=width)

interval_ms = max(1, int(round(1000.0 / max(1, fps))))
eabs = json.dumps([float(e) for e in energies]) if energies else "null"
erel = json.dumps([float(e) for e in rel_e]) if rel_e else "null"
fjs = json.dumps(formula or "")
eabs = _script_json([float(e) for e in energies]) if energies else "null"
erel = _script_json([float(e) for e in rel_e]) if rel_e else "null"
fjs = _script_json(formula or "")
label_js = (
'var s="Step "+i+" / "+(N-1);'
f'if({fjs}) s+=" \\u00b7 "+{fjs};'
Expand Down Expand Up @@ -4022,7 +4019,6 @@ def build_vib_viewer_html(
equivalent client-side capture global, same reasoning as the main molecule
viewer.
"""
import json
import re

import numpy as np
Expand Down Expand Up @@ -4056,14 +4052,14 @@ def build_vib_viewer_html(
interval_ms = max(1, int(round(1000.0 / max(1, fps))))
js = (
_VIB_VIEWER_JS.replace("__UID__", uid)
.replace("__SYM__", json.dumps(atoms))
.replace("__BASE__", json.dumps(base.tolist()))
.replace("__DISPL__", json.dumps(displ_map))
.replace("__SYM__", _script_json(atoms))
.replace("__BASE__", _script_json(base.tolist()))
.replace("__DISPL__", _script_json(displ_map))
.replace("__NAT__", str(n_atoms))
.replace("__NF__", str(int(n_frames)))
.replace("__AMP__", repr(float(amplitude)))
.replace("__IV__", str(interval_ms))
.replace("__BG__", json.dumps(bgcolor))
.replace("__BG__", _script_json(bgcolor))
.replace("__INIT__", str(int(initial_mode)))
.replace("__ARROWS__", "true" if arrows else "false")
.replace("__ORIENT__", orient_js("v", base))
Expand All @@ -4074,7 +4070,7 @@ def build_vib_viewer_html(
capture_js = (
_GENERIC_CAPTURE_JS.replace("__UID__", uid)
.replace("__CAPFN__", capture_fn)
.replace("__BG__", json.dumps(bgcolor))
.replace("__BG__", _script_json(bgcolor))
)
body = (
body
Expand Down
30 changes: 21 additions & 9 deletions quantui/backends/slurm.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
SlurmJobAccounting,
default_job_name,
estimate_slurm_resources,
normalize_slurm_state,
parse_sacct_accounting,
parse_sacct_states,
parse_slurm_job_id,
Expand All @@ -54,8 +55,19 @@
"TIMEOUT",
"NODE_FAIL",
"OUT_OF_MEMORY",
# Also final for this job id: a preempted job is not requeued
# under it unless the site requeues (then squeue reports it again).
"PREEMPTED",
"BOOT_FAIL",
"DEADLINE",
"REVOKED",
}
)
# Non-terminal states that are not literally PENDING/RUNNING.
_RUNNING_LIKE_SLURM = frozenset({"COMPLETING", "SUSPENDED", "STOPPED", "RESIZING"})
_PENDING_LIKE_SLURM = frozenset(
{"PENDING", "CONFIGURING", "REQUEUED", "REQUEUE_HOLD", "REQUEUE_FED"}
)
_TERMINAL_RECORD = frozenset({"success", "error", "cancelled"})
_ACTIVE_RECORD = frozenset({"queued", "pending", "running", "submitted"})
# A request id (uuid hex / job-name style) or a numeric SLURM job id.
Expand Down Expand Up @@ -463,8 +475,8 @@ def _squeue_status(self, slurm_job_id: str) -> str | None:
):
return None

status = result.stdout.strip()
return status.upper() if status else None
status = normalize_slurm_state(result.stdout)
return status or None

def _sacct_status(self, slurm_job_id: str) -> str | None:
batch = self._batch_sacct([slurm_job_id])
Expand Down Expand Up @@ -566,8 +578,8 @@ def _batch_squeue(self, slurm_job_ids: List[str]) -> Dict[str, str]:
)
for line in result.stdout.splitlines():
parts = line.strip().split()
if len(parts) == 2:
statuses[parts[0]] = parts[1]
if len(parts) >= 2:
statuses[parts[0]] = normalize_slurm_state(" ".join(parts[1:]))
except (
subprocess.TimeoutExpired,
FileNotFoundError,
Expand Down Expand Up @@ -746,8 +758,8 @@ def cancel(self, request_id: str) -> bool:
)
if status in _TERMINAL_SLURM:
return self._finalize_cancel_from_slurm_state(record, status)
if status and status not in ("PENDING", "RUNNING", "CONFIGURING"):
return self._finalize_cancel_from_slurm_state(record, status)
# Anything else (PENDING, RUNNING, COMPLETING, ...) is still on
# its way to CANCELLED: keep waiting until the deadline.
time.sleep(cfg.CANCEL_POLL_INTERVAL_SECONDS)

self._record_cancel_failure(
Expand Down Expand Up @@ -812,10 +824,10 @@ def _is_within(path: Path, parent: Path) -> bool:


def _map_slurm_status(slurm_status: str) -> str:
upper = slurm_status.upper()
if upper in ("PENDING", "CONFIGURING"):
upper = normalize_slurm_state(slurm_status)
if upper in _PENDING_LIKE_SLURM:
return "pending"
if upper == "RUNNING":
if upper == "RUNNING" or upper in _RUNNING_LIKE_SLURM:
return "running"
if upper in _TERMINAL_SLURM:
if upper == "COMPLETED":
Expand Down
14 changes: 13 additions & 1 deletion quantui/backends/slurm_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@ def parse_slurm_job_id(sbatch_output: str) -> Optional[str]:
return None


def normalize_slurm_state(state: str) -> str:
"""Reduce a SLURM state string to its bare upper-case state name.

``sacct`` reports a cancel as ``CANCELLED by <uid>`` and may append ``+``
to a state (``CANCELLED+``); ``squeue`` long forms can carry a reason in
the same way. Every consumer compares against bare names
(``CANCELLED``, ``COMPLETED``, ...), so the extra text is dropped here.
"""
parts = str(state or "").strip().upper().split()
return parts[0].rstrip("+") if parts else ""


def parse_sacct_accounting(sacct_output: str) -> Dict[str, SlurmJobAccounting]:
"""Parse ``sacct -P --format=JobID,State,ExitCode,Elapsed`` output."""
rows: Dict[str, SlurmJobAccounting] = {}
Expand All @@ -116,7 +128,7 @@ def parse_sacct_accounting(sacct_output: str) -> Dict[str, SlurmJobAccounting]:
if len(parts) < 2:
continue
job_id = parts[0].strip()
state = parts[1].strip().upper()
state = normalize_slurm_state(parts[1])
if not job_id or not state or "." in job_id:
continue
exit_code = parts[2].strip() if len(parts) > 2 else ""
Expand Down
24 changes: 24 additions & 0 deletions quantui/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ def generate_calculation_script(
calc_type, solvent=solvent, density_fit=density_fit, nstates=nstates
)
script_content = config.PYSCF_SCRIPT_TEMPLATE.format(
chg_dispersion_block=(
chg_dispersion_script_block()
if self.method.upper() == "WB97X-D"
else ""
),
job_name=job_name,
method=self.method,
basis=self.basis,
Expand Down Expand Up @@ -295,6 +300,25 @@ def create_calculation(
}


def chg_dispersion_script_block() -> str:
"""Source of :mod:`quantui.chg_dispersion` for a standalone script.

The exported script must reproduce wB97X-D's dispersion term without
importing QuantUI, so the (numpy + pyscf only) module is pasted in.
"""
import inspect

from . import chg_dispersion

src = inspect.getsource(chg_dispersion)
# A __future__ import is only legal at the top of a file.
src = src.replace("from __future__ import annotations\n", "")
return (
"\n\n# ---- wB97X-D dispersion term (copy of quantui/chg_dispersion.py)"
" ----\n" + src + "# ---- end of wB97X-D dispersion term ----\n"
)


def script_sections(
calc_type: str = "single_point",
*,
Expand Down
Loading
Loading