From 976c54c51958f897cfab38cf26dd81164b6f2be2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 19:59:52 +0000 Subject: [PATCH 1/5] PyFock optimizations: convert step energies with PyFock's eV/Hartree PyFock's ASE calculator reports energies in eV using its own constant (pyfock.Data.au2eVFactor = 27.211324570273), while the optimizer divided by QuantUI's CODATA 2018 value (27.211386...). Every optimization step energy except the final one (which comes from the required single point) was therefore high by 2.3e-6 of the total energy: 1.7225e-4 Eh for water, predicted exactly by the ratio of the two constants, and about 1.4 kcal/mol near -1000 Eh. The optimizer now converts PyFock energies with PyFock's factor (falling back to QuantUI's if PyFock cannot be imported). Forces carried the same 2.3e-6 relative factor, which does not affect convergence. Contributions: - Claude (Opus 5.5): code edits, review, and conceptual discussion - Jonathan Schultz: overall vision, planning, review, and orchestration Co-authored-by: Jonathan Schultz --- CHANGELOG.md | 10 ++++++++ quantui/optimizer.py | 26 +++++++++++++++++++-- tests/test_pyfock_energy_units.py | 39 +++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 tests/test_pyfock_energy_units.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 103324d..1792536 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +### Fixed + +- **PyFock geometry optimizations:** every step energy except the final one + was too high by 2.3 × 10⁻⁶ of the total energy (0.11 kcal/mol for water, + about 1.4 kcal/mol for a molecule near −1000 Eh). PyFock reports energies + in eV with its own Hartree→eV constant; QuantUI now converts them back + with the same constant. The final energy was already right (it comes from + the required single point). The backend cross-check now also compares the + first optimization step's energy. + ## [0.13.1] - 2026-12-05 ### Fixed diff --git a/quantui/optimizer.py b/quantui/optimizer.py index a505af2..8e97320 100644 --- a/quantui/optimizer.py +++ b/quantui/optimizer.py @@ -542,6 +542,27 @@ def _resume_start_geometry(checkpoint: Optional[Any]) -> Optional[Molecule]: return None +def ev_per_hartree_for(engine_id: str) -> float: + """eV per Hartree the engine's ASE calculator used to report energies. + + PyFock's calculator converts with its own constant + (``pyfock.Data.au2eVFactor`` = 27.211324570273 in PyFock 0.2), not the + CODATA 2018 value QuantUI and ASE use (27.2113862...). Dividing PyFock's + eV energies by QuantUI's factor shifted every optimization step energy by + 2.3e-6 of the total energy (1.7e-4 Eh for water, about 1.4 kcal/mol at + -1000 Eh). Converting back with the engine's own factor recovers its + Hartree values exactly. Found by the backend cross-check (M-XCHECK). + """ + if engine_id == "pyfock": + try: + from pyfock import Data as _PyfockData + + return float(_PyfockData.au2eVFactor) + except (ImportError, AttributeError): + pass + return float(HARTREE_TO_EV) + + def optimize_geometry( molecule: Molecule, method: str = "RHF", @@ -966,6 +987,7 @@ def _report_opt_fraction() -> None: trajectory: List[Molecule] = [] energies_hartree: List[float] = [] + _ev_per_ha = ev_per_hartree_for(engine_id) for frame in traj_frames: mol_frame = atoms_to_molecule(frame, charge=charge, multiplicity=mult) @@ -973,7 +995,7 @@ def _report_opt_fraction() -> None: # Each frame has a SinglePointCalculator with the stored energy (eV) try: e_ev = frame.get_potential_energy() - energies_hartree.append(e_ev / HARTREE_TO_EV) + energies_hartree.append(e_ev / _ev_per_ha) except Exception: # noqa: BLE001 — NaN fallback for missing per-frame energy energies_hartree.append(float("nan")) @@ -982,7 +1004,7 @@ def _report_opt_fraction() -> None: trajectory = [atoms_to_molecule(atoms, charge=charge, multiplicity=mult)] try: e_ev = atoms.get_potential_energy() - energies_hartree = [e_ev / HARTREE_TO_EV] + energies_hartree = [e_ev / _ev_per_ha] except Exception: # noqa: BLE001 — NaN fallback for missing final energy energies_hartree = [float("nan")] diff --git a/tests/test_pyfock_energy_units.py b/tests/test_pyfock_energy_units.py new file mode 100644 index 0000000..421d2d3 --- /dev/null +++ b/tests/test_pyfock_energy_units.py @@ -0,0 +1,39 @@ +"""PyFock step energies are converted back with PyFock's own eV/Hartree. + +PyFock's ASE calculator reports energies in eV using pyfock.Data.au2eVFactor +(27.211324570273), not the CODATA 2018 value QuantUI uses; dividing by +QuantUI's factor shifted every optimization step energy by 2.3e-6 of the +total (found by the backend cross-check). +""" + +from __future__ import annotations + +import sys +import types + +import pytest + +from quantui.optimizer import ev_per_hartree_for +from quantui.session_calc import HARTREE_TO_EV + + +def test_pyscf_uses_quantui_factor(): + assert ev_per_hartree_for("pyscf") == pytest.approx(HARTREE_TO_EV, abs=0) + + +def test_pyfock_uses_its_own_factor(monkeypatch): + fake = types.ModuleType("pyfock") + fake.Data = types.SimpleNamespace(au2eVFactor=27.211324570273) + monkeypatch.setitem(sys.modules, "pyfock", fake) + f = ev_per_hartree_for("pyfock") + assert f == 27.211324570273 + # Round trip of a water-sized energy is exact with the engine's factor, + # and off by ~1.7e-4 Eh with QuantUI's. + e_ha = -76.2720937503 + assert (e_ha * f) / f == pytest.approx(e_ha, abs=1e-12) + assert abs((e_ha * f) / HARTREE_TO_EV - e_ha) > 1e-4 + + +def test_pyfock_missing_falls_back(monkeypatch): + monkeypatch.setitem(sys.modules, "pyfock", None) # import raises ImportError + assert ev_per_hartree_for("pyfock") == pytest.approx(HARTREE_TO_EV, abs=0) From 265b0fa16bc47cff9bb6fa1a4319bead3e550427 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 19:59:52 +0000 Subject: [PATCH 2/5] Cross-check: compare the first optimization step's energy too The app path's saved result keeps only the final energy, which comes from the required single point, so a constant offset in the optimization's step energies went unnoticed. The geometry-optimization check now also compares the first step's energy (starting geometry) with the backend. Without the previous commit the PyFock case fails here (1.73e-4 Eh); with it, it passes. Contributions: - Claude (Opus 5.5): code edits, review, and conceptual discussion - Jonathan Schultz: overall vision, planning, review, and orchestration Co-authored-by: Jonathan Schultz --- quantui/xcheck/runner.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/quantui/xcheck/runner.py b/quantui/xcheck/runner.py index 2f54528..af4ea26 100644 --- a/quantui/xcheck/runner.py +++ b/quantui/xcheck/runner.py @@ -360,6 +360,11 @@ def run_session_case(case: XCase, workdir: Path, engine: str) -> Dict[str, Any]: ), pref, ).to_session_result() + first_step = ( + float(result.energies_hartree[0]) + if len(result.energies_hartree) > 1 + else None + ) if result.energies_hartree: result.energies_hartree[-1] = float(sp.energy_hartree) if case.calc_type == "geometry_opt": @@ -381,6 +386,10 @@ def run_session_case(case: XCase, workdir: Path, engine: str) -> Dict[str, Any]: molecule=mol, ) data: Dict[str, Any] = load_result(saved) + if case.calc_type == "geometry_opt" and first_step is not None: + # Step energies are what the optimization plot shows; the saved + # result keeps only the final (single-point) energy. + data["_first_step_energy_hartree"] = first_step return data @@ -805,6 +814,27 @@ def _check_geometry_opt(case: XCase, path: str, data: Dict[str, Any]) -> List[Ch # PyFock always fits the density; compare with PySCF doing the same. density_fit="pyfock" in case.engines, ) + first_rows: List[CheckRow] = [] + if data.get("_first_step_energy_hartree") is not None: + r0 = ref.stationary_point( + case.atoms, + case.coords, + case.method, + case.basis, + case.charge, + case.multiplicity, + density_fit="pyfock" in case.engines, + ) + first_rows.append( + compare( + case.case_id, + path, + "energy_hartree", + data["_first_step_energy_hartree"], + r0["energy_hartree"], + note="first optimization step (starting geometry)", + ) + ) fmax = float(case.options.get("fmax", 0.05)) limit = ref.fmax_ev_ang_to_hartree_bohr(fmax) g = r["max_gradient_hartree_bohr"] @@ -846,7 +876,7 @@ def _check_geometry_opt(case: XCase, path: str, data: Dict[str, Any]) -> List[Ch ), ) ) - return rows + return first_rows + rows def _check_pes_scan(case: XCase, path: str, data: Dict[str, Any]) -> List[CheckRow]: From 9c1f5335b0a9f45f96a941ef05104a9026ba4f5c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 20:22:11 +0000 Subject: [PATCH 3/5] Workspace: scroll only the atom list to a picked row Selection sync brought the picked atom's row into view with scrollIntoView, which also scrolls every scrollable ancestor: the height-capped pane body (and the page). Each click on an atom therefore slid the 3D viewer up, away from the pointer, while the student was still clicking atoms in it. Scroll the atom list's own box instead, leaving the pane and the page where they are. Contributions: - Claude (Opus 5.5): code edits, review, and conceptual discussion - Jonathan Schultz: overall vision, planning, review, and orchestration Co-authored-by: Jonathan Schultz --- quantui/app_workspace.py | 12 ++++++++++-- tests/test_app_workspace.py | 9 +++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 1cdab72..23fda04 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -259,10 +259,18 @@ "if(f){f();}else if(n<40){setTimeout(go,50);}}go();})();" ) +# Scrolls only the atom list's own box: scrollIntoView would also scroll the +# pane body (and the page), moving the 3D viewer away while atoms are being +# clicked in it. _SCROLL_PUSH_JS = ( "(function(){var n=0;function go(){n++;" - "var r=document.querySelector('.%s tr[data-atom=\"%d\"]');" - "if(r){r.scrollIntoView({block:'nearest'});}" + "var c=document.querySelector('.%s');" + "var r=c&&c.querySelector('tr[data-atom=\"%d\"]');" + "if(r){var h=c.querySelector('thead');" + "var top=c.getBoundingClientRect().top+(h?h.getBoundingClientRect().height:0);" + "var bot=c.getBoundingClientRect().bottom,b=r.getBoundingClientRect();" + "if(b.topbot){c.scrollTop+=b.bottom-bot;}}" "else if(n<20){setTimeout(go,50);}}go();})();" ) diff --git a/tests/test_app_workspace.py b/tests/test_app_workspace.py index 5662936..9be2e29 100644 --- a/tests/test_app_workspace.py +++ b/tests/test_app_workspace.py @@ -364,3 +364,12 @@ def test_toolbar_is_the_fixed_head_of_the_pane(app): assert BODY_CLASS in app._ws_body._dom_classes body_rule = WORKSPACE_CSS.split(f".{BODY_CLASS} {{", 1)[1].split("}", 1)[0] assert "overflow-y: auto" in body_rule + + +def test_selection_scroll_moves_only_the_atom_list(): + # scrollIntoView would also scroll the pane body, moving the viewer away + # from the pointer while atoms are being clicked in it. + from quantui.app_workspace import _SCROLL_PUSH_JS + + assert "scrollIntoView" not in _SCROLL_PUSH_JS + assert "scrollTop" in _SCROLL_PUSH_JS From a5132043b52dc93e17908622a5ebfa40640330e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 20:26:10 +0000 Subject: [PATCH 4/5] Workspace: one 3D viewer, with a pick mode for Edit Structure and PES scans With the two-pane workspace on, the Calculate tab still drew its own 3D viewer, so the molecule appeared twice. It was kept because Edit Structure and PES scan click-to-pick wired their clicks and highlights into it. Those tools now pick on the pane's viewer instead, and the Calculate tab's viewer, its backend toggle and style dropdown are hidden (and left empty) while the workspace is on. New companion module app_pick_mode gives the pane's viewer an explicit pick mode, exactly one at a time: - measure (normal): click-to-measure and atom-list selection; - edit: while the Edit Structure panel is open; - scan: while Calc. Type is PES Scan (Edit Structure wins if both). A pick mode is entered only while the Calculate tab is selected. It shows the Calculate-tab molecule with atom numbers and wires the tool's own click inbox and highlight slot into the viewer, so the tools' handlers and highlight pushes are unchanged. Atom-list row clicks, the row highlights, Clear selection and the status footer follow the active tool. A banner at the top of the pane says "Clicking picks atoms for ..." with Done (Done closes Edit Structure, or pauses scan picking). Leaving the mode puts back what the viewer showed before, so a result stays a result. A result arriving during a pick mode pauses it; the banner then offers "Pick atoms" to resume, as does reopening Edit Structure or choosing PES Scan again. With PlotlyMol the banner says that picking by clicking needs py3Dmol. app.py gets hooks only: _refresh_calc_mol_viewer syncs the pick mode instead of drawing when the workspace is on, the root-tab observer syncs it, _rerender_3d_views keeps the tool's wiring on a redraw, and a lighting change redraws the workspace viewer. Switching the workspace off leaves any pick mode and gives the Calculate viewer (with its tool wiring) back; that path is unchanged. The setup dialog still covers the page, so its hint ("close the dialog first" to pick scan atoms) stays accurate. Help text for measuring, Edit Structure and PES picking says where the clicks go. Tests that check the Calculate viewer itself now switch the workspace off first. Contributions: - Claude (Opus 5.5): code edits, review, and conceptual discussion - Jonathan Schultz: overall vision, planning, review, and orchestration Co-authored-by: Jonathan Schultz --- .github/copilot-instructions.md | 1 + quantui/app.py | 30 +- quantui/app_builders.py | 2 +- quantui/app_measurement.py | 8 +- quantui/app_pes_pick.py | 13 +- quantui/app_pick_mode.py | 455 +++++++++++++++++++++++++++++ quantui/app_runflow.py | 7 +- quantui/app_structure_edit.py | 22 +- quantui/app_visualization.py | 7 + quantui/app_workspace.py | 146 +++++++-- quantui/help_content.py | 23 +- tests/test_app_pick_mode.py | 414 ++++++++++++++++++++++++++ tests/test_export2_molecule_png.py | 5 + tests/test_uiaudit_design.py | 4 + 14 files changed, 1095 insertions(+), 42 deletions(-) create mode 100644 quantui/app_pick_mode.py create mode 100644 tests/test_app_pick_mode.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 763b098..3c46699 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -45,6 +45,7 @@ QuantUI/ │ ├── app_structure_edit.py ← Edit Structure tools (set bond/angle/dihedral, delete atoms…) │ ├── app_measurement.py ← click-to-measure distances/angles in the viewer │ ├── app_pes_pick.py ← pick PES-scan atoms in the viewer +│ ├── app_pick_mode.py ← workspace viewer pick mode (measure / edit structure / pick scan atoms) │ ├── app_xyz_input.py ← XYZ Input tab handlers │ ├── app_visualization.py ← Trajectory / vib / IR / orbital / PES rendering │ ├── app_history.py ← History tab loaders, replay context diff --git a/quantui/app.py b/quantui/app.py index 60f5a83..88f2b63 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -268,6 +268,8 @@ from quantui.app_menubar import build_menubar as _mb_build_menubar from quantui.app_menubar import menubar_js as _mb_menubar_js from quantui.app_pes2d import scan2d_enabled as _scan2d_enabled +from quantui.app_pick_mode import pick_mode_active as _pm_active +from quantui.app_pick_mode import sync_pick_mode as _pm_sync from quantui.app_runflow import ( apply_scan_range_around_current as _run_apply_scan_range_around_current, ) @@ -639,8 +641,10 @@ from quantui.app_workspace import build_workspace as _ws_build_workspace from quantui.app_workspace import finalize_viewer_html as _ws_finalize_viewer_html from quantui.app_workspace import labels_enabled as _ws_labels_enabled +from quantui.app_workspace import render_viewer as _ws_render_viewer from quantui.app_workspace import show_input_preview as _ws_show_input_preview from quantui.app_workspace import viewer_render_kwargs as _ws_viewer_render_kwargs +from quantui.app_workspace import workspace_enabled as _ws_workspace_on from quantui.app_xyz_input import ( on_load_xyz as _xyz_on_load_xyz, ) @@ -2006,6 +2010,13 @@ class QuantUIApp: _analysis_empty_html: Any _analysis_mol_output: Any _ws_shell: Any + _ws_pick_mode: str + _ws_pick_paused: bool + _ws_pick_snapshot: Any + _ws_pick_backend: str + _ws_pick_banner: Any + _ws_pick_banner_html: Any + _ws_pick_btn: Any _mb_host: Any _mb_row: Any _mb_js_bridge: Any @@ -2539,6 +2550,9 @@ def _on_root_tab_changed(self, change) -> None: new = change.get("new") if self._is_tab(new, "analysis"): _ana_scroll_analysis_tab_to_top(self) + # The Calculate tab's click tools own the workspace viewer only while + # that tab is selected (app_pick_mode). + _pm_sync(self) if _slurm_jobs_tab_visible(self) and self._is_tab(new, "slurm_jobs"): _slurm_refresh_jobs_tab(self) # Runs save new result folders while Files is out of view; re-list on @@ -4349,6 +4363,11 @@ def _refresh_calc_mol_viewer(self, *, backend: Optional[str] = None) -> None: """ if self._molecule is None or _render_molecule_html is None: return + if _ws_workspace_on(self): + # Two-pane workspace: no Calculate viewer; Edit Structure and PES + # scan picking use the pane's viewer through a pick mode. + _pm_sync(self) + return # Reserve the viewer's height only once there is a viewer, so the # empty Calculate tab has no blank block. self.viz_output.layout.min_height = _CALC_VIEWER_MIN_HEIGHT @@ -4564,7 +4583,10 @@ def _rerender_3d_views(self, *, keep_picks: bool = False) -> None: self._refresh_calc_mol_viewer(backend=str(chosen)) # Analysis-tab molecule viewer (ANALYSIS_STRUCTURE_VIEW task). - if self._analysis_displayed_molecule is not None: + if self._analysis_displayed_molecule is not None and _pm_active(self): + # A Calculate tool owns the workspace viewer: its click wiring. + _ws_render_viewer(self, keep_picks=True) + elif self._analysis_displayed_molecule is not None: chosen = self._resolve_backend(VizTask.ANALYSIS_STRUCTURE_VIEW) if chosen is not None: # Same render path as the first draw (app_visualization. @@ -4903,7 +4925,11 @@ def _on_viz_style_changed(self, change) -> None: def _on_viz_lighting_changed(self, change) -> None: self._viz_lighting = change["new"] - self._refresh_calc_mol_viewer() + if _ws_workspace_on(self): + # The workspace viewer is the only one on screen. + self._rerender_3d_views(keep_picks=True) + else: + self._refresh_calc_mol_viewer() # ── Molecule input ──────────────────────────────────────────────────── diff --git a/quantui/app_builders.py b/quantui/app_builders.py index baedd7f..36f3490 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -1591,7 +1591,7 @@ def build_shared_widgets( app._scan_pick_readout = widgets.HTML( value=( f'' - "Click atoms in the viewer above (py3Dmol) to fill the fields." + "Click atoms in the 3D viewer (py3Dmol) to fill the fields." ) ) app._scan_pick_clear_btn = widgets.Button( diff --git a/quantui/app_measurement.py b/quantui/app_measurement.py index 7d9b3de..0d31503 100644 --- a/quantui/app_measurement.py +++ b/quantui/app_measurement.py @@ -414,8 +414,14 @@ def _clear_inbox() -> None: def on_measure_clear(app: Any, btn: Any = None) -> None: """Clear button: empty the pick chain and its highlights.""" _ = btn + from .app_pick_mode import measuring_off_text, pick_mode_active + app._measure_picks = [] - _set_readout(app, _PLACEHOLDER_TEXT) + # While a Calculate tool owns the workspace viewer's clicks, the readout + # keeps saying so (the Clear button is still on screen). + _set_readout( + app, measuring_off_text(app) if pick_mode_active(app) else _PLACEHOLDER_TEXT + ) push_highlight(app, []) _notify_selection(app) diff --git a/quantui/app_pes_pick.py b/quantui/app_pes_pick.py index 66aec19..b517a3d 100644 --- a/quantui/app_pes_pick.py +++ b/quantui/app_pes_pick.py @@ -1,8 +1,10 @@ -"""Click-to-pick atom selection for PES Scan setup (Calculate-tab viewer). +"""Click-to-pick atom selection for PES Scan setup. Reuses the py3Dmol click transport and highlight overlay from :mod:`quantui.app_measurement`, but fills the PES scan atom dropdowns instead -of the measure readout. +of the measure readout. The viewer clicked is the Calculate tab's own one, or +— with the two-pane workspace on — the pane's viewer in its "pick scan atoms" +mode (``app_pick_mode``). """ from __future__ import annotations @@ -34,7 +36,10 @@ def _scan_pick_indices(app: Any) -> List[int]: def push_scan_highlight(app: Any, indices: Sequence[int]) -> None: - """Highlight scan atoms on the live Calculate-tab viewer.""" + """Highlight scan atoms on the live viewer that takes the scan clicks.""" + from .app_pick_mode import notify_pick_views + + notify_pick_views(app) # workspace atom list / footer, in the scan mode bridge = getattr(app, "_scan_pick_bridge", None) if bridge is None: return @@ -124,6 +129,6 @@ def clear_pes_pick(app: Any) -> None: if readout is not None: readout.value = ( '' - "Click atoms in the viewer above (py3Dmol) to fill the fields." + "Click atoms in the 3D viewer (py3Dmol) to fill the fields." ) push_scan_highlight(app, _scan_pick_indices(app)) diff --git a/quantui/app_pick_mode.py b/quantui/app_pick_mode.py new file mode 100644 index 0000000..2164d5d --- /dev/null +++ b/quantui/app_pick_mode.py @@ -0,0 +1,455 @@ +"""Pick modes for the workspace viewer: what a click on the 3D structure does. + +With the two-pane workspace on (``app_workspace``), the Calculate tab has no +3D viewer of its own; the pane's viewer is the only one. Three tools pick +atoms by clicking it, so that viewer has an explicit pick mode, exactly one +at a time: + +- ``measure`` (normal) — click-to-measure and atom-list selection + (``app_measurement``); +- ``edit`` — the Edit Structure panel's atom picks (``app_structure_edit``), + while that panel is open; +- ``scan`` — the PES scan coordinate atoms (``app_pes_pick``), while + Calc. Type is PES Scan. + +Both tools live on the Calculate tab, so a pick mode is entered only while +that tab is selected; on every other tab the viewer measures. A pick mode +shows the Calculate-tab molecule (the input) with atom numbers, and wires the +tool's own click inbox and highlight slot into the viewer — the same click +transport and overlay the tools used on the Calculate tab's viewer, so their +Python handlers are unchanged. A banner at the top of the pane says what a +click does, with a Done button. Leaving the mode puts back what the viewer +showed before (a result stays a result) and clicks measure again. + +Done closes Edit Structure, or pauses scan picking; a result arriving while a +pick mode is on also pauses it, so the new result shows normally. While +paused the banner offers a button to pick again; reopening Edit Structure or +choosing PES Scan again also ends the pause. + +With the workspace off nothing here applies: the Calculate tab keeps its own +viewer and both tools wire into it as before (``app._refresh_calc_mol_viewer``). +""" + +from __future__ import annotations + +import html as _html +import logging +from typing import Any, List, Optional + +import ipywidgets as widgets + +from quantui import theme as _theme +from quantui.app_measurement import ( + MEASURE_INBOX_CLASS, + _set_readout, + inject_click_js, + on_measure_clear, + reset_picks, + update_panel_for_backend, +) +from quantui.app_pes_pick import PES_PICK_INBOX_CLASS +from quantui.app_structure_edit import EDIT_PICK_INBOX_CLASS, editing_active + +logger = logging.getLogger(__name__) + +MODE_MEASURE = "measure" +MODE_EDIT = "edit" +MODE_SCAN = "scan" + +BANNER_CLASS = "quantui-ws-pickbar" + +_INBOX = { + MODE_MEASURE: MEASURE_INBOX_CLASS, + MODE_EDIT: EDIT_PICK_INBOX_CLASS, + MODE_SCAN: PES_PICK_INBOX_CLASS, +} + +_TOOL_NAME = {MODE_EDIT: "Edit Structure", MODE_SCAN: "the PES scan"} + +PICK_BANNER_CSS = f""" +/* Pick-mode banner at the top of the workspace pane (app_pick_mode) ----- */ +.{BANNER_CLASS} {{ + background: var(--q-surface-info-bg); + border: 1px solid var(--q-accent-info); + border-radius: 6px; + padding: 4px 6px 4px 10px; + margin: 0 0 4px; +}} +.{BANNER_CLASS}.is-paused {{ + background: var(--q-bg-panel); + border-color: var(--q-border); +}} +""" + + +# --------------------------------------------------------------------------- +# State +# --------------------------------------------------------------------------- + + +def _ws_on(app: Any) -> bool: + return bool(getattr(app, "_ws_enabled", False)) + + +def pick_mode(app: Any) -> str: + """The viewer's current pick mode (``measure`` unless a tool owns it).""" + mode = getattr(app, "_ws_pick_mode", MODE_MEASURE) + return mode if mode in _INBOX else MODE_MEASURE + + +def pick_mode_active(app: Any) -> bool: + """True while a Calculate-tab tool owns the workspace viewer's clicks.""" + return _ws_on(app) and pick_mode(app) != MODE_MEASURE + + +def inbox_class(mode: str) -> str: + """Hidden inbox a click (viewer or atom-list row) writes to in *mode*.""" + return _INBOX.get(mode, MEASURE_INBOX_CLASS) + + +def _on_calculate_tab(app: Any) -> bool: + tab = getattr(app, "root_tab", None) + is_tab = getattr(app, "_is_tab", None) + if tab is None or is_tab is None: + return False + return bool(is_tab(tab.selected_index, "calculate")) + + +def available_tool(app: Any) -> str: + """The pick tool the Calculate tab offers right now, ignoring a pause. + + Edit Structure wins over a PES scan setup (as on the Calculate viewer). + """ + if not _ws_on(app) or getattr(app, "_molecule", None) is None: + return MODE_MEASURE + if not _on_calculate_tab(app): + return MODE_MEASURE + if editing_active(app): + return MODE_EDIT + if getattr(getattr(app, "calc_type_dd", None), "value", None) == "PES Scan": + return MODE_SCAN + return MODE_MEASURE + + +def desired_mode(app: Any) -> str: + if getattr(app, "_ws_pick_paused", False): + return MODE_MEASURE + return available_tool(app) + + +def mode_picks(app: Any, mode: Optional[str] = None) -> List[int]: + """0-based atoms the *mode*'s tool has picked, in pick order.""" + mode = mode or pick_mode(app) + if mode == MODE_MEASURE: + raw = getattr(app, "_measure_picks", None) + return list(raw) if isinstance(raw, (list, tuple)) else [] + mol = getattr(app, "_molecule", None) + n = len(getattr(mol, "atoms", []) or []) if mol is not None else 0 + picks: List[int] = [] + try: + if mode == MODE_EDIT: + from quantui.app_structure_edit import current_picks + + picks = current_picks(app) + else: + from quantui.app_pes_pick import _scan_pick_indices + + picks = list(getattr(app, "_scan_pick_buffer", None) or []) + if not picks: + picks = _scan_pick_indices(app) + except (AttributeError, TypeError, ValueError) as exc: + logger.debug("pick-mode picks unavailable: %s", exc) + return [] + return [int(p) for p in picks if 0 <= int(p) < n] + + +def measuring_off_text(app: Any) -> str: + """The measurement readout while a tool owns the clicks.""" + tool = _TOOL_NAME.get(pick_mode(app), "a Calculate tool") + return ( + f"Measuring is off while clicks pick atoms for {tool}. " + "Press Done above the viewer to measure again." + ) + + +# --------------------------------------------------------------------------- +# Rendering hook (called by app_workspace.render_viewer) +# --------------------------------------------------------------------------- + + +def finalize_pick_html(app: Any, html: str, backend: Any) -> str: + """Wire the active tool's click inbox into the workspace viewer HTML. + + The pick-mode counterpart of ``app_measurement.finalize_analysis_html``: + the tool's picks are drawn as soon as the viewer exists, and its own + highlight slot is registered, so the tool's existing highlight pushes + (``push_scan_highlight`` / Edit Structure's) reach this viewer. + """ + mode = pick_mode(app) + app._ws_pick_backend = str(backend) + app._measure_picks = [] + update_panel_for_backend(app, backend) + _set_readout(app, measuring_off_text(app)) + if str(backend) == "py3dmol": + html = inject_click_js( + html, inbox_class=inbox_class(mode), initial_picks=mode_picks(app, mode) + ) + refresh_banner(app) # its text depends on the backend + return html + + +# --------------------------------------------------------------------------- +# Switching +# --------------------------------------------------------------------------- + + +def sync_pick_mode(app: Any) -> None: + """Enter or leave a pick mode to match the Calculate tab's tools. + + Called whenever one of the inputs changes: Edit Structure opened/closed, + Calc. Type changed, the root tab changed, a molecule loaded (all reach + here through ``app._refresh_calc_mol_viewer`` or the tab observer), the + banner's button, and the workspace setting. + """ + if not isinstance(getattr(app, "_ws_pick_banner", None), widgets.Widget): + return + new = desired_mode(app) + old = pick_mode(app) + if new != old: + _switch(app, old, new) + refresh_banner(app) + + +def _switch(app: Any, old: str, new: str) -> None: + from quantui.app_workspace import refresh_workspace, render_viewer + + if old == MODE_MEASURE: + app._ws_pick_snapshot = ( + getattr(app, "_analysis_displayed_molecule", None), + getattr(app, "_ws_source", None), + str(getattr(app, "_ws_result_label", "") or ""), + ) + app._ws_pick_mode = new + _log("pick_mode_changed", f"{old}->{new}") + if new == MODE_MEASURE: + _restore_view(app, render=True) + else: + mol = app._molecule + app._ws_source = "input" + if not render_viewer(app, mol, keep_picks=False): + app._analysis_displayed_molecule = mol + refresh_workspace(app) + + +def _restore_view(app: Any, *, render: bool) -> None: + """Put back what the viewer showed before the pick mode began.""" + snap = getattr(app, "_ws_pick_snapshot", None) + app._ws_pick_snapshot = None + mol, source, label = snap if snap else (None, None, "") + if source == "result" and mol is not None: + app._ws_source = "result" + app._ws_result_label = label + target = mol + else: + target = getattr(app, "_molecule", None) + app._ws_source = "input" if target is not None else None + reset_picks(app) + if render and target is not None: + from quantui.app_workspace import render_viewer + + if render_viewer(app, target, keep_picks=False): + return + app._analysis_displayed_molecule = target + + +def leave_pick_mode(app: Any, *, render: bool = True) -> None: + """Back to normal (measure) mode now; used when the layout is switched off.""" + if pick_mode(app) == MODE_MEASURE: + return + app._ws_pick_mode = MODE_MEASURE + _log("pick_mode_changed", "left") + _restore_view(app, render=render) + refresh_banner(app) + + +def pause_for_result(app: Any) -> None: + """A result is about to be drawn: stop picking so it shows normally. + + Called by ``app_visualization.show_result_3d`` before it renders into the + workspace viewer. The pre-pick view is dropped (the result replaces it). + """ + if not pick_mode_active(app): + return + app._ws_pick_mode = MODE_MEASURE + app._ws_pick_snapshot = None + app._ws_pick_paused = True + _log("pick_mode_changed", "paused for a result") + refresh_banner(app) + + +def forget_view(app: Any) -> None: + """A run started: leaving the pick mode later shows the input, not the + previous result (which the run replaces).""" + if pick_mode_active(app): + app._ws_pick_snapshot = None + + +def tool_entered(app: Any) -> None: + """Edit Structure opened or PES Scan chosen: a pause no longer applies.""" + app._ws_pick_paused = False + + +def on_banner_button(app: Any) -> None: + """Done (leave the pick mode) or Pick atoms (resume after a pause).""" + if pick_mode_active(app): + if pick_mode(app) == MODE_EDIT: + # Leaving Edit Structure: close its panel (its observer syncs). + app._edit_accordion.selected_index = None + sync_pick_mode(app) + return + app._ws_pick_paused = True + else: + app._ws_pick_paused = False + sync_pick_mode(app) + + +def on_clear_selection(app: Any) -> None: + """The atom list's Clear selection button, for whichever mode is on.""" + mode = pick_mode(app) if pick_mode_active(app) else MODE_MEASURE + if mode == MODE_EDIT: + from quantui.app_structure_edit import on_clear_picks + + on_clear_picks(app) + elif mode == MODE_SCAN: + from quantui.app_pes_pick import clear_pes_pick + + clear_pes_pick(app) + else: + on_measure_clear(app) + + +def notify_pick_views(app: Any) -> None: + """A tool's picks changed: redraw the atom list, footer and banner.""" + if not pick_mode_active(app): + return + from quantui.app_workspace import sync_selection_views + + sync_selection_views(app) + refresh_banner(app) + + +# --------------------------------------------------------------------------- +# Banner +# --------------------------------------------------------------------------- + + +def build_pick_banner(app: Any, *, layout_fn: Any) -> None: + """The "Clicking picks atoms for … [Done]" strip (hidden in measure mode).""" + app._ws_pick_mode = MODE_MEASURE + app._ws_pick_paused = False + app._ws_pick_snapshot = None + app._ws_pick_backend = "py3dmol" + app._ws_pick_banner_html = widgets.HTML( + value="", layout=layout_fn(flex="1 1 auto", min_width="0") + ) + app._ws_pick_btn = widgets.Button( + description="Done", + icon="check", + tooltip="Stop picking atoms; clicks measure again", + layout=layout_fn( + width="auto", min_width="84px", height="28px", flex="0 0 auto" + ), + ) + app._ws_pick_banner = widgets.HBox( + [app._ws_pick_banner_html, app._ws_pick_btn], + layout=layout_fn(align_items="center", gap="8px", display="none"), + ) + app._ws_pick_banner.add_class(BANNER_CLASS) + app._ws_pick_btn.on_click(lambda _b: on_banner_button(app)) + + +def banner_text(app: Any) -> tuple: + """(state, html, button label) — state is ``active``, ``paused`` or ``""``.""" + body = f"font-size:12px;color:{_theme.css.TEXT_BODY};line-height:1.35" + if pick_mode_active(app): + mode = pick_mode(app) + tool = _TOOL_NAME[mode] + if mode == MODE_EDIT: + how = "up to 4; click a picked atom again to drop it" + else: + kind = str(getattr(getattr(app, "_scan_type_dd", None), "value", "Bond")) + need = {"bond": 2, "angle": 3, "dihedral": 4}.get(kind.lower(), 2) + what = _html.escape(kind.lower()) + how = f"{need} atoms for {'an' if what[:1] in 'aeiou' else 'a'} {what}" + if getattr(app, "_ws_pick_backend", "py3dmol") != "py3dmol": + text = ( + f"Atom numbers are shown for {tool}. Picking by clicking " + "needs the py3Dmol viewer; type the atom numbers instead." + ) + else: + text = f"Clicking picks atoms for {tool} ({how})." + return "active", f'
{text}
', "Done" + tool_mode = available_tool(app) + if tool_mode != MODE_MEASURE: + tool = _TOOL_NAME[tool_mode] + text = f"Clicks measure. To pick atoms for {tool} by clicking:" + return "paused", f'
{text}
', "Pick atoms" + return "", "", "Done" + + +def refresh_banner(app: Any) -> None: + banner = getattr(app, "_ws_pick_banner", None) + if not isinstance(banner, widgets.Widget): + return + state, text, label = banner_text(app) + banner.layout.display = "" if state else "none" + if state == "paused": + banner.add_class("is-paused") + else: + banner.remove_class("is-paused") + app._ws_pick_banner_html.value = text + btn = app._ws_pick_btn + btn.description = label + btn.icon = "check" if state == "active" else "mouse-pointer" + btn.tooltip = ( + "Stop picking atoms; clicks measure again" + if state == "active" + else "Clicks in the viewer pick atoms for this tool again" + ) + + +def _log(event: str, detail: str = "") -> None: + try: + from quantui import calc_log as _clog + + _clog.log_event(event, detail) + except OSError as exc: + logger.debug("pick-mode log failed: %s", exc) + + +__all__ = [ + "BANNER_CLASS", + "MODE_EDIT", + "MODE_MEASURE", + "MODE_SCAN", + "PICK_BANNER_CSS", + "available_tool", + "banner_text", + "build_pick_banner", + "desired_mode", + "finalize_pick_html", + "forget_view", + "inbox_class", + "leave_pick_mode", + "measuring_off_text", + "mode_picks", + "notify_pick_views", + "on_banner_button", + "on_clear_selection", + "pause_for_result", + "pick_mode", + "pick_mode_active", + "refresh_banner", + "sync_pick_mode", + "tool_entered", +] diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index 18e04b8..a3e97f6 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -792,8 +792,13 @@ def on_calc_type_changed(app: Any, change: Any, *, layout_fn: Any) -> None: except Exception: # noqa: BLE001 — a stale hint must not break the tab pass - # PES Scan overlays 1-based atom indices on the Calculate-tab viewer. + # PES Scan overlays 1-based atom indices on the Calculate-tab viewer (or + # puts the workspace viewer in its scan pick mode, app_pick_mode). old_ct = change.get("old") + if ct == "PES Scan" and old_ct != "PES Scan": + from quantui.app_pick_mode import tool_entered + + tool_entered(app) if ct == "PES Scan" or old_ct == "PES Scan": try: app._refresh_calc_mol_viewer() diff --git a/quantui/app_structure_edit.py b/quantui/app_structure_edit.py index 9f37394..f38f1bc 100644 --- a/quantui/app_structure_edit.py +++ b/quantui/app_structure_edit.py @@ -1,10 +1,14 @@ """Edit Structure panel on the Calculate tab. -Pick atoms by clicking the Calculate-tab viewer (py3Dmol; same click bridge -as click-to-measure and PES picking) or by typing their numbers, then set a +Pick atoms by clicking the 3D viewer (py3Dmol; same click bridge as +click-to-measure and PES picking) or by typing their numbers, then set a bond length / angle / dihedral, delete atoms, add a hydrogen, change an element, or mark atoms frozen for a Geometry Opt. Every edit replaces the working molecule (charge and multiplicity unchanged) and can be undone. + +The viewer clicked is the Calculate tab's own one, or — with the two-pane +workspace on — the pane's viewer in its "edit structure" pick mode +(``app_pick_mode``), entered while this panel is open. """ from __future__ import annotations @@ -136,7 +140,7 @@ def wire_edit_widgets(app: Any) -> None: ) app._edit_pick_inbox.observe(safe(lambda c: on_edit_pick(app, c)), names="value") app._edit_accordion.observe( - safe(lambda c: app._refresh_calc_mol_viewer()), names="selected_index" + safe(lambda c: on_edit_panel_toggled(app, c)), names="selected_index" ) for btn, fn in ( (app._edit_bond_btn, on_set_bond), @@ -152,6 +156,15 @@ def wire_edit_widgets(app: Any) -> None: btn.on_click(safe(lambda _b, _fn=fn: _fn(app))) +def on_edit_panel_toggled(app: Any, change: Any = None) -> None: + """Panel opened or closed: redraw the viewer that takes the clicks.""" + if (change or {}).get("new") == 0: + from .app_pick_mode import tool_entered + + tool_entered(app) + app._refresh_calc_mol_viewer() + + def editing_active(app: Any) -> bool: acc = getattr(app, "_edit_accordion", None) return acc is not None and acc.selected_index == 0 @@ -167,6 +180,9 @@ def finalize_edit_calc_html(app: Any, html: str, backend: Any) -> str: def _push_edit_highlight(app: Any, indices: Sequence[int]) -> None: + from .app_pick_mode import notify_pick_views + + notify_pick_views(app) # workspace atom list / footer, in the edit mode bridge = getattr(app, "_edit_pick_bridge", None) if bridge is None: return diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index f268ed9..0737c1c 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -170,6 +170,13 @@ def show_result_3d( ) app._set_html_output(app.result_viz_output, html) + # A result replaces whatever a Calculate tool was picking on in the + # workspace viewer; it shows normally (click-to-measure). + if is_analysis_output: + from quantui.app_pick_mode import pause_for_result + + pause_for_result(app) + # Optional second viewer (typically the Analysis tab). if extra_output is not None: task = ( diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 23fda04..840f99f 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -24,9 +24,15 @@ and the footer. The 3D highlight is the measurement overlay (``push_highlight``), py3Dmol only. +With the layout on, this viewer is the only 3D structure viewer: the +Calculate tab's own viewer is hidden, and its two click tools (Edit Structure, +PES scan atom picking) pick on this viewer through an explicit pick mode +(``app_pick_mode``) with a banner at the top of the pane. + The layout can be switched off (System Settings → Workspace layout, ``ui.workspace_layout``); the viewer block then sits at the top of the -Analysis tab as before, still with the toolbar and atom list. +Analysis tab as before, still with the toolbar and atom list, and the +Calculate tab gets its own viewer back. """ from __future__ import annotations @@ -38,7 +44,19 @@ import ipywidgets as widgets from quantui import theme as _theme -from quantui.app_measurement import MEASURE_INBOX_CLASS, on_measure_clear +from quantui.app_measurement import MEASURE_INBOX_CLASS +from quantui.app_pick_mode import ( + PICK_BANNER_CSS, + build_pick_banner, + inbox_class, + leave_pick_mode, + mode_picks, + on_clear_selection, + pick_mode, + pick_mode_active, + refresh_banner, + sync_pick_mode, +) from quantui.config import ( WORKSPACE_ATOM_LIST_MAX_HEIGHT, WORKSPACE_STACK_BELOW_PX, @@ -221,19 +239,25 @@ border-top: 1px solid var(--q-border); margin-top: 6px; }} -""" +""" + PICK_BANNER_CSS -# Row click → the measure inbox (the same transport as a viewer click; see -# app_measurement.inject_click_js). Event delegation on the table, so one -# handler serves every row; single quotes only — it sits in a "-quoted -# attribute. widgets.HTML assigns innerHTML, which keeps inline handlers. -_ROW_CLICK_JS = ( - "var r=event.target.closest('tr[data-atom]');if(!r){return;}" - f"var b=document.querySelector('.{MEASURE_INBOX_CLASS} textarea');" - "if(!b){return;}" - "b.value=r.getAttribute('data-atom');" - "b.dispatchEvent(new Event('input',{bubbles:true}));" -) + +# Row click → the active pick mode's inbox (the measure inbox normally; the +# same transport as a viewer click, see app_measurement.inject_click_js). +# Event delegation on the table, so one handler serves every row; single +# quotes only — it sits in a "-quoted attribute. widgets.HTML assigns +# innerHTML, which keeps inline handlers. +def _row_click_js(inbox: str) -> str: + return ( + "var r=event.target.closest('tr[data-atom]');if(!r){return;}" + f"var b=document.querySelector('.{inbox} textarea');" + "if(!b){return;}" + "b.value=r.getAttribute('data-atom');" + "b.dispatchEvent(new Event('input',{bubbles:true}));" + ) + + +_ROW_CLICK_JS = _row_click_js(MEASURE_INBOX_CLASS) # Remember the freshly rendered viewer's camera so "Reset view" can return # to it without a Python re-render (which would rebuild the viewer). @@ -295,9 +319,12 @@ def viewer_render_kwargs(app: Any) -> Dict[str, Any]: """Extra ``render_molecule_html`` kwargs for the Analysis/workspace viewer. The pane is narrower than a tab, so the viewer renders smaller there; the - single-column fallback keeps the original 600×500 size. + single-column fallback keeps the original 600×500 size. A pick mode + shows atom numbers, as the Calculate viewer did for its tools. """ - kwargs: Dict[str, Any] = {"show_atom_indices": labels_enabled(app)} + kwargs: Dict[str, Any] = { + "show_atom_indices": labels_enabled(app) or pick_mode_active(app) + } if workspace_enabled(app): kwargs["width"] = WORKSPACE_VIEWER_WIDTH kwargs["height"] = WORKSPACE_VIEWER_HEIGHT @@ -309,6 +336,10 @@ def _viewed_molecule(app: Any) -> Any: def _picks(app: Any) -> list: + """The selection the list and footer show: the active tool's picks in a + pick mode, the measurement chain otherwise.""" + if pick_mode_active(app): + return mode_picks(app) raw = getattr(app, "_measure_picks", None) return list(raw) if isinstance(raw, (list, tuple)) else [] @@ -331,12 +362,14 @@ def atom_list_html( *, mulliken: Optional[Sequence[float]] = None, npa: Optional[Sequence[float]] = None, + inbox: str = MEASURE_INBOX_CLASS, ) -> str: """Read-only atom table: 1-based index, element, x/y/z (Å), charges. Picked atoms (0-based ``picks``) are highlighted and carry their pick order, matching the numbered chain the measurement readout describes. - Charge columns appear only when given and the right length. + Charge columns appear only when given and the right length. A row click + writes to *inbox* (the active pick mode's). """ if molecule is None: return ( @@ -378,7 +411,7 @@ def atom_list_html( f'' + "".join(f"{c}" for c in cells) ) return ( - f'' + f'
' f"{head}{''.join(rows)}
" ) @@ -450,6 +483,12 @@ def footer_html(app: Any) -> str: ) + "" ) + if pick_mode_active(app): + tool = "Edit Structure" if pick_mode(app) == "edit" else "PES scan" + parts.append( + f'' + f"Picking for {tool}" + ) parts.append(f"{_html.escape(selection_text(mol, _picks(app)))}") else: parts.append( @@ -470,6 +509,11 @@ def caption_html(app: Any) -> str: style = f"font-size:12px;color:{_theme.css.TEXT_SECONDARY};margin:2px 0 4px" if mol is None: text = "No structure yet — load a molecule on the Calculate tab." + elif pick_mode_active(app): + text = ( + f"Input structure {_html.escape(mol.get_formula())}, as set up " + "on the Calculate tab." + ) elif source == "input": text = ( f"Input structure {_html.escape(mol.get_formula())} — run a " @@ -583,7 +627,8 @@ def build_workspace(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: # The block that moves between the pane and the Analysis tab. # Head (toolbar + caption) stays put in the pane; the body scrolls. - app._ws_head = widgets.VBox([app._ws_toolbar, app._ws_caption]) + build_pick_banner(app, layout_fn=layout_fn) + app._ws_head = widgets.VBox([app._ws_toolbar, app._ws_caption, app._ws_pick_banner]) app._ws_head.add_class(HEAD_CLASS) app._ws_body = widgets.VBox([app._ana_viewer_row, app._ws_atom_box]) app._ws_body.add_class(BODY_CLASS) @@ -609,7 +654,7 @@ def build_workspace(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: safe(lambda ch: on_labels_toggled(app, ch)), names="value" ) app._ws_reset_btn.on_click(lambda _b: on_reset_view(app)) - app._ws_atom_clear_btn.on_click(lambda _b: on_measure_clear(app)) + app._ws_atom_clear_btn.on_click(lambda _b: on_clear_selection(app)) layout_cb = getattr(app, "workspace_layout_cb", None) if layout_cb is not None: layout_cb.observe( @@ -647,7 +692,15 @@ def _drop_child(box: Any, child: Any) -> None: def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> None: - """Place the viewer block in the side pane (on) or the Analysis tab (off).""" + """Place the viewer block in the side pane (on) or the Analysis tab (off). + + On: the Calculate tab's own viewer is hidden (the pane's is the one + viewer). Off: it comes back and the Calculate tools pick on it again. + """ + if not enabled: + # Leave any pick mode first; the single-column code below then + # handles the restored view like any other. + leave_pick_mode(app, render=False) block = app._ws_viewer_block panel = app.analysis_tab_panel row = getattr(app, "_ana_viewer_row", None) @@ -665,6 +718,8 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> panel.children = tuple(kids) app._ws_enabled = bool(enabled) app._ws_caption.layout.display = "" if enabled else "none" + _show_calc_viewer(app, not enabled) + refresh_banner(app) if not rerender: return if not enabled and getattr(app, "_ws_source", None) == "input": @@ -681,6 +736,32 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> # The viewer changes size with the layout. render_viewer(app, keep_picks=True) refresh_workspace(app) + if enabled: + sync_pick_mode(app) + elif getattr(app, "_molecule", None) is not None: + # The Calculate tab's viewer is back (with its tools' click wiring). + app._refresh_calc_mol_viewer() + + +def _show_calc_viewer(app: Any, shown: bool) -> None: + """Show or hide the Calculate tab's own 3D viewer and its controls. + + Hidden (workspace on) it is also emptied, so no second live viewer holds + a tool's click wiring; the style dropdown is hidden too (the pane's + toolbar is linked to it). Lighting stays: it is not in the toolbar. + """ + display = "" if shown else "none" + for name in ("viz_output", "_mol_calc_png_status", "viz_backend_toggle"): + w = getattr(app, name, None) + if isinstance(w, widgets.Widget): + w.layout.display = display + style_dd = getattr(app, "viz_style_dd", None) + if isinstance(style_dd, widgets.Widget): + style_dd.layout.display = display + out = getattr(app, "viz_output", None) + if not shown and isinstance(out, widgets.Output): + app._clear_output_widget(out) + out.layout.min_height = "0px" def on_workspace_layout_changed(app: Any, change: dict) -> None: @@ -720,7 +801,8 @@ def render_viewer(app: Any, molecule: Any = None, *, keep_picks: bool) -> bool: """(Re)draw the Analysis/workspace viewer through the router. Same task, render function, PNG-capture slot and click-to-measure wiring - as ``app_visualization.show_result_3d``'s Analysis branch. Returns True + as ``app_visualization.show_result_3d``'s Analysis branch; in a pick mode + the active tool's click wiring instead (``app_pick_mode``). Returns True when something was rendered. """ import quantui.app as _app_mod @@ -748,7 +830,12 @@ def render_viewer(app: Any, molecule: Any = None, *, keep_picks: bool) -> bool: show_info=False, **viewer_render_kwargs(app), ) - html = finalize_analysis_html(app, html, chosen, keep_picks=keep_picks) + if pick_mode_active(app): + from quantui.app_pick_mode import finalize_pick_html + + html = finalize_pick_html(app, html, chosen) + else: + html = finalize_analysis_html(app, html, chosen, keep_picks=keep_picks) html = finalize_viewer_html(app, html, chosen) app._set_html_output(out, html) app._analysis_displayed_molecule = mol @@ -771,6 +858,10 @@ def show_input_preview(app: Any, *, force: bool = False) -> None: if getattr(app, "_ws_source", None) == "result" and not force: refresh_footer(app) return + if force: + from quantui.app_pick_mode import forget_view + + forget_view(app) app._ws_source = "input" app._ws_result_label = "" if not render_viewer(app, mol, keep_picks=False): @@ -817,7 +908,14 @@ def _refresh_atom_list(app: Any) -> None: if getattr(app, "_ws_source", None) == "result": mull = getattr(app, "_last_mulliken_charges", None) npa = getattr(app, "_last_npa_charges", None) - app._ws_atom_html.value = atom_list_html(mol, _picks(app), mulliken=mull, npa=npa) + inbox = inbox_class(pick_mode(app)) if pick_mode_active(app) else None + app._ws_atom_html.value = atom_list_html( + mol, + _picks(app), + mulliken=mull, + npa=npa, + inbox=inbox or MEASURE_INBOX_CLASS, + ) n = len(getattr(mol, "atoms", []) or []) if mol is not None else 0 hint = " · click a row or an atom in the viewer" if n else "" app._ws_atom_count.value = ( diff --git a/quantui/help_content.py b/quantui/help_content.py index c67ea87..480e62b 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -549,7 +549,10 @@ "Pre-optimize starting geometry — scans are most meaningful " "from a good starting structure." "
  • Pick atoms via the dropdowns or by clicking in the viewer " - "(py3Dmol only).
  • " + "(py3Dmol only). With the two-pane workspace on, that is the side " + "viewer: while PES Scan is chosen on the Calculate tab, a banner " + "there says clicks pick scan atoms; Done makes clicks " + "measure again." "
  • Use Suggest range or ± around current to fill " "Start/Stop from the current geometry.
  • " "
  • Each scan point runs a constrained QM optimization + " @@ -811,8 +814,9 @@ "measure": { "title": "Click-to-measure (bond / angle / dihedral)", "body": ( - "

    Click atoms directly in the Analysis tab's molecule viewer to " - "read off geometry:

    " + "

    Click atoms directly in the Analysis tab's molecule viewer (the " + "side viewer, with the two-pane workspace on) to read off " + "geometry:

    " "" f"" " " @@ -832,6 +836,10 @@ "atom already in the chain is ignored — repeating an atom makes " "the geometry undefined. Picked atoms are highlighted in the " "viewer; Clear resets the selection.

    " + "

    While Edit Structure is open or PES Scan is chosen on the " + "Calculate tab, clicks in the side viewer pick atoms for that tool " + "instead; a banner above the viewer says so, and its Done " + "button makes clicks measure again.

    " "

    Note: this needs the py3Dmol viewer — if the " "panel shows a message instead of the picker, switch backends " "with the toggle above the viewer (or in Settings). Whenever the " @@ -846,9 +854,12 @@ "editing": { "title": "Editing a structure", "body": ( - "

    Open Edit Structure under the molecule viewer on the " - "Calculate tab. Atom numbers appear in the viewer; click atoms " - "(py3Dmol) or type their numbers.

    " + "

    Open Edit Structure under the molecule on the " + "Calculate tab. Atom numbers appear in the 3D viewer; click atoms " + "(py3Dmol) or type their numbers. With the two-pane workspace on, " + "the viewer is the side one: a banner there says clicks pick atoms " + "for Edit Structure, and Done (or closing the panel) makes " + "clicks measure again.

    " "
      " "
    • 2 atoms → set a bond length; 3 → an angle (at " "the middle atom); 4 → a dihedral (about the middle bond). " diff --git a/tests/test_app_pick_mode.py b/tests/test_app_pick_mode.py new file mode 100644 index 0000000..c51af04 --- /dev/null +++ b/tests/test_app_pick_mode.py @@ -0,0 +1,414 @@ +"""Pick modes on the workspace viewer (quantui/app_pick_mode.py). + +With the two-pane workspace on, the Calculate tab has no viewer of its own: +Edit Structure and PES scan click-to-pick work through the pane's viewer, in +an explicit pick mode (measure / edit / scan), one at a time. With the +workspace off, the Calculate viewer and its tool wiring are unchanged. + +Widget-level and HTML-content checks; the browser side (a click reaching the +tool's inbox, the overlay) is checked headlessly and in Voilà. +""" + +from __future__ import annotations + +import json + +import pytest + +from quantui.app_pick_mode import ( + BANNER_CLASS, + MODE_EDIT, + MODE_MEASURE, + MODE_SCAN, + banner_text, + pick_mode, +) +from quantui.molecule import Molecule +from quantui.visualization_py3dmol import PY3DMOL_AVAILABLE + +WATER = [[0.0, 0.0, 0.117], [0.0, 0.757, -0.469], [0.0, -0.757, -0.469]] + +needs_py3dmol = pytest.mark.skipif( + not PY3DMOL_AVAILABLE, reason="py3Dmol not installed" +) + + +def _water() -> Molecule: + return Molecule(["O", "H", "H"], WATER) + + +def _make_app(tmp_path, monkeypatch, *, workspace: bool = True): + path = tmp_path / "settings.json" + if not workspace: + path.write_text( + json.dumps({"_schema_version": 1, "ui": {"workspace_layout": False}}) + ) + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(path)) + from quantui.app import QuantUIApp + + app = QuantUIApp() + if PY3DMOL_AVAILABLE: + # The pick wiring is py3Dmol-only; pin the backend so the tests do + # not depend on which viewers happen to be installed. + app._viz_backend_preference = "py3dmol" + app._set_molecule(_water()) + return app + + +@pytest.fixture +def app(tmp_path, monkeypatch): + return _make_app(tmp_path, monkeypatch) + + +@pytest.fixture +def app_off(tmp_path, monkeypatch): + return _make_app(tmp_path, monkeypatch, workspace=False) + + +def _html(out) -> str: + return "".join( + o.get("data", {}).get("text/html", "") + for o in out.outputs + if o.get("output_type") == "display_data" + ) + + +def _pane(app) -> str: + return _html(app._analysis_mol_output) + + +# --------------------------------------------------------------------------- +# One viewer +# --------------------------------------------------------------------------- + + +class TestOneViewer: + def test_calculate_tab_has_no_viewer_of_its_own(self, app): + assert app.viz_output.layout.display == "none" + assert app.viz_output.outputs == () + assert app.viz_style_dd.layout.display == "none" + if app.viz_backend_toggle is not None: + assert app.viz_backend_toggle.layout.display == "none" + # Still in the tree (hidden, not removed): the layout can come back. + assert app.viz_output in app.mol_input_container.children + assert app._analysis_displayed_molecule is app._molecule + + def test_tools_never_render_the_hidden_viewer(self, app): + app._edit_accordion.selected_index = 0 + app.calc_type_dd.value = "PES Scan" + app._viz_style = "stick" + app._rerender_3d_views(keep_picks=True) + assert app.viz_output.outputs == () + + def test_off_keeps_the_calculate_viewer(self, app_off): + assert app_off.viz_output.layout.display in ("", None) + assert "Edit Structure" in ( + app._ws_pick_banner_html.value + ) + assert app._ws_pick_btn.description == "Done" + from quantui.app_workspace import viewer_render_kwargs + + assert viewer_render_kwargs(app)["show_atom_indices"] is True + + @needs_py3dmol + def test_clicks_go_to_the_edit_inbox_not_measure(self, app): + app._edit_accordion.selected_index = 0 + html = _pane(app) + assert "quantui-edit-pick-inbox" in html + assert "quantui-measure-inbox" not in html.split("
    Clicks