From 6dd5263ed8b22aded35f081b1adfb54e4d57f441 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:40:05 +0000 Subject: [PATCH 01/12] Accessibility: focus ring, keyboard menus, live status, AA contrast UI/UX review 2026-12-05, UX-21 to UX-25 and part of UX-26 (M-UXREV UXR.5). - Focus: one :focus-visible rule in the theme (2 px ring in accent_info, offset 2 px) for buttons, selects including the Theme dropdown, inputs, tabs and accordion headers. The old ring was the 1 px browser default, the same look as an open menu title. - New quantui/app_a11y.py: a page script, installed once like the menu bar's Esc handler, that adds what ipywidgets cannot express: menu roles (menubar/menu/menuitem, aria-expanded, aria-disabled), arrow-key, Home, End and Esc navigation in the menus, role=dialog with focus in, a Tab trap and focus return for the setup dialog, a status chip outside the Tab order, and a "Skip to molecule input" link shown on the first Tab press. - A visually hidden role=status live region announces a run starting, finishing or failing; the status footer's refresh feeds it. - Contrast: text_faint/text_subtle in Midnight, Dark Blue, Dark Maroon and Hot Pink now clear 4.5:1; Light accent_success #15803d (Run button text 5.0:1, success text 4.8:1) and text_muted_light #6b6b6b (5.1:1). - Disabled accent buttons use the panel surface, subtle text and a dashed border rather than opacity alone. - tests/test_theme_contrast.py computes text, button-text and focus-ring contrast from the tokens of every palette; tests/test_a11y.py covers the script, skip link and live region. Screen-reader output and real keyboard use still need a human check. 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 | 26 +++ quantui/app.py | 13 ++ quantui/app_a11y.py | 367 +++++++++++++++++++++++++++++++++++ quantui/app_workspace.py | 4 + quantui/theme.py | 100 +++++++++- tests/test_a11y.py | 123 ++++++++++++ tests/test_theme_contrast.py | 118 ++++++++++- 7 files changed, 739 insertions(+), 12 deletions(-) create mode 100644 quantui/app_a11y.py create mode 100644 tests/test_a11y.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a2fec5c..52d18f8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,32 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +### Accessibility + +- **Visible keyboard focus.** One `:focus-visible` rule in the theme draws a + 2 px ring in the palette's accent colour (at least 3:1 on every palette) + around buttons, dropdowns (including the Theme selector), text inputs, tabs + and accordion headers. Mouse clicks do not show it. +- **Keyboard menus.** The menu bar has menu roles (`menubar`, `menu`, + `menuitem`, `aria-expanded`, `aria-disabled`). ArrowDown/ArrowUp open a + menu and move through its items, ArrowLeft/ArrowRight move between menus, + Home/End jump to the ends, Esc closes the menu and returns focus to its + title. +- **Setup dialog** is announced as a modal dialog; focus moves into it, Tab + stays inside it, and focus returns to the opener when it closes. +- **Run status is announced** to screen readers (a polite live region says + when a calculation starts, finishes or fails). +- **Shorter Tab path:** the header status chip is no longer a Tab stop, and a + "Skip to molecule input" link appears on the first Tab press. +- **Contrast (WCAG AA):** secondary text in the Midnight, Dark Blue, Dark + Maroon and Hot Pink palettes now clears 4.5:1 (was 3.5–4.46:1); in Light, + the Run button and success-coloured text use a darker green (5.0:1, was + 3.3:1) and the lightest grey text is darker (5.1:1, was 4.3:1). A test now + computes contrast from the tokens of every palette. +- **Disabled buttons look disabled** on every palette: panel-coloured + surface, subtle text and a dashed border instead of a faded accent colour + (a disabled Run looked clickable on dark palettes). + ## [0.13.2] - 2026-12-05 ### Changed diff --git a/quantui/app.py b/quantui/app.py index 88f2b638..e5ffe55b 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -35,6 +35,10 @@ import quantui.issue_tracker as _issue_tracker from quantui import molecule_library as _ml from quantui import theme as _theme +from quantui.app_a11y import A11Y_CSS as _A11Y_CSS +from quantui.app_a11y import a11y_js as _a11y_js +from quantui.app_a11y import build_live_region as _a11y_build_live_region +from quantui.app_a11y import skip_link_html as _a11y_skip_link_html from quantui.app_analysis import ( activate_ana_panel as _ana_activate_ana_panel, ) @@ -1032,6 +1036,8 @@ class carries a per-app uid suffix. LiveLog also sets the stack inline — this } """ + _theme.slider_chrome_css() + + _theme.focus_ring_css() + + _theme.disabled_button_css() + """ .quantui-completion-banner { padding: 10px 12px; @@ -2372,10 +2378,13 @@ def display(self) -> None: + _WS_CSS + _MB_CSS + _SD_CSS + + _A11Y_CSS ) display(HTML(_theme.theme_injection_html(app_css, style_id="quantui-app-css"))) display(Javascript(_HELP_ESC_JS)) display(Javascript(_mb_menubar_js())) + # After the menu bar's handler: its Esc closes a menu first. + display(Javascript(_a11y_js())) display(Javascript(_PLOT_RESIZE_JS)) # NOTE: 3Dmol.js is loaded offline per-view via py3Dmol's own loader # (``viz_assets.make_view`` passes ``js=``), NOT a @@ -2397,6 +2406,10 @@ def display(self) -> None: display( widgets.VBox( [ + # First Tab stop: jumps past the header and menus. + widgets.HTML(value=_a11y_skip_link_html()), + # Screen-reader announcements (run started / done). + _a11y_build_live_region(self), self._plotly_bootstrap_out, # Title and toolbar share one row; the toolbar wraps # under the title on narrow windows. diff --git a/quantui/app_a11y.py b/quantui/app_a11y.py new file mode 100644 index 00000000..d8f3a083 --- /dev/null +++ b/quantui/app_a11y.py @@ -0,0 +1,367 @@ +"""Keyboard and screen-reader support layered on the ipywidgets UI. + +ipywidgets has no API for ARIA roles, ``aria-*`` attributes or ``tabindex``, +so this module adds them from the page, the same way the menu bar +(``app_menubar.MENUBAR_JS``) and the Help drawer (``app._HELP_ESC_JS``) +already add their Esc handling: one small script, installed once per page, +that finds QuantUI's widgets by their CSS classes. Nothing here changes what +a widget does; every action still goes through the widget's own button. + +What it adds (UI/UX review 2026-12-05, UX-22, UX-23, UX-26): + +- **Menu bar semantics:** ``role="menubar"`` / ``"menu"`` / ``"menuitem"``, + ``aria-haspopup`` and ``aria-expanded`` on the titles, ``aria-disabled`` on + unavailable items. +- **Menu keyboard navigation:** ArrowDown / ArrowUp open a menu and move + through its enabled items, ArrowLeft / ArrowRight move between menus, + Home / End jump to the first / last item, Esc closes the menu (the existing + handler) and puts focus back on its title, Tab closes it. +- **Setup dialog:** ``role="dialog"`` and ``aria-modal``; focus moves into + the dialog when it opens, Tab stays inside it, and focus returns to the + control that opened it when it closes. +- **Run status announcements:** a visually hidden ``role="status"`` live + region (:func:`build_live_region`) that :func:`announce` fills when a run + starts, finishes or fails. +- **Shorter tab path:** the header status chip (a display, not a control) is + taken out of the Tab order, and a "Skip to molecule input" link becomes + visible on the first Tab press (:func:`skip_link_html`). + +Limits: the menus are still ipywidgets Buttons, so the roles are applied +after the widgets render (on load, then after every click or key press). +Screen-reader output needs a check with a real screen reader; it cannot be +verified headless. +""" + +from __future__ import annotations + +import html as _html +import logging +from typing import Any + +import ipywidgets as widgets + +logger = logging.getLogger(__name__) + +LIVE_REGION_CLASS = "quantui-sr-live" +SR_ONLY_CLASS = "quantui-sr-only" +SKIP_LINK_CLASS = "quantui-skip-link" +STATUS_CHIP_CLASS = "quantui-status-chip" + +A11Y_CSS = f""" +/* Accessibility helpers (app_a11y) --------------------------------------- */ +.{SR_ONLY_CLASS} {{ + position: absolute !important; + width: 1px !important; + height: 1px !important; + padding: 0 !important; + margin: -1px !important; + overflow: hidden !important; + clip: rect(0, 0, 0, 0) !important; + white-space: nowrap !important; + border: 0 !important; +}} +a.{SKIP_LINK_CLASS} {{ + position: absolute; + left: -9999px; + top: 0; +}} +a.{SKIP_LINK_CLASS}:focus {{ + left: 8px; + top: 8px; + z-index: 2000; + padding: 6px 12px; + background: var(--q-bg-panel); + color: var(--q-text-strong); + border: 2px solid var(--q-accent-info); + border-radius: 4px; + font-size: 13px; + text-decoration: none; +}} +""" + +# Installed once per page (guarded by a window flag). Class names are +# substituted by a11y_js(). ES5 only, like the other page scripts. +_A11Y_JS = r""" +(function(){ + if (window.__quantuiA11y) { return; } + window.__quantuiA11y = true; + var BAR=".__BAR__", MENU=".__MENU__", TITLE=".__TITLE__", LIST=".__LIST__", + ITEM=".__ITEM__", OPEN="__OPEN__", PANEL=".__PANEL__", BODY=".__BODY__", + BACKDROP=".__BACKDROP__", LIVE=".__LIVE__", CHIP=".__CHIP__"; + var FOCUSABLE="button:not(:disabled), select:not(:disabled), "+ + "input:not(:disabled):not([type=hidden]), textarea:not(:disabled), "+ + "a[href], [tabindex]:not([tabindex='-1'])"; + function shown(el){ return !!el && el.offsetParent !== null; } + function all(sel, root){ + return Array.prototype.slice.call((root||document).querySelectorAll(sel)); + } + function set(el, k, v){ if (el.getAttribute(k) !== v) { el.setAttribute(k, v); } } + + // ── Roles and states ──────────────────────────────────────────────── + function roles(){ + all(BAR).forEach(function(b){ set(b,"role","menubar"); set(b,"aria-label","Main menu"); }); + all(TITLE).forEach(function(t){ + set(t,"role","menuitem"); set(t,"aria-haspopup","menu"); + set(t,"aria-expanded", t.classList.contains(OPEN) ? "true" : "false"); + }); + all(LIST).forEach(function(l){ + set(l,"role","menu"); + var m=l.closest(MENU), t=m && m.querySelector(TITLE); + if (t) { set(l,"aria-label", t.textContent.trim()); } + Array.prototype.forEach.call(l.children, function(c){ + if (!c.matches(ITEM)) { set(c,"role","presentation"); } + }); + }); + all(ITEM).forEach(function(i){ + set(i,"role","menuitem"); + set(i,"tabindex","-1"); + set(i,"aria-disabled", i.disabled ? "true" : "false"); + }); + all(PANEL).forEach(function(p){ + set(p,"role","dialog"); set(p,"aria-modal","true"); + set(p,"aria-label","Calculation setup"); + }); + all(LIVE).forEach(function(r){ + set(r,"role","status"); set(r,"aria-live","polite"); set(r,"aria-atomic","true"); + }); + all(CHIP).forEach(function(c){ set(c,"tabindex","-1"); set(c,"aria-hidden","true"); }); + dialogFocus(); + } + function later(){ [60, 250, 700].forEach(function(ms){ setTimeout(roles, ms); }); } + // Voila renders widgets progressively: keep applying for a while after load. + var boot=0, bootTimer=setInterval(function(){ roles(); if (++boot > 40) { clearInterval(bootTimer); } }, 500); + document.addEventListener("click", later, true); + document.addEventListener("keyup", later, true); + + // ── Setup dialog: focus in, Tab trapped, focus back ────────────────── + var dlgOpen=false, opener=null; + function dialogFocus(){ + var bd=document.querySelector(BACKDROP), open=shown(bd); + if (open && !dlgOpen) { + dlgOpen=true; + if (!opener) { opener=document.activeElement; } + var body=bd.querySelector(BODY), first=body && all(FOCUSABLE, body).filter(shown)[0]; + if (first) { first.focus(); } + } else if (!open && dlgOpen) { + dlgOpen=false; + if (opener && shown(opener) && document.contains(opener)) { opener.focus(); } + opener=null; + } + } + document.addEventListener("focusin", function(e){ + if (!dlgOpen) { opener = e.target; } + }, true); + + // ── Menu keyboard navigation ──────────────────────────────────────── + function titles(){ return all(BAR+" "+TITLE).filter(shown); } + function listOf(t){ var m=t && t.closest(MENU); return m && m.querySelector(LIST); } + function titleOf(el){ var m=el && el.closest(MENU); return m && m.querySelector(TITLE); } + function items(list){ return all(ITEM, list).filter(function(b){ return shown(b) && !b.disabled; }); } + function whenOpen(t, which){ + var l=listOf(t), n=0; + (function go(){ + n++; + if (shown(l)) { + roles(); + var its=items(l); + if (its.length) { (which === "last" ? its[its.length-1] : its[0]).focus(); } + return; + } + if (n < 40) { setTimeout(go, 50); } + })(); + } + function openMenu(t, which){ + if (!shown(listOf(t))) { t.click(); } + whenOpen(t, which); + } + function openTitle(){ return document.querySelector(BAR+" ."+OPEN); } + document.addEventListener("keydown", function(e){ + var t=e.target; + if (!t || !t.closest) { return; } + if (dlgOpen && e.key === "Tab") { + var panel=document.querySelector(PANEL), f=panel ? all(FOCUSABLE, panel).filter(shown) : []; + if (f.length) { + var first=f[0], last=f[f.length-1]; + if (!panel.contains(t)) { e.preventDefault(); first.focus(); } + else if (e.shiftKey && t === first) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && t === last) { e.preventDefault(); first.focus(); } + } + return; + } + var title=t.closest(TITLE), item=t.closest(ITEM); + if (!title && !item) { return; } + var ts=titles(); + if (title) { + var i=ts.indexOf(title); + if (e.key === "ArrowDown") { e.preventDefault(); openMenu(title, "first"); } + else if (e.key === "ArrowUp") { e.preventDefault(); openMenu(title, "last"); } + else if (e.key === "Enter" || e.key === " ") { + // The native click toggles the menu; focus its first item once open. + if (!shown(listOf(title))) { whenOpen(title, "first"); } + } + else if (e.key === "ArrowRight" || e.key === "ArrowLeft") { + e.preventDefault(); + var nxt=ts[(i + (e.key === "ArrowRight" ? 1 : ts.length - 1)) % ts.length]; + var wasOpen=!!openTitle(); + nxt.focus(); + if (wasOpen) { openMenu(nxt, "first"); } + } + else if (e.key === "Home") { e.preventDefault(); ts[0].focus(); } + else if (e.key === "End") { e.preventDefault(); ts[ts.length-1].focus(); } + return; + } + var own=titleOf(item), its=items(listOf(own)), k=its.indexOf(item); + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + if (its.length) { + var step=(e.key === "ArrowDown") ? 1 : its.length - 1; + its[(k + step) % its.length].focus(); + } + } else if (e.key === "Home") { e.preventDefault(); if (its.length) { its[0].focus(); } } + else if (e.key === "End") { e.preventDefault(); if (its.length) { its[its.length-1].focus(); } } + else if (e.key === "ArrowRight" || e.key === "ArrowLeft") { + e.preventDefault(); + var j=ts.indexOf(own); + var other=ts[(j + (e.key === "ArrowRight" ? 1 : ts.length - 1)) % ts.length]; + other.focus(); openMenu(other, "first"); + } else if (e.key === "Escape") { + // MENUBAR_JS (registered first) has already closed the menu. + if (own) { setTimeout(function(){ own.focus(); }, 0); } + } else if (e.key === "Tab") { + var o=openTitle(); if (o) { o.click(); } + } else if (e.key === "Enter" || e.key === " ") { + // The item runs its action and the menu closes; if nothing else took + // focus, give it back to the menu title rather than the page. + setTimeout(function(){ + var a=document.activeElement; + if ((!a || a === document.body || !shown(a)) && own) { own.focus(); } + }, 300); + } + }); + roles(); +})(); +""" + + +def a11y_js() -> str: + """The page-level accessibility script, with QuantUI's class names.""" + from quantui.app_menubar import ( + MENU_CLASS, + MENU_ITEM_CLASS, + MENU_LIST_CLASS, + MENU_OPEN_CLASS, + MENU_TITLE_CLASS, + MENUBAR_CLASS, + ) + from quantui.app_setup_dialog import BACKDROP_CLASS, BODY_CLASS, PANEL_CLASS + + subs = { + "__BAR__": MENUBAR_CLASS, + "__MENU__": MENU_CLASS, + "__TITLE__": MENU_TITLE_CLASS, + "__LIST__": MENU_LIST_CLASS, + "__ITEM__": MENU_ITEM_CLASS, + "__OPEN__": MENU_OPEN_CLASS, + "__PANEL__": PANEL_CLASS, + "__BODY__": BODY_CLASS, + "__BACKDROP__": BACKDROP_CLASS, + "__LIVE__": LIVE_REGION_CLASS, + "__CHIP__": STATUS_CHIP_CLASS, + } + js = _A11Y_JS + # Longest first, so __BAR__ cannot eat part of __BACKDROP__. + for key in sorted(subs, key=len, reverse=True): + js = js.replace(key, subs[key]) + return js + + +# --------------------------------------------------------------------------- +# Skip link +# --------------------------------------------------------------------------- + +# Focus the first control of the molecule input on the Calculate tab, +# selecting that tab first if needed. Single quotes only: it sits in a +# "-quoted onclick attribute (widgets.HTML keeps inline handlers). +_SKIP_JS = ( + "event.preventDefault();" + "function vis(e){return !!e&&e.offsetParent!==null;}" + "function target(){var c=document.querySelector('.quantui-mol-input');" + "if(!vis(c)){return null;}" + "var f=c.querySelectorAll('input:not([type=hidden]),select,textarea,button');" + "for(var i=0;i str: + """A "Skip to molecule input" link, visible only while it has focus.""" + return ( + f'' + "Skip to molecule input" + ) + + +# --------------------------------------------------------------------------- +# Live region +# --------------------------------------------------------------------------- + + +def build_live_region(app: Any) -> Any: + """The visually hidden status region screen readers announce from.""" + region = widgets.HTML(value="") + region.add_class(LIVE_REGION_CLASS) + region.add_class(SR_ONLY_CLASS) + app._a11y_live = region + app._a11y_last_job = None + return region + + +def announce(app: Any, text: str) -> None: + """Put *text* in the live region (screen readers read it out politely).""" + region = getattr(app, "_a11y_live", None) + if not isinstance(region, widgets.HTML): + return + region.value = f"{_html.escape(str(text))}" + + +_JOB_ANNOUNCEMENTS = { + "running": "{label}", + "done": "Calculation finished. Results are ready.", + "failed": "Calculation failed. See the Calculate tab for the reason.", +} + + +def announce_job_state(app: Any, key: str, label: str) -> None: + """Announce a run starting, finishing or failing (once per change).""" + if key == getattr(app, "_a11y_last_job", None): + return + previous = getattr(app, "_a11y_last_job", None) + app._a11y_last_job = key + if previous is None and key == "idle": + return # start-up: nothing happened yet + template = _JOB_ANNOUNCEMENTS.get(key) + if template is None: + return + announce(app, template.format(label=label)) + + +__all__ = [ + "A11Y_CSS", + "LIVE_REGION_CLASS", + "SKIP_LINK_CLASS", + "SR_ONLY_CLASS", + "a11y_js", + "announce", + "announce_job_state", + "build_live_region", + "skip_link_html", +] diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 840f99f8..06fbfcd3 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -900,6 +900,10 @@ def refresh_footer(app: Any) -> None: footer = getattr(app, "_ws_footer", None) if isinstance(footer, widgets.HTML): footer.value = footer_html(app) + # Screen readers hear a run start, finish or fail (app_a11y live region). + from quantui.app_a11y import announce_job_state + + announce_job_state(app, *job_state(app)) def _refresh_atom_list(app: Any) -> None: diff --git a/quantui/theme.py b/quantui/theme.py index 88b0510e..75f590dc 100644 --- a/quantui/theme.py +++ b/quantui/theme.py @@ -30,7 +30,8 @@ TEXT_LABEL = "#444" TEXT_SECONDARY = "#555" TEXT_MUTED = "#666" -TEXT_MUTED_LIGHT = "#777" +# #777 was 4.28:1 on BG_PANEL (UI/UX review 2026-12-05, UX-24). +TEXT_MUTED_LIGHT = "#6b6b6b" # Faint/subtle text clears WCAG AA 4.5:1 on BG_PANEL (audit UI-7; was # #888 at 3.4:1 and #94a3b8 at 2.5:1). TEXT_FAINT = "#707070" @@ -42,7 +43,9 @@ ACCENT_ERROR = "#b91c1c" ACCENT_ERROR_ALT = "#c00" -ACCENT_SUCCESS = "#16a34a" +# #16a34a gave the Run button 3.30:1 (white text) and success text 3.15:1 +# on BG_PANEL; #15803d clears 4.5:1 for both (UX-24). +ACCENT_SUCCESS = "#15803d" ACCENT_SUCCESS_BG = "#f0fff0" ACCENT_SUCCESS_ALT = "#4caf50" ACCENT_WARNING = "#b45309" @@ -217,6 +220,76 @@ def _accent_button_css() -> str: "{ background-color: var(--q-accent-error) !important; " "color: var(--q-page-bg) !important; " "border-color: var(--q-accent-error) !important; }\n" + f"{disabled_button_css()}" + ) + + +_ACCENT_MODS: Tuple[str, ...] = ( + "mod-primary", + "mod-info", + "mod-success", + "mod-warning", + "mod-danger", +) + + +def disabled_button_css() -> str: + """A disabled accent button reads as disabled on every palette. + + Opacity alone was not enough: a 60 % bright green on navy looked like an + ordinary muted green, so a disabled Run looked clickable (UI/UX review + 2026-12-05, UX-25). Disabled accent buttons drop to the panel surface with + subtle text and a dashed border. ``:disabled`` adds a pseudo-class, so + these rules outrank the enabled accent rules above. + """ + sel = ", ".join( + f".jupyter-button.{m}:disabled, button.jupyter-button.{m}:disabled" + for m in _ACCENT_MODS + ) + return ( + f"{sel} " + "{ background-color: var(--q-bg-panel) !important; " + "color: var(--q-text-subtle) !important; " + "border: 1px dashed var(--q-border-strong) !important; " + "opacity: 1 !important; box-shadow: none !important; " + "cursor: not-allowed !important; }\n" + ) + + +# Everything a keyboard user can land on. One rule, so every control shows +# the same ring (UX-21: the old ring was the browser's 1 px default, the same +# look as an open menu title, and the Theme select had none at all). +_FOCUSABLE_SELECTORS: Tuple[str, ...] = ( + ".jupyter-widgets button", + "button.jupyter-button", + ".jupyter-widgets select", + ".jupyter-widgets input", + ".jupyter-widgets textarea", + ".widget-dropdown select", + ".lm-TabBar-tab", + ".p-TabBar-tab", + ".lm-AccordionPanel-title", + ".jupyter-widget-Collapse-header", + ".p-Collapse-header", + "a", + "summary", + "[tabindex]", +) + + +def focus_ring_css() -> str: + """A visible keyboard focus ring (WCAG 2.4.7 / 2.4.11). + + 2 px in the palette's ``accent_info`` (>= 3:1 against both the panel and + page backgrounds on every palette; ``tests/test_theme_contrast.py``), + offset so it sits on the background rather than on the control's own + fill. ``:focus-visible`` keeps mouse clicks free of the ring. + """ + sel = ", ".join(f"{s}:focus-visible" for s in _FOCUSABLE_SELECTORS) + return ( + f"{sel} " + "{ outline: 2px solid var(--q-accent-info) !important; " + "outline-offset: 2px !important; }\n" ) @@ -378,6 +451,7 @@ def _widget_chrome_css() -> str: "border-color: var(--q-border) !important; }\n" f"{_neutral_button_css()}" f"{_accent_button_css()}" + f"{focus_ring_css()}" f"{slider_chrome_css()}" ".quantui-info-box " f"{{ background: {surface} !important; " @@ -488,8 +562,9 @@ def _midnight_palette() -> ThemePalette: text_secondary="#cbd5e1", text_muted="#94a3b8", text_muted_light="#94a3b8", - text_faint="#64748b", - text_subtle="#64748b", + # >= 4.5:1 on black (#64748b was 4.41:1; UX-24). + text_faint="#7c8aa0", + text_subtle="#7c8aa0", text_body="#e2e8f0", text_strong="#f1f5f9", text_slate="#94a3b8", @@ -529,8 +604,9 @@ def _dark_blue_palette() -> ThemePalette: text_secondary="#a8c4e8", text_muted="#8fb0d9", text_muted_light="#7a9fcc", - text_faint="#6b8fbf", - text_subtle="#6b8fbf", + # >= 4.5:1 on bg_panel (#6b8fbf was 4.46:1; UX-24). + text_faint="#7a9fcc", + text_subtle="#7a9fcc", text_body="#d6e6ff", text_strong="#f0f6ff", text_slate="#8fb0d9", @@ -570,8 +646,9 @@ def _hot_pink_palette() -> ThemePalette: text_secondary="#f9a8d4", text_muted="#f472b6", text_muted_light="#ec4899", - text_faint="#db2777", - text_subtle="#db2777", + # >= 4.5:1 on bg_panel (#db2777 was 3.47:1; UX-24). + text_faint="#e879b0", + text_subtle="#e879b0", text_body="#fce7f3", text_strong="#fff5f8", text_slate="#f472b6", @@ -611,8 +688,9 @@ def _dark_maroon_palette() -> ThemePalette: text_secondary="#d4a8b8", text_muted="#b88898", text_muted_light="#a87888", - text_faint="#986878", - text_subtle="#986878", + # >= 4.5:1 on bg_panel (#986878 was 3.78:1; UX-24). + text_faint="#b0899a", + text_subtle="#b0899a", text_body="#f0d8e0", text_strong="#fff5f8", text_slate="#b88898", @@ -798,6 +876,8 @@ def frame_viewer_html(view_html: str, *, width: int, controls: str = "") -> str: "TEXT_SUBTLE", "ThemePalette", "css", + "disabled_button_css", + "focus_ring_css", "frame_viewer_html", "get_palette", "plotly_colors", diff --git a/tests/test_a11y.py b/tests/test_a11y.py new file mode 100644 index 00000000..de1e70b3 --- /dev/null +++ b/tests/test_a11y.py @@ -0,0 +1,123 @@ +"""Keyboard and screen-reader layer (app_a11y; UI/UX review 2026-12-05). + +The script itself runs in the browser and is checked by hand (screen reader, +keyboard) — these tests pin what the Python side provides: the class names +are filled in, every behaviour the review asked for is present, and the live +region announces run state once per change. +""" + +from __future__ import annotations + +import ipywidgets as widgets +import pytest + +from quantui import app_a11y + + +class TestScript: + def test_class_names_are_filled_in(self): + js = app_a11y.a11y_js() + assert "__" + "BAR__" not in js + assert "__BACKDROP__" not in js + from quantui.app_menubar import MENU_ITEM_CLASS, MENUBAR_CLASS + + assert f".{MENUBAR_CLASS}" in js + assert f".{MENU_ITEM_CLASS}" in js + + @pytest.mark.parametrize( + "needle", + [ + '"role","menubar"', + '"role","menu"', + '"role","menuitem"', + '"aria-expanded"', + '"aria-haspopup"', + '"aria-disabled"', + '"role","dialog"', + '"aria-modal"', + '"aria-live","polite"', + '"role","status"', + "ArrowDown", + "ArrowUp", + "ArrowLeft", + "ArrowRight", + '"Home"', + '"End"', + "Escape", + ], + ) + def test_behaviour_present(self, needle): + assert needle in app_a11y.a11y_js() + + def test_installed_once_per_page(self): + assert "window.__quantuiA11y" in app_a11y.a11y_js() + + def test_status_chip_leaves_the_tab_order(self): + js = app_a11y.a11y_js() + assert ".quantui-status-chip" in js + assert '"tabindex","-1"' in js + + +class TestSkipLink: + def test_skip_link_targets_molecule_input(self): + html = app_a11y.skip_link_html() + assert 'class="quantui-skip-link"' in html + assert ".quantui-mol-input" in html + assert "Skip to molecule input" in html + + def test_handler_has_no_double_quotes(self): + # It sits inside a "-quoted onclick attribute. + assert '"' not in app_a11y._SKIP_JS + + def test_hidden_until_focused(self): + css = app_a11y.A11Y_CSS + assert "a.quantui-skip-link {" in css + assert "a.quantui-skip-link:focus {" in css + assert "left: -9999px" in css + + +class _App: + pass + + +class TestLiveRegion: + def test_region_is_hidden_html(self): + app = _App() + region = app_a11y.build_live_region(app) + assert isinstance(region, widgets.HTML) + assert app_a11y.LIVE_REGION_CLASS in region._dom_classes + assert app_a11y.SR_ONLY_CLASS in region._dom_classes + + def test_announces_each_change_once(self): + app = _App() + region = app_a11y.build_live_region(app) + app_a11y.announce_job_state(app, "idle", "Idle") + assert region.value == "" # start-up: nothing to say + app_a11y.announce_job_state(app, "running", "Running Frequency…") + assert "Running Frequency" in region.value + region.value = "sentinel" + app_a11y.announce_job_state(app, "running", "Running Frequency…") + assert region.value == "sentinel" # same state: no repeat + app_a11y.announce_job_state(app, "done", "Done") + assert "finished" in region.value + app_a11y.announce_job_state(app, "failed", "Failed") + assert "failed" in region.value + + def test_announce_escapes(self): + app = _App() + region = app_a11y.build_live_region(app) + app_a11y.announce(app, "x") + assert "" not in region.value + + def test_announce_without_region_is_a_no_op(self): + app_a11y.announce(_App(), "nothing to do") + + +def test_footer_refresh_feeds_the_live_region(): + from quantui import app_workspace + + app = _App() + region = app_a11y.build_live_region(app) + app._calc_running = True + app_workspace.refresh_footer(app) + assert "Running" in region.value diff --git a/tests/test_theme_contrast.py b/tests/test_theme_contrast.py index dc8e56d2..f8576d3e 100644 --- a/tests/test_theme_contrast.py +++ b/tests/test_theme_contrast.py @@ -25,6 +25,8 @@ def _hex_rgb(h: str) -> tuple[int, int, int]: h = h.lstrip("#") + if len(h) == 3: # CSS shorthand (#444) + h = "".join(c * 2 for c in h) return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value] @@ -373,9 +375,14 @@ def test_light_only_text_colours_are_gone_from_audited_chrome(self): class TestFaintTextMeetsAA: - """text_faint / text_subtle are text, so WCAG AA 4.5:1 (audit UI-7).""" + """text_faint / text_subtle are text, so WCAG AA 4.5:1 (audit UI-7). - @pytest.mark.parametrize("palette_id", ["Light", "Dark"]) + Every palette, not only Light and Dark: the UI/UX review (2026-12-05, + UX-24) measured Hot Pink 3.47, Dark Maroon 3.78, Midnight 4.41 and Dark + Blue 4.46 here. + """ + + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) @pytest.mark.parametrize("token", ["text_faint", "text_subtle"]) def test_faint_tokens_clear_4_5_on_panel(self, palette_id, token): p = theme.get_palette(palette_id) @@ -383,6 +390,113 @@ def test_faint_tokens_clear_4_5_on_panel(self, palette_id, token): assert ratio >= 4.5, f"{palette_id}.{token} {ratio:.2f}:1" +# Tokens used as text. Every one must clear WCAG AA (4.5:1) on both +# backgrounds text sits on, in every palette (UX-24). The *_alt / *_light +# accents, purple and teal are fills and chart colours, not text. +TEXT_TOKENS = ( + "text_heading", + "text_label", + "text_secondary", + "text_muted", + "text_muted_light", + "text_faint", + "text_subtle", + "text_body", + "text_strong", + "text_slate", + "text_slate_dark", + "accent_error", + "accent_success", + "accent_warning", + "accent_info", +) +# Accent buttons draw page_bg-coloured text on the accent fill (theme. +# _accent_button_css). +BUTTON_FILLS = ("accent_info", "accent_success", "accent_warning", "accent_error") +TEXT_AA = 4.5 + + +def _ratio(fg: str, bg: str) -> float: + return _contrast(_hex_rgb(fg), _hex_rgb(bg)) + + +class TestEveryPaletteMeetsAA: + """Contrast computed from the palette tokens, for every palette. + + Adding a palette (or changing a token) that fails here is a regression + of the 2026-12-05 contrast fixes. + """ + + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + @pytest.mark.parametrize("token", TEXT_TOKENS) + def test_text_token_on_panel_and_page(self, palette_id, token): + p = theme.get_palette(palette_id) + for bg_name in ("bg_panel", "page_bg"): + ratio = _ratio(getattr(p, token), getattr(p, bg_name)) + assert ( + ratio >= TEXT_AA + ), f"{palette_id}: {token} on {bg_name} is {ratio:.2f}:1" + + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + @pytest.mark.parametrize("fill", BUTTON_FILLS) + def test_accent_button_text(self, palette_id, fill): + p = theme.get_palette(palette_id) + ratio = _ratio(p.page_bg, getattr(p, fill)) + assert ratio >= TEXT_AA, f"{palette_id}: button text on {fill} {ratio:.2f}:1" + + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + def test_focus_ring_is_visible_on_both_backgrounds(self, palette_id): + # The focus ring is drawn in accent_info (theme.focus_ring_css): + # a UI component, so 3:1 (WCAG 1.4.11 / 2.4.11). + p = theme.get_palette(palette_id) + for bg_name in ("bg_panel", "page_bg"): + ratio = _ratio(p.accent_info, getattr(p, bg_name)) + assert ratio >= UI_COMPONENT_MIN, f"{palette_id} on {bg_name}" + + def test_light_run_button_was_the_failing_case(self): + # Documents UX-24: the old Light success green failed 4.5:1. + assert _ratio("#ffffff", "#16a34a") < TEXT_AA + assert _ratio(theme.PAGE_BG, theme.ACCENT_SUCCESS) >= TEXT_AA + + +class TestFocusAndDisabledChrome: + def test_theme_block_has_one_focus_visible_rule(self): + css = theme.focus_ring_css() + assert css in theme._widget_chrome_css() + assert "focus-visible" in theme.theme_css_block("Dark") + assert css.count("{") == 1, "one rule, not one per control" + assert "outline: 2px solid var(--q-accent-info)" in css + assert "outline-offset: 2px" in css + for sel in ( + "button.jupyter-button:focus-visible", + ".jupyter-widgets select:focus-visible", + ".widget-dropdown select:focus-visible", + ".jupyter-widgets input:focus-visible", + ".lm-TabBar-tab:focus-visible", + ): + assert sel in css, sel + + def test_app_css_carries_the_focus_ring_too(self): + from quantui.app import _APP_CSS + + assert theme.focus_ring_css() in _APP_CSS + assert theme.disabled_button_css() in _APP_CSS + + def test_disabled_accent_buttons_are_restyled_not_just_faded(self): + css = theme.disabled_button_css() + for mod in ("mod-primary", "mod-info", "mod-success", "mod-warning"): + assert f".jupyter-button.{mod}:disabled" in css + assert "background-color: var(--q-bg-panel)" in css + assert "color: var(--q-text-subtle)" in css + assert "dashed" in css + assert "cursor: not-allowed" in css + # Comes after the enabled accent rules in the theme block. + block = theme.theme_css_block("Dark") + assert block.index(".jupyter-button.mod-success:disabled") > block.index( + ".jupyter-button.mod-success, button.jupyter-button.mod-success" + ) + + class TestNoRawHexReintroducedInMigratedChrome: """M-THEME Execution Sequence step 1: migrated chrome must keep using tokens.""" From 7afa2a5c903a9042bcc13d4faeb239e79065e1c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:00:04 +0000 Subject: [PATCH 02/12] Workspace: panels drive the pane viewer; calmer Analysis and narrow layout UI/UX review 2026-12-05, UX-7 to UX-14 (M-UXREV UXR.4; DEC-035 item 6). - New quantui/app_pane_views.py. With the workspace on, the Populations, Vibrational and Isosurface viewers are moved (not copied) into the pane when used: opening the panel, the Results-menu jump, "Show in viewer", choosing a mode or pressing Generate. A banner names what the pane shows and has "Back to structure". Collapsing the panel, a new result, or a Calculate-tab pick mode gives the pane back to the structure. The panel keeps a one-line note in the viewer's place (DEC-009). Moving a viewer re-creates it, so a claim re-applies the mode, charge overlay or surface appearance from the panel's controls. - Opt-in side-by-side for orbitals: "Keep the surface here" leaves the isosurface in its panel next to the plain structure in the pane. - The Results tab's own viewer is hidden (and not rendered) with the workspace on; turning the workspace off brings it back with the shown result. Workspace off keeps every panel's own viewer (the fallback). - Analysis expands only the primary panel (UX-8): 1,990 px instead of 6,600 px after a water Frequency run at 1400 px. - Pane empty state before a molecule: one line and a Load molecule button; toolbar, measurement and atom list appear with a structure (UX-10). The viewer Output itself is never hidden. - Narrow (< 1100 px): the pane body scrolls inside a viewer-sized box and the tab bar scrolls sideways with full labels (tabs at y 310 instead of 540 at 800 px on first launch). The tabs now come before the pane in the DOM (keyboard order); CSS still draws the pane on the left (UX-9, UX-26). - Lighting moves into the pane toolbar with the workspace on (UX-11). - Setup dialog: "Open in dialog" sits in the Calculation Setup heading row, no negative margin; that heading is hidden inside the dialog; one-line footer note (UX-12, UX-13). - viz_assets.fit_zoom: extra zoom after zoomTo() when the molecule is smaller than 3Dmol's 5 A minimum framing radius (at most 3x), for the structure, trajectory, pre-opt, reorganization and vibration viewers (UX-14). Tests updated where the approved behaviour changed (one panel expanded, the Results viewer only without the workspace, DOM order); new tests/test_app_pane_views.py. Checked in Voila with headless Chromium (software WebGL); real-GPU rendering and the vibration animation in the pane need a human look. 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 | 7 +- CHANGELOG.md | 27 ++ quantui/app_analysis.py | 37 +- quantui/app_menubar.py | 5 + quantui/app_pane_views.py | 517 +++++++++++++++++++++++++ quantui/app_setup_dialog.py | 53 ++- quantui/app_visualization.py | 19 +- quantui/app_workspace.py | 190 ++++++++- quantui/visualization_py3dmol.py | 4 +- quantui/viz_assets.py | 44 +++ tests/test_app.py | 21 +- tests/test_app_pane_views.py | 395 +++++++++++++++++++ tests/test_app_workspace.py | 4 +- tests/test_export2_molecule_png.py | 5 + tests/test_geo_opt_analysis_history.py | 7 +- tests/test_uipolish.py | 6 + 16 files changed, 1297 insertions(+), 44 deletions(-) create mode 100644 quantui/app_pane_views.py create mode 100644 tests/test_app_pane_views.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 3c466995..fb123b0c 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -39,6 +39,8 @@ QuantUI/ │ ├── app_launcher.py ← `quantui run app` / `quantui view` Voilà launch │ ├── app_viewer.py ← read-only viewer mode (History + Analysis only) │ ├── app_workspace.py ← two-pane workspace: persistent viewer pane, view toolbar, atom list, status footer +│ ├── app_pane_views.py ← Populations / Vibrational / Isosurface panels show their 3D view in the pane (one viewer) +│ ├── app_a11y.py ← page script for menu ARIA roles + arrow keys, dialog focus, live status region, skip link │ ├── app_menubar.py ← menu bar (File / Calculate / View / Results / Help); items call existing handlers │ ├── app_setup_dialog.py ← modal dialog that moves calc_setup_panel in and back out │ ├── app_slurm.py ← Cluster Jobs tab + SLURM result ingestion @@ -411,7 +413,8 @@ bail out instead of overwriting newer output. All 12 panels are **always in the DOM** (`layout.display=""`, `selected_index=None`). Unavailable panels show a "Not available — run a X calculation first" placeholder. -`_activate_ana_panel()` swaps the placeholder for real content and expands the accordion. +`_activate_ana_panel()` swaps the placeholder for real content; only the primary +(first auto-selected) panel is expanded, the rest stay collapsed (UX-8). `_deactivate_all_ana_panels()` restores placeholders and collapses — never hides. Source of truth: `_PANEL_META` / `_PANEL_REGISTRY` in `app.py`. @@ -603,7 +606,7 @@ __init__() | `self.method_dd` | `widgets.Dropdown` | Selected QC method | | `self.basis_dd` | `widgets.Dropdown` | Selected basis set | | `self.calc_type_dd` | `widgets.Dropdown` | Calc type selector | -| `self.result_viz_output` | `widgets.Output` | 3D molecule rendered after every calc | +| `self.result_viz_output` | `widgets.Output` | Results-tab 3D molecule; only with the workspace off (the pane is the one viewer otherwise) | | `self._last_result_dir` | `Optional[Path]` | Saved result directory from most recent run | --- diff --git a/CHANGELOG.md b/CHANGELOG.md index 52d18f8e..15438e8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,33 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +### Changed + +- **One 3D viewer with the workspace.** The Populations, Vibrational and + Isosurface panels show their 3D view in the workspace pane instead of a + viewer of their own: opening the panel, choosing a mode or generating a + surface puts it in the pane, with a "Showing … — Back to structure" banner. + The Results tab no longer repeats the pane's viewer. For orbitals, "Keep + the surface here" shows the surface in its panel next to the plain + structure in the pane. With the workspace turned off, every panel keeps its + own viewer as before. +- **Analysis opens one panel.** Only the main panel for the result is + expanded; the others stay collapsed with their titles visible (a Frequency + result was a 6,600 px page). +- **Workspace pane before a molecule** shows "Load a molecule to see it here" + and a Load molecule button instead of an empty toolbar, measurement panel + and atom list. +- **Narrow windows (< 1100 px):** the stacked pane shows the viewer and + scrolls the rest inside itself, so the tabs start much higher; tab labels + are no longer clipped (the tab bar scrolls sideways). +- **Lighting** moved into the pane's view toolbar, next to the viewer it + changes. +- **Setup dialog:** "Open in dialog" sits in the Calculation Setup heading + (it was clipped and floating), the heading is not repeated inside the + dialog, and the footer note is one line. +- **Small molecules fill the viewer** when they open (water was a dot in the + middle of the viewer). + ### Accessibility - **Visible keyboard focus.** One `:focus-visible` rule in the theme draws a diff --git a/quantui/app_analysis.py b/quantui/app_analysis.py index 6ac0e534..a0334fe2 100644 --- a/quantui/app_analysis.py +++ b/quantui/app_analysis.py @@ -181,25 +181,30 @@ def build_ana_switcher(app: Any, *, layout_fn: Any) -> None: def select_ana_panel(app: Any, name: str) -> None: """Mark the primary analysis panel for this result (scroll target). - Does not collapse other panels — every panel with data stays expanded - so students can see trajectory, energies, etc. at once. + Does not collapse other panels: one the student opened stays open. """ app._ana_active = name app._ana_unavail_html.layout.display = "none" def activate_ana_panel(app: Any, name: str, auto_select: bool = True) -> None: - """Mark a panel as available, reveal its content, and expand it.""" + """Mark a panel as available and reveal its content. + + Only the primary panel (*auto_select*) is expanded; the other panels with + data stay collapsed with their titles visible (DEC-009: always in the + DOM, content swapped). Expanding every panel made a Frequency result a + 6,600 px page (UI/UX review 2026-12-05, UX-8). + """ app._ana_available.add(name) _set_panel_title_hint(app, name, "") if name in app._ana_unavail_msgs: app._ana_unavail_msgs[name].layout.display = "none" app._ana_content_boxes[name].layout.display = "" - for panel_name, acc in zip(app._ana_panel_names, app._ana_accordions): - if panel_name == name: - acc.selected_index = 0 - break if auto_select: + for panel_name, acc in zip(app._ana_panel_names, app._ana_accordions): + if panel_name == name: + acc.selected_index = 0 + break app._select_ana_panel(name) @@ -252,7 +257,23 @@ def deactivate_all_ana_panels(app: Any) -> None: def apply_analysis_context(app: Any, ctx: Any) -> None: - """Populate Analysis panels from context and activate panels with data.""" + """Populate Analysis panels from context and activate panels with data. + + The workspace pane shows the new result's structure; opening the primary + panel here does not move a panel viewer into the pane (only a student's + own action does, ``app_pane_views``). + """ + from quantui.app_pane_views import reset_for_new_result + + reset_for_new_result(app) + app._pv_suppress = True + try: + _apply_analysis_context(app, ctx) + finally: + app._pv_suppress = False + + +def _apply_analysis_context(app: Any, ctx: Any) -> None: app._deactivate_all_ana_panels() # The level of theory of the result now on display (live run or History), # for export provenance; the setup dropdowns may describe a different one. diff --git a/quantui/app_menubar.py b/quantui/app_menubar.py index 17d71e7f..f822cc09 100644 --- a/quantui/app_menubar.py +++ b/quantui/app_menubar.py @@ -126,6 +126,11 @@ background: var(--q-surface-muted-bg) !important; color: var(--q-text-strong) !important; }} +/* The theme's focus ring, drawn inside the item so the list does not + clip it (theme.focus_ring_css). */ +button.jupyter-button.{MENU_ITEM_CLASS}:focus-visible {{ + outline-offset: -2px !important; +}} button.jupyter-button.{MENU_ITEM_CLASS}{_NEUTRAL}:disabled {{ color: var(--q-text-subtle) !important; opacity: 0.6 !important; diff --git a/quantui/app_pane_views.py b/quantui/app_pane_views.py new file mode 100644 index 00000000..339c625e --- /dev/null +++ b/quantui/app_pane_views.py @@ -0,0 +1,517 @@ +"""Analysis panels drive the workspace pane's viewer (one viewer, DEC-035). + +With the two-pane workspace on (``app_workspace``), the Populations, +Vibrational and Isosurface panels no longer draw a 3D viewer of their own +next to the pane's copy of the same molecule (UI/UX review 2026-12-05, +UX-7). Their viewer is *moved* into the pane while it is in use, the way the +workspace moves the Analysis viewer and the setup dialog moves Calculation +Setup: one widget, one state, no copy. + +- **Claiming the pane.** Opening one of these panels (its header, the + Results menu, or the panel's "Show in viewer" button), choosing another + vibrational mode, or generating a surface puts that panel's viewer in the + pane in place of the structure viewer. A banner at the top of the pane + names what it shows and has a **Back to structure** button. +- **In the panel** the viewer's place holds a one-line note (DEC-009: the + panel stays visible; only its content changes): what is shown in the pane, + or a "Show in viewer" button when the pane shows something else. +- **Back to the structure** when the student presses the button, collapses + the panel, a new result arrives, or a Calculate-tab pick mode needs the + structure (``app_pick_mode``). +- **Side by side (orbitals, opt-in).** The Isosurface panel has a "Keep the + surface here" checkbox: the surface then stays in the panel and the pane + keeps the plain structure, e.g. HOMO next to the molecule. The orbital + gallery is another opt-in side-by-side view and is untouched. + +Moving a viewer re-creates it in the browser, which drops client-side state +(the mode the single vibration viewer switched to, live isosurface +appearance tweaks, the charge overlay). Each claim therefore refreshes the +moved viewer from the panel's controls (:func:`_refresh`). + +With the workspace off nothing here applies: every panel keeps its own +viewer, as before (the fallback). +""" + +from __future__ import annotations + +import html as _html +import logging +from typing import Any, Dict, Optional, Tuple + +import ipywidgets as widgets + +from quantui import theme as _theme +from quantui.app_pick_mode import BANNER_CLASS + +logger = logging.getLogger(__name__) + +PANE_VIEW_BANNER_CLASS = "quantui-ws-viewbar" + +# Panel name → (viewer Output attribute, banner label, note in the panel). +PANE_VIEWS: Dict[str, Tuple[str, str, str]] = { + "Vibrational": ( + "vib_output", + "Vibration", + "The selected mode animates in the viewer pane.", + ), + "Populations": ( + "_mulliken_mol_output", + "Charges", + "Atoms coloured by charge (and the dipole) show in the viewer pane.", + ), + "Isosurface": ( + "_orb_iso_output", + "Surface", + "Generated surfaces show in the viewer pane.", + ), +} + +ISOSURFACE = "Isosurface" + + +# --------------------------------------------------------------------------- +# State +# --------------------------------------------------------------------------- + + +def holder(app: Any) -> str: + """The panel whose viewer is in the pane ("" = the structure).""" + return str(getattr(app, "_pv_holder", "") or "") + + +def side_by_side(app: Any) -> bool: + """True when the student keeps the isosurface in its panel.""" + cb = getattr(app, "_iso_side_cb", None) + return bool(isinstance(cb, widgets.Checkbox) and cb.value) + + +def _ws_on(app: Any) -> bool: + return bool(getattr(app, "_ws_enabled", False)) + + +def _accordion(app: Any, name: str) -> Any: + names = list(getattr(app, "_ana_panel_names", []) or []) + accs = list(getattr(app, "_ana_accordions", []) or []) + return accs[names.index(name)] if name in names else None + + +def _viewer(app: Any, name: str) -> Any: + attr = PANE_VIEWS[name][0] + return getattr(app, attr, None) + + +def _pane_hosts(app: Any, name: str) -> bool: + """Whether *name*'s viewer belongs in the pane rather than its panel.""" + return _ws_on(app) and not (name == ISOSURFACE and side_by_side(app)) + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +def build_pane_views(app: Any, *, layout_fn: Any) -> None: + """Banner, per-panel notes, the orbital side-by-side checkbox, wiring. + + Called by ``app_workspace.build_workspace`` (the panels exist by then). + """ + safe = getattr(app, "_safe_cb", lambda f: f) + app._pv_holder = "" + app._pv_slots = {} + app._pv_suppress = False + app._pv_iso_has_surface = False + + app._pv_banner_text = widgets.HTML(value="") + app._pv_back_btn = widgets.Button( + description="Back to structure", + icon="undo", + tooltip="Show the plain structure in the viewer again (measuring, atom picks)", + layout=layout_fn(width="150px", height="28px"), + ) + app._pv_banner = widgets.HBox( + [app._pv_banner_text, app._pv_back_btn], + layout=layout_fn( + display="none", + align_items="center", + justify_content="space-between", + gap="6px", + flex_wrap="wrap", + ), + ) + app._pv_banner.add_class(BANNER_CLASS) + app._pv_banner.add_class(PANE_VIEW_BANNER_CLASS) + app._pv_back_btn.on_click(lambda _b: show_structure(app)) + + app._pv_notes = {} + app._pv_note_btns = {} + for name in PANE_VIEWS: + text = widgets.HTML(value="") + btn = widgets.Button( + description="Show in viewer", + icon="cube", + tooltip="Show this in the viewer pane", + layout=layout_fn(width="150px", height="28px"), + ) + btn.on_click(lambda _b, n=name: claim(app, n)) + note = widgets.VBox( + [text, btn], + layout=layout_fn( + gap="6px", + padding="10px 12px", + margin="0 0 8px", + border=f"1px dashed {_theme.css.BORDER}", + ), + ) + app._pv_notes[name] = (note, text, btn) + acc = _accordion(app, name) + if acc is not None: + acc.observe( + safe(lambda ch, n=name: _on_accordion(app, n, ch)), + names="selected_index", + ) + + # Opt-in side-by-side view for orbitals: next to the generate controls. + app._iso_side_cb = widgets.Checkbox( + value=False, + description="Keep the surface here (side by side with the structure)", + indent=False, + tooltip=( + "Show the surface in this panel and keep the plain structure in " + "the viewer pane, e.g. HOMO next to the molecule" + ), + layout=layout_fn(width="auto", margin="4px 0"), + ) + controls = getattr(app, "_orb_iso_controls", None) + if isinstance(controls, widgets.Box): + controls.children = tuple(controls.children) + (app._iso_side_cb,) + app._iso_side_cb.observe(safe(lambda ch: on_side_by_side(app, ch)), names="value") + + dd = getattr(app, "vib_mode_dd", None) + if isinstance(dd, widgets.Widget): + # Choosing a mode means "show me this mode": into the pane. + dd.observe(safe(lambda _ch: _on_vib_mode(app)), names="value") + + +# --------------------------------------------------------------------------- +# Moving viewers +# --------------------------------------------------------------------------- + + +def _find_parent(root: Any, child: Any) -> Optional[Tuple[Any, int]]: + from quantui.app_setup_dialog import _find_parent as find + + return find(root, child) + + +def _park(app: Any, name: str) -> None: + """Take *name*'s viewer out of its panel; its note takes the place.""" + if name in app._pv_slots: + return + acc, out = _accordion(app, name), _viewer(app, name) + hit = _find_parent(acc, out) + if hit is None: + return + box, idx = hit + kids = list(box.children) + kids[idx] = app._pv_notes[name][0] + box.children = tuple(kids) + app._pv_slots[name] = (box, idx) + + +def _unpark(app: Any, name: str) -> None: + """Put *name*'s viewer back in its panel (workspace off / side by side).""" + if holder(app) == name: + _leave_pane(app) + if name not in app._pv_slots: + return + note, out = app._pv_notes[name][0], _viewer(app, name) + box, idx = app._pv_slots.pop(name) + kids = list(box.children) + if not (idx < len(kids) and kids[idx] is note): + hit = _find_parent(_accordion(app, name), note) + if hit is None: + logger.warning("pane views: note for %s not found", name) + return + box, idx = hit + kids = list(box.children) + kids[idx] = out + box.children = tuple(kids) + + +def _body(app: Any) -> Any: + return getattr(app, "_ws_body", None) + + +def _set_pane_view(app: Any, view: Any) -> None: + """Put *view* in the pane body's viewer slot (first child).""" + body = _body(app) + if body is None: + return + kids = list(body.children) + if kids: + kids[0] = view + else: + kids = [view] + body.children = tuple(kids) + + +def _leave_pane(app: Any) -> None: + """The structure viewer back in the pane (no re-render).""" + _set_pane_view(app, app._ana_viewer_row) + app._pv_holder = "" + + +def claim(app: Any, name: str, *, refresh: bool = True) -> bool: + """Show *name*'s viewer in the pane. False when it stays where it is.""" + if name not in PANE_VIEWS or not _pane_hosts(app, name): + return False + from quantui.app_pick_mode import pick_mode_active + + if pick_mode_active(app): + return False # a Calculate tool is picking on the structure + if name not in getattr(app, "_ana_available", set()): + return False + if holder(app) == name: + return True + _park(app, name) + out = _viewer(app, name) + if isinstance(out, widgets.Widget): + out.layout.max_width = "100%" + _set_pane_view(app, out) + app._pv_holder = name + _sync(app) + if refresh: + _refresh(app, name) + _log("pane_view_claimed", name) + return True + + +def show_structure(app: Any, *, rerender: bool = True) -> None: + """Back to the plain structure in the pane (if a panel holds it).""" + name = holder(app) + if not name: + return + _leave_pane(app) + _sync(app) + if rerender and getattr(app, "_analysis_displayed_molecule", None) is not None: + # The structure viewer was re-created by the move: redraw it with + # the current picks (measurement highlights) and view settings. + from quantui.app_workspace import render_viewer + + render_viewer(app, keep_picks=True) + _log("pane_view_released", name) + + +def apply_pane_views_layout(app: Any, enabled: bool) -> None: + """Workspace on: panel viewers live in the pane; off: back home.""" + if not hasattr(app, "_pv_notes"): + return + if enabled: + for name in PANE_VIEWS: + if _pane_hosts(app, name): + _park(app, name) + else: + show_structure(app, rerender=False) + for name in PANE_VIEWS: + _unpark(app, name) + _sync(app) + + +def reset_for_new_result(app: Any) -> None: + """A new result (live or History): the pane shows its structure.""" + if not hasattr(app, "_pv_notes"): + return + app._pv_iso_has_surface = False + show_structure(app, rerender=False) + + +# --------------------------------------------------------------------------- +# Triggers +# --------------------------------------------------------------------------- + + +def _on_accordion(app: Any, name: str, change: Dict[str, Any]) -> None: + if getattr(app, "_pv_suppress", False) or not _ws_on(app): + return + if change.get("new") == 0: + if name == ISOSURFACE and not getattr(app, "_pv_iso_has_surface", False): + return # nothing but the molecule until Generate + claim(app, name) + elif holder(app) == name: + show_structure(app) + + +def _on_vib_mode(app: Any) -> None: + if getattr(app, "_pv_suppress", False): + return + if holder(app) != "Vibrational": + claim(app, "Vibrational") + + +def claim_for_surface(app: Any, label: str = "") -> None: + """Generate was pressed: the new surface goes to the pane. + + Claimed before the surface lands, so nothing needs re-applying. + """ + if not hasattr(app, "_pv_notes"): + return + app._pv_iso_has_surface = True + app._pv_iso_label = str(label or "") + claim(app, ISOSURFACE, refresh=False) + + +def on_side_by_side(app: Any, change: Dict[str, Any]) -> None: + """Isosurface "Keep the surface here": in the panel, or the pane's.""" + if not _ws_on(app): + return + if bool(change.get("new")): + if holder(app) == ISOSURFACE: + show_structure(app) + _unpark(app, ISOSURFACE) + _refresh(app, ISOSURFACE) + else: + _park(app, ISOSURFACE) + acc = _accordion(app, ISOSURFACE) + if ( + acc is not None + and acc.selected_index == 0 + and getattr(app, "_pv_iso_has_surface", False) + ): + claim(app, ISOSURFACE) + _sync(app) + + +# --------------------------------------------------------------------------- +# Refresh after a move +# --------------------------------------------------------------------------- + + +def _refresh(app: Any, name: str) -> None: + """Re-apply client-side state the move dropped (see module docstring).""" + try: + if name == "Vibrational": + _refresh_vib(app) + elif name == "Populations": + if getattr(app, "_last_mulliken_charges", None): + app._show_mulliken_viewer() + elif name == ISOSURFACE: + _push_iso_appearance(app) + except Exception as exc: # noqa: BLE001 — a refresh must never break a click + logger.debug("pane view refresh failed for %s: %s", name, exc) + + +def _refresh_vib(app: Any) -> None: + if not getattr(app, "_vib_single_viewer_active", False): + return # legacy path: the HTML already is the selected mode + from quantui.app_visualization import _render_vib_single_viewer + + freq = getattr(app, "_last_vib_freq_result", None) + mol = getattr(app, "_last_vib_molecule", None) + dd = getattr(app, "vib_mode_dd", None) + if freq is None or mol is None or dd is None or dd.value is None: + return + modes = [m for _label, m in dd.options] + _render_vib_single_viewer(app, freq, mol, int(dd.value), modes) + + +def _push_iso_appearance(app: Any) -> None: + """Isovalue/opacity/colours again, once the moved viewer exists.""" + bridge = getattr(app, "_iso_js_bridge", None) + if bridge is None: + return + from IPython.display import Javascript, display + + from quantui.app_visualization import iso_render_options + from quantui.orbital_visualization import orbital_colors + from quantui.viz_assets import script_json + + opts = iso_render_options(app) + pos, neg = orbital_colors(str(opts["color_scheme"])) + payload = script_json( + { + "iso": opts["isovalue"], + "op": opts["opacity"], + "wf": opts["wireframe"], + "pos": pos, + "neg": neg, + "range": opts["esp_range"], + } + ) + # The old viewer's hook may still be defined for a moment: wait for the + # re-created viewer before pushing (it redefines the hook). + js = ( + "(function(){var n=0;function go(){n++;" # noqa: UP031 — JS is brace-dense + "if(window.__quantuiIsoUpdate){window.__quantuiIsoUpdate(%s);}" + "else if(n<40){setTimeout(go,50);}}setTimeout(go,600);})();" % payload + ) + try: + bridge.clear_output(wait=True) + with bridge: + display(Javascript(js)) + except Exception as exc: # noqa: BLE001 — cosmetic + logger.debug("iso appearance push failed: %s", exc) + + +# --------------------------------------------------------------------------- +# Banner and notes +# --------------------------------------------------------------------------- + + +def _banner_label(app: Any, name: str) -> str: + label = PANE_VIEWS[name][1] + if name == ISOSURFACE and getattr(app, "_pv_iso_label", ""): + return f"{label}: {app._pv_iso_label}" + if name == "Vibrational": + dd = getattr(app, "vib_mode_dd", None) + for text, value in getattr(dd, "options", ()) or (): + if value == getattr(dd, "value", None): + return f"{label}: {text}" + return label + + +def _sync(app: Any) -> None: + """Banner and panel notes follow the current holder.""" + if not hasattr(app, "_pv_banner"): + return + name = holder(app) + app._pv_banner.layout.display = "" if name else "none" + if name: + app._pv_banner_text.value = ( + f'' + f"Showing {_html.escape(_banner_label(app, name))} from the " + f"{_html.escape(name)} panel" + ) + has_surface = bool(getattr(app, "_pv_iso_has_surface", False)) + for panel, (_note, text, btn) in app._pv_notes.items(): + here = panel == name + no_surface = panel == ISOSURFACE and not has_surface + msg = "Shown in the viewer pane now." if here else PANE_VIEWS[panel][2] + text.value = ( + f'' + f"{_html.escape(msg)}" + ) + btn.layout.display = "none" if (here or no_surface) else "" + + +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("pane view log failed: %s", exc) + + +__all__ = [ + "ISOSURFACE", + "PANE_VIEWS", + "apply_pane_views_layout", + "build_pane_views", + "claim", + "claim_for_surface", + "holder", + "on_side_by_side", + "reset_for_new_result", + "show_structure", + "side_by_side", +] diff --git a/quantui/app_setup_dialog.py b/quantui/app_setup_dialog.py index 434df3ba..b0c85c26 100644 --- a/quantui/app_setup_dialog.py +++ b/quantui/app_setup_dialog.py @@ -14,7 +14,7 @@ any "not started — please fix …" message appear. Opened from Calculate → "Set up calculation…" in the menu bar and from the -"Set up in a dialog" button above Calculation Setup on the Calculate tab. +"Open in dialog" button in the Calculation Setup heading on the Calculate tab. Closed by its Close / Done buttons, Esc, or a click on the backdrop (``app_menubar.MENUBAR_JS``). """ @@ -136,7 +136,7 @@ def _run_tip(app: Any) -> str: def build_setup_dialog(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: - """Build the overlay and the Calculate tab's "Set up in a dialog" button. + """Build the overlay and the Calculate tab's "Open in dialog" button. Must run after ``_assemble_tabs`` built ``_calculate_tab_panel``. """ @@ -175,12 +175,12 @@ def build_setup_dialog(app: Any, *, layout_fn: Any, enabled: bool = True) -> Non tooltip="Close the dialog; the settings are kept", layout=layout_fn(width="90px", height="34px"), ) + # One line (UX-13): it ran to two before. app._sd_hint = widgets.HTML( f'
' - "Settings here are the Calculate tab's own: nothing is lost on close. " - "Running closes the dialog and shows the live output. To pick scan " - "atoms by clicking the structure, close the dialog first.
" + 'line-height:1.35">' + "Changes apply to the Calculate tab. To pick atoms in the viewer, " + "close the dialog first." ) foot = widgets.HBox( [app._sd_run_btn, app._sd_done_btn, app._sd_hint], @@ -213,26 +213,33 @@ def build_setup_dialog(app: Any, *, layout_fn: Any, enabled: bool = True) -> Non ) app._sd_placeholder.add_class(PLACEHOLDER_CLASS) - # "Set up in a dialog" above Calculation Setup on the Calculate tab. + # "Open in dialog" in the Calculation Setup heading row. It used to float + # above the section with a negative margin that clipped its border + # (UX-12). The row is part of the panel, so it moves into the dialog + # with it, where it is hidden: the dialog's own title says the same + # (UX-13). app._sd_open_btn = widgets.Button( - description="Set up in a dialog", + description="Open in dialog", icon="window-maximize", tooltip="Open Calculation Setup in a larger dialog (Esc closes it)", - layout=layout_fn(width="170px", height="28px"), - ) - app._sd_open_row = widgets.HBox( - [app._sd_open_btn], - layout=layout_fn(justify_content="flex-end", margin="8px 0 -6px"), + layout=layout_fn(width="150px", height="28px", margin="0"), ) setup = getattr(app, "calc_setup_panel", None) host = _find_parent(getattr(app, "_calculate_tab_panel", None), setup) - if enabled and host is not None: - box, idx = host - kids = list(box.children) - kids.insert(idx, app._sd_open_row) - box.children = tuple(kids) + heading = _setup_heading(setup) + if enabled and host is not None and heading is not None: + heading.layout.flex = "1 1 auto" + app._sd_open_row = widgets.HBox( + [heading, app._sd_open_btn], + layout=layout_fn(align_items="center", gap="12px", width="100%"), + ) + kids = list(setup.children) + kids[kids.index(heading)] = app._sd_open_row + setup.children = tuple(kids) else: - app._sd_open_row.layout.display = "none" + app._sd_open_row = widgets.HBox( + [app._sd_open_btn], layout=layout_fn(display="none") + ) # ── Wiring ──────────────────────────────────────────────────────────── app._sd_open_btn.on_click(lambda _b: open_setup_dialog(app)) @@ -246,6 +253,14 @@ def build_setup_dialog(app: Any, *, layout_fn: Any, enabled: bool = True) -> Non sync_run_button(app) +def _setup_heading(setup: Any) -> Any: + """The "Calculation Setup" heading widget at the top of the panel.""" + for child in getattr(setup, "children", ()) or (): + if isinstance(child, widgets.HTML) and "Calculation Setup" in child.value: + return child + return None + + def sync_run_button(app: Any) -> None: """Mirror the real Run button's enabled state (and say why not).""" btn = getattr(app, "_sd_run_btn", None) diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index 0737c1c4..e9533264 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -24,13 +24,14 @@ from quantui.app_workspace import ( finalize_viewer_html, on_result_shown, + results_viewer_shown, viewer_render_kwargs, ) from quantui.downloads import download_link_html as _download_link_html from quantui.orbital_visualization import _GENERIC_CAPTURE_JS, _png_capture_controls from quantui.plotly_embed import figure_html as _plotly_figure_html from quantui.symmetry import html_irrep -from quantui.viz_assets import orient_js, orient_view +from quantui.viz_assets import fit_zoom, fit_zoom_js, orient_js, orient_view from quantui.viz_assets import script_json as _script_json logger = logging.getLogger(__name__) @@ -149,8 +150,9 @@ def show_result_3d( app, "_analysis_mol_output", None ) - # Results-tab viewer. - if app.result_viz_output is not None: + # Results-tab viewer: only without the workspace pane, which is then + # the one viewer (UX-7). + if app.result_viz_output is not None and results_viewer_shown(app): chosen = app._resolve_backend(_VT.STRUCTURE_VIEW_RESULTS) if chosen is not None: with _viz_render_event( @@ -2038,6 +2040,11 @@ def on_iso_generate(app: Any, btn: Any) -> None: orbital_label = _SURFACE_LABELS[_mode] app._iso_render_token = int(getattr(app, "_iso_render_token", 0)) + 1 render_token = app._iso_render_token + # With the workspace on, the surface goes to the pane's viewer (unless + # the student keeps it side by side in the panel; app_pane_views). + from quantui.app_pane_views import claim_for_surface + + claim_for_surface(app, orbital_label) btn.disabled = True btn.description = "Generating…" # Reveal the inline spinner + light the toolbar activity indicator @@ -3837,6 +3844,7 @@ def build_reorg_geometry_viewer_html( view.setBackgroundColor(bgcolor) view.zoomTo() orient_view(view, geometries[0]["coordinates"]) + fit_zoom(view, geometries[0]["coordinates"]) view_html = view._make_html() m = re.search(r"3dmolviewer_(\w+)", view_html) @@ -3983,6 +3991,7 @@ def _xyz(g: dict) -> str: view.setBackgroundColor(bgcolor) view.zoomTo() orient_view(view, ref_c) + fit_zoom(view, ref_c) # py3Dmol has no type stubs (ignore_missing_imports); _make_html() # genuinely returns str. view_html = cast(str, view._make_html()) @@ -4072,6 +4081,7 @@ def build_preopt_preview_html( view.setBackgroundColor(bgcolor) view.zoomTo() orient_view(view, frames[0]) + fit_zoom(view, frames[0]) view_html = view._make_html() n_frames = len(frames) @@ -4134,6 +4144,7 @@ def build_trajectory_viewer_html( view.setBackgroundColor(bgcolor) view.zoomTo() orient_view(view, _xyz_block_coords(xyzblocks[0])) + fit_zoom(view, _xyz_block_coords(xyzblocks[0])) view_html = view._make_html() m = re.search(r"3dmolviewer_(\w+)", view_html) @@ -4360,7 +4371,7 @@ def build_vib_viewer_html( .replace("__BG__", _script_json(bgcolor)) .replace("__INIT__", str(int(initial_mode))) .replace("__ARROWS__", "true" if arrows else "false") - .replace("__ORIENT__", orient_js("v", base)) + .replace("__ORIENT__", orient_js("v", base) + fit_zoom_js("v", base, pad=2.0)) ) body = f"{view_html}" if capture_class: diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 06fbfcd3..7744c75e 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -27,7 +27,11 @@ 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. +(``app_pick_mode``) with a banner at the top of the pane. The Results tab's +viewer is hidden too, and the Populations, Vibrational and Isosurface panels +show their 3D view in the pane instead of a viewer of their own +(``app_pane_views``). Before any structure exists the pane shows one line and +a Load molecule button instead of its controls. The layout can be switched off (System Settings → Workspace layout, ``ui.workspace_layout``); the viewer block then sits at the top of the @@ -90,6 +94,10 @@ # The pane holds the viewer frame plus a little padding. _PANE_WIDTH_PX = WORKSPACE_VIEWER_WIDTH + 24 +# Narrow (stacked) layout: the pane body shows the viewer plus this much +# before it scrolls inside itself. +_NARROW_BODY_EXTRA_PX = 40 +EMPTY_CLASS = "quantui-ws-empty" WORKSPACE_CSS = f""" /* Two-pane workspace (app_workspace) ------------------------------------ */ @@ -112,6 +120,9 @@ gap: 16px; }} .{PANE_CLASS} {{ + /* The pane comes after the tabs in the DOM, so the keyboard reaches the + tabs first (UX-26); it is still drawn on the left. */ + order: -1; flex: 0 0 {_PANE_WIDTH_PX}px; width: {_PANE_WIDTH_PX}px; max-width: 100%; @@ -168,14 +179,31 @@ max-height: none; overflow: visible; }} - .{PANE_CLASS} > .{BLOCK_CLASS}, - .{PANE_CLASS} .{BODY_CLASS} {{ + .{PANE_CLASS} > .{BLOCK_CLASS} {{ overflow: visible !important; }} + /* Compact pane: the viewer shows, measurement and the atom list scroll + inside the pane, so the tabs start near the top of the window instead + of 540-1000 px down (UX-9). */ + .{PANE_CLASS} .{BODY_CLASS} {{ + max-height: {WORKSPACE_VIEWER_HEIGHT + _NARROW_BODY_EXTRA_PX}px; + overflow-y: auto !important; + }} .{MAIN_CLASS} {{ /* flex-basis 0 in a column would collapse the tabs to zero height. */ flex: 0 0 auto; }} + /* Tab labels keep their full width ("System Settings" was clipped); + the bar scrolls sideways instead. */ + .{MAIN_CLASS} .lm-TabBar-content, .{MAIN_CLASS} .p-TabBar-content {{ + flex-wrap: nowrap !important; + overflow-x: auto !important; + overflow-y: hidden !important; + }} + .{MAIN_CLASS} .lm-TabBar-tab, .{MAIN_CLASS} .p-TabBar-tab {{ + flex: 0 0 auto !important; + min-width: max-content !important; + }} }} .{TOOLBAR_CLASS} .widget-toggle-buttons .widget-toggle-button {{ font-size: 12px; @@ -625,10 +653,43 @@ def build_workspace(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: ] ) + # Empty state (UX-10): before any structure, one line and one action + # instead of a toolbar, measurement panel and atom list with nothing to + # act on. + app._ws_empty_load_btn = widgets.Button( + description="Load molecule…", + icon="flask", + button_style="info", + tooltip="Pick a molecule from the library, paste XYZ or search online", + layout=layout_fn(width="150px"), + ) + app._ws_empty = widgets.VBox( + [ + widgets.HTML( + f'
Load a molecule to see it here.
' + ), + app._ws_empty_load_btn, + ], + layout=layout_fn(display="none", padding="12px 4px"), + ) + app._ws_empty.add_class(EMPTY_CLASS) + # The block that moves between the pane and the Analysis tab. # Head (toolbar + caption) stays put in the pane; the body scrolls. build_pick_banner(app, layout_fn=layout_fn) - app._ws_head = widgets.VBox([app._ws_toolbar, app._ws_caption, app._ws_pick_banner]) + from quantui.app_pane_views import build_pane_views + + build_pane_views(app, layout_fn=layout_fn) + app._ws_head = widgets.VBox( + [ + app._ws_toolbar, + app._ws_caption, + app._ws_empty, + app._ws_pick_banner, + app._pv_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) @@ -654,6 +715,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_empty_load_btn.on_click(lambda _b: _open_molecule_input(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: @@ -708,7 +770,8 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> if enabled: panel.children = tuple(kids) app._ws_pane.children = (block,) - app._ws_row.children = (app._ws_pane, app._ws_main) + # Tabs first in the DOM (keyboard order); CSS draws the pane left. + app._ws_row.children = (app._ws_main, app._ws_pane) else: app._ws_pane.children = () app._ws_row.children = (app._ws_main,) @@ -719,7 +782,13 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> app._ws_enabled = bool(enabled) app._ws_caption.layout.display = "" if enabled else "none" _show_calc_viewer(app, not enabled) + _place_lighting(app, in_toolbar=enabled) + _show_results_viewer(app, not enabled, render=rerender) + from quantui.app_pane_views import apply_pane_views_layout + + apply_pane_views_layout(app, enabled) refresh_banner(app) + _sync_empty_state(app) if not rerender: return if not enabled and getattr(app, "_ws_source", None) == "input": @@ -743,12 +812,111 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> app._refresh_calc_mol_viewer() +def _open_molecule_input(app: Any) -> None: + from quantui.app_menubar import open_molecule_input + + open_molecule_input(app, 0) + + +def _place_lighting(app: Any, *, in_toolbar: bool) -> None: + """Lighting sits next to the viewer it changes (UX-11). + + In the pane's toolbar with the workspace on; back beside the style + dropdown on the Calculate tab with it off. Not moved when it does not + apply (PlotlyMol not installed: it is hidden where it is). + """ + dd = getattr(app, "viz_lighting_dd", None) + toolbar = getattr(app, "_ws_toolbar", None) + home = getattr(app, "viz_controls_box", None) + if not isinstance(dd, widgets.Widget) or toolbar is None or home is None: + return + if dd.layout.visibility == "hidden": + return + _drop_child(toolbar, dd) + _drop_child(home, dd) + if in_toolbar: + toolbar.children = tuple(toolbar.children) + (dd,) + else: + home.children = tuple(home.children) + (dd,) + + +def _results_viewer_column(app: Any) -> Any: + """The Results tab box that holds its own 3D viewer, or None.""" + from quantui.app_setup_dialog import _find_parent + + hit = _find_parent( + getattr(app, "results_tab_panel", None), + getattr(app, "result_viz_output", None), + ) + return hit[0] if hit is not None else None + + +def results_viewer_shown(app: Any) -> bool: + """False while the pane is the one viewer (the Results tab has none).""" + return not workspace_enabled(app) + + +def _show_results_viewer(app: Any, shown: bool, *, render: bool = True) -> None: + """The Results tab's own viewer duplicated the pane (UX-7). + + With the workspace on, the whole column is hidden and emptied (one WebGL + context fewer); with it off it comes back, redrawn with the result the + pane was showing. + """ + column = _results_viewer_column(app) + out = getattr(app, "result_viz_output", None) + if column is not None: + column.layout.display = "" if shown else "none" + if not isinstance(out, widgets.Output): + return + if not shown: + app._clear_output_widget(out) + return + mol = _viewed_molecule(app) + if not render or mol is None or getattr(app, "_ws_source", None) != "result": + return + import quantui.app as _app_mod + from quantui.app_visualization import show_result_3d + + render_fn = getattr(_app_mod, "_render_molecule_html", None) + if render_fn is not None: + show_result_3d(app, mol, None, render_html_fn=render_fn) + + +def _sync_empty_state(app: Any) -> None: + """Viewer controls only once there is a structure to act on (UX-10). + + The viewer Output itself is never hidden (an empty one takes no room, + and a 3D viewer must not start inside a hidden box); the toolbar, + measurement panel and atom list are. + """ + if not _has_workspace(app): + return + has_mol = _viewed_molecule(app) is not None + show = "" if has_mol else "none" + for w in ( + getattr(app, "_ws_toolbar", None), + getattr(app, "_measure_panel", None), + getattr(app, "_ws_atom_box", None), + ): + if isinstance(w, widgets.Widget): + w.layout.display = show + empty = getattr(app, "_ws_empty", None) + if isinstance(empty, widgets.Widget): + empty.layout.display = ( + "" if (workspace_enabled(app) and not has_mol) else "none" + ) + caption = getattr(app, "_ws_caption", None) + if isinstance(caption, widgets.Widget): + caption.layout.display = "" if (workspace_enabled(app) and has_mol) else "none" + + 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. + toolbar is linked to it, and Lighting moves into that toolbar). """ display = "" if shown else "none" for name in ("viz_output", "_mol_calc_png_status", "viz_backend_toggle"): @@ -819,6 +987,12 @@ def render_viewer(app: Any, molecule: Any = None, *, keep_picks: bool) -> bool: chosen = app._resolve_backend(VizTask.ANALYSIS_STRUCTURE_VIEW) if chosen is None: return False + if pick_mode_active(app): + # A Calculate tool picks on the structure: a panel's viewer (charges, + # vibration, surface) gives the pane back first. + from quantui.app_pane_views import show_structure + + show_structure(app, rerender=False) with _viz_render_event(app, task="analysis_structure_view", backend=str(chosen)): html = render_fn( mol, @@ -871,7 +1045,10 @@ def show_input_preview(app: Any, *, force: bool = False) -> None: def on_result_shown(app: Any) -> None: """``show_result_3d`` drew a result into the viewer.""" + from quantui.app_pane_views import reset_for_new_result + app._ws_source = "result" + reset_for_new_result(app) # a panel's viewer gives the pane back refresh_workspace(app) @@ -934,6 +1111,7 @@ def refresh_workspace(app: Any) -> None: if not _has_workspace(app): return app._ws_caption.value = caption_html(app) + _sync_empty_state(app) _refresh_atom_list(app) refresh_footer(app) diff --git a/quantui/visualization_py3dmol.py b/quantui/visualization_py3dmol.py index ad7629a9..1f12a29e 100644 --- a/quantui/visualization_py3dmol.py +++ b/quantui/visualization_py3dmol.py @@ -217,9 +217,11 @@ def visualize_molecule_py3dmol( # Zoom to fit — includes the (now bonded) metal, so it is never off-screen. view.zoomTo() # Face the camera (a planar molecule in the xz/yz plane was seen edge-on). - from quantui.viz_assets import orient_view + from quantui.viz_assets import fit_zoom, orient_view orient_view(view, molecule.coordinates) + # Small molecules open filling the viewer, not as a dot (UX-14). + fit_zoom(view, molecule.coordinates) return view diff --git a/quantui/viz_assets.py b/quantui/viz_assets.py index a2709437..450d47b3 100644 --- a/quantui/viz_assets.py +++ b/quantui/viz_assets.py @@ -180,6 +180,50 @@ def orient_view(view: Any, coords: Any) -> None: view.rotate(angle, {"x": x, "y": y, "z": z}) +# 3Dmol's zoomTo() frames a radius of at least 5 Å around the centre, so a +# small molecule (water: atoms within 0.8 Å) filled about 60 px of a 440 px +# viewer (UI/UX review 2026-12-05, UX-14). +_ZOOMTO_MIN_RADIUS = 5.0 +# Room around the atom centres for the drawn spheres, labels and vibration +# arrows, in Å. +_FIT_PAD = 1.6 +_FIT_MAX_FACTOR = 3.0 + + +def fit_zoom_factor(coords: Any, *, pad: float = _FIT_PAD) -> float: + """Extra zoom after ``zoomTo()`` so a small molecule fills the viewer. + + 1.0 (no change) for anything whose atoms plus *pad* already reach + 3Dmol's 5 Å minimum framing radius; at most 3x. + """ + import numpy as np + + try: + xyz = np.asarray(coords, dtype=float).reshape(-1, 3) + except (TypeError, ValueError): + return 1.0 + if xyz.size == 0: + return 1.0 + centre = xyz.mean(axis=0) + radius = float(np.sqrt(((xyz - centre) ** 2).sum(axis=1).max())) + pad + if radius >= _ZOOMTO_MIN_RADIUS: + return 1.0 + return min(_FIT_MAX_FACTOR, _ZOOMTO_MIN_RADIUS / radius) + + +def fit_zoom(view: Any, coords: Any, *, pad: float = _FIT_PAD) -> None: + """Apply :func:`fit_zoom_factor` to a ``py3Dmol`` view (after zoomTo).""" + factor = fit_zoom_factor(coords, pad=pad) + if factor > 1.01: + view.zoom(factor) + + +def fit_zoom_js(var: str, coords: Any, *, pad: float = _FIT_PAD) -> str: + """Same as :func:`fit_zoom`, as a JS statement for hand-built viewers.""" + factor = fit_zoom_factor(coords, pad=pad) + return f"{var}.zoom({factor:.3f});" if factor > 1.01 else "" + + def orient_js(var: str, coords: Any) -> str: """Same as :func:`orient_view`, as a JS statement for hand-built viewers.""" rot = principal_view_rotation(coords) diff --git a/tests/test_app.py b/tests/test_app.py index f285ea27..8f73473d 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -1923,6 +1923,11 @@ def test_result_viz_output_is_single_entry_after_show(self): if _render_molecule_html is None: pytest.skip("No 3D visualization backend installed") app = QuantUIApp() + # The Results tab has its own viewer only without the workspace pane + # (UX-7); switched without the checkbox, which would save it. + from quantui.app_workspace import apply_workspace_layout + + apply_workspace_layout(app, False) app._show_result_3d(self._make_water(), extra_output=None) assert len(app.result_viz_output.outputs) == 1 entry = app.result_viz_output.outputs[0] @@ -1941,6 +1946,14 @@ def test_repeated_calls_do_not_accumulate_outputs(self): for _ in range(3): app._show_result_3d(mol, extra_output=app._analysis_mol_output) assert len(app._analysis_mol_output.outputs) == 1 + # Workspace on: the pane is the one viewer, the Results tab has none. + assert app.result_viz_output.outputs == () + from quantui.app_workspace import apply_workspace_layout + + apply_workspace_layout(app, False) + for _ in range(3): + app._show_result_3d(mol, extra_output=app._analysis_mol_output) + assert len(app._analysis_mol_output.outputs) == 1 assert len(app.result_viz_output.outputs) == 1 @@ -3593,16 +3606,20 @@ def test_activate_panel_auto_selects(self): app._activate_ana_panel("Energies") assert app._orb_accordion.selected_index == 0 - def test_activate_panel_no_auto_select_still_expands(self): + def test_activate_panel_no_auto_select_stays_collapsed(self): + # UX-8 (UI/UX review 2026-12-05): only the primary panel opens; the + # rest stay collapsed but visible (DEC-009), content ready. app = QuantUIApp() app._activate_ana_panel("Energies", auto_select=False) assert "Energies" in app._ana_available - assert app._orb_accordion.selected_index == 0 + assert app._orb_accordion.selected_index is None assert app._orb_accordion.layout.display == "" + assert app._ana_content_boxes["Energies"].layout.display == "" def test_activate_does_not_collapse_other_accordions(self): app = QuantUIApp() app._activate_ana_panel("Energies") + app._ir_accordion.selected_index = 0 # opened by the student app._activate_ana_panel("IR Spectrum", auto_select=False) assert app._orb_accordion.selected_index == 0 assert app._ir_accordion.selected_index == 0 diff --git a/tests/test_app_pane_views.py b/tests/test_app_pane_views.py new file mode 100644 index 00000000..f5864a0c --- /dev/null +++ b/tests/test_app_pane_views.py @@ -0,0 +1,395 @@ +"""One viewer: Analysis panels drive the workspace pane (app_pane_views), +plus the rest of M-UXREV UXR.4 — no Results-tab duplicate, the pane's empty +state, Lighting in the pane toolbar, the setup-dialog heading row, the +narrow layout and small-molecule zoom (UI/UX review 2026-12-05, UX-7…14). + +Widget-level checks; the browser side (viewer re-creation after a move, +sizes) needs a Voilà look. +""" + +from __future__ import annotations + +import json + +import pytest + +from quantui.app_pane_views import ( + ISOSURFACE, + PANE_VIEWS, + claim, + holder, +) +from quantui.molecule import Molecule + +WATER = [[0.0, 0.0, 0.117], [0.0, 0.757, -0.469], [0.0, -0.757, -0.469]] + + +def _water() -> Molecule: + return Molecule(["O", "H", "H"], WATER) + + +def _make_app(tmp_path, monkeypatch, *, workspace: bool = True): + path = tmp_path / "settings.json" + path.write_text( + json.dumps({"_schema_version": 1, "ui": {"workspace_layout": workspace}}) + ) + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(path)) + from quantui.app import QuantUIApp + + return QuantUIApp() + + +@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 _walk(w): + yield w + for c in getattr(w, "children", ()): + yield from _walk(c) + + +def _in(root, widget) -> bool: + return any(w is widget for w in _walk(root)) + + +def _viewer(app, name): + return getattr(app, PANE_VIEWS[name][0]) + + +def _acc(app, name): + return app._ana_accordions[app._ana_panel_names.index(name)] + + +def _available(app, name): + app._activate_ana_panel(name, auto_select=False) + + +# --------------------------------------------------------------------------- +# Panel viewers live in the pane, not in their panels +# --------------------------------------------------------------------------- + + +class TestPlacement: + @pytest.mark.parametrize("name", list(PANE_VIEWS)) + def test_panel_viewer_is_not_in_its_panel(self, app, name): + acc = _acc(app, name) + assert not _in(acc, _viewer(app, name)) + # DEC-009: the panel stays; a note takes the viewer's place. + assert _in(acc, app._pv_notes[name][0]) + assert acc in app.analysis_tab_panel.children + + @pytest.mark.parametrize("name", list(PANE_VIEWS)) + def test_fallback_keeps_each_panel_viewer(self, app_off, name): + acc = _acc(app_off, name) + assert _in(acc, _viewer(app_off, name)) + assert not _in(acc, app_off._pv_notes[name][0]) + + def test_turning_the_workspace_off_puts_viewers_back(self, app): + _available(app, "Vibrational") + assert claim(app, "Vibrational") + app.workspace_layout_cb.value = False + assert holder(app) == "" + for name in PANE_VIEWS: + assert _in(_acc(app, name), _viewer(app, name)) + app.workspace_layout_cb.value = True + for name in PANE_VIEWS: + assert not _in(_acc(app, name), _viewer(app, name)) + + +class TestClaim: + def test_needs_data(self, app): + assert claim(app, "Vibrational") is False + assert holder(app) == "" + + def test_claim_and_back(self, app): + _available(app, "Vibrational") + assert claim(app, "Vibrational") is True + assert app._ws_body.children[0] is app.vib_output + assert app._ana_viewer_row not in app._ws_body.children + assert app._pv_banner.layout.display == "" + assert "Vibrational" in app._pv_banner_text.value + assert "Shown in the viewer pane" in app._pv_notes["Vibrational"][1].value + app._pv_back_btn.click() + assert holder(app) == "" + assert app._ws_body.children[0] is app._ana_viewer_row + assert app._pv_banner.layout.display == "none" + # Still out of the panel: one viewer. + assert not _in(_acc(app, "Vibrational"), app.vib_output) + + def test_one_holder_at_a_time(self, app): + _available(app, "Vibrational") + _available(app, "Populations") + claim(app, "Vibrational") + claim(app, "Populations") + assert holder(app) == "Populations" + assert app._ws_body.children[0] is app._mulliken_mol_output + assert not _in(app._ws_pane, app.vib_output) + assert not _in(_acc(app, "Vibrational"), app.vib_output) + + def test_opening_the_panel_claims_closing_releases(self, app): + _available(app, "Populations") + acc = _acc(app, "Populations") + acc.selected_index = 0 + assert holder(app) == "Populations" + acc.selected_index = None + assert holder(app) == "" + + def test_note_button_claims(self, app): + _available(app, "Populations") + app._pv_notes["Populations"][2].click() + assert holder(app) == "Populations" + + def test_results_menu_jump_claims(self, app): + from quantui.app_menubar import jump_to_panel + + _available(app, "Vibrational") + jump_to_panel(app, "Vibrational") + assert holder(app) == "Vibrational" + + def test_choosing_a_mode_claims(self, app): + _available(app, "Vibrational") + app.vib_mode_dd.options = [("Mode 7: 1650 cm⁻¹", 7), ("Mode 8", 8)] + app.vib_mode_dd.value = 8 + assert holder(app) == "Vibrational" + assert "Mode 8" in app._pv_banner_text.value + + def test_new_result_gives_the_pane_back(self, app): + _available(app, "Vibrational") + claim(app, "Vibrational") + app._show_result_3d(_water(), extra_output=app._analysis_mol_output) + assert holder(app) == "" + assert app._ws_body.children[0] is app._ana_viewer_row + + def test_applying_a_context_does_not_claim(self, app): + from quantui.app import _AnalysisContext + + _available(app, "Populations") + claim(app, "Populations") + ctx = _AnalysisContext( + calc_type="nmr", formula="H2O", method="RHF", basis="STO-3G" + ) + app._apply_analysis_context(ctx) + assert holder(app) == "" + assert app._pv_suppress is False + + def test_suppressed_while_a_context_is_applied(self, app): + _available(app, "Populations") + app._pv_suppress = True + _acc(app, "Populations").selected_index = 0 + assert holder(app) == "" + + def test_pick_mode_takes_the_structure_back(self, app): + app._set_molecule(_water()) + _available(app, "Vibrational") + claim(app, "Vibrational") + app.root_tab.selected_index = app._tab_index("calculate") + app.calc_type_dd.value = "PES Scan" + assert holder(app) == "" + assert app._ws_body.children[0] is app._ana_viewer_row + # ...and while picking, panels cannot take it. + assert claim(app, "Vibrational") is False + + def test_no_claims_without_the_workspace(self, app_off): + _available(app_off, "Vibrational") + assert claim(app_off, "Vibrational") is False + + +class TestIsosurface: + def test_opening_without_a_surface_keeps_the_structure(self, app): + _available(app, ISOSURFACE) + _acc(app, ISOSURFACE).selected_index = 0 + assert holder(app) == "" + # "Show in viewer" only once there is something to show. + assert app._pv_notes[ISOSURFACE][2].layout.display == "none" + + def test_generate_claims(self, app): + from quantui.app_pane_views import claim_for_surface + + _available(app, ISOSURFACE) + claim_for_surface(app, "HOMO") + assert holder(app) == ISOSURFACE + assert app._ws_body.children[0] is app._orb_iso_output + assert "Surface: HOMO" in app._pv_banner_text.value + + def test_side_by_side_keeps_the_surface_in_the_panel(self, app): + from quantui.app_pane_views import claim_for_surface + + _available(app, ISOSURFACE) + claim_for_surface(app) + app._iso_side_cb.value = True + assert holder(app) == "" + assert _in(_acc(app, ISOSURFACE), app._orb_iso_output) + assert claim(app, ISOSURFACE) is False + # The checkbox sits with the surface controls. + assert app._iso_side_cb in app._orb_iso_controls.children + app._iso_side_cb.value = False + assert not _in(_acc(app, ISOSURFACE), app._orb_iso_output) + + +# --------------------------------------------------------------------------- +# No Results-tab duplicate (UX-7) +# --------------------------------------------------------------------------- + + +class TestResultsViewer: + def _column(self, app): + from quantui.app_workspace import _results_viewer_column + + return _results_viewer_column(app) + + def test_hidden_with_the_workspace(self, app): + assert self._column(app).layout.display == "none" + app._show_result_3d(_water(), extra_output=app._analysis_mol_output) + assert app.result_viz_output.outputs == () + assert len(app._analysis_mol_output.outputs) == 1 + + def test_fallback_keeps_it(self, app_off): + assert self._column(app_off).layout.display == "" + app_off._show_result_3d(_water(), extra_output=app_off._analysis_mol_output) + assert len(app_off.result_viz_output.outputs) == 1 + + def test_turning_the_workspace_off_redraws_the_shown_result(self, app): + app._show_result_3d(_water(), extra_output=app._analysis_mol_output) + app.workspace_layout_cb.value = False + assert self._column(app).layout.display == "" + assert len(app.result_viz_output.outputs) == 1 + app.workspace_layout_cb.value = True + assert app.result_viz_output.outputs == () + + +# --------------------------------------------------------------------------- +# Pane empty state (UX-10), Lighting (UX-11) +# --------------------------------------------------------------------------- + + +class TestEmptyState: + def test_no_dead_controls_before_a_molecule(self, app): + assert app._ws_empty.layout.display == "" + assert app._ws_toolbar.layout.display == "none" + assert app._measure_panel.layout.display == "none" + assert app._ws_atom_box.layout.display == "none" + assert app._ws_caption.layout.display == "none" + assert app._ws_empty_load_btn.description.startswith("Load molecule") + + def test_controls_appear_with_a_molecule(self, app): + app._set_molecule(_water()) + assert app._ws_empty.layout.display == "none" + assert app._ws_toolbar.layout.display == "" + assert app._measure_panel.layout.display == "" + assert app._ws_atom_box.layout.display == "" + assert app._ws_caption.layout.display == "" + # The viewer output itself is never hidden (3D needs a sized box). + assert app._analysis_mol_output.layout.display in (None, "") + + def test_load_button_opens_the_molecule_input(self, app): + app.root_tab.selected_index = app._tab_index("history") + app._ws_empty_load_btn.click() + assert app.root_tab.selected_index == app._tab_index("calculate") + + def test_no_empty_state_in_the_single_column(self, app_off): + assert app_off._ws_empty.layout.display == "none" + + +class TestLighting: + def test_lighting_sits_in_the_pane_toolbar(self, app, app_off): + if app.viz_lighting_dd.layout.visibility == "hidden": + pytest.skip("PlotlyMol not installed: Lighting does not apply") + assert app.viz_lighting_dd in app._ws_toolbar.children + assert app.viz_lighting_dd not in app.viz_controls_box.children + assert app_off.viz_lighting_dd in app_off.viz_controls_box.children + assert app_off.viz_lighting_dd not in app_off._ws_toolbar.children + + +# --------------------------------------------------------------------------- +# Setup dialog (UX-12, UX-13) +# --------------------------------------------------------------------------- + + +class TestSetupDialogHeading: + def test_button_sits_in_the_heading_row(self, app): + row = app._sd_open_row + assert row in app.calc_setup_panel.children + assert app._sd_open_btn in row.children + assert "Calculation Setup" in row.children[0].value + assert "-" not in str(row.layout.margin or "") + + def test_heading_hidden_inside_the_dialog(self, app): + from quantui.app_setup_dialog import close_setup_dialog, open_setup_dialog + + open_setup_dialog(app) + assert app._sd_open_row.layout.display == "none" + close_setup_dialog(app) + assert app._sd_open_row.layout.display == "" + + def test_footer_note_is_short(self, app): + assert "Changes apply to the Calculate tab" in app._sd_hint.value + assert "nothing is lost" not in app._sd_hint.value + + +# --------------------------------------------------------------------------- +# Narrow layout (UX-9), keyboard order (UX-26) +# --------------------------------------------------------------------------- + + +def test_narrow_layout_keeps_the_tabs_near_the_top(): + from quantui.app_workspace import BODY_CLASS, WORKSPACE_CSS + + narrow = WORKSPACE_CSS.split("@media (max-width:", 1)[1] + narrow = narrow.split("\n}\n", 1)[0] + body_rule = narrow.split(f".{BODY_CLASS} {{", 1)[1].split("}", 1)[0] + assert "max-height:" in body_rule and "overflow-y: auto" in body_rule + assert "overflow-x: auto" in narrow # tab bar scrolls, labels not clipped + assert "min-width: max-content" in narrow + + +def test_pane_is_drawn_first_but_comes_after_the_tabs(): + from quantui.app_workspace import PANE_CLASS, WORKSPACE_CSS + + rule = WORKSPACE_CSS.split(f".{PANE_CLASS} {{", 1)[1].split("}", 1)[0] + assert "order: -1" in rule + + +# --------------------------------------------------------------------------- +# Small-molecule zoom (UX-14) +# --------------------------------------------------------------------------- + + +class TestFitZoom: + def test_small_molecule_is_zoomed_in(self): + from quantui.viz_assets import fit_zoom_factor + + f = fit_zoom_factor(WATER) + assert 1.5 < f <= 3.0 + + def test_large_molecule_is_left_alone(self): + from quantui.viz_assets import fit_zoom_factor + + coords = [[x, 0.0, 0.0] for x in range(0, 12)] + assert fit_zoom_factor(coords) == 1.0 + + def test_degenerate_input(self): + from quantui.viz_assets import fit_zoom_factor, fit_zoom_js + + assert fit_zoom_factor([]) == 1.0 + assert fit_zoom_factor("nonsense") == 1.0 + assert fit_zoom_js("v", [[0, 0, 0], [0, 0, 20]]) == "" + assert fit_zoom_js("v", WATER).startswith("v.zoom(") + + def test_single_atom_is_capped(self): + from quantui.viz_assets import fit_zoom_factor + + assert fit_zoom_factor([[0.0, 0.0, 0.0]]) == 3.0 + + def test_molecule_viewer_zooms_water(self): + pytest.importorskip("py3Dmol") + from quantui.visualization_py3dmol import render_molecule_html + + html = render_molecule_html(_water(), width=440) + assert ".zoom(" in html diff --git a/tests/test_app_workspace.py b/tests/test_app_workspace.py index 9be2e292..2a245f41 100644 --- a/tests/test_app_workspace.py +++ b/tests/test_app_workspace.py @@ -154,7 +154,9 @@ def test_round_trip_and_junk(self, tmp_path): class TestLayout: def test_default_is_two_panes(self, app): assert app._ws_enabled is True - assert app._ws_row.children == (app._ws_pane, app._ws_main) + # Tabs first in the DOM (keyboard order, UX-26); CSS draws the pane + # on the left (order: -1). + assert app._ws_row.children == (app._ws_main, app._ws_pane) assert app.root_tab in app._ws_main.children assert app._ws_viewer_block in app._ws_pane.children # Moved, not copied: one Analysis viewer, now outside the tab. diff --git a/tests/test_export2_molecule_png.py b/tests/test_export2_molecule_png.py index 6b6c9536..c5c8471a 100644 --- a/tests/test_export2_molecule_png.py +++ b/tests/test_export2_molecule_png.py @@ -263,6 +263,11 @@ def test_calc_tab_preview_gets_its_own_capture_button(self): def test_results_and_analysis_render_together_without_cross_talk(self): app, mol = self._app_with_molecule() + # Both viewers exist only in the single-column layout (with the + # workspace on, the Results tab has no viewer of its own; UX-7). + from quantui.app_workspace import apply_workspace_layout + + apply_workspace_layout(app, False) app._show_result_3d(mol, extra_output=app._analysis_mol_output) results_html = app.result_viz_output.outputs[0]["data"]["text/html"] analysis_html = app._analysis_mol_output.outputs[0]["data"]["text/html"] diff --git a/tests/test_geo_opt_analysis_history.py b/tests/test_geo_opt_analysis_history.py index 01a12f95..954ce2c9 100644 --- a/tests/test_geo_opt_analysis_history.py +++ b/tests/test_geo_opt_analysis_history.py @@ -194,7 +194,12 @@ def test_trajectory_panel_activates(self, tmp_path, app, geo_opt_result): ctx = app._build_history_context(saved) app._apply_analysis_context(ctx) assert "Trajectory" in app._ana_available - assert app.traj_accordion.selected_index == 0 + # Only the primary panel opens (UX-8): Isosurface when the result has + # orbitals (the geometry_opt default), Trajectory otherwise. + primary = "Isosurface" if "Isosurface" in app._ana_available else "Trajectory" + assert app._ana_active == primary + expected = 0 if primary == "Trajectory" else None + assert app.traj_accordion.selected_index == expected def test_energies_panel_activates(self, tmp_path, app, geo_opt_result): saved = self._save_all(tmp_path, geo_opt_result) diff --git a/tests/test_uipolish.py b/tests/test_uipolish.py index 40acbcf4..83bcad4a 100644 --- a/tests/test_uipolish.py +++ b/tests/test_uipolish.py @@ -436,6 +436,12 @@ def test_compare_table_rows_are_theme_coloured(self): assert "var(--q-bg-panel" in comparison_table_html([s]) def test_side_by_side_viewers(self, app): + # The panel layout with each panel's own viewer: the workspace-off + # fallback (with it on, those viewers move to the pane; + # app_pane_views). + from quantui.app_workspace import apply_workspace_layout + + apply_workspace_layout(app, False, rerender=False) # Without PySCF the isosurface panel is a note, not a viewer (VA.2). viewers = [app._mulliken_mol_output, app.vib_output] if _PYSCF: From 157c224c7874faf06a958af0b44fef85b284a187 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:03:17 +0000 Subject: [PATCH 03/12] Course preset: instructors can trim the Method and Basis Set lists M-UXREV UXR.7 (DEC-035 item 5; UI/UX review 2026-12-05, Q4). - New quantui/course_preset.py. Sources, first wins per list: QUANTUI_COURSE_METHODS / QUANTUI_COURSE_BASIS_SETS (comma lists, for container definitions such as NCShare's), a JSON file named by QUANTUI_COURSE_PRESET ({"name", "methods", "basis_sets"}), then a "course" section in the settings file. The settings section is read from the file rather than added to UserSettings: it has no control in the app, and UserSettings.save already keeps sections it does not know. - Names match without regard to case and keep QuantUI's spelling and order. Unknown names are ignored with a log warning; a list with nothing valid, or an engine that supports none of the preset's methods, shows the full list, so a dropdown is never empty. - The Calculate tab's dropdowns (at build and after an engine change) use the trimmed lists; the default method/basis falls back to the first allowed one. Calculation Setup shows a one-line note while a preset is active. The open-shell RHF -> UHF switch (molecule load, charge/mult suggestion) only happens when UHF is offered. - Docs: docs/course-preset.md (in the mkdocs nav), a pointer in apptainer/README.md, the environment table in copilot-instructions. - tests/test_course_preset.py: loading from each source, precedence, invalid entries, never-empty, settings round-trip, and the app's dropdowns with and without a preset. 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 | 2 + CHANGELOG.md | 10 ++ apptainer/README.md | 8 ++ docs/course-preset.md | 86 ++++++++++++ mkdocs.yml | 1 + quantui/app.py | 39 +++++- quantui/app_runflow.py | 6 +- quantui/course_preset.py | 239 ++++++++++++++++++++++++++++++++ tests/test_course_preset.py | 217 +++++++++++++++++++++++++++++ 9 files changed, 600 insertions(+), 8 deletions(-) create mode 100644 docs/course-preset.md create mode 100644 quantui/course_preset.py create mode 100644 tests/test_course_preset.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index fb123b0c..49be5908 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -802,6 +802,8 @@ Everything incl. the app server and notebook smoke tests: `pip install -e ".[pys | `QUANTUI_ENABLE_SLURM` | (unset / off) | Offer the SLURM batch backend (needs `sbatch`) | | `QUANTUI_STAGING_DIR` | System Settings value, else `~/.quantui/staging` | SLURM job-folder root | | `QUANTUI_SLURM_*` | see `apptainer/slurm/README.md` | Partition, GRES, limits, cooldowns for batch jobs | +| `QUANTUI_COURSE_METHODS` / `QUANTUI_COURSE_BASIS_SETS` | (unset = full lists) | Instructor course preset: comma-separated names the Method / Basis Set dropdowns are limited to (`course_preset.py`, `docs/course-preset.md`) | +| `QUANTUI_COURSE_PRESET` | (unset) | Path to a JSON course preset `{"name", "methods", "basis_sets"}`; the settings file's `course` section is the third source | --- diff --git a/CHANGELOG.md b/CHANGELOG.md index 15438e8a..6c5e1929 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] +### Added + +- **Course preset for instructors.** An optional preset trims the Method and + Basis Set lists on the Calculate tab (e.g. only RHF and B3LYP with STO-3G + and 6-31G\*). Set it with `QUANTUI_COURSE_METHODS` / + `QUANTUI_COURSE_BASIS_SETS`, a JSON file named by `QUANTUI_COURSE_PRESET`, + or a `course` section in the settings file. Full lists by default; unknown + names are ignored with a log warning; students see a one-line note. See + `docs/course-preset.md`. + ### Changed - **One 3D viewer with the workspace.** The Populations, Vibrational and diff --git a/apptainer/README.md b/apptainer/README.md index 77a3e664..fdc8ea14 100644 --- a/apptainer/README.md +++ b/apptainer/README.md @@ -345,6 +345,14 @@ apptainer run quantui.sif app No Python, no conda, no pip — everything is bundled. +### Limit methods and basis sets for a course + +To offer students only the methods and basis sets a course uses, set +`QUANTUI_COURSE_METHODS` / `QUANTUI_COURSE_BASIS_SETS` (comma-separated) or +point `QUANTUI_COURSE_PRESET` at a JSON preset file, e.g. +`apptainer run --env QUANTUI_COURSE_METHODS="RHF,B3LYP" quantui.sif app`. +See [Course preset](../docs/course-preset.md). + --- ## Rebuilding after code changes diff --git a/docs/course-preset.md b/docs/course-preset.md new file mode 100644 index 00000000..695fd1c6 --- /dev/null +++ b/docs/course-preset.md @@ -0,0 +1,86 @@ +# Course preset (for instructors) + +By default QuantUI offers every method and basis set it supports. For a +course you can trim the **Method** and **Basis Set** lists on the Calculate +tab to the ones your lab uses, for example only RHF and B3LYP with STO-3G and +6-31G\*. Students then see a short note under Calculation Setup saying that +the lists were chosen by their instructor. + +Only the setup dropdowns change. History, Compare and results saved earlier +keep working with any method or basis set, and the command-line tools are +not limited. + +## Ways to set it + +Use whichever suits your deployment. When more than one is set, the first in +this list wins (separately for methods and for basis sets). + +### 1. Environment variables + +Comma-separated names. Handy in a container definition or a launcher script: + +```bash +export QUANTUI_COURSE_METHODS="RHF, B3LYP" +export QUANTUI_COURSE_BASIS_SETS="STO-3G, 6-31G*" +``` + +### 2. A preset file + +Point `QUANTUI_COURSE_PRESET` at a JSON file: + +```bash +export QUANTUI_COURSE_PRESET=/shared/chem2100/quantui-course.json +``` + +```json +{ + "name": "CHEM 2100", + "methods": ["RHF", "B3LYP"], + "basis_sets": ["STO-3G", "6-31G*"] +} +``` + +The optional `name` appears in the note students see ("Course preset for +CHEM 2100: …"). + +### 3. The settings file + +Add a `course` section to the QuantUI settings file +(`~/.quantui/settings.json`, or the file named by `QUANTUI_SETTINGS_PATH`): + +```json +{ + "_schema_version": 1, + "course": { + "name": "CHEM 2100", + "methods": ["RHF", "B3LYP"], + "basis_sets": ["STO-3G", "6-31G*"] + } +} +``` + +QuantUI keeps this section when it saves the student's own preferences to +the same file. There is no control for it in the app. + +## Rules + +- Names are matched without regard to case (`b3lyp` works) and shown in + QuantUI's spelling and order. The supported names are listed under + [Supported Methods](methods.md). +- An unknown name is ignored and a warning is written to the log. If none of + the names in a list is valid, students get the full list rather than an + empty dropdown. +- Leave a list out (or empty) to keep the full list for it. +- If the quantum engine in use supports none of the preset's methods (for + example PyFock on native Windows), the engine's full list is shown. +- A molecule with unpaired electrons normally switches RHF to UHF. If the + preset leaves UHF out, the method is not switched: include UHF if the + course works with radicals or triplets. + +## On NCShare or in the Apptainer image + +Set the variables in the container's environment, for example in the +`%environment` section of `apptainer/quantui.def`, or with +`apptainer run --env QUANTUI_COURSE_METHODS="RHF,B3LYP" quantui.sif app`. +A preset file on a shared path (`QUANTUI_COURSE_PRESET`) lets you change the +lists for a new term without rebuilding the image. diff --git a/mkdocs.yml b/mkdocs.yml index fa3a9ad1..7faa2c01 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -94,6 +94,7 @@ nav: - Features: features.md - Gallery: gallery.md - Supported Methods: methods.md + - Course Preset (instructors): course-preset.md - CLI Reference: CLI.md - Import into Avogadro: IMPORTING-INTO-AVOGADRO.md - Development: diff --git a/quantui/app.py b/quantui/app.py index e5ffe55b..e54dec85 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -692,6 +692,10 @@ SUPPORTED_BASIS_SETS, SUPPORTED_METHODS, ) +from quantui.course_preset import CoursePreset as _CoursePreset +from quantui.course_preset import limit as _course_limit +from quantui.course_preset import load_course_preset as _load_course_preset +from quantui.course_preset import note_html as _course_note_html from quantui.downloads import download_link_html as _download_link_html from quantui.engines import is_pyfock_available as _is_pyfock_available from quantui.engines import is_pyscf_available as _is_pyscf_available @@ -2252,6 +2256,9 @@ def __init__( BackendAvailability.from_environment() ) self._viz_backend_preference: str = self._user_settings.viz.default_backend + # Instructor course preset: may trim the Method / Basis Set lists + # (environment, preset file or the settings file's "course" section). + self._course_preset: _CoursePreset = _load_course_preset() # Synchronization state for Calculate/Analysis backend toggles. # When _set_viz_backend updates one toggle, it sets this flag so the @@ -2641,14 +2648,17 @@ def _build_welcome_header(self) -> None: # ── Shared widgets (Cell 3) ─────────────────────────────────────────── def _build_shared_widgets(self) -> None: + preset = self._course_preset + methods = _course_limit(SUPPORTED_METHODS, preset.methods) + bases = _course_limit(SUPPORTED_BASIS_SETS, preset.basis_sets) _bld_build_shared_widgets( self, layout_fn=_layout, step_progress_cls=StepProgress, - supported_methods=SUPPORTED_METHODS, - supported_basis_sets=SUPPORTED_BASIS_SETS, - default_method=DEFAULT_METHOD, - default_basis=DEFAULT_BASIS, + supported_methods=methods, + supported_basis_sets=bases, + default_method=DEFAULT_METHOD if DEFAULT_METHOD in methods else methods[0], + default_basis=DEFAULT_BASIS if DEFAULT_BASIS in bases else bases[0], default_charge=DEFAULT_CHARGE, default_multiplicity=DEFAULT_MULTIPLICITY, default_fmax=DEFAULT_FMAX, @@ -2679,6 +2689,11 @@ def _build_molecule_section(self) -> None: def _build_calc_setup(self) -> None: _bld_build_calc_setup(self, layout_fn=_layout) + # Say when an instructor's course preset trims the lists. + self._course_note = widgets.HTML(value=_course_note_html(self._course_preset)) + kids = list(self.calc_setup_panel.children) + kids.insert(1, self._course_note) + self.calc_setup_panel.children = tuple(kids) # ── Run panel (Cell 6) ──────────────────────────────────────────────── @@ -4834,7 +4849,10 @@ def _apply_quantum_engine_capabilities(self) -> None: elif calc_options: self.calc_type_dd.value = calc_options[0] - method_options = [m for m in SUPPORTED_METHODS if m in caps.supported_methods] + method_options = _course_limit( + [m for m in SUPPORTED_METHODS if m in caps.supported_methods], + self._course_preset.methods, + ) current_method = self.method_dd.value self.method_dd.options = method_options self.method_dd.value = ( @@ -4842,7 +4860,10 @@ def _apply_quantum_engine_capabilities(self) -> None: ) supported_bases = caps.supported_basis_sets or tuple(SUPPORTED_BASIS_SETS) - basis_options = [b for b in SUPPORTED_BASIS_SETS if b in supported_bases] + basis_options = _course_limit( + [b for b in SUPPORTED_BASIS_SETS if b in supported_bases], + self._course_preset.basis_sets, + ) current_basis = self.basis_dd.value self.basis_dd.options = basis_options self.basis_dd.value = ( @@ -6298,7 +6319,11 @@ def _set_molecule( if sync_charge_mult: self.charge_si.value = mol.charge self.mult_si.value = mol.multiplicity - if mol.multiplicity > 1 and self.method_dd.value == "RHF": + if ( + mol.multiplicity > 1 + and self.method_dd.value == "RHF" + and "UHF" in self.method_dd.options # a course preset may omit it + ): self.method_dd.value = "UHF" else: # Geometry-only load: calc-setup fields own charge/mult. diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index a3e97f68..97dfff9a 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -449,7 +449,11 @@ def on_charge_mult_apply(app: Any, btn: Any = None) -> None: return app.charge_si.value = suggestion.charge app.mult_si.value = suggestion.multiplicity - if suggestion.multiplicity > 1 and app.method_dd.value == "RHF": + if ( + suggestion.multiplicity > 1 + and app.method_dd.value == "RHF" + and "UHF" in app.method_dd.options # a course preset may omit it + ): app.method_dd.value = "UHF" if getattr(app, "_molecule", None) is not None: app._molecule.charge = suggestion.charge diff --git a/quantui/course_preset.py b/quantui/course_preset.py new file mode 100644 index 00000000..a695328d --- /dev/null +++ b/quantui/course_preset.py @@ -0,0 +1,239 @@ +"""Instructor course preset: limit the Method and Basis Set lists. + +Off by default: students see every method and basis set QuantUI supports. +An instructor (or a deployment such as NCShare) can trim both lists to what a +course uses, e.g. only RHF and B3LYP with STO-3G and 6-31G*. Only the +Calculate tab's dropdowns change; History, Compare and saved results keep +working with anything. + +Where the preset comes from (first one that sets a list wins, per list): + +1. ``QUANTUI_COURSE_METHODS`` / ``QUANTUI_COURSE_BASIS_SETS`` — comma-separated + names in the environment (handy in a container definition). +2. ``QUANTUI_COURSE_PRESET`` — path to a JSON file + ``{"name": "CHEM 2100", "methods": [...], "basis_sets": [...]}``. +3. The ``course`` section of the settings file (``~/.quantui/settings.json``): + ``{"course": {"name": ..., "methods": [...], "basis_sets": [...]}}``. + +Names are matched without regard to case and stored in QuantUI's spelling. +Unknown names are ignored with a log warning; a list in which nothing is +valid falls back to the full list (also with a warning), so a typo can never +leave a dropdown empty. The lists keep QuantUI's own order. +""" + +from __future__ import annotations + +import json +import logging +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple + +logger = logging.getLogger(__name__) + +ENV_METHODS = "QUANTUI_COURSE_METHODS" +ENV_BASIS_SETS = "QUANTUI_COURSE_BASIS_SETS" +ENV_PRESET_FILE = "QUANTUI_COURSE_PRESET" + + +@dataclass(frozen=True) +class CoursePreset: + """The allowed names (empty tuple = no limit) and where they came from.""" + + name: str = "" + methods: Tuple[str, ...] = () + basis_sets: Tuple[str, ...] = () + source: str = "" + + @property + def active(self) -> bool: + return bool(self.methods or self.basis_sets) + + +def _split_env(value: str) -> List[str]: + return [p.strip() for p in value.split(",") if p.strip()] + + +def _as_names(raw: Any, what: str, source: str) -> List[str]: + """A list of strings from JSON, or [] (with a warning) for anything else.""" + if raw is None: + return [] + if isinstance(raw, str): + return _split_env(raw) + if isinstance(raw, (list, tuple)) and all(isinstance(x, str) for x in raw): + return [x.strip() for x in raw if x.strip()] + logger.warning( + "Course preset (%s): %s must be a list of names; ignored", source, what + ) + return [] + + +def _read_file(path: str) -> Mapping[str, Any]: + try: + data = json.loads(Path(path).expanduser().read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + logger.warning( + "Course preset file %s could not be read (%s); ignored", path, exc + ) + return {} + if not isinstance(data, dict): + logger.warning("Course preset file %s is not a JSON object; ignored", path) + return {} + return data + + +def _canonical( + names: Iterable[str], supported: Sequence[str], what: str, source: str +) -> Tuple[str, ...]: + """Keep the supported names (QuantUI's spelling and order); warn on the rest.""" + by_upper = {s.upper(): s for s in supported} + wanted = set() + for name in names: + hit = by_upper.get(name.upper()) + if hit is None: + logger.warning( + "Course preset (%s): unknown %s %r ignored", source, what, name + ) + else: + wanted.add(hit) + return tuple(s for s in supported if s in wanted) + + +def _settings_course(settings_path: Optional[Path]) -> Mapping[str, Any]: + """The ``course`` section of the settings file ({} when absent). + + Read straight from the file: it is an instructor/deployment setting with + no control in the app, so it is not part of ``UserSettings`` (whose + ``save`` keeps sections it does not know). + """ + from quantui.user_settings import UserSettings + + path = UserSettings._resolve_path(settings_path) + if not path.exists(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError, RecursionError): + return {} # UserSettings.load already warned about this file + course = data.get("course") if isinstance(data, dict) else None + if course is None: + return {} + if not isinstance(course, dict): + logger.warning("Settings 'course' section is not an object; ignored") + return {} + return course + + +def load_course_preset( + settings_path: Optional[Path] = None, + environ: Optional[Mapping[str, str]] = None, + *, + supported_methods: Optional[Sequence[str]] = None, + supported_basis_sets: Optional[Sequence[str]] = None, +) -> CoursePreset: + """Read the preset from the environment, a preset file, or settings.""" + from quantui import config + + env = os.environ if environ is None else environ + methods_all = list(supported_methods or config.SUPPORTED_METHODS) + bases_all = list(supported_basis_sets or config.SUPPORTED_BASIS_SETS) + + layers: List[Tuple[str, Mapping[str, Any]]] = [] + env_layer = {} + if env.get(ENV_METHODS, "").strip(): + env_layer["methods"] = _split_env(env[ENV_METHODS]) + if env.get(ENV_BASIS_SETS, "").strip(): + env_layer["basis_sets"] = _split_env(env[ENV_BASIS_SETS]) + if env_layer: + layers.append(("environment", env_layer)) + path = env.get(ENV_PRESET_FILE, "").strip() + if path: + layers.append((f"file {path}", _read_file(path))) + course = _settings_course(settings_path) + if course: + layers.append(("settings", course)) + + name = "" + methods: Tuple[str, ...] = () + bases: Tuple[str, ...] = () + sources: List[str] = [] + for source, layer in layers: + if not name and isinstance(layer.get("name"), str): + name = str(layer["name"]).strip() + if not methods: + raw = _as_names(layer.get("methods"), "methods", source) + if raw: + methods = _canonical(raw, methods_all, "method", source) + if not methods: + logger.warning( + "Course preset (%s): no valid methods; showing all", source + ) + else: + sources.append(source) + if not bases: + raw = _as_names(layer.get("basis_sets"), "basis_sets", source) + if raw: + bases = _canonical(raw, bases_all, "basis set", source) + if not bases: + logger.warning( + "Course preset (%s): no valid basis sets; showing all", source + ) + elif source not in sources: + sources.append(source) + return CoursePreset( + name=name, + methods=methods, + basis_sets=bases, + source=", ".join(sources), + ) + + +def limit(options: Sequence[str], allowed: Sequence[str]) -> List[str]: + """*options* trimmed to *allowed*, in *options*' order. + + No limit (empty *allowed*), or a limit that would leave nothing (e.g. an + engine that supports none of the course's methods), gives *options* + unchanged. + """ + if not allowed: + return list(options) + kept = [o for o in options if o in set(allowed)] + if not kept: + logger.warning( + "Course preset allows none of %s; showing all", ", ".join(options) + ) + return list(options) + return kept + + +def note_html(preset: CoursePreset) -> str: + """One line under Calculation Setup saying the lists are limited.""" + import html as _html + + from quantui import theme as _theme + + if not preset.active: + return "" + what = " and ".join( + w + for w, on in (("methods", preset.methods), ("basis sets", preset.basis_sets)) + if on + ) + course = f" for {_html.escape(preset.name)}" if preset.name else "" + return ( + f'
' + f"Course preset{course}: your instructor chose which {what} are " + "offered.
" + ) + + +__all__ = [ + "ENV_BASIS_SETS", + "ENV_METHODS", + "ENV_PRESET_FILE", + "CoursePreset", + "limit", + "load_course_preset", + "note_html", +] diff --git a/tests/test_course_preset.py b/tests/test_course_preset.py new file mode 100644 index 00000000..ffdee500 --- /dev/null +++ b/tests/test_course_preset.py @@ -0,0 +1,217 @@ +"""Instructor course preset (quantui/course_preset.py; M-UXREV UXR.7). + +Full lists by default; environment, preset file or the settings file's +``course`` section trim the Method / Basis Set dropdowns; unknown names are +ignored with a warning and never leave a dropdown empty. +""" + +from __future__ import annotations + +import json +import logging + +import pytest + +from quantui import config +from quantui.course_preset import ( + ENV_BASIS_SETS, + ENV_METHODS, + ENV_PRESET_FILE, + CoursePreset, + limit, + load_course_preset, + note_html, +) + + +@pytest.fixture +def no_settings(tmp_path, monkeypatch): + path = tmp_path / "settings.json" + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(path)) + for var in (ENV_METHODS, ENV_BASIS_SETS, ENV_PRESET_FILE): + monkeypatch.delenv(var, raising=False) + return path + + +class TestLoad: + def test_default_is_no_limit(self, no_settings): + preset = load_course_preset(environ={}) + assert preset == CoursePreset() + assert not preset.active + + def test_environment_lists(self, no_settings): + preset = load_course_preset( + environ={ENV_METHODS: "b3lyp, RHF", ENV_BASIS_SETS: "sto-3g,6-31g*"} + ) + # QuantUI's spelling and order, not the order typed. + assert preset.methods == ("RHF", "B3LYP") + assert preset.basis_sets == ("STO-3G", "6-31G*") + assert preset.active + assert preset.source == "environment" + + def test_unknown_names_are_ignored_with_a_warning(self, no_settings, caplog): + with caplog.at_level(logging.WARNING, logger="quantui.course_preset"): + preset = load_course_preset(environ={ENV_METHODS: "RHF, NotAMethod"}) + assert preset.methods == ("RHF",) + assert "NotAMethod" in caplog.text + + def test_nothing_valid_means_full_list(self, no_settings, caplog): + with caplog.at_level(logging.WARNING, logger="quantui.course_preset"): + preset = load_course_preset(environ={ENV_METHODS: "nope, never"}) + assert preset.methods == () + assert "no valid methods" in caplog.text + + def test_preset_file(self, no_settings, tmp_path): + f = tmp_path / "course.json" + f.write_text( + json.dumps( + {"name": "CHEM 2100", "methods": ["RHF"], "basis_sets": ["STO-3G"]} + ) + ) + preset = load_course_preset(environ={ENV_PRESET_FILE: str(f)}) + assert preset.name == "CHEM 2100" + assert preset.methods == ("RHF",) + assert preset.basis_sets == ("STO-3G",) + assert preset.source.startswith("file") + + def test_unreadable_preset_file_is_ignored(self, no_settings, tmp_path, caplog): + f = tmp_path / "broken.json" + f.write_text("{not json") + with caplog.at_level(logging.WARNING, logger="quantui.course_preset"): + preset = load_course_preset(environ={ENV_PRESET_FILE: str(f)}) + assert not preset.active + assert "could not be read" in caplog.text + assert not load_course_preset( + environ={ENV_PRESET_FILE: str(tmp_path / "missing.json")} + ).active + + def test_wrong_types_are_ignored(self, no_settings, tmp_path, caplog): + f = tmp_path / "course.json" + f.write_text(json.dumps({"methods": [1, 2], "basis_sets": "STO-3G"})) + with caplog.at_level(logging.WARNING, logger="quantui.course_preset"): + preset = load_course_preset(environ={ENV_PRESET_FILE: str(f)}) + assert preset.methods == () + # A plain string is accepted as a comma list. + assert preset.basis_sets == ("STO-3G",) + assert "must be a list" in caplog.text + + def test_settings_file_course_section(self, no_settings): + no_settings.write_text( + json.dumps( + { + "_schema_version": 1, + "course": {"methods": ["UHF", "RHF"], "basis_sets": []}, + } + ) + ) + preset = load_course_preset(environ={}) + assert preset.methods == ("RHF", "UHF") + assert preset.basis_sets == () + assert preset.source == "settings" + + def test_environment_wins_per_list(self, no_settings, tmp_path): + no_settings.write_text( + json.dumps( + { + "_schema_version": 1, + "course": {"methods": ["UHF"], "basis_sets": ["3-21G"]}, + } + ) + ) + preset = load_course_preset(environ={ENV_METHODS: "B3LYP"}) + assert preset.methods == ("B3LYP",) + assert preset.basis_sets == ("3-21G",) # from the settings file + + def test_settings_save_keeps_the_course_section(self, no_settings): + from quantui.user_settings import UserSettings + + no_settings.write_text( + json.dumps({"_schema_version": 1, "course": {"methods": ["RHF"]}}) + ) + s = UserSettings.load() + s.ui.menu_bar = False + s.save() + assert load_course_preset(environ={}).methods == ("RHF",) + + +class TestLimit: + def test_no_limit(self): + assert limit(["A", "B"], ()) == ["A", "B"] + + def test_keeps_order_of_options(self): + assert limit(["A", "B", "C"], ("C", "A")) == ["A", "C"] + + def test_never_empty(self, caplog): + with caplog.at_level(logging.WARNING, logger="quantui.course_preset"): + assert limit(["A", "B"], ("Z",)) == ["A", "B"] + assert "allows none" in caplog.text + + +class TestNote: + def test_empty_without_preset(self): + assert note_html(CoursePreset()) == "" + + def test_names_course_and_lists(self): + html = note_html(CoursePreset(name="CHEM <2100>", methods=("RHF",))) + assert "CHEM <2100>" in html + assert "methods" in html and "basis sets" not in html + + +class TestApp: + def _app(self, monkeypatch, tmp_path, **env): + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(tmp_path / "s.json")) + for var in (ENV_METHODS, ENV_BASIS_SETS, ENV_PRESET_FILE): + monkeypatch.delenv(var, raising=False) + for k, v in env.items(): + monkeypatch.setenv(k, v) + from quantui.app import QuantUIApp + + return QuantUIApp() + + def test_full_lists_by_default(self, monkeypatch, tmp_path): + app = self._app(monkeypatch, tmp_path) + assert len(app.method_dd.options) > 2 + assert "STO-3G" in app.basis_dd.options and "cc-pVDZ" in app.basis_dd.options + assert app._course_note.value == "" + + def test_preset_trims_the_dropdowns(self, monkeypatch, tmp_path): + app = self._app( + monkeypatch, + tmp_path, + QUANTUI_COURSE_METHODS="B3LYP,RHF", + QUANTUI_COURSE_BASIS_SETS="STO-3G,6-31G*", + ) + assert tuple(app.method_dd.options) == ("RHF", "B3LYP") + assert tuple(app.basis_dd.options) == ("STO-3G", "6-31G*") + assert app.method_dd.value in app.method_dd.options + assert app.basis_dd.value in app.basis_dd.options + assert "Course preset" in app._course_note.value + assert app._course_note in app.calc_setup_panel.children + + def test_default_method_outside_the_preset(self, monkeypatch, tmp_path): + if config.DEFAULT_METHOD == "B3LYP": + pytest.skip("the default is already in this preset") + app = self._app(monkeypatch, tmp_path, QUANTUI_COURSE_METHODS="B3LYP") + assert app.method_dd.value == "B3LYP" + + def test_open_shell_does_not_pick_a_hidden_uhf(self, monkeypatch, tmp_path): + from quantui.molecule import Molecule + + app = self._app(monkeypatch, tmp_path, QUANTUI_COURSE_METHODS="RHF,B3LYP") + app.method_dd.value = "RHF" + radical = Molecule( + ["O", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.97]], multiplicity=2 + ) + app._set_molecule(radical) # would switch to UHF without a preset + assert app.method_dd.value == "RHF" + + def test_open_shell_still_switches_without_a_preset(self, monkeypatch, tmp_path): + from quantui.molecule import Molecule + + app = self._app(monkeypatch, tmp_path) + app.method_dd.value = "RHF" + radical = Molecule( + ["O", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.97]], multiplicity=2 + ) + app._set_molecule(radical) + assert app.method_dd.value == "UHF" From 0b9ee00e0c75eda4c5a4b65805838d43636847e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:47:49 +0000 Subject: [PATCH 04/12] Run feedback: Frequency pre-opt on, "completed with warnings", one status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M-UXREV UXR.1 (UI/UX review 2026-12-05, UX-1/2/3/4/6; DEC-035 items 1 and 7). - UX-1: "Geometry optimization before calculation" starts ticked for Frequency; every calc type remembers its own tick (the box is shared). At run time the optimization is skipped, with a log line, when the geometry is the final geometry of a saved QuantUI optimization (converged Geometry Opt or Transition State, or a Frequency run that optimized first) at the same method, basis, charge, multiplicity and solvent (app_runflow.find_same_level_optimization, 1e-3 A RMSD). Applies to the generic pre-opt path and UV-Vis too. "Use mode -> new Frequency calc" always ticks the box, since the displaced geometry must be re-optimized. - UX-2: log_utils.collect_run_warnings gathers plain-language warnings (not converged, not a stationary point, imaginary modes, failed pre-opt, known solver warnings). A serious one turns the completion banner amber ("Completed with warnings" plus the first warning), the Results button amber, the run status and the log footer ("completed with warnings"). "Converged: Yes" on a non-stationary Frequency card (live and History) is shown in the neutral colour instead of green. - UX-3: known solver lines (Krylov residuals, HOMO == LUMO, retried SCF, linear dependence) map to one sentence each in the digest; unknown lines stay verbatim as notes; digest lines wrap at the banner width. - UX-4: the header chip is HTML (no Tab stop, not clickable) rendered from app_workspace.job_state, the footer's source, which now also knows "Done — with warnings" and compute work. Brief UI work no longer flashes "UI Active". Tests updated for the approved chip change. - UX-6: the run status label wraps (CSS class + flexible column). 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 | 31 +++ quantui/app.py | 145 +++++++---- quantui/app_builders.py | 52 ++-- quantui/app_formatters.py | 39 ++- quantui/app_runflow.py | 188 ++++++++++++++ quantui/app_workspace.py | 54 +++- quantui/help_content.py | 7 +- quantui/log_utils.py | 207 ++++++++++++++-- tests/test_app.py | 16 +- tests/test_uiaudit_design.py | 6 +- tests/test_uxrev_run_feedback.py | 407 +++++++++++++++++++++++++++++++ 11 files changed, 1060 insertions(+), 92 deletions(-) create mode 100644 tests/test_uxrev_run_feedback.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a2fec5c..74e2a1fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,37 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +### Changed + +- **Frequency calculations optimize the geometry first by default.** + "Geometry optimization before calculation" now starts ticked for + Frequency (other calculation types keep it unticked, and each type + remembers your own choice). Library and pasted structures are not minima at + the chosen level, so frequencies and thermochemistry at them were not + meaningful. The optimization is skipped automatically, with a line in the + log, when the structure already is the result of a QuantUI optimization + (Geometry Opt, Transition State, or a Frequency run that optimized first) + at the same method, basis, charge, multiplicity and solvent. +- **"Completed with warnings" instead of a green tick.** When a result + carries a warning (not a stationary point, imaginary frequencies, a + calculation or solver that did not converge, a failed optimization before + the calculation), the completion banner turns amber and names the warning, + the run status says so, the log ends with "completed with warnings", and + "Converged: Yes" on a non-stationary Frequency result is no longer green. +- **Plain-language warnings in the log digest.** Known solver messages (for + example the Krylov solver used for Raman activities) are summarised in one + sentence that says what they mean for the numbers; the raw lines stay in + the full log. +- **One status for the header and the footer.** The status chip in the + header and the workspace footer now show the same job state (Idle, + Running…, Done, Done — with warnings, Failed); the chip no longer drops back + to "Idle" after a run, and it is no longer a button. + +### Fixed + +- The run status line next to Cancel wraps instead of being cut off at the + panel edge. + ## [0.13.2] - 2026-12-05 ### Changed diff --git a/quantui/app.py b/quantui/app.py index 88f2b638..b0d46095 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -285,6 +285,9 @@ from quantui.app_runflow import ( do_calibration as _run_do_calibration, ) +from quantui.app_runflow import ( + find_same_level_optimization as _run_find_same_level_optimization, +) from quantui.app_runflow import ( frozen_atom_indices as _run_frozen_atoms, ) @@ -438,6 +441,9 @@ from quantui.app_runflow import ( seed_with_run_charge as _run_seed_with_run_charge, ) +from quantui.app_runflow import ( + show_completion_banner as _show_completion_banner, +) from quantui.app_runflow import ( update_estimate as _run_update_estimate, ) @@ -641,6 +647,7 @@ 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 refresh_status as _ws_refresh_status 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 @@ -696,6 +703,7 @@ freq_parallel_opt_in, ) from quantui.help_content import HELP_TOPICS, VIEWER_HELP_TOPICS +from quantui.log_utils import has_serious_warnings as _has_serious_warnings from quantui.molecule import Molecule from quantui.progress import StepProgress from quantui.user_settings import UserSettings @@ -1019,9 +1027,8 @@ class carries a per-app uid suffix. LiveLog also sets the stack inline — this height: auto !important; } .quantui-history-recent:hover { text-decoration: underline !important; } -/* Activity indicator: a status chip, not a button. */ +/* Job status: a chip, not a button (UX-4). Hover still shows its tooltip. */ .quantui-status-chip { - pointer-events: none !important; cursor: default !important; border-radius: 14px !important; box-shadow: none !important; @@ -1040,6 +1047,22 @@ class carries a per-app uid suffix. LiveLog also sets the stack inline — this background: var(--q-accent-success-bg); margin: 8px 0; } +/* Finished, but the result carries a warning (UX-2): amber, not green. */ +.quantui-completion-banner.is-warning { + border-color: var(--q-accent-warning); + background: var(--q-surface-warning-bg); +} +/* The run status line wraps instead of being cut off at the panel edge + (UX-6): long progress lines ("IR intensities: 9/24 ... remaining"). */ +.quantui-run-status, +.quantui-run-status .widget-label, +.quantui-run-status.widget-label { + white-space: normal !important; + overflow: visible !important; + text-overflow: clip !important; + height: auto !important; + line-height: 1.35 !important; +} /* Suppress Jupyter stderr pink in dark palettes */ .jp-OutputArea-stderr, .output_stderr { @@ -1625,6 +1648,9 @@ class _RunContext: # is shown on the result card, not only in the log: the run otherwise # ends "Done" at a geometry the student did not ask for (audit APP-11). preopt_warning: Optional[str] = None + # Set when the optimization was skipped because the geometry already is + # a QuantUI optimization at this level (DEC-035 item 1): what it was. + preopt_skipped: Optional[str] = None # ══ APP CLASS ════════════════════════════════════════════════════════════════ @@ -2206,6 +2232,9 @@ def __init__( self._calc_running: bool = False # Set once a run has its result in hand; Cancel is ignored from then on. self._run_result_ready: bool = False + # Plain-language warnings about the last run (log_utils.RunWarning); + # they turn the banner, footer and header chip amber (UX-2, UX-4). + self._last_run_warnings: list = [] # True while the calibration suite runs; Run and calibration exclude # each other (audit APP-13). self._cal_running: bool = False @@ -2482,34 +2511,21 @@ def _theme_css(self, palette_id: str) -> str: return _theme.theme_css_block(palette_id) def _set_activity_indicator(self, state: str = "idle", message: str = "") -> None: - """Update the toolbar activity light state and tooltip.""" - if state == "compute": - self._activity_btn.description = "Computing" - self._activity_btn.icon = "cog" - self._activity_btn.button_style = "warning" - self._activity_btn.tooltip = message or "Running compute operations..." - return - if state == "ui": - self._activity_btn.description = "UI Active" - self._activity_btn.icon = "bolt" - self._activity_btn.button_style = "info" - self._activity_btn.tooltip = message or "Running UI operations..." - return + """Redraw the header status chip. - self._activity_btn.description = "Idle" - self._activity_btn.icon = "circle-o" - self._activity_btn.button_style = "" - self._activity_btn.tooltip = "No active operations." + The chip shows the job state (idle / running / done / done with + warnings / failed) from the same source as the workspace footer + (``app_workspace.job_state``), so the two never disagree (UX-4). + *state* and *message* are kept for callers; brief UI work no longer + flashes the chip. + """ + _ws_refresh_status(self) def _refresh_activity_indicator(self, message: str = "") -> None: - """Recompute activity light state from active operation counters.""" - if self._activity_count <= 0: - self._set_activity_indicator("idle") - return - if self._activity_compute_count > 0: - self._set_activity_indicator("compute", message) - return - self._set_activity_indicator("ui", message) + """Recompute the status chip (and footer) from the run state.""" + self._set_activity_indicator( + "compute" if self._activity_compute_count else "idle", message + ) def _activity_begin(self, message: str = "", kind: str = "ui") -> None: """Mark one operation as active.""" @@ -6882,6 +6898,7 @@ def _do_run(self) -> None: # live output mid-run), reset the cancel flag for this fresh run. self._calc_running = True self._run_result_ready = False + self._last_run_warnings = [] self._cancel_event.clear() self.cancel_btn.disabled = False self.log_clear_btn.disabled = True @@ -7149,16 +7166,22 @@ def _run_required_final_single_point(target_mol, reason: str): source="live", ) + # Plain-language warnings about this result (non-stationary + # geometry, unconverged solver, failed pre-optimization, ...). + # Set before the step indicator completes: the footer and the + # header chip read them when it does (UX-2, UX-4). + _extra_warnings = [_preopt_warning] if _preopt_warning else [] + from quantui.log_utils import collect_run_warnings as _collect_warnings + + self._last_run_warnings = _collect_warnings( + result, log_text=log.getvalue(), extra=_extra_warnings + ) + self.step_progress.complete(2) self.step_progress.complete(3) - # Update completion banner - _mol_label = _ana_ctx.label - self._completion_mol_lbl.value = ( - f'' - f"{_mol_label}" - ) - self._completion_banner.layout.display = "" + # Completion banner: green, or amber "Completed with warnings". + _show_completion_banner(self, _ana_ctx.label, self._last_run_warnings) _mark("banner_ready") # Write structured log footer @@ -7172,6 +7195,7 @@ def _run_required_final_single_point(target_mol, reason: str): cpu_time=_elapsed_cpu, log_text=log.getvalue(), success=True, + extra_warnings=_extra_warnings, ) ) except Exception: @@ -7330,7 +7354,11 @@ def _run_required_final_single_point(target_mol, reason: str): _mark("success_done") _elapsed_total = _tail_marks["success_done"] - _run_wall_t if _save_error is None: - self.run_status.value = f"Done in {_elapsed_total:.1f} s." + self.run_status.value = f"Done in {_elapsed_total:.1f} s." + ( + " Completed with warnings — see Results." + if _has_serious_warnings(self._last_run_warnings) + else "" + ) else: self.run_status.value = ( f"Finished in {_elapsed_total:.1f} s — NOT saved: {_save_error}" @@ -7561,6 +7589,40 @@ def _run_apply_seed_before_preopt(self, rc: _RunContext) -> None: f"Atoms: {len(rc.calc_mol.atoms)}\n" ) + def _run_skip_preopt_if_already_optimized(self, rc: _RunContext) -> None: + """Untick the run's pre-optimization when it would repeat one. + + When ``rc.calc_mol`` is the final geometry of a saved QuantUI + optimization at the same method/basis/charge/multiplicity/solvent, + optimizing again only costs time: skip it and say so in the log. + """ + if not rc.preopt: + return + try: + match = _run_find_same_level_optimization( + rc.calc_mol, method=rc.method, basis=rc.basis, solvent=rc.solvent + ) + except (OSError, ValueError, TypeError) as exc: + logger.debug("same-level optimization lookup failed: %s", exc) + return + if match is None: + return + from quantui.app_formatters import friendly_timestamp + + rc.preopt = False + rc.preopt_skipped = ( + f"{match['label']} at {rc.method}/{rc.basis}, " + f"{friendly_timestamp(match['timestamp'])}" + ) + rc.log.write( + f"\n── Geometry optimization before {rc.ct}: skipped ──\n" + "This geometry is already optimized at the same level " + f"({rc.preopt_skipped}), so it is used as-is.\n\n" + ) + self.run_status.value = ( + "Geometry already optimized at this level — skipping the optimization." + ) + def _run_optional_preopt(self, rc: _RunContext) -> None: """Optional QM geometry optimization before the calculation. @@ -7570,11 +7632,10 @@ def _run_optional_preopt(self, rc: _RunContext) -> None: # Frequency and UV-Vis (TD-DFT) both have dedicated seed/pre-opt # handling in their own branches so they can layer a seed # geometry under the pre-opt step. - if rc.preopt and rc.ct not in ( - "Geometry Opt", - "Frequency", - "UV-Vis (TD-DFT)", - ): + if rc.ct in ("Geometry Opt", "Frequency", "UV-Vis (TD-DFT)"): + return + self._run_skip_preopt_if_already_optimized(rc) + if rc.preopt: from quantui import optimize_geometry # Rename user-facing @@ -7875,6 +7936,7 @@ def _run_calc_frequency(self, rc: _RunContext) -> None: # ── Step 1: resolve seed geometry (geo-opt or mode perturbation) rc.calc_mol = _run_resolve_seed_geometry(self, rc.calc_mol, log=rc.log) + self._run_skip_preopt_if_already_optimized(rc) # ── Step 2: optional geometry optimization ──────────────────── # @@ -7951,7 +8013,7 @@ def _run_calc_frequency(self, rc: _RunContext) -> None: ) # ── Step 3: frequency analysis ──────────────────────────────── - if rc.solvent and not rc.preopt: + if rc.solvent and not rc.preopt and not rc.preopt_skipped: rc.log.write( f"\nNote: PCM ({rc.solvent}) frequencies are only " "meaningful at a geometry optimized in the same " @@ -8044,6 +8106,7 @@ def _run_calc_tddft(self, rc: _RunContext) -> None: # ── Step 2: optional geometry optimization ──────────────────── # Renamed from # "pre-optimisation" — DFT geom-opt is just geom-opt. + self._run_skip_preopt_if_already_optimized(rc) if rc.preopt: from quantui import optimize_geometry diff --git a/quantui/app_builders.py b/quantui/app_builders.py index 36f34907..c9c8f321 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -1821,6 +1821,7 @@ def build_shared_widgets( layout=layout_fn(width="200px", height="36px"), ) app.run_status = widgets.Label() + app.run_status.add_class("quantui-run-status") # wraps (UX-6) # Live elapsed-time chip next to the status text — a bg-thread # ticker updates it every ~1 s while a calc runs, so even a fully silent # native phase (first gradient / Hessian) visibly advances. @@ -1966,20 +1967,33 @@ def _cancel_style(change: Any) -> None: app._download_html = widgets.HTML(value="", layout=layout_fn(margin="6px 0 0 0")) +def completion_status_html(*, warned: bool) -> str: + """The completion banner's leading status words (UX-2).""" + if warned: + return ( + f'⚠ Completed with warnings — ' + ) + return ( + f'' + "✓ Calculation complete — " + ) + + def build_theme_selector(app: Any, *, layout_fn: Any) -> None: """Build the theme selector widgets and apply default theme CSS.""" app._theme_style = widgets.Output( layout=layout_fn(height="0px", overflow="hidden", margin="0", padding="0") ) - # A status indicator, not a control: neutral while idle, - # coloured only while busy, and styled as a non-clickable chip - # (.quantui-status-chip in the app CSS). - app._activity_btn = widgets.Button( - description="Idle", - icon="circle-o", - tooltip="No active operations.", - button_style="", - layout=layout_fn(width="118px", margin="0 8px 0 0"), + # A status indicator, not a control (UX-4): plain HTML, so it is not a + # Tab stop and does not look clickable. It shows the same job state as + # the workspace footer (app_workspace.job_state), so the two always agree. + # Kept under its old name: app_viewer hides it in viewer mode. + from quantui.app_workspace import status_chip_html + + app._activity_btn = widgets.HTML( + value=status_chip_html("idle", "Idle"), + layout=layout_fn(margin="0 8px 0 0"), ) app._activity_btn.add_class("quantui-status-chip") default_palette = getattr(app, "_user_settings", None) @@ -2461,7 +2475,9 @@ def build_run_section(app: Any, *, layout_fn: Any) -> None: # timer never crowds/truncates the (longer) status line. widgets.VBox( [app.run_status, app._run_elapsed_lbl], - layout=layout_fn(gap="0px"), + # Takes the rest of the row and may shrink, so a + # long status wraps inside it (UX-6). + layout=layout_fn(gap="0px", flex="1 1 0%", min_width="0"), ), ], layout=layout_fn(align_items="center", gap="8px"), @@ -3848,20 +3864,28 @@ def _plot_export_row(prefix: str) -> widgets.HBox: layout=layout_fn(width="140px"), ) app._completion_mol_lbl = widgets.HTML(value="") + # Status word: green "Calculation complete", or amber "Completed with + # warnings" when the result carries a warning (app_runflow + # .show_completion_banner, UX-2). The note under it names the warning. + app._completion_status_html = widgets.HTML( + value=completion_status_html(warned=False) + ) + app._completion_note_html = widgets.HTML( + value="", layout=layout_fn(display="none", flex="1 1 100%") + ) app._completion_banner = widgets.HBox( [ - widgets.HTML( - f'' - "✓ Calculation complete — " - ), + app._completion_status_html, app._completion_mol_lbl, app._go_results_btn, app._go_analysis_btn, + app._completion_note_html, ], layout=layout_fn( display="none", align_items="center", gap="8px", + flex_flow="row wrap", ), ) app._completion_banner.add_class("quantui-completion-banner") diff --git a/quantui/app_formatters.py b/quantui/app_formatters.py index f9dab601..96d88947 100644 --- a/quantui/app_formatters.py +++ b/quantui/app_formatters.py @@ -10,8 +10,24 @@ from quantui import theme as _theme -def _converged_color(converged: bool) -> str: - return _theme.css.ACCENT_SUCCESS if converged else _theme.css.ACCENT_ERROR_ALT +def _converged_color(converged: bool, *, usable: bool = True) -> str: + """Colour of a "Converged" value. + + Converged but not *usable* (e.g. a Frequency result at a geometry that is + not a stationary point) is shown in the neutral heading colour: the value + stays factual, but it must not be the green signal next to a warning that + the numbers are not meaningful (UX-2). + """ + if not converged: + return _theme.css.ACCENT_ERROR_ALT + return _theme.css.ACCENT_SUCCESS if usable else _theme.css.TEXT_HEADING + + +def _stationary_ok(max_force: Any) -> bool: + """False only when the stationary-point check ran and failed.""" + from quantui.freq_calc import is_stationary + + return is_stationary(max_force) is not False def signed(x: Any, ndigits: int) -> str: @@ -855,7 +871,9 @@ def format_freq_result(r: Any) -> str: # analysis step to have completed, not just the reference SCF, so the # row is labeled/colored on overall status rather than "SCF converged". _conv = "Yes" if r.converged else "No (treat with caution)" - _cc = _converged_color(r.converged) + _cc = _converged_color( + r.converged, usable=_stationary_ok(getattr(r, "max_force_ev_per_ang", None)) + ) def get(k: str, d: Any = None) -> Any: return getattr(r, k, d) @@ -1077,7 +1095,9 @@ def format_tddft_result(r: Any) -> str: # r.converged now folds in per-root TD convergence, so the # row is labeled/colored on overall status, not just the ground SCF. _conv = "Yes" if r.converged else "No (treat with caution)" - _cc = _converged_color(r.converged) + _cc = _converged_color( + r.converged, usable=_stationary_ok(getattr(r, "max_force_ev_per_ang", None)) + ) _n_converged = getattr(r, "n_converged_states", None) _states_detail = str(len(r.excitation_energies_ev)) if _n_converged is not None and _n_converged != len(r.excitation_energies_ev): @@ -1135,7 +1155,9 @@ def format_tddft_result(r: Any) -> str: def format_nmr_result(r: Any) -> str: """Format an NMR shielding result card.""" _conv = "Yes" if r.converged else "No (treat with caution)" - _cc = _converged_color(r.converged) + _cc = _converged_color( + r.converged, usable=_stationary_ok(getattr(r, "max_force_ev_per_ang", None)) + ) header_rows = ( f'SCF converged' f'{_conv}' @@ -1754,6 +1776,13 @@ def format_past_result(data: dict[str, Any], result_dir: Optional[Path] = None) _conv = "No (some steps did not converge)" elif ct in ("frequency", "transition_state", "irc"): _conv_label = "Converged" + if ct == "frequency": + _mf = ((data.get("spectra") or {}).get("ir") or {}).get( + "max_force_ev_per_ang" + ) + _cc = _converged_color( + bool(data.get("converged")), usable=_stationary_ok(_mf) + ) elif ct == "tddft": _conv_label = "Converged" elif data.get("cc_converged") is not None: diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index a3e97f68..3cd34d0a 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -117,6 +117,44 @@ def _write_run_header(app: Any) -> None: ) +def show_completion_banner(app: Any, label: str, warnings: Any = ()) -> None: + """Show the "Calculation complete" banner under Run. + + With a serious warning (non-stationary geometry, unconverged solver, ...) + it reads "Completed with warnings" in amber and names the first warning, + instead of a green tick next to a result whose numbers are not usable + (UX-2). *label* is plain text (escaped here). + """ + from quantui.app_builders import completion_status_html + from quantui.log_utils import SEVERITY_WARN + + serious = [w for w in warnings or () if w.severity == SEVERITY_WARN] + app._completion_status_html.value = completion_status_html(warned=bool(serious)) + app._completion_mol_lbl.value = ( + f'' + f"{html.escape(str(label))}" + ) + app._go_results_btn.button_style = "warning" if serious else "success" + banner = app._completion_banner + if serious: + banner.add_class("is-warning") + more = ( + f" (+{len(serious) - 1} more on the Results tab)" + if len(serious) > 1 + else " See the Results tab." + ) + app._completion_note_html.value = ( + f'' + f"{html.escape(serious[0].text)}{html.escape(more)}" + ) + app._completion_note_html.layout.display = "" + else: + banner.remove_class("is-warning") + app._completion_note_html.value = "" + app._completion_note_html.layout.display = "none" + banner.layout.display = "" + + def _set_run_output(app: Any, outputs: tuple) -> None: """Atomically set ``run_output.outputs`` (fallback to clear_output).""" try: @@ -290,6 +328,40 @@ def on_run_clicked(app: Any, btn: Any) -> None: _FREQ_PREOPT_DESC_DEFAULT = "Geometry optimization before calculation (QM, slower)" _PES_PREOPT_DESC = "Pre-optimize starting geometry before scan (recommended)" +# Calc types whose "Geometry optimization before calculation" box starts +# ticked. Frequency: harmonic frequencies and thermochemistry are only +# meaningful at a stationary point, and library/pasted geometries are not +# minima at the chosen level (DEC-035 item 1, amending DEC-026). The run skips +# the optimization when the geometry already comes from one at the same level +# (see quantui.preopt_skip). +PREOPT_ON_BY_DEFAULT = frozenset({"Frequency"}) + + +def _remember_preopt_choice(app: Any, calc_type: Any) -> None: + """Store the pre-opt tick the user left on *calc_type* before switching. + + Not stored while the box is hidden or locked by a seed geometry: then the + value is the app's, not the user's choice. + """ + cb = getattr(app, "_freq_preopt_cb", None) + if cb is None or not calc_type: + return + if bool(getattr(cb, "disabled", False)) or cb.layout.display == "none": + return + choices = getattr(app, "_preopt_choice", None) + if not isinstance(choices, dict): + choices = {} + app._preopt_choice = choices + choices[str(calc_type)] = bool(cb.value) + + +def preopt_default_for(app: Any, calc_type: str) -> bool: + """The pre-opt tick for *calc_type*: the user's last choice, else the default.""" + choices = getattr(app, "_preopt_choice", None) + if isinstance(choices, dict) and calc_type in choices: + return bool(choices[calc_type]) + return calc_type in PREOPT_ON_BY_DEFAULT + def _hide_basis_fix_button(app: Any) -> None: try: @@ -602,11 +674,15 @@ def on_calc_type_changed(app: Any, change: Any, *, layout_fn: Any) -> None: app._freq_preopt_cb.description = ( _PES_PREOPT_DESC if ct == "PES Scan" else _FREQ_PREOPT_DESC_DEFAULT ) + # One checkbox serves every calc type, so its tick is remembered per type + # (Frequency defaults to ticked, DEC-035 item 1; the rest to unticked). + _remember_preopt_choice(app, change.get("old", ct)) if ct in ("Geometry Opt", "Reorganization Energy", "Transition State", "IRC"): app._freq_preopt_cb.value = False app._freq_preopt_cb.layout.display = "none" elif ct in ("Frequency", "UV-Vis (TD-DFT)"): app._freq_preopt_cb.layout.display = "" + app._freq_preopt_cb.value = preopt_default_for(app, ct) # The seed dropdown is shared across all three seed-consuming calc # types, so it can carry a value in from whichever of these # two was active before. Re-evaluate .disabled here rather than trust @@ -619,6 +695,7 @@ def on_calc_type_changed(app: Any, change: Any, *, layout_fn: Any) -> None: else: app._freq_preopt_cb.layout.display = "" app._freq_preopt_cb.disabled = False + app._freq_preopt_cb.value = preopt_default_for(app, ct) if ct == "Geometry Opt": app._refresh_geo_seed_options() @@ -1202,6 +1279,112 @@ def _load_freq_result_geometry(result_dir: Path): return None +# A geometry counts as "already optimized" only when it is that optimization's +# final geometry, not merely close to it: 0.1 Å (the seed-list tolerance above) +# would let an unoptimized library structure through. Saved coordinates +# round-trip through JSON (exact) or an XYZ export (5-6 decimals). +_SAME_GEOMETRY_RMSD_TOLERANCE: float = 1e-3 + +_OPT_CALC_LABELS = { + "geometry_opt": "Geometry Opt", + "transition_state": "Transition State", + "frequency": "Frequency (optimized first)", +} + + +def _same_text(a: Any, b: Any) -> bool: + return str(a or "").strip().casefold() == str(b or "").strip().casefold() + + +def _optimized_geometry_of(result_dir: Path, data: dict): + """``(atoms, coords)`` an optimization in *result_dir* ended at, or None. + + Geometry Opt / Transition State: the last frame of ``trajectory.json`` + (only when the search converged). Frequency: the geometry it ran at, and + only when it optimized first (``preopt_trajectory.json``). + """ + ct = data.get("calc_type") + if ct in ("geometry_opt", "transition_state"): + if data.get("converged") is not True: + return None + return _load_final_geometry(result_dir) + if ct == "frequency" and (result_dir / "preopt_trajectory.json").exists(): + geom = data.get("geometry") or {} + atoms, coords = geom.get("atoms"), geom.get("coordinates") + if atoms and coords: + import numpy as _np + + arr = _np.asarray(coords, dtype=float) + if arr.shape == (len(atoms), 3): + return list(atoms), arr + return None + + +def find_same_level_optimization( + molecule: Any, + *, + method: str, + basis: str, + solvent: Optional[str] = None, +) -> Optional[dict]: + """A saved QuantUI optimization that ended at *molecule*, at this level. + + "This level" is the same method, basis, charge, multiplicity and implicit + solvent. Returns ``{"label", "timestamp", "dir"}`` for the newest match, + or None. Used to skip the "Geometry optimization before calculation" step + when it would only repeat an optimization already done (DEC-035 item 1). + """ + from quantui.results_storage import list_results, load_result + + try: + formula = molecule.get_formula() + atoms = list(molecule.atoms) + coords = molecule.coordinates + charge = int(getattr(molecule, "charge", 0) or 0) + mult = int(getattr(molecule, "multiplicity", 1) or 1) + except (AttributeError, TypeError, ValueError): + return None + for d in list_results(): # newest first + try: + data = load_result(d) + except (OSError, ValueError) as exc: + logger.debug("skip %s while matching optimizations: %s", d, exc) + continue + if data.get("calc_type") not in _OPT_CALC_LABELS: + continue + if data.get("formula") != formula: + continue + if not ( + _same_text(data.get("method"), method) + and _same_text(data.get("basis"), basis) + ): + continue + if (data.get("solvent") or None) != (solvent or None): + continue + geom = data.get("geometry") or {} + if int(geom.get("charge", charge) or 0) != charge: + continue + if int(geom.get("multiplicity", mult) or 1) != mult: + continue + final = _optimized_geometry_of(d, data) + if final is None: + continue + if not _geometries_match( + atoms, + coords, + final[0], + final[1], + rmsd_tol=_SAME_GEOMETRY_RMSD_TOLERANCE, + ): + continue + return { + "label": _OPT_CALC_LABELS[data["calc_type"]], + "timestamp": str(data.get("timestamp", d.name)), + "dir": d, + } + return None + + def populate_freq_perturb_modes(app: Any, result_dir: Path) -> bool: """Fill the mode dropdown from a Frequency result directory.""" from quantui.freq_calc import load_frequency_mode_seed_data @@ -1366,6 +1549,11 @@ def apply_vib_mode_for_frequency(app: Any) -> None: ) app.calc_type_dd.value = "Frequency" app._seed_dd.value = "" + # The displaced geometry is deliberately off the stationary point: it must + # be re-optimized before its frequencies mean anything, whatever the box + # was last left at for Frequency. + app._freq_preopt_cb.disabled = False + app._freq_preopt_cb.value = True _update_freq_perturb_seed_ui(app, "") app.run_status.value = ( f"Applied mode {mode_number} displacement — ready to rerun Frequency." diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 840f99f8..7a0451d2 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -437,27 +437,71 @@ def selection_text(molecule: Any, picks: Sequence[int]) -> str: "idle": _theme.css.TEXT_SUBTLE, "running": _theme.css.ACCENT_WARNING, "done": _theme.css.ACCENT_SUCCESS, + "warn": _theme.css.ACCENT_WARNING, "failed": _theme.css.ACCENT_ERROR, } def job_state(app: Any) -> tuple[str, str]: - """(key, label) for the current job: idle / running / done / failed. + """(key, label) for the current job: idle / running / done / warn / failed. - Read from the existing run state — ``_calc_running`` and the step - indicator's last two steps (run, results) — rather than a second copy. + The one status source for both the workspace footer and the header chip + (UX-4). Read from the existing run state — ``_calc_running``, the + compute-activity counter (calibration, isosurfaces), the step indicator's + last two steps (run, results) and the last run's warnings — rather than a + second copy. """ if bool(getattr(app, "_calc_running", False)): calc = getattr(getattr(app, "calc_type_dd", None), "value", "") or "" return "running", f"Running {calc}".strip() + "…" + if int(getattr(app, "_activity_compute_count", 0) or 0) > 0: + return "running", "Computing…" states = list(getattr(getattr(app, "step_progress", None), "_states", []) or []) if len(states) > 2 and states[2] == "fail": return "failed", "Failed" if len(states) > 3 and states[3] == "done": + from quantui.log_utils import has_serious_warnings + + if has_serious_warnings(getattr(app, "_last_run_warnings", None) or ()): + return "warn", "Done — with warnings" return "done", "Done" return "idle", "Idle" +_CHIP_TOOLTIPS = { + "idle": "No calculation running.", + "running": "A calculation is running.", + "done": "The last calculation finished.", + "warn": "The last calculation finished with warnings — see Results.", + "failed": "The last calculation failed — see Results.", +} + + +def status_chip_html(key: str, label: str) -> str: + """The header status chip: a coloured dot and the job state (UX-4). + + HTML, not a button: it is not a Tab stop and does not look clickable. + """ + color = _JOB_COLORS.get(key, _theme.css.TEXT_SUBTLE) + tip = _html.escape(_CHIP_TOOLTIPS.get(key, label), quote=True) + return ( + f'' + f'' + f"{_html.escape(label)}" + ) + + +def refresh_status(app: Any) -> None: + """Redraw the header chip and the footer from :func:`job_state`.""" + chip = getattr(app, "_activity_btn", None) + if isinstance(chip, widgets.HTML): + chip.value = status_chip_html(*job_state(app)) + refresh_footer(app) + + def footer_html(app: Any) -> str: """The status bar: job state · viewed molecule · selection.""" key, label = job_state(app) @@ -671,7 +715,7 @@ def build_workspace(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: (getattr(app, "mult_si", None), "value"), ): if isinstance(w, widgets.Widget) and w.has_trait(trait): - w.observe(safe(lambda _ch: refresh_footer(app)), names=trait) + w.observe(safe(lambda _ch: refresh_status(app)), names=trait) app._ws_enabled = False app._ws_source = None @@ -1000,6 +1044,8 @@ def on_reset_view(app: Any) -> None: "finalize_viewer_html", "footer_html", "job_state", + "refresh_status", + "status_chip_html", "labels_enabled", "on_analysis_context_applied", "on_result_shown", diff --git a/quantui/help_content.py b/quantui/help_content.py index 480e62be..0bba2e18 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -597,8 +597,11 @@ "stored frequencies — no new calculation needed." "" "

Optimize first. Frequencies only mean something at a " - "stationary point. Tick Geometry optimization before " - "calculation (it uses a tighter force threshold for this) or start " + "stationary point, so Geometry optimization before " + "calculation is ticked by default for Frequency (it uses a " + "tighter force threshold for this). It is skipped automatically " + "when the structure already comes from a QuantUI optimization at the " + "same method and basis, and the log says so. You can also start " "from an optimized result with Start from:.

" "

Imaginary frequencies (shown as negative numbers) mean the " "structure is not a minimum: one means a saddle point such as a " diff --git a/quantui/log_utils.py b/quantui/log_utils.py index f3507d73..abce4c2a 100644 --- a/quantui/log_utils.py +++ b/quantui/log_utils.py @@ -14,9 +14,10 @@ import socket import subprocess import uuid +from dataclasses import dataclass from datetime import datetime, timezone from functools import lru_cache -from typing import Any, Dict, Optional +from typing import Any, Dict, Optional, Sequence _WIDTH = 80 # total width of === border lines _SEP = "=" * _WIDTH @@ -273,6 +274,13 @@ def _split_method_functional( return ("RKS" if multiplicity <= 1 else "UKS"), method +def _wrap(text: str, width: int) -> list: + """*text* wrapped to *width* columns (at least one line).""" + import textwrap + + return textwrap.wrap(text, width=width) or [""] + + def _row(label: str, value: Any) -> str: """One aligned `` Label : value`` header row.""" return f" {label:<16}: {value}" @@ -436,6 +444,161 @@ def _extract_warnings( ) +# ============================================================================ +# Plain-language warnings (UX-2, UX-3) +# ============================================================================ + +#: A warning that should change how the result is read ("completed with +#: warnings", amber), versus a note that is listed but leaves a successful run +#: green. +SEVERITY_WARN = "warn" +SEVERITY_NOTE = "note" + + +@dataclass(frozen=True) +class RunWarning: + """One plain-language warning about a finished run.""" + + text: str + severity: str = SEVERITY_WARN + + +_SCF_RETRY_NOTE = ( + "One SCF attempt did not converge; QuantUI retried it (details in the " "full log)." +) + +# Known PySCF/solver log lines → one plain sentence each. The raw line stays in +# the full log; students see what it means for their numbers. Order matters: +# the first pattern that matches a line wins. +_PLAIN_LOG_WARNINGS: tuple = ( + ( + re.compile(r"krylov", re.IGNORECASE), + "An iterative solver for response properties (polarizabilities, " + "Raman activities, IR intensities) did not fully converge, so those " + "values may be less accurate.", + SEVERITY_WARN, + ), + ( + re.compile(r"homo\b.*==\s*lumo", re.IGNORECASE), + "The highest occupied and lowest unoccupied orbitals have the same " + "energy: the electronic state may be degenerate, or the charge or " + "multiplicity may be wrong.", + SEVERITY_WARN, + ), + ( + re.compile(r"scf not converged|scf did not converge", re.IGNORECASE), + _SCF_RETRY_NOTE, + SEVERITY_NOTE, + ), + ( + re.compile(r"linear(ly)? dependen", re.IGNORECASE), + "The basis set is nearly linearly dependent; results can be " + "numerically less stable.", + SEVERITY_NOTE, + ), +) + +# Raw lines longer than this are cut in the digest (the full log keeps them). +_RAW_WARNING_WIDTH = 74 + + +def _result_warnings(result: Any) -> list: + """Warnings about the result itself: convergence and stationary point.""" + out: list = [] + if result is None: + return out + if getattr(result, "converged", None) is False: + if getattr(result, "n_steps", None) is not None: + text = ( + "The geometry optimization did not converge, so this geometry " + "is not a minimum yet. Run it again from here, or raise the " + "step limit." + ) + else: + text = "The calculation did not converge, so its numbers are not reliable." + out.append(RunWarning(text)) + max_force = getattr(result, "max_force_ev_per_ang", None) + if max_force is not None: + try: + from .freq_calc import STATIONARY_FMAX_EV_PER_ANG + + if float(max_force) > STATIONARY_FMAX_EV_PER_ANG: + out.append( + RunWarning( + f"This geometry is not a stationary point (max force " + f"{float(max_force):.3f} eV/Å), so the frequencies and " + "thermochemistry are not meaningful. Tick 'Geometry " + "optimization before calculation' and run again." + ) + ) + except (ImportError, TypeError, ValueError): + pass + try: + n_imag = int(result.n_imaginary_modes()) + except (AttributeError, TypeError, ValueError): + n_imag = 0 + if n_imag > 0: + word = "frequency" if n_imag == 1 else "frequencies" + out.append( + RunWarning( + f"{n_imag} imaginary {word}: this geometry is not a minimum " + "(expected only for a transition state)." + ) + ) + return out + + +def collect_run_warnings( + result: Any, + *, + log_text: str = "", + extra: Sequence[str] = (), +) -> list: + """Every warning about a run, in plain language, most important first. + + *result* contributes convergence / stationary-point / imaginary-mode + warnings; *extra* are app-level warnings (e.g. a failed geometry + optimization before the calculation); *log_text* is scanned for known + solver warnings, which are mapped to one sentence each. Unrecognised + warning lines are kept verbatim (shortened) as notes. + """ + found: list = [RunWarning(str(t)) for t in extra if t] + found += _result_warnings(result) + gap = getattr(result, "homo_lumo_gap_ev", None) if result is not None else None + raw: list = [] + seen: set = {w.text for w in found} + # An unconverged result already says so; "QuantUI retried it" would + # then be wrong. + unconverged = result is not None and getattr(result, "converged", None) is False + for line in _extract_warnings(log_text, converged_gap_ev=gap): + for pattern, text, severity in _PLAIN_LOG_WARNINGS: + if pattern.search(line): + if unconverged and text == _SCF_RETRY_NOTE: + break + if text not in seen: + seen.add(text) + found.append(RunWarning(text, severity)) + break + else: + raw.append(line) + for line in raw: + short = ( + line + if len(line) <= _RAW_WARNING_WIDTH + else line[: _RAW_WARNING_WIDTH - 3] + "..." + ) + if short not in seen: + seen.add(short) + found.append(RunWarning(short, SEVERITY_NOTE)) + return found + + +def has_serious_warnings(warnings: Sequence[Any]) -> bool: + """True when any warning should turn "completed" into "completed with + warnings".""" + return any(getattr(w, "severity", SEVERITY_WARN) == SEVERITY_WARN for w in warnings) + + def format_log_footer( *, result: Any, @@ -443,6 +606,7 @@ def format_log_footer( cpu_time: float, log_text: str = "", success: bool = True, + extra_warnings: Sequence[str] = (), ) -> str: """Return a formatted footer string to append to calculation log output. @@ -499,16 +663,13 @@ def format_log_footer( f" ZPVE: {zpve:.6f} Ha ({zpve * HARTREE_TO_EV:.4f} eV)" ) - # Imaginary frequencies (FreqResult) - n_imag = None + # Imaginary frequencies: counted here, explained in the digest below. try: - n_imag = result.n_imaginary_modes() # type: ignore[attr-defined] - except AttributeError: - pass - if n_imag is not None and n_imag > 0: - lines.append( - f" ⚠ {n_imag} imaginary frequency mode(s) — geometry may not be a true minimum" - ) + n_imag = int(result.n_imaginary_modes()) # type: ignore[attr-defined] + except (AttributeError, TypeError, ValueError): + n_imag = 0 + if n_imag > 0: + lines.append(f" Imaginary modes: {n_imag}") # Timing section lines.append(" ── Timing " + "─" * (_WIDTH - 12)) @@ -519,25 +680,33 @@ def format_log_footer( f" Wall time: {wall_str} CPU time: {cpu_str} CPU/Wall: {ratio:.1f}×" ) - # Warnings digest + # Warnings digest: plain-language sentences for known warnings (UX-3), + # unrecognised lines verbatim. The raw lines stay in the log above. lines.append(" ── Warnings Digest " + "─" * (_WIDTH - 22)) - warnings = _extract_warnings(log_text, converged_gap_ev=gap_ev) + warnings = collect_run_warnings(result, log_text=log_text, extra=extra_warnings) if warnings: for w in warnings[:10]: # cap at 10 - # Truncate very long lines - w_disp = w if len(w) <= 74 else w[:71] + "..." - lines.append(f" ⚠ {w_disp}") + mark = "⚠" if w.severity == SEVERITY_WARN else "·" + for i, part in enumerate(_wrap(w.text, _WIDTH - 6)): + lines.append(f" {mark if i == 0 else ' '} {part}") if len(warnings) > 10: lines.append(f" ... and {len(warnings) - 10} more (see full log)") else: lines.append(" (none)") - # Final status line + # Final status line. A run can finish and still not be usable as is (a + # non-stationary geometry, an unconverged solver): then it says so, + # rather than "completed successfully" under the warnings (UX-2). lines.append(_SEP) - if success: - lines.append(" ✓ Calculation completed successfully.") - else: + if not success: lines.append(" ✗ Calculation ended with errors — see log above.") + elif has_serious_warnings(warnings): + lines.append( + " ⚠ Calculation completed with warnings — read them before " + "using the results." + ) + else: + lines.append(" ✓ Calculation completed successfully.") lines.append(_SEP) lines.append("") diff --git a/tests/test_app.py b/tests/test_app.py index f285ea27..4df4a7a6 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -73,24 +73,28 @@ def test_initial_molecule_is_none(self): app = QuantUIApp() assert app._molecule is None + # UX-4 (UI/UX review 2026-12-05): the header chip is HTML driven by the + # same job state as the workspace footer. def test_activity_indicator_defaults_idle(self): app = QuantUIApp() assert hasattr(app, "_activity_btn") - assert app._activity_btn.description == "Idle" + assert ">Idle" in app._activity_btn.value def test_activity_indicator_compute_state(self): app = QuantUIApp() app._activity_begin("Running compute operations...", kind="compute") - assert app._activity_btn.description == "Computing" + assert "Computing" in app._activity_btn.value app._activity_end(kind="compute") - assert app._activity_btn.description == "Idle" + assert ">Idle" in app._activity_btn.value - def test_activity_indicator_ui_state(self): + def test_activity_indicator_ignores_brief_ui_work(self): + # Brief UI work no longer flashes the chip ("UI Active"): the chip + # and the footer show the job state only, so they always agree. app = QuantUIApp() app._activity_begin("Switching tabs...", kind="ui") - assert app._activity_btn.description == "UI Active" + assert ">Idle" in app._activity_btn.value app._activity_end(kind="ui") - assert app._activity_btn.description == "Idle" + assert ">Idle" in app._activity_btn.value def test_run_btn_initially_disabled(self): app = QuantUIApp() diff --git a/tests/test_uiaudit_design.py b/tests/test_uiaudit_design.py index 8bf35322..ee9f69ac 100644 --- a/tests/test_uiaudit_design.py +++ b/tests/test_uiaudit_design.py @@ -205,8 +205,12 @@ def test_report_issue_text_uses_theme_colours(self, app): class TestD15StatusChip: def test_idle_indicator_is_a_neutral_chip(self, app): + import ipywidgets as widgets + assert "quantui-status-chip" in app._activity_btn._dom_classes - assert app._activity_btn.button_style == "" + # UX-4: HTML, not a Button, so it is no Tab stop and not clickable. + assert isinstance(app._activity_btn, widgets.HTML) + assert not isinstance(app._activity_btn, widgets.Button) class TestD16Labels: diff --git a/tests/test_uxrev_run_feedback.py b/tests/test_uxrev_run_feedback.py new file mode 100644 index 00000000..25ededd2 --- /dev/null +++ b/tests/test_uxrev_run_feedback.py @@ -0,0 +1,407 @@ +"""M-UXREV UXR.1: run feedback and chemistry signals (UI/UX review 2026-12-05). + +- UX-1: Frequency's "Geometry optimization before calculation" is on by + default, remembered per calc type, and skipped when the geometry already is + a QuantUI optimization at the same level (DEC-035 item 1). +- UX-2: a result with a serious warning reads "completed with warnings" + (banner, log footer, status chip), and "Converged: Yes" is not green next to + a non-stationary result. +- UX-3: known solver warnings are summarised in plain language. +- UX-4: header chip and footer share one status source; the chip is HTML. +- UX-6: the run status line wraps. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace + +import ipywidgets as widgets +import pytest + +from quantui.app import QuantUIApp +from quantui.log_utils import ( + SEVERITY_NOTE, + SEVERITY_WARN, + collect_run_warnings, + format_log_footer, + has_serious_warnings, +) +from quantui.molecule import Molecule + +_WATER_ATOMS = ["O", "H", "H"] +_WATER_XYZ = [[0.0, 0.0, 0.1173], [0.0, 0.7572, -0.4692], [0.0, -0.7572, -0.4692]] + + +def _water() -> Molecule: + return Molecule(atoms=list(_WATER_ATOMS), coordinates=[r[:] for r in _WATER_XYZ]) + + +@pytest.fixture +def app(): + return QuantUIApp() + + +# ── UX-1: pre-optimization default ─────────────────────────────────────────── + + +class TestPreoptDefault: + def test_frequency_starts_ticked_single_point_does_not(self, app): + app.calc_type_dd.value = "Frequency" + assert app._freq_preopt_cb.value is True + app.calc_type_dd.value = "Single Point" + assert app._freq_preopt_cb.value is False + + def test_choice_is_remembered_per_calc_type(self, app): + app.calc_type_dd.value = "Frequency" + app._freq_preopt_cb.value = False + app.calc_type_dd.value = "Single Point" + app._freq_preopt_cb.value = True + app.calc_type_dd.value = "Frequency" + assert app._freq_preopt_cb.value is False + app.calc_type_dd.value = "Single Point" + assert app._freq_preopt_cb.value is True + + def test_hidden_types_do_not_overwrite_the_choice(self, app): + app.calc_type_dd.value = "Frequency" + app.calc_type_dd.value = "Geometry Opt" # hides + unticks the box + app.calc_type_dd.value = "Frequency" + assert app._freq_preopt_cb.value is True + + +def _write_opt_result( + base: Path, + name: str, + coords, + *, + method="RHF", + basis="STO-3G", + calc_type="geometry_opt", + converged=True, + solvent=None, + charge=0, + multiplicity=1, +): + d = base / name + d.mkdir(parents=True) + data = { + "calc_type": calc_type, + "formula": "H2O", + "method": method, + "basis": basis, + "converged": converged, + "solvent": solvent, + "timestamp": name, + "geometry": { + "atoms": list(_WATER_ATOMS), + "coordinates": coords, + "charge": charge, + "multiplicity": multiplicity, + }, + } + (d / "result.json").write_text(json.dumps(data)) + traj = { + "atoms": list(_WATER_ATOMS), + "charge": charge, + "multiplicity": multiplicity, + "steps": [ + {"coords": [[0.0, 0.0, 0.2], [0.0, 0.8, -0.5], [0.0, -0.8, -0.5]]}, + {"coords": coords}, + ], + } + (d / "trajectory.json").write_text(json.dumps(traj)) + return d + + +class TestSameLevelOptimization: + @pytest.fixture + def results(self, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + return tmp_path + + def _find(self, mol, **kw): + from quantui.app_runflow import find_same_level_optimization + + kw.setdefault("method", "RHF") + kw.setdefault("basis", "STO-3G") + return find_same_level_optimization(mol, **kw) + + def test_final_geometry_at_same_level_matches(self, results): + _write_opt_result(results, "2026-12-05_10-00-00-000001", _WATER_XYZ) + match = self._find(_water()) + assert match is not None + assert match["label"] == "Geometry Opt" + + def test_method_basis_case_does_not_matter(self, results): + _write_opt_result(results, "2026-12-05_10-00-00-000001", _WATER_XYZ) + assert self._find(_water(), method="rhf", basis="sto-3g") is not None + + @pytest.mark.parametrize( + "kw", + [ + {"basis": "6-31G"}, + {"method": "B3LYP"}, + {"solvent": "Water"}, + ], + ) + def test_different_level_does_not_match(self, results, kw): + _write_opt_result(results, "2026-12-05_10-00-00-000001", _WATER_XYZ) + assert self._find(_water(), **kw) is None + + def test_different_charge_or_multiplicity_does_not_match(self, results): + _write_opt_result( + results, "2026-12-05_10-00-00-000001", _WATER_XYZ, multiplicity=3 + ) + assert self._find(_water()) is None + + def test_unconverged_optimization_does_not_count(self, results): + _write_opt_result( + results, "2026-12-05_10-00-00-000001", _WATER_XYZ, converged=False + ) + assert self._find(_water()) is None + + def test_nearby_but_different_geometry_does_not_match(self, results): + # 0.02 Å off: well inside the seed list's 0.1 Å, but not "the same". + moved = [r[:] for r in _WATER_XYZ] + moved[1][1] += 0.035 + _write_opt_result(results, "2026-12-05_10-00-00-000001", moved) + assert self._find(_water()) is None + + def test_transition_state_result_counts(self, results): + _write_opt_result( + results, + "2026-12-05_10-00-00-000001", + _WATER_XYZ, + calc_type="transition_state", + ) + match = self._find(_water()) + assert match is not None and match["label"] == "Transition State" + + def test_single_point_result_does_not_count(self, results): + _write_opt_result( + results, "2026-12-05_10-00-00-000001", _WATER_XYZ, calc_type="single_point" + ) + assert self._find(_water()) is None + + +class _Log: + def __init__(self): + self.text = "" + + def write(self, t): + self.text += t + + +class TestSkipAtRunTime: + def _rc(self, preopt=True): + from quantui.app import _RunContext + + return _RunContext( + ct="Frequency", + mol=_water(), + calc_mol=_water(), + log=_Log(), + method="RHF", + basis="STO-3G", + solvent=None, + fmax=0.05, + max_steps=100, + preopt=preopt, + sigma=None, + ckpt=None, + resume=False, + required_single_point=lambda *a, **k: None, + ) + + def test_skips_and_says_so_in_the_log(self, app, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + _write_opt_result(tmp_path, "2026-12-05_10-00-00-000001", _WATER_XYZ) + rc = self._rc() + app._run_skip_preopt_if_already_optimized(rc) + assert rc.preopt is False + assert rc.preopt_skipped and "RHF/STO-3G" in rc.preopt_skipped + assert "skipped" in rc.log.text + assert "already optimized at the same level" in rc.log.text + + def test_keeps_preopt_without_a_match(self, app, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + rc = self._rc() + app._run_skip_preopt_if_already_optimized(rc) + assert rc.preopt is True + assert rc.log.text == "" + + def test_does_nothing_when_unticked(self, app, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + _write_opt_result(tmp_path, "2026-12-05_10-00-00-000001", _WATER_XYZ) + rc = self._rc(preopt=False) + app._run_skip_preopt_if_already_optimized(rc) + assert rc.preopt_skipped is None + + +# ── UX-2 / UX-3: warnings ──────────────────────────────────────────────────── + + +def _freq_result(max_force=None, n_imag=0, converged=True): + freqs = [-300.0] * n_imag + [1600.0, 3600.0, 3800.0] + return SimpleNamespace( + converged=converged, + n_iterations=6, + energy_hartree=-74.96, + homo_lumo_gap_ev=12.0, + zpve_hartree=0.02, + max_force_ev_per_ang=max_force, + n_imaginary_modes=lambda: sum(1 for f in freqs if f < 0), + ) + + +class TestRunWarnings: + def test_non_stationary_geometry_is_a_serious_warning(self): + warns = collect_run_warnings(_freq_result(max_force=3.14)) + assert has_serious_warnings(warns) + assert any("not a stationary point" in w.text for w in warns) + + def test_clean_result_has_no_warnings(self): + assert collect_run_warnings(_freq_result(max_force=0.001)) == [] + + def test_imaginary_modes_are_explained(self): + warns = collect_run_warnings(_freq_result(max_force=0.001, n_imag=1)) + assert any("1 imaginary frequency" in w.text for w in warns) + + def test_krylov_lines_become_one_plain_sentence(self): + log = ( + "WARN: Krylov solver reached subspace convergence but true residual " + "|aop(x)-b| = 1e-3 > tol\n" + "WARN: Krylov solver reached subspace convergence but true residual " + "|aop(x)-b| = 2e-3 > tol\n" + ) + warns = collect_run_warnings(_freq_result(max_force=0.001), log_text=log) + assert len(warns) == 1 + assert "Raman activities" in warns[0].text + assert "Krylov" not in warns[0].text + assert warns[0].severity == SEVERITY_WARN + + def test_unknown_warning_lines_stay_verbatim_as_notes(self): + warns = collect_run_warnings( + _freq_result(max_force=0.001), + log_text="UserWarning: Module polarizability is under testing\n", + ) + assert [w.severity for w in warns] == [SEVERITY_NOTE] + assert not has_serious_warnings(warns) + + def test_preopt_warning_is_carried(self): + warns = collect_run_warnings(None, extra=["The optimization failed."]) + assert warns[0].text == "The optimization failed." + + def test_footer_says_completed_with_warnings(self): + footer = format_log_footer( + result=_freq_result(max_force=3.14), + wall_time=2.0, + cpu_time=2.0, + success=True, + ) + assert "completed with warnings" in footer + assert "completed successfully" not in footer + assert "not a stationary point" in footer + + def test_footer_still_says_success_for_a_clean_run(self): + footer = format_log_footer( + result=_freq_result(max_force=0.001), + wall_time=2.0, + cpu_time=2.0, + success=True, + ) + assert "completed successfully" in footer + + def test_footer_lines_stay_within_the_banner_width(self): + footer = format_log_footer( + result=_freq_result(max_force=3.14, n_imag=2), + wall_time=2.0, + cpu_time=2.0, + success=True, + ) + assert max(len(line) for line in footer.splitlines()) <= 80 + + +class TestCompletionBanner: + def test_green_without_warnings(self, app): + from quantui.app_runflow import show_completion_banner + + show_completion_banner(app, "H2O RHF/STO-3G", []) + assert "Calculation complete" in app._completion_status_html.value + assert "is-warning" not in app._completion_banner._dom_classes + assert app._completion_note_html.layout.display == "none" + assert app._go_results_btn.button_style == "success" + + def test_amber_with_a_serious_warning(self, app): + from quantui.app_runflow import show_completion_banner + + warns = collect_run_warnings(_freq_result(max_force=3.14)) + show_completion_banner(app, "H2O RHF/STO-3G", warns) + assert "Completed with warnings" in app._completion_status_html.value + assert "is-warning" in app._completion_banner._dom_classes + assert "not a stationary point" in app._completion_note_html.value + assert app._go_results_btn.button_style == "warning" + # And back to green for the next clean run. + show_completion_banner(app, "H2O RHF/STO-3G", []) + assert "is-warning" not in app._completion_banner._dom_classes + + def test_label_is_escaped(self, app): + from quantui.app_runflow import show_completion_banner + + show_completion_banner(app, "x", []) + assert "x" not in app._completion_mol_lbl.value + + +class TestConvergedColour: + def test_converged_is_not_green_next_to_a_non_stationary_result(self): + from quantui import theme as _theme + from quantui.app_formatters import _converged_color + + assert _converged_color(True) == _theme.css.ACCENT_SUCCESS + assert _converged_color(True, usable=False) == _theme.css.TEXT_HEADING + assert _converged_color(False, usable=False) == _theme.css.ACCENT_ERROR_ALT + + +# ── UX-4: one status source ────────────────────────────────────────────────── + + +class TestStatusSource: + def test_chip_is_html_not_a_button(self, app): + assert isinstance(app._activity_btn, widgets.HTML) + + def test_chip_and_footer_agree_after_a_run_with_warnings(self, app): + from quantui.app_workspace import footer_html, job_state, refresh_status + + app._last_run_warnings = collect_run_warnings(_freq_result(max_force=3.14)) + app.step_progress.complete(2) + app.step_progress.complete(3) + refresh_status(app) + assert job_state(app) == ("warn", "Done — with warnings") + assert "Done — with warnings" in app._activity_btn.value + assert "Done — with warnings" in footer_html(app) + + def test_chip_says_done_not_idle_after_a_clean_run(self, app): + from quantui.app_workspace import refresh_status + + app._last_run_warnings = [] + app.step_progress.complete(2) + app.step_progress.complete(3) + refresh_status(app) + assert ">Done" in app._activity_btn.value + + def test_chip_follows_the_run_flag(self, app): + app.calc_type_dd.value = "Frequency" + app._calc_running = True + app._refresh_activity_indicator() + assert "Running Frequency" in app._activity_btn.value + + +# ── UX-6 ───────────────────────────────────────────────────────────────────── + + +def test_run_status_line_can_wrap(app): + from quantui.app import _APP_CSS + + assert "quantui-run-status" in app.run_status._dom_classes + assert ".quantui-run-status" in _APP_CSS From 03981e1ddd65cc5cfa9ff34e7f4cdd70b76d2ac2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:52:13 +0000 Subject: [PATCH 05/12] Run log: summary first, full log one click away, internal lines hidden MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M-UXREV UXR.2 (UI/UX review 2026-12-05, UX-5; DEC-035 item 3). - LiveLog gains a summary view: while a run streams, nothing changes; when it ends (done, failed or cancelled) _do_run calls show_summary(), which shows a short result summary (status, key numbers, plain-language warnings, time) in front of the log and folds the full log behind a "Show full log" button. The full log is repainted whole from Python's copy at that moment, so it is complete and in order when opened. A new run header or Clear returns to the live view. The log no longer ends on the ASCII banner. - Internal lines hidden from the on-screen log again: M-UIPOLISH L5 hid only "[checkpoint] saved"; the later "opened — " / "discarded" lines and PySCF's machine/version header and [CONFIG]/[INPUT] echo came back. A resumed run keeps its announcement, without the checkpoint path. The saved pyscf.log keeps every line. - Placeholder not glued to the first output: the placeholder is marked (data-qempty) in the container and in placeholder "set" messages, and the browser bridge clears it before the first append even if the clearing "set" never arrived. 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 | 11 +++ quantui/app.py | 66 ++++++++++++- quantui/app_runflow.py | 130 +++++++++++++++++++++++++ quantui/live_log.py | 105 ++++++++++++++++++-- tests/test_uxrev_run_log.py | 189 ++++++++++++++++++++++++++++++++++++ 5 files changed, 490 insertions(+), 11 deletions(-) create mode 100644 tests/test_uxrev_run_log.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 74e2a1fe..47bf7536 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,12 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht example the Krylov solver used for Raman activities) are summarised in one sentence that says what they mean for the numbers; the raw lines stay in the full log. +- **The run log ends on a summary.** While a calculation runs, its output + still streams live. When it finishes (or fails, or is cancelled), the log + area shows a short summary first: the result, the key numbers, any + warnings and the time. The complete output is one click away under + **Show full log**, and is still saved with the result. The log no longer + jumps back to the banner at the top when a run ends. - **One status for the header and the footer.** The status chip in the header and the workspace footer now show the same job state (Idle, Running…, Done, Done — with warnings, Failed); the chip no longer drops back @@ -37,6 +43,11 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht - The run status line next to Cancel wraps instead of being cut off at the panel edge. +- Internal lines are hidden from the on-screen run log again (checkpoint + bookkeeping such as "[checkpoint] opened — /root/…", PySCF's machine and + version header, and its [CONFIG]/[INPUT] echo); the saved log keeps them. +- The first run's output no longer starts glued to the "Output and any + errors appear here…" placeholder. ## [0.13.2] - 2026-12-05 diff --git a/quantui/app.py b/quantui/app.py index b0d46095..63ef5c6d 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -444,6 +444,9 @@ from quantui.app_runflow import ( show_completion_banner as _show_completion_banner, ) +from quantui.app_runflow import ( + show_run_summary as _show_run_summary, +) from quantui.app_runflow import ( update_estimate as _run_update_estimate, ) @@ -1151,9 +1154,28 @@ def _layout(**kwargs: Any) -> widgets.Layout: _RE_CONV = re.compile(r"converged SCF energy\s*=\s*([\-\d\.]+)") _RE_Q_STATUS = re.compile(r"\[QuantUI_STATUS\]\s*(.+)") # Internal bookkeeping lines hidden from the on-screen log (the saved -# pyscf.log keeps every line): checkpoint saves are noise to a student, and -# the status marker reads better as an arrow. -_RE_LOG_HIDDEN = re.compile(r"^\[checkpoint\] saved.*(?:\n|$)", re.MULTILINE) +# pyscf.log keeps every line): checkpoint bookkeeping, PySCF's machine/version +# header and its [CONFIG]/[INPUT] echo are noise to a student, and the status +# marker reads better as an arrow. M-UIPOLISH L5 hid only "[checkpoint] saved"; +# later checkpoint lines ("opened — /root/.quantui/...", "discarded") and the +# PySCF header came back (UI/UX review 2026-12-05, UX-5). +_RE_LOG_HIDDEN = re.compile( + r"^(?:" + r"\[checkpoint\] (?!RESUMED| ).*" # opened / saved / discarded + r"|\[CONFIG\].*" + r"|\[INPUT\].*" + r"|System: uname_result\(.*" + r"|Python \d+\.\d+\.\d+.*" + r"|numpy \d\S*\s+scipy .*" + r"|Date: \w{3} \w{3} .*" + r"|PySCF version .*" + r"|PySCF path .*" + r")(?:\n|$)", + re.MULTILINE, +) +# A resumed run keeps its announcement, without the checkpoint folder path. +_RE_LOG_RESUMED = re.compile(r"^\[checkpoint\] RESUMED from .*$", re.MULTILINE) +_RE_LOG_CKPT_DETAIL = re.compile(r"^\[checkpoint\] ( .*)$", re.MULTILINE) def _dependency_hint(platform: Optional[str] = None) -> str: @@ -1174,7 +1196,10 @@ def _dependency_hint(platform: Optional[str] = None) -> str: def _friendly_log_text(text: str) -> str: """Text as shown in the live log: internal markers hidden or softened.""" - return _RE_LOG_HIDDEN.sub("", text).replace("[QuantUI_STATUS] ", "→ ") + text = _RE_LOG_HIDDEN.sub("", text) + text = _RE_LOG_RESUMED.sub("→ Resumed from a saved checkpoint", text) + text = _RE_LOG_CKPT_DETAIL.sub(r"\1", text) + return text.replace("[QuantUI_STATUS] ", "→ ") # TD-DFT root convergence. PySCF's Davidson solver prints @@ -6886,6 +6911,11 @@ def _do_run(self) -> None: _run_fmax = self.fmax_fi.value _run_max_steps = self.max_steps_si.value _run_preopt = bool(self._freq_preopt_cb.value) + # Names the run in the after-run summary at the top of the log (UX-5). + _summary_label = ( + f"{mol.get_formula()} {_run_method}/{_run_basis} · " + f"{self.calc_type_dd.value}" + ) # Thermochemistry sigma override (audit SCF-4); 0 = detect it. _run_sigma = int(getattr(self._freq_sigma_si, "value", 0) or 0) or None self._activity_begin( @@ -7363,6 +7393,18 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = ( f"Finished in {_elapsed_total:.1f} s — NOT saved: {_save_error}" ) + # Summary first in the run log, full log one click away (UX-5). + _show_run_summary( + self, + status="done", + label=_summary_label, + result=result, + warnings=self._last_run_warnings, + elapsed_s=_elapsed_total, + detail=( + f"The result was NOT saved: {_save_error}" if _save_error else "" + ), + ) try: _tail_end = _tail_marks.get("success_done") @@ -7416,6 +7458,9 @@ def _run_required_final_single_point(target_mol, reason: str): ) self.result_output.append_display_data(HTML(_err_html)) self.run_status.value = "Dependency unavailable." + _show_run_summary( + self, status="failed", label=_summary_label, detail=_err_detail + ) self.step_progress.fail(2, _err_detail[:60]) _calc_log.log_event("calc_error", _err_detail[:200]) @@ -7441,6 +7486,12 @@ def _run_required_final_single_point(target_mol, reason: str): ) ) self.run_status.value = "Cancelled." + _show_run_summary( + self, + status="cancelled", + label=_summary_label, + elapsed_s=_elapsed, + ) try: self.step_progress.reset() except Exception: @@ -7520,6 +7571,13 @@ def _run_required_final_single_point(target_mol, reason: str): ) self.result_output.append_display_data(HTML(_err_html)) self.run_status.value = "Calculation failed." + _show_run_summary( + self, + status="failed", + label=_summary_label, + elapsed_s=_elapsed, + detail=str(exc), + ) self.step_progress.fail(2, str(exc)[:60]) _calc_log.log_event( "calc_error", str(exc)[:200], elapsed_s=round(_elapsed, 2) diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index 3cd34d0a..a6e39231 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -155,6 +155,136 @@ def show_completion_banner(app: Any, label: str, warnings: Any = ()) -> None: banner.layout.display = "" +def _fmt_seconds(seconds: float) -> str: + """``"54.2 s"`` under a minute, else ``"3:05"`` (m:ss) / ``"1:03:22"``.""" + if seconds < 60: + return f"{max(0.0, seconds):.1f} s" + from quantui.log_utils import format_elapsed + + return format_elapsed(float(seconds)) + + +def run_summary_html( + *, + status: str, + label: str, + result: Any = None, + warnings: Any = (), + elapsed_s: Optional[float] = None, + detail: str = "", +) -> str: + """The short summary shown first in the run log after a run (UX-5). + + *status* is ``"done"``, ``"failed"`` or ``"cancelled"``; *label* names the + calculation ("H2O RHF/STO-3G · Frequency"). For a finished run the key + numbers and the plain-language warnings follow; *detail* is the error + message of a failed run. The full log stays one click away. + """ + from quantui.log_utils import SEVERITY_WARN + + c = _theme.css + serious = [w for w in warnings or () if w.severity == SEVERITY_WARN] + notes = [w for w in warnings or () if w.severity != SEVERITY_WARN] + if status == "failed": + head, color = "✗ Calculation failed", c.ACCENT_ERROR + elif status == "cancelled": + head, color = "■ Calculation cancelled — nothing was saved", c.TEXT_BODY + elif serious: + head, color = "⚠ Completed with warnings", c.ACCENT_WARNING + else: + head, color = "✓ Calculation complete", c.ACCENT_SUCCESS + parts = [ + f'

' + f"{head}" + + ( + f' — ' + f"{html.escape(label)}" + if label + else "" + ) + + "
" + ] + rows: list = [] + if result is not None and status == "done": + energy = getattr(result, "energy_hartree", None) + if isinstance(energy, (int, float)): + rows.append( + ("Energy", f"{energy:.8f} Ha ({energy * 27.211386245988:.4f} eV)") + ) + gap = getattr(result, "homo_lumo_gap_ev", None) + if isinstance(gap, (int, float)): + rows.append(("HOMO–LUMO gap", f"{gap:.4f} eV")) + n_steps = getattr(result, "n_steps", None) + if isinstance(n_steps, int): + rows.append(("Optimization steps", str(n_steps))) + try: + n_imag = int(result.n_imaginary_modes()) + except (AttributeError, TypeError, ValueError): + n_imag = None + if n_imag is not None: + rows.append(("Imaginary modes", str(n_imag))) + converged = getattr(result, "converged", None) + if converged is not None: + rows.append(("Converged", "Yes" if converged else "No")) + if elapsed_s is not None: + rows.append(("Time", _fmt_seconds(elapsed_s))) + if rows: + parts.append( + '' + + "".join( + f'' + f'' + for k, v in rows + ) + + "
{k}{html.escape(v)}
" + ) + if detail: + parts.append( + f'
{html.escape(detail)}
' + ) + items = [ + f'
  • ' + f"{html.escape(w.text)}
  • " + for w in serious + ] + [ + f'
  • ' + f"{html.escape(w.text)}
  • " + for w in notes[:5] + ] + if items: + parts.append( + '
      ' + + "".join(items) + + "
    " + ) + parts.append( + f'
    ' + + ( + "Details are in the full log below." + if status != "done" + else "The full calculation output is below (Show full log) and is " + "saved with the result." + ) + + "
    " + ) + return ( + f'
    ' + "".join(parts) + "
    " + ) + + +def show_run_summary(app: Any, **kwargs: Any) -> None: + """Put the after-run summary in front of the run log (best effort).""" + show = getattr(getattr(app, "run_output", None), "show_summary", None) + if show is None: + return + try: + show(run_summary_html(**kwargs)) + except (AttributeError, TypeError, ValueError) as exc: + logger.warning("run summary failed: %s", exc) + + def _set_run_output(app: Any, outputs: tuple) -> None: """Atomically set ``run_output.outputs`` (fallback to clear_output).""" try: diff --git a/quantui/live_log.py b/quantui/live_log.py index b9629df6..bfdfe7aa 100644 --- a/quantui/live_log.py +++ b/quantui/live_log.py @@ -101,6 +101,9 @@ _PLACEHOLDER = "Output and any errors appear here when you run a calculation." +_TOGGLE_SHOW = "Show full log" +_TOGGLE_HIDE = "Hide full log" + def _bridge_js(log_cls: str, mail_cls: str) -> str: """JS installed once at render: mailbox mutations → log container. @@ -127,9 +130,20 @@ def _bridge_js(log_cls: str, mail_cls: str) -> str: var txt = node.textContent || ''; if (op === 'set') { box.textContent = txt; + // data-qempty marks the placeholder, so the first append replaces it + // even if the 'set' that should have cleared it never arrived. + if (node.getAttribute('data-qempty') === '1') { + box.setAttribute('data-qempty', '1'); + } else { + box.removeAttribute('data-qempty'); + } box.scrollTop = box.scrollHeight; return; } + if (box.getAttribute('data-qempty') === '1') { + box.textContent = ''; + box.removeAttribute('data-qempty'); + } // Append a text node: the existing DOM is untouched, so there is no // re-render and therefore no scrollTop reset. That is the whole fix. var atBottom = (box.scrollHeight - box.scrollTop - box.clientHeight) < 8; @@ -188,6 +202,12 @@ def _bridge_js(log_cls: str, mail_cls: str) -> str: class LiveLog(widgets.VBox): """An append-only, scroll-stable log surface. + During a run the log streams live. When the run ends the app calls + :meth:`show_summary`: a short result summary is shown first and the full + log folds away behind a "Show full log" button (UI/UX review 2026-12-05, + UX-5; DEC-035 item 3). Any new text set by :meth:`set_text` (the next + run's header, Clear) returns to the live view. + Parameters ---------- uid: @@ -200,8 +220,18 @@ def __init__(self, uid: str = "main", **kwargs: Any) -> None: self._mail_cls = f"{_MAIL_CLASS}-{uid}" self._container = widgets.HTML( - f'
    {_PLACEHOLDER}
    ' + f'
    {_PLACEHOLDER}
    ' ) + # Summary shown first after a run; the full log is one click away. + self._summary = widgets.HTML("", layout=widgets.Layout(display="none")) + self._full_toggle = widgets.Button( + description=_TOGGLE_SHOW, + icon="chevron-down", + tooltip="The complete calculation output (also saved with the result)", + layout=widgets.Layout(display="none", width="auto", margin="4px 0"), + ) + self._full_toggle.on_click(lambda _b: self.toggle_full_log()) # Transport. Setting .value is a traitlet sync over the widget comm — # thread-safe and independent of message parentage, which is exactly # what display() was not. Zero height so it never affects layout. @@ -225,7 +255,16 @@ def __init__(self, uid: str = "main", **kwargs: Any) -> None: self._posts = 0 self._post_errors = 0 - super().__init__([self._container, self._mailbox, self._bridge], **kwargs) + super().__init__( + [ + self._summary, + self._full_toggle, + self._container, + self._mailbox, + self._bridge, + ], + **kwargs, + ) self._install_bridge() # ── public state ──────────────────────────────────────────────────────── @@ -289,21 +328,72 @@ def outputs(self, value: tuple) -> None: ) self.set_text(text) + # ── summary view (UX-5) ───────────────────────────────────────────────── + + @property + def summary_showing(self) -> bool: + """True while the after-run summary is shown in place of the log.""" + return bool(self._summary.layout.display != "none") + + @property + def full_log_showing(self) -> bool: + return bool(self._container.layout.display != "none") + + def show_summary(self, html: str) -> None: + """Show *html* (the result summary) first; fold the full log away. + + The full log is repainted from :attr:`text` at the same time, so it is + complete and in order when opened, even if a streamed chunk was lost. + Safe to call from a background thread (traitlet updates only). + """ + self.flush() + self.resync() + self._summary.value = html + self._summary.layout.display = "" + self._full_toggle.description = _TOGGLE_SHOW + self._full_toggle.icon = "chevron-down" + self._full_toggle.layout.display = "" + self._container.layout.display = "none" + + def show_live(self) -> None: + """Back to the plain streaming log (summary and toggle hidden).""" + self._summary.layout.display = "none" + self._summary.value = "" + self._full_toggle.layout.display = "none" + self._container.layout.display = "" + + def toggle_full_log(self) -> None: + """Open or fold the full log under the summary.""" + if self.full_log_showing: + self._container.layout.display = "none" + self._full_toggle.description = _TOGGLE_SHOW + self._full_toggle.icon = "chevron-down" + else: + self._container.layout.display = "" + self._full_toggle.description = _TOGGLE_HIDE + self._full_toggle.icon = "chevron-up" + # ── core operations ───────────────────────────────────────────────────── def set_text(self, text: str) -> None: - """Replace the entire log body with *text* (empty → placeholder).""" + """Replace the entire log body with *text* (empty → placeholder). + + Also leaves the after-run summary: a new run header (or Clear) shows + the live log again. + """ with self._lock: self._cancel_timer_locked() self._pending = "" self._text = text self._placeholder_showing = not text - self._post("set", text if text else _PLACEHOLDER) + self._post("set", text if text else _PLACEHOLDER, empty=not text) + self.show_live() def resync(self) -> None: """Repaint the container from :attr:`text` after a frontend re-render.""" with self._lock: - self._post("set", (self._text + self._pending) or _PLACEHOLDER) + full = self._text + self._pending + self._post("set", full or _PLACEHOLDER, empty=not full) def flush(self) -> None: """Force any buffered text out immediately.""" @@ -342,7 +432,7 @@ def _flush(self) -> None: else: self._post("append", chunk) - def _post(self, op: str, payload: str) -> None: + def _post(self, op: str, payload: str, *, empty: bool = False) -> None: """Hand one chunk to the browser via the mailbox traitlet. NOT named ``_send``: that is ``widgets.Widget._send``, the comm @@ -355,8 +445,9 @@ def _post(self, op: str, payload: str) -> None: """ self._seq += 1 try: + empty_attr = ' data-qempty="1"' if empty else "" self._mailbox.value = ( - f'' + f'' f"{_html.escape(payload)}" ) self._posts += 1 diff --git a/tests/test_uxrev_run_log.py b/tests/test_uxrev_run_log.py new file mode 100644 index 00000000..9fa087c9 --- /dev/null +++ b/tests/test_uxrev_run_log.py @@ -0,0 +1,189 @@ +"""M-UXREV UXR.2: the run log after a run (UI/UX review 2026-12-05, UX-5). + +Summary first, the full log one click away, the live log still streaming +during the run; internal lines hidden again; the placeholder never glued to +the first run's output (DEC-035 item 3). +""" + +from __future__ import annotations + +import pytest + +from quantui.app import QuantUIApp, _friendly_log_text +from quantui.live_log import LiveLog, _bridge_js +from quantui.log_utils import RunWarning + + +class TestHiddenLines: + def test_checkpoint_bookkeeping_is_hidden(self): + text = ( + "[checkpoint] opened — /root/.quantui/checkpoints/abc\n" + "[checkpoint] saved — status=complete\n" + "[checkpoint] discarded\n" + "E=1\n" + ) + assert _friendly_log_text(text) == "E=1\n" + + def test_pyscf_machine_header_and_input_echo_are_hidden(self): + text = ( + "System: uname_result(system='Linux', node='vm') Threads 4\n" + "Python 3.11.18 (main, Oct 26 2026, 15:28:55) [GCC 13.3.0]\n" + "numpy 2.4.6 scipy 1.17.1 h5py 3.16.0\n" + "Date: Sat Dec 5 21:47:54 2026\n" + "PySCF version 2.15.1\n" + "PySCF path /opt/pyscf\n" + "[CONFIG] conf_file None\n" + "[INPUT] verbose = 4\n" + "[INPUT] 1 H 0.000000000000 0.000000000000 0.0 AA\n" + "nuclear repulsion = 0.715104339081081\n" + ) + assert _friendly_log_text(text) == "nuclear repulsion = 0.715104339081081\n" + + def test_resumed_run_is_announced_without_the_path(self): + text = ( + "[checkpoint] RESUMED from /root/.quantui/checkpoints/abc\n" + "[checkpoint] 3 of 24 displacements banked\n" + ) + shown = _friendly_log_text(text) + assert "Resumed from a saved checkpoint" in shown + assert "3 of 24 displacements banked" in shown + assert "/root" not in shown and "[checkpoint]" not in shown + + def test_ordinary_lines_are_untouched(self): + text = "converged SCF energy = -1.1\nPython is not mentioned here\n" + assert _friendly_log_text(text) == text + + +class TestSummaryView: + def test_live_log_by_default(self): + lg = LiveLog(uid="t1") + assert not lg.summary_showing + assert lg.full_log_showing + + def test_show_summary_folds_the_full_log_away(self): + lg = LiveLog(uid="t2") + lg.set_text("HEADER\n") + lg.append_stdout("scf output\n") + lg.show_summary("Calculation complete") + assert lg.summary_showing + assert not lg.full_log_showing + assert lg._full_toggle.layout.display == "" + assert lg._full_toggle.description == "Show full log" + assert "Calculation complete" in lg._summary.value + # The full log is complete (pending text flushed) and repainted whole. + assert lg.text == "HEADER\nscf output\n" + assert 'data-qop="set"' in lg._mailbox.value + assert "scf output" in lg._mailbox.value + + def test_toggle_opens_and_folds_the_full_log(self): + lg = LiveLog(uid="t3") + lg.set_text("x\n") + lg.show_summary("s") + lg.toggle_full_log() + assert lg.full_log_showing + assert lg._full_toggle.description == "Hide full log" + lg.toggle_full_log() + assert not lg.full_log_showing + + def test_toggle_button_click_works(self): + lg = LiveLog(uid="t4") + lg.set_text("x\n") + lg.show_summary("s") + lg._full_toggle.click() + assert lg.full_log_showing + + def test_next_run_header_returns_to_the_live_view(self): + lg = LiveLog(uid="t5") + lg.set_text("run 1\n") + lg.show_summary("s") + lg.outputs = ({"output_type": "stream", "name": "stdout", "text": "run 2\n"},) + assert not lg.summary_showing + assert lg.full_log_showing + assert lg._full_toggle.layout.display == "none" + + def test_clear_returns_to_the_placeholder(self): + lg = LiveLog(uid="t6") + lg.set_text("run\n") + lg.show_summary("s") + lg.clear_output() + assert not lg.summary_showing + assert lg.text == "" + + +class TestPlaceholderNotGlued: + def test_placeholder_is_marked_in_the_initial_html(self): + lg = LiveLog(uid="t7") + assert 'data-qempty="1"' in lg._container.value + + def test_placeholder_set_carries_the_marker(self): + lg = LiveLog(uid="t8") + lg.set_text("x\n") + assert "data-qempty" not in lg._mailbox.value + lg.set_text("") + assert 'data-qempty="1"' in lg._mailbox.value + + def test_bridge_clears_the_placeholder_before_the_first_append(self): + js = _bridge_js("log", "mail") + assert "data-qempty" in js + # The append branch checks the marker before appending. + append_at = js.index("box.appendChild(") + check_at = js.rindex("getAttribute('data-qempty') === '1'", 0, append_at) + assert check_at < append_at + + +class TestRunSummaryHtml: + def test_done_with_warnings(self): + from types import SimpleNamespace + + from quantui.app_runflow import run_summary_html + + result = SimpleNamespace( + energy_hartree=-74.96, homo_lumo_gap_ev=12.0, converged=True + ) + html = run_summary_html( + status="done", + label="H2O RHF/STO-3G · Frequency", + result=result, + warnings=[RunWarning("Not a stationary point.")], + elapsed_s=2.04, + ) + assert "Completed with warnings" in html + assert "-74.96000000 Ha" in html + assert "Not a stationary point." in html + assert "2.0 s" in html + assert "Show full log" in html + + def test_failed_shows_the_error(self): + from quantui.app_runflow import run_summary_html + + html = run_summary_html(status="failed", label="H2", detail="boom ") + assert "Calculation failed" in html + assert "boom <x>" in html + + def test_clean_run(self): + from quantui.app_runflow import run_summary_html + + html = run_summary_html(status="done", label="H2", warnings=[]) + assert "Calculation complete" in html + + +def test_real_run_ends_on_the_summary(tmp_path, monkeypatch): + pytest.importorskip("pyscf") + from quantui.molecule import Molecule + + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + app = QuantUIApp() + app._set_molecule(Molecule(atoms=["H", "H"], coordinates=[[0, 0, 0], [0, 0, 0.74]])) + app.method_dd.value = "RHF" + app.basis_dd.value = "STO-3G" + app.calc_type_dd.value = "Single Point" + app._do_run() + assert app.run_output.summary_showing + assert not app.run_output.full_log_showing + summary = app.run_output._summary.value + assert "Calculation complete" in summary + assert "H2" in summary + # The full log is still all there, minus the hidden internal lines. + assert "converged SCF energy" in app.run_output.text + assert "[checkpoint]" not in app.run_output.text + assert "[INPUT]" not in app.run_output.text From 11dbb8c276e092011e848c4a263c87efab0f6ae7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:01:46 +0000 Subject: [PATCH 06/12] =?UTF-8?q?Results,=20Compare=20and=20plots:=20empty?= =?UTF-8?q?=20states,=20readable=20XYZ=20errors,=20=CE=94E=20compare?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M-UXREV UXR.3 (UI/UX review 2026-12-05, UX-15/16/17/18/19/20; DEC-035 item 4). - UX-15: the Results tab opens with "No result yet ..." and buttons to Calculate and History; it hides when a result card is shown (observes result_output.outputs, refreshed on tab entry and run start, where it says a calculation is running). - UX-16: molecule.xyz_line_problems lists every bad line ("Line 5: 'Xx' is not an element symbol", wrong value counts, non-numbers, count-line mismatch, capitalisation hints). The XYZ message is an HTML row of its own (wraps, error colour, capped at 8 lines + "N more"). The atom table is greyed with a note while it does not match the text, and a successful Load fills it with the loaded molecule (up to 60 atoms; above that the note points to "Fill table from text"). - UX-17: Compare says what to do before any result is saved; the Compare button appears once two results are ticked (CheckList.on_change, observers wrapped in the app's _safe_cb), with a hint until then. - UX-18: any pair can be compared; an amber box warns when molecules (formula) or method/basis differ. Table gains "ΔE (kJ/mol)" relative to the first ticked result. Labels are "H2O · RHF/3-21G · 20:54" (seconds, the date or a counter only for repeats), not folder IDs; the table drops the Formula and Method/Basis columns the label already carries. The chart is a Plotly ΔE + gap figure in theme colours through plotly_embed.figure_html (DEC-010), redrawn on theme change; the matplotlib PNG is no longer used in-app (plot_comparison stays for library use). - UX-19: energy diagram fills the panel up to 900 px (width=None, autosize) and by default frames ±15 eV around the gap (frontier_window_ev; a subtitle counts levels outside it, or outside a hand-set Y range); "Show core orbitals" fits everything. Irreps in hover/labels are subscripted (test updated). - UX-20: plot_ir_spectrum(color=...) and the app passes the palette's info accent (>= 4.9:1 on every palette); axis padding is max(100 cm-1, 4 % of the span); axis options read "High/Low → low/high wavenumber". 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 | 22 ++ quantui/app.py | 21 ++ quantui/app_builders.py | 130 +++++++++- quantui/app_history.py | 4 + quantui/app_runflow.py | 151 ++++++++--- quantui/app_visualization.py | 33 ++- quantui/app_xyz_input.py | 163 ++++++++++-- quantui/checklist_widget.py | 24 +- quantui/comparison.py | 244 +++++++++++++++-- quantui/ir_plot.py | 19 +- quantui/molecule.py | 80 ++++++ quantui/orbital_visualization.py | 47 +++- tests/test_appui_audit_low.py | 4 +- tests/test_symmetry.py | 3 +- tests/test_uxrev_results_compare.py | 390 ++++++++++++++++++++++++++++ 15 files changed, 1232 insertions(+), 103 deletions(-) create mode 100644 tests/test_uxrev_results_compare.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 47bf7536..a1cf96ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,23 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht warnings and the time. The complete output is one click away under **Show full log**, and is still saved with the result. The log no longer jumps back to the banner at the top when a run ends. +- **Compare shows energy differences.** The chart and table now give ΔE in + kJ/mol relative to the first ticked result (plus the HOMO–LUMO gap), with + short labels such as "H2O · RHF/3-21G · 20:54" instead of result folder + names. Any results can still be compared, but an amber note says when + they are for different molecules or at different methods or basis sets, + whose total energies are not directly comparable. The chart follows the + theme. Before any calculation is saved, Compare says what to do, and the + Compare button appears once two results are ticked. +- **Results tab before the first result** explains what to do, with buttons + to the Calculate tab and to History, instead of a blank page. +- **Energy-level diagram:** fills the panel width (up to 900 px) and by + default frames ±15 eV around the HOMO–LUMO gap, so the frontier orbitals + are readable; the Y range fields or "Show core orbitals" show the rest. + Symmetry labels are subscripted (a₁, b₂). +- **IR spectrum:** the sticks use the theme's accent colour (the fixed blue + was hard to see on dark themes), the highest band no longer sits on the + plot edge, and the axis option reads "High → low wavenumber". - **One status for the header and the footer.** The status chip in the header and the workspace footer now show the same job state (Idle, Running…, Done, Done — with warnings, Failed); the chip no longer drops back @@ -48,6 +65,11 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht version header, and its [CONFIG]/[INPUT] echo); the saved log keeps them. - The first run's output no longer starts glued to the "Output and any errors appear here…" placeholder. +- Invalid XYZ input: the error now lists every bad line ("Line 5: 'Xx' is + not an element symbol"), wraps instead of running off the panel, and is + shown in the error colour; the atom table is greyed out with a note while + it does not match the text, and a successful load fills it with the loaded + molecule. ## [0.13.2] - 2026-12-05 diff --git a/quantui/app.py b/quantui/app.py index 63ef5c6d..40a8a12a 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -135,6 +135,9 @@ from quantui.app_builders import ( build_output_tab as _bld_build_output_tab, ) +from quantui.app_builders import ( + build_results_empty_state as _bld_build_results_empty_state, +) from quantui.app_builders import ( build_results_section as _bld_build_results_section, ) @@ -162,6 +165,9 @@ from quantui.app_builders import ( mol_input_children as _bld_mol_input_children, ) +from quantui.app_builders import ( + refresh_results_empty_state as _bld_refresh_results_empty_state, +) from quantui.app_exports import ( export_molecule_and_label as _exp_export_molecule_and_label, ) @@ -432,6 +438,9 @@ from quantui.app_runflow import ( refresh_ts_product_options as _run_refresh_ts_product_options, ) +from quantui.app_runflow import ( + rerender_compare_for_theme as _run_rerender_compare_for_theme, +) from quantui.app_runflow import ( resolve_seed_geometry as _run_resolve_seed_geometry, ) @@ -1055,6 +1064,10 @@ class carries a per-app uid suffix. LiveLog also sets the stack inline — this border-color: var(--q-accent-warning); background: var(--q-surface-warning-bg); } +/* XYZ atom table that does not match the text above it (UX-16). */ +.quantui-xyz-stale { + opacity: 0.45; +} /* The run status line wraps instead of being cut off at the panel edge (UX-6): long progress lines ("IR intensities: 9/24 ... remaining"). */ .quantui-run-status, @@ -2104,6 +2117,7 @@ class QuantUIApp: charge_mult_suggest_output: Any clear_btn: Any _completion_banner: Any + _results_empty_box: Any _completion_mol_lbl: Any comparison_output: Any export_btn: Any @@ -2601,6 +2615,8 @@ def _on_root_tab_changed(self, change) -> None: # the current folder. if self._is_tab(new, "files"): self._refresh_file_browser() + if self._is_tab(new, "results"): + _bld_refresh_results_empty_state(self) # The GPU badge is filled in by a background probe; when it finishes # before the browser's widgets connect (instantly, without gpu4pyscf) # the update is lost and the row says "checking…" forever. Re-send it. @@ -3123,6 +3139,9 @@ def _assemble_tabs(self) -> None: # in _build_compare_section. _rtp = list(self.results_tab_panel.children) _rtp.insert(_rtp.index(self._to_analysis_btn), self.advanced_accordion) + # Empty state first: the tab was blank but for Export (UX-15). + _bld_build_results_empty_state(self, layout_fn=_layout) + _rtp.insert(0, self._results_empty_box) self.results_tab_panel.children = tuple(_rtp) self._slurm_jobs_tab_index = None @@ -4486,6 +4505,8 @@ def _rerender_plotly_theme(self) -> None: _last_pes = getattr(self, "_last_pes_result", None) if _last_pes is not None: self._show_pes_scan_result(_last_pes) + # The Compare chart bakes the palette's colours in too (UX-18). + _run_rerender_compare_for_theme(self) # Re-render BOTH 3D molecule viewers so scene_bgcolor updates # immediately. This used to call _refresh_calc_mol_viewer directly, # which covered the Calculate tab only — the Analysis-tab viewer kept diff --git a/quantui/app_builders.py b/quantui/app_builders.py index c9c8f321..37001346 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -2191,7 +2191,9 @@ def build_molecule_section( app.xyz_btn = widgets.Button( description="Load XYZ", button_style="info", icon="upload" ) - app.xyz_msg = widgets.Label() + # HTML on its own row (not a Label beside the buttons): an error lists + # every bad line and must wrap, not run off the panel (UX-16). + app.xyz_msg = widgets.HTML(value="", layout=layout_fn(width="100%")) # File upload: the bytes travel over the widget # channel, so it works on a remote Voilà/OnDemand session too. @@ -2259,9 +2261,11 @@ def build_molecule_section( ), app.xyz_area, widgets.HBox( - [app.xyz_btn, app.xyz_cleanup_btn, app.xyz_msg], + [app.xyz_btn, app.xyz_cleanup_btn], layout=layout_fn(gap="8px", align_items="center", flex_wrap="wrap"), ), + app.xyz_msg, + app.xyz_table_note, app.xyz_table_header, app.xyz_table_box, widgets.HBox( @@ -2831,14 +2835,19 @@ def _plot_export_row(prefix: str) -> widgets.HBox: # saved in user settings. app._ir_axis_dd = widgets.Dropdown( options=[ - ("4000 → 400 cm⁻¹ (high → low)", "descending"), - ("400 → 4000 cm⁻¹ (low → high)", "ascending"), + # Direction only: the range always covers every computed mode, + # which can lie above 4000 cm⁻¹ (UX-20). + ("High → low wavenumber", "descending"), + ("Low → high wavenumber", "ascending"), ], value=_persisted_ir_axis(app), description="Axis:", style={"description_width": "40px"}, layout=layout_fn(width="270px", margin="0 8px 0 0"), - tooltip="Wavenumber direction for the IR and Raman plots; 4000 → 400 is the FTIR convention", + tooltip=( + "Wavenumber direction for the IR and Raman plots; high → low is " + "the FTIR convention" + ), ) # Line shape (Broadened only), frequency scale factor and y axis. @@ -4152,7 +4161,23 @@ def build_compare_section(app: Any, *, layout_fn: Any, rdkit_available: bool) -> from quantui.checklist_widget import CheckList # Checkboxes, not a Ctrl/Shift-click list box. - app.compare_select = CheckList(options=[("(no saved results)", "")]) + app.compare_select = CheckList( + options=[("(no saved results)", "")], + safe_cb=getattr(app, "_safe_cb", None), + ) + # Before any saved result: what to do, instead of an empty list and a + # Compare button (UX-17). After: a hint until two are ticked. + app._compare_empty_html = widgets.HTML( + f'

    ' + "No saved calculations yet. Run or load at least two calculations; " + "they appear here automatically.

    ", + layout=layout_fn(display="none"), + ) + app._compare_hint_html = widgets.HTML( + f'' + "Tick at least two results to compare them.", + layout=layout_fn(display="none"), + ) app.compare_refresh_btn = widgets.Button( description="Refresh", button_style="", @@ -4178,10 +4203,13 @@ def build_compare_section(app: Any, *, layout_fn: Any, rdkit_available: bool) -> [ widgets.HTML( f'

    ' - "Tick two or more saved calculations to compare them side by side.

    " + "Tick two or more saved calculations to compare them side by side. " + "Energies are shown relative to the first one ticked.

    " ), widgets.HBox([app.compare_refresh_btn]), + app._compare_empty_html, app.compare_select, + app._compare_hint_html, widgets.HBox( [app.compare_btn, app.compare_clear_btn], layout=layout_fn(gap="8px", margin="6px 0"), @@ -4244,6 +4272,10 @@ def build_compare_section(app: Any, *, layout_fn: Any, rdkit_available: bool) -> # Deferred to a background startup task (loads every saved result) — see # app._start_deferred_startup_tasks. Placeholder until then. app.compare_select.options = [("⏳ loading saved results…", "")] + from quantui.app_runflow import sync_compare_controls + + app.compare_select.on_change(lambda: sync_compare_controls(app)) + sync_compare_controls(app) def build_output_tab(app: Any, *, layout_fn: Any) -> None: @@ -4702,3 +4734,87 @@ def build_issue_widgets(app: Any, *, layout_fn: Any) -> None: ), ) app._issue_overlay.add_class("quantui-drawer") + + +# ── Results tab empty state (UX-15) ───────────────────────────────────────── + +_RESULTS_EMPTY_TEXT = ( + "No result yet. Load a molecule and press Run Calculation on the " + "Calculate tab, or open a past calculation from History." +) +_RESULTS_RUNNING_TEXT = ( + "A calculation is running. Its result appears here when it finishes." +) + + +def _results_empty_html(running: bool) -> str: + text = _RESULTS_RUNNING_TEXT if running else _RESULTS_EMPTY_TEXT + return ( + f'

    ' + f"{text}

    " + ) + + +def build_results_empty_state(app: Any, *, layout_fn: Any) -> None: + """The Results tab before any result: what to do, with two shortcuts. + + Before UX-15 the tab showed only the Export accordion. Visibility follows + the result card (``result_output``): see :func:`refresh_results_empty_state`. + """ + app._results_empty_html = widgets.HTML(_results_empty_html(running=False)) + app._results_empty_calc_btn = widgets.Button( + description="Go to Calculate", + icon="flask", + button_style="", + layout=layout_fn(width="auto"), + ) + app._results_empty_history_btn = widgets.Button( + description="Open History", + icon="history", + button_style="", + layout=layout_fn(width="auto"), + ) + app._results_empty_box = widgets.VBox( + [ + app._results_empty_html, + widgets.HBox( + [app._results_empty_calc_btn, app._results_empty_history_btn], + layout=layout_fn(gap="8px", flex_wrap="wrap"), + ), + ], + layout=layout_fn( + border=f"1px dashed {_theme.css.BORDER}", + border_radius="6px", + padding="12px 16px", + margin="0 0 12px", + ), + ) + app._results_empty_box.add_class("quantui-results-empty") + + def _to_tab(name: str) -> None: + app.root_tab.selected_index = app._tab_index(name) + + app._results_empty_calc_btn.on_click(lambda _b: _to_tab("calculate")) + app._results_empty_history_btn.on_click(lambda _b: _to_tab("history")) + safe = getattr(app, "_safe_cb", lambda f: f) + app.result_output.observe( + safe(lambda _ch: refresh_results_empty_state(app)), names="outputs" + ) + + +def refresh_results_empty_state(app: Any, *, has_card: Any = None) -> None: + """Show the empty state while the Results tab has no result card. + + *has_card* overrides the check of ``result_output.outputs`` (a cleared + Output only reports empty once the browser syncs it back). + """ + box = getattr(app, "_results_empty_box", None) + if box is None: + return + if has_card is None: + has_card = bool(getattr(app.result_output, "outputs", ())) + running = bool(getattr(app, "_calc_running", False)) + app._results_empty_html.value = _results_empty_html(running=running) + app._results_empty_calc_btn.layout.display = "none" if running else "" + app._results_empty_history_btn.layout.display = "none" if running else "" + box.layout.display = "none" if has_card else "" diff --git a/quantui/app_history.py b/quantui/app_history.py index 9b831a62..97004bd5 100644 --- a/quantui/app_history.py +++ b/quantui/app_history.py @@ -560,6 +560,10 @@ def history_load_results( with app.result_output: display(HTML(app._format_past_result(data, result_dir=result_dir))) app._result_dir_label.layout.display = "none" + # A card is shown: hide the "No result yet" state (UX-15). + _empty = getattr(app, "_results_empty_box", None) + if _empty is not None: + _empty.layout.display = "none" with timer.stage("mol_reconstruction"): mol = app._mol_from_result_dir(result_dir, data) if mol is not None: diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index a6e39231..f87bbc39 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -452,6 +452,10 @@ def on_run_clicked(app: Any, btn: Any) -> None: # 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() + from quantui.app_builders import refresh_results_empty_state + + # The card was just cleared: "A calculation is running…" until it lands. + refresh_results_empty_state(app, has_card=False) threading.Thread(target=app._run_in_thread, daemon=True).start() @@ -2286,22 +2290,46 @@ def on_compare_refresh(app: Any, btn: Any) -> None: app._populate_compare_list() +def _compare_warning_html(warnings: list) -> str: + """Amber box naming why the compared energies are not like with like.""" + if not warnings: + return "" + items = "".join(f'
  • {html.escape(w)}
  • ' for w in warnings) + return ( + f'
    ' + f'⚠ These results are ' + "not directly comparable" + f'
      {items}
    ' + ) + + def on_compare(app: Any, btn: Any, *, layout_fn: Any) -> None: - """Render selected saved results in the Compare tab.""" + """Render selected saved results in the Compare tab. + + Any selection is allowed, with an amber warning when the molecules or + levels of theory differ; energies are shown as ΔE in kJ/mol relative to + the first ticked result, with short labels instead of folder IDs, and the + chart follows the theme (UX-18; DEC-035 item 4). + """ from pathlib import Path selected = app.compare_select.value if not selected or selected == ("",): return app.compare_output.clear_output(wait=True) - from quantui import ( + from quantui import summary_from_saved_result + from quantui.comparison import ( + comparison_mismatches, comparison_table_html, - summary_from_saved_result, + unique_short_labels, ) from quantui.results_storage import load_result summaries = [] valid_dirs: list[Any] = [] + datas: list[dict] = [] for path_str in selected: if not path_str: continue @@ -2309,42 +2337,47 @@ def on_compare(app: Any, btn: Any, *, layout_fn: Any) -> None: data = load_result(Path(path_str)) summaries.append(summary_from_saved_result(data)) valid_dirs.append(Path(path_str)) + datas.append(data) except Exception as exc: with app.compare_output: display( HTML( - '

    Error loading result: ' + f'

    ' + "Error loading result: " f"{html.escape(str(exc))}

    " ) ) if not summaries: return + # Repeats of the same calculation get their date (and a counter) added. + for s_, lbl in zip(summaries, unique_short_labels(summaries)): + s_.label = lbl + app._compare_last_selection = tuple(selected) # λ comparison: screening candidates by reorganization energy is # the workflow this calculation type exists for, and a single λ is hard to # judge without others beside it. - _reorg_entries = [] - for d in valid_dirs: - try: - _rd = load_result(d) - if _rd.get("calc_type") == "reorganization_energy": - _reorg_entries.append((_rd.get("formula", d.name), _rd)) - except Exception: # noqa: BLE001 — already reported above - pass + _reorg_entries = [ + (d.get("formula", p.name), d) + for p, d in zip(valid_dirs, datas) + if d.get("calc_type") == "reorganization_energy" + ] with app.compare_output: - display(HTML(comparison_table_html(summaries))) + if len(summaries) > 1: + display(HTML(_compare_warning_html(comparison_mismatches(summaries)))) + display(HTML(comparison_table_html(summaries, reference_index=0))) if _reorg_entries: from quantui.app_formatters import reorg_comparison_html display(HTML(reorg_comparison_html(_reorg_entries))) if len(summaries) > 1: - _chart = _comparison_chart_html(summaries) + _chart = _comparison_chart_html(summaries, app=app) if _chart: display(HTML(_chart)) if valid_dirs: btns = [] for s, rdir in zip(summaries, valid_dirs): - short = f"{s.formula} {s.method}/{s.basis}" + short = s.label button = widgets.Button( description=f"→ Analyse {short}"[:48], button_style="info", @@ -2366,10 +2399,41 @@ def on_compare(app: Any, btn: Any, *, layout_fn: Any) -> None: display(widgets.VBox(btns, layout=layout_fn(gap="4px"))) +def rerender_compare_for_theme(app: Any) -> None: + """Redraw the last comparison so its chart takes the new theme colours.""" + last = getattr(app, "_compare_last_selection", None) + if not last or not getattr(app.compare_output, "outputs", ()): + return + if tuple(app.compare_select.value) != tuple(last): + return + app._on_compare(None) + + +def sync_compare_controls(app: Any) -> None: + """Empty state / "tick two" hint / Compare button, from the list (UX-17).""" + sel = getattr(app, "compare_select", None) + if sel is None: + return + has_results = any(val not in ("", None) for _lbl, val in sel.options) + loading = any("loading" in str(lbl) for lbl, _v in sel.options) + n = len(sel.value) + empty = getattr(app, "_compare_empty_html", None) + if empty is not None: + empty.layout.display = "none" if (has_results or loading) else "" + sel.layout.display = "" if (has_results or loading) else "none" + hint = getattr(app, "_compare_hint_html", None) + if hint is not None: + hint.layout.display = "" if has_results and n < 2 else "none" + app.compare_btn.layout.display = "" if n >= 2 else "none" + app.compare_clear_btn.layout.display = "" if n >= 1 else "none" + + def on_compare_clear(app: Any, btn: Any) -> None: """Clear Compare tab selection and output area.""" app.compare_select.value = () app.compare_output.clear_output() + app._compare_last_selection = None + sync_compare_controls(app) def on_past_refresh(app: Any, btn: Any) -> None: @@ -3569,34 +3633,39 @@ def refresh_results_browser(app: Any) -> None: app._refresh_freq_seed_options() -def _comparison_chart_html(summaries: Any) -> str: - """Render the comparison chart as an inline PNG ```` ("" on failure). +def _comparison_chart_html(summaries: Any, *, app: Any = None) -> str: + """The comparison chart as an in-app Plotly figure ("" on failure). - As a PNG: display(fig) printed "
    " under - Voila, where no inline backend is active. The figure is always closed so - repeated comparisons do not accumulate open matplotlib figures. + ΔE (kJ/mol) relative to the first result plus the HOMO–LUMO gap, in the + current theme's colours, rendered through ``plotly_embed.figure_html`` + (DEC-010). It replaced a white matplotlib PNG of absolute energies + (UX-18). """ try: - import base64 as _b64 - import io as _io - - import matplotlib.pyplot as plt - - from quantui import plot_comparison + from quantui.comparison import plot_comparison_plotly + from quantui.plotly_embed import figure_html - fig = plot_comparison(summaries) - try: - _buf = _io.BytesIO() - fig.savefig(_buf, format="png", dpi=100, bbox_inches="tight") - finally: - plt.close(fig) - _png = _b64.b64encode(_buf.getvalue()).decode("ascii") - except Exception: # noqa: BLE001 — chart is optional; the table is shown + palette_id = str( + getattr(getattr(app, "theme_btn", None), "value", "") or "Dark" + ) + palette = _theme.get_palette(palette_id) + tc = _theme.plotly_colors(palette_id) + fig = plot_comparison_plotly( + summaries, + reference_index=0, + bar_color=palette.accent_info, + gap_color=palette.accent_purple, + font_color=tc["font_color"], + grid_color=tc["grid_color"], + axis_color=tc["axis_line_color"], + ) + body = figure_html(fig, config={"displaylogo": False, "responsive": True}) + except Exception as exc: # noqa: BLE001 — chart is optional; the table is shown + logger.warning("comparison chart failed: %s", exc) return "" return ( - f'Comparison chart' + '
    {body}
    ' ) @@ -3609,9 +3678,9 @@ def refresh_comparison(app: Any) -> None: return summaries = [summary_from_session_result(r) for r in app._results] with app.comparison_output: - display(HTML(comparison_table_html(summaries))) + display(HTML(comparison_table_html(summaries, reference_index=0))) if len(summaries) > 1: - _chart = _comparison_chart_html(summaries) + _chart = _comparison_chart_html(summaries, app=app) if _chart: display(HTML(_chart)) @@ -3623,8 +3692,9 @@ def populate_compare_list(app: Any) -> None: dirs = list_results() if not dirs: - app.compare_select.options = [("(no saved results)", "")] + app.compare_select.options = [] app.compare_btn.disabled = True + sync_compare_controls(app) return options = [] for d in dirs: @@ -3642,3 +3712,4 @@ def populate_compare_list(app: Any) -> None: options.append((d.name, str(d))) app.compare_select.options = options app.compare_btn.disabled = False + sync_compare_controls(app) diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index 0737c1c4..8cd05662 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -905,6 +905,10 @@ def update_ir_figure(app: Any, mode: str, fwhm: float) -> None: descending=getattr(getattr(app, "_ir_axis_dd", None), "value", "descending") == "descending", labels=getattr(app, "_last_ir_labels", None), + # Theme accent, not a fixed blue (2.8:1 on Dark, UX-20). + color=_theme.get_palette( + str(getattr(getattr(app, "theme_btn", None), "value", "") or "Dark") + ).accent_info, ) app._apply_plotly_theme(fig) app._last_ir_fig = fig @@ -1899,6 +1903,7 @@ def show_orbital_diagram(app: Any, result: Any) -> bool: max_orbitals=app._orb_n_orb_input.value, font_scale=app._orb_font_scale_slider.value, show_core=_orb_show_core(app), + **_orb_view_kwargs(app), ) _sync_orb_range_inputs(app, fig) app._apply_plotly_theme(fig) @@ -2141,6 +2146,21 @@ def _orb_show_core(app: Any) -> bool: return bool(getattr(getattr(app, "_orb_show_core_cb", None), "value", False)) +def _orb_view_kwargs(app: Any) -> dict: + """Responsive width, and the frontier window for the automatic Y range. + + By default the diagram frames ±FRONTIER_WINDOW_EV around the HOMO–LUMO + gap so the frontier orbitals stay readable (UX-19); "Show core orbitals" + asks for everything, so it fits every level instead. + """ + from quantui.orbital_visualization import FRONTIER_WINDOW_EV + + return { + "width": None, + "frontier_window_ev": None if _orb_show_core(app) else FRONTIER_WINDOW_EV, + } + + def _sync_orb_range_inputs(app: Any, fig: Any) -> None: """Copy the figure's auto Y range into Y min/max without re-rendering.""" yr = fig.layout.yaxis.range @@ -2155,15 +2175,20 @@ def _sync_orb_range_inputs(app: Any, fig: Any) -> None: def _orb_screen_html(fig: Any) -> str: - """Energy diagram HTML for the panel (fixed width; the panel scrolls - sideways on a narrow window rather than clipping the levels).""" + """Energy diagram HTML for the panel: fills the panel up to 900 px (it + was a fixed 560 px inside a 1,370 px panel, UX-19), and never narrower + than 360 px (the panel scrolls sideways rather than clipping levels).""" html_str = _plotly_figure_html( fig, full_html=False, config={"responsive": True}, ) - return f'
    {html_str}
    ' + return ( + '
    ' + f'
    {html_str}
    ' + "
    " + ) def on_orb_show_core_changed(app: Any, _change: Any = None) -> None: @@ -2180,6 +2205,7 @@ def on_orb_show_core_changed(app: Any, _change: Any = None) -> None: max_orbitals=app._orb_n_orb_input.value, font_scale=app._orb_font_scale_slider.value, show_core=_orb_show_core(app), + **_orb_view_kwargs(app), ) _sync_orb_range_inputs(app, fig) app._apply_plotly_theme(fig) @@ -2208,6 +2234,7 @@ def on_orb_range_changed(app: Any, _change: Any = None) -> None: yrange=(ymin, ymax), font_scale=app._orb_font_scale_slider.value, show_core=_orb_show_core(app), + width=None, ) app._apply_plotly_theme(fig) app._last_orb_fig = fig diff --git a/quantui/app_xyz_input.py b/quantui/app_xyz_input.py index 2b200646..4fe7ab6e 100644 --- a/quantui/app_xyz_input.py +++ b/quantui/app_xyz_input.py @@ -3,6 +3,7 @@ from __future__ import annotations import html +import logging from typing import Any, List, Tuple import ipywidgets as widgets @@ -15,6 +16,8 @@ propose_xyz_cleanup, ) +logger = logging.getLogger(__name__) + # Atom-table column widths, shared by the header and every row. _SYM_W = "52px" _COORD_W = "92px" @@ -46,6 +49,8 @@ def _head(text: str, width: str) -> widgets.HTML: app.xyz_table_box = widgets.VBox( layout=layout_fn(gap="4px", width="440px"), ) + # Says when the table does not show what the text above holds (UX-16). + app.xyz_table_note = widgets.HTML(value="", layout=layout_fn(display="none")) app.xyz_add_atom_btn = widgets.Button( description="Add atom", icon="plus", @@ -152,6 +157,86 @@ def _remove(_btn: Any, *, _row=row_data, _box=row_box) -> None: remove_btn.on_click(_remove) +# Bad lines listed under the XYZ box; the rest are summarised as "N more". +_MAX_LISTED_PROBLEMS = 8 + +# Above this many atoms "Load XYZ" does not rebuild the atom table (five +# widgets per row); the note says so and "Fill table from text" does it. +_AUTO_TABLE_MAX_ATOMS = 60 + +_STALE_CLASS = "quantui-xyz-stale" + + +def set_xyz_msg(app: Any, text: str, kind: str = "info") -> None: + """Show *text* (plain, escaped here) under the XYZ buttons. + + ``kind="error"`` uses the error colour and an icon. + """ + if not text: + app.xyz_msg.value = "" + return + color = _theme.css.ACCENT_ERROR if kind == "error" else _theme.css.TEXT_BODY + icon = "⚠ " if kind == "error" else "" + app.xyz_msg.value = ( + f'
    {icon}{html.escape(text)}
    ' + ) + + +def xyz_error_html(text: str, exc: BaseException) -> str: + """The parse error for *text*: every bad line, wrapped, in the error colour. + + Falls back to the parser's own message when the problem is not about + individual lines (empty input, a multi-frame file). + """ + from quantui.molecule import xyz_line_problems + + problems = xyz_line_problems(text) + color = _theme.css.ACCENT_ERROR + if not problems: + return ( + f'
    ⚠ ' + f"{html.escape(str(exc).replace('❌ ', ''))}
    " + ) + shown = problems[:_MAX_LISTED_PROBLEMS] + more = len(problems) - len(shown) + items = "".join( + f'
  • {html.escape(p)}
  • ' for p in shown + ) + ( + f'
  • … and {more} more
  • ' + if more > 0 + else "" + ) + n = len(problems) + return ( + f'
    ⚠ The coordinates could not be read ' + f"({n} problem{'s' if n != 1 else ''}):" + f'
      {items}
    ' + f'' + "Each line needs an element symbol and x, y, z in Å, for example:" + f'
    ' + "H 0.000 0.757 0.587
    " + ) + + +def mark_table_stale(app: Any, reason: str) -> None: + """Dim the atom table and say why it differs from the text above.""" + app.xyz_table_box.add_class(_STALE_CLASS) + app.xyz_table_note.value = ( + f'' + f"{html.escape(reason)}" + ) + app.xyz_table_note.layout.display = "" + + +def mark_table_current(app: Any) -> None: + app.xyz_table_box.remove_class(_STALE_CLASS) + app.xyz_table_note.value = "" + app.xyz_table_note.layout.display = "none" + + def on_xyz_add_atom(app: Any, _btn: Any = None) -> None: _add_xyz_table_row(app, app._layout_fn) @@ -186,32 +271,38 @@ def sync_table_from_textarea(app: Any, *, layout_fn: Any) -> None: def on_xyz_apply_table(app: Any, _btn: Any = None) -> None: try: sync_textarea_from_table(app) - app.xyz_msg.value = "Updated coordinate text from the atom table." + mark_table_current(app) + set_xyz_msg(app, "Updated coordinate text from the atom table.") except Exception as exc: - app.xyz_msg.value = f"Table error: {exc}" + set_xyz_msg(app, f"Table error: {exc}", "error") def on_xyz_fill_table(app: Any, _btn: Any = None) -> None: + text = app.xyz_area.value.strip() try: sync_table_from_textarea(app, layout_fn=app._layout_fn) - app.xyz_msg.value = "Filled atom table from coordinate text." + mark_table_current(app) + set_xyz_msg(app, "Filled atom table from coordinate text.") except Exception as exc: - app.xyz_msg.value = f"Parse error: {exc}" + app.xyz_msg.value = xyz_error_html(text, exc) + mark_table_stale( + app, "The atom table was not updated: the text above has errors." + ) def on_xyz_cleanup(app: Any, _btn: Any = None) -> None: text = app.xyz_area.value.strip() if not text: - app.xyz_msg.value = "Paste or enter coordinates before cleaning up." + set_xyz_msg(app, "Paste or enter coordinates before cleaning up.") return try: cleaned, notes = propose_xyz_cleanup(text) except Exception as exc: - app.xyz_msg.value = f"Cleanup error: {exc}" + set_xyz_msg(app, f"Cleanup error: {exc}", "error") return if cleaned.strip() == text.strip(): - app.xyz_msg.value = "Coordinates are already in standard format." + set_xyz_msg(app, "Coordinates are already in standard format.") app.xyz_cleanup_preview_box.layout.display = "none" return @@ -222,29 +313,30 @@ def on_xyz_cleanup(app: Any, _btn: Any = None) -> None: ) app.xyz_cleanup_preview.value = cleaned app.xyz_cleanup_preview_box.layout.display = "" - app.xyz_msg.value = "Review the proposed cleanup, then accept or reject." + set_xyz_msg(app, "Review the proposed cleanup, then accept or reject.") def on_xyz_cleanup_accept(app: Any, _btn: Any = None) -> None: app.xyz_area.value = app.xyz_cleanup_preview.value app.xyz_cleanup_preview_box.layout.display = "none" - app.xyz_msg.value = "Accepted cleanup — coordinate text updated." + set_xyz_msg(app, "Accepted cleanup — coordinate text updated.") try: sync_table_from_textarea(app, layout_fn=app._layout_fn) + mark_table_current(app) except Exception: pass def on_xyz_cleanup_reject(app: Any, _btn: Any = None) -> None: app.xyz_cleanup_preview_box.layout.display = "none" - app.xyz_msg.value = "Cleanup rejected — original text unchanged." + set_xyz_msg(app, "Cleanup rejected — original text unchanged.") def on_load_xyz(app: Any, _btn: Any = None) -> None: """Load geometry from the textarea using calc-setup charge/multiplicity.""" text = app.xyz_area.value.strip() if not text: - app.xyz_msg.value = "Enter or paste coordinates first." + set_xyz_msg(app, "Enter or paste coordinates first.") return try: mol, spin_note = load_molecule_from_xyz_text( @@ -252,22 +344,41 @@ def on_load_xyz(app: Any, _btn: Any = None) -> None: charge=int(app.charge_si.value), multiplicity=int(app.mult_si.value), ) - app._set_molecule( - mol, - "Loaded from XYZ input", - sync_charge_mult=False, - ) - if spin_note: - app.xyz_msg.value = ( - f"Loaded {mol.get_formula()}. Note: {spin_note} " - "Adjust charge or multiplicity in Calculation Setup before running." - ) - else: - app.xyz_msg.value = f"Loaded {mol.get_formula()} ({len(mol.atoms)} atoms)." - if has_isotope_labels(text): - app.xyz_msg.value += f" {ISOTOPE_NOTE}" except Exception as exc: - app.xyz_msg.value = f"Parse error: {exc}" + app.xyz_msg.value = xyz_error_html(text, exc) + mark_table_stale( + app, + "The atom table below was not updated: the text above has errors.", + ) + return + app._set_molecule( + mol, + "Loaded from XYZ input", + sync_charge_mult=False, + ) + if spin_note: + msg = ( + f"Loaded {mol.get_formula()}. Note: {spin_note} " + "Adjust charge or multiplicity in Calculation Setup before running." + ) + else: + msg = f"Loaded {mol.get_formula()} ({len(mol.atoms)} atoms)." + if has_isotope_labels(text): + msg += f" {ISOTOPE_NOTE}" + set_xyz_msg(app, msg) + # The table shows what was just loaded, not the previous structure. + if len(mol.atoms) <= _AUTO_TABLE_MAX_ATOMS: + try: + sync_table_from_textarea(app, layout_fn=app._layout_fn) + mark_table_current(app) + except ValueError as exc: + logger.debug("atom table sync after load failed: %s", exc) + else: + mark_table_stale( + app, + f"The atom table is not filled automatically for {len(mol.atoms)} " + "atoms; press Fill table from text to edit them here.", + ) def load_structure_bytes(app: Any, filename: str, content: bytes) -> str: diff --git a/quantui/checklist_widget.py b/quantui/checklist_widget.py index b96ad895..0d379f0c 100644 --- a/quantui/checklist_widget.py +++ b/quantui/checklist_widget.py @@ -9,7 +9,7 @@ from __future__ import annotations import html -from typing import Any, List, Sequence, Tuple +from typing import Any, Callable, List, Optional, Sequence, Tuple import ipywidgets as widgets @@ -17,7 +17,13 @@ class CheckList(widgets.VBox): """Checkboxes for ``(label, value)`` options; empty values are notes.""" - def __init__(self, options: Sequence[Tuple[str, Any]] = (), **kwargs: Any) -> None: + def __init__( + self, + options: Sequence[Tuple[str, Any]] = (), + *, + safe_cb: Optional[Callable[[Callable], Callable]] = None, + **kwargs: Any, + ) -> None: kwargs.setdefault( "layout", widgets.Layout(max_height="260px", overflow_y="auto", width="100%"), @@ -25,8 +31,20 @@ def __init__(self, options: Sequence[Tuple[str, Any]] = (), **kwargs: Any) -> No super().__init__(**kwargs) self._options: List[Tuple[str, Any]] = [] self._boxes: List[Tuple[widgets.Checkbox, Any]] = [] + self._listeners: List[Callable[[], None]] = [] + # The app's exception-logging wrapper for the checkbox observers + # (an exception in a raw .observe handler vanishes in Voilà). + self._safe_cb = safe_cb or (lambda f: f) self.options = list(options) + def on_change(self, callback: Callable[[], None]) -> None: + """Call *callback* (no arguments) whenever a box is ticked or unticked.""" + self._listeners.append(callback) + + def _fire(self, _change: Any = None) -> None: + for cb in list(self._listeners): + cb() + @property def options(self) -> List[Tuple[str, Any]]: return list(self._options) @@ -46,9 +64,11 @@ def options(self, options: Sequence[Tuple[str, Any]]) -> None: indent=False, layout=widgets.Layout(width="auto", margin="0"), ) + box.observe(self._safe_cb(self._fire), names="value") self._boxes.append((box, value)) rows.append(box) self.children = tuple(rows) + self._fire() @property def value(self) -> Tuple[Any, ...]: diff --git a/quantui/comparison.py b/quantui/comparison.py index 43ee9b50..e1138c6c 100644 --- a/quantui/comparison.py +++ b/quantui/comparison.py @@ -22,7 +22,7 @@ import numpy as np -from .config import HARTREE_TO_EV +from .config import HARTREE_TO_EV, HARTREE_TO_KJ_MOL logger = logging.getLogger(__name__) @@ -50,6 +50,7 @@ class CalcSummary: converged: Optional[bool] = None n_iterations: Optional[int] = None status: str = "" + timestamp: str = "" @property def energy_ev(self) -> Optional[float]: @@ -140,10 +141,9 @@ def summary_from_saved_result(data: dict, *, label: str = "") -> CalcSummary: formula = data.get("formula", "?") method = data.get("method", "?") basis = data.get("basis", "?") - ts = data.get("timestamp", "") - auto_label = f"{formula} {method}/{basis}" + (f" ({ts})" if ts else "") + ts = str(data.get("timestamp", "") or "") return CalcSummary( - label=label or auto_label, + label=label or short_label(formula, method, basis, ts), formula=formula, method=method, basis=basis, @@ -152,37 +152,159 @@ def summary_from_saved_result(data: dict, *, label: str = "") -> CalcSummary: converged=data.get("converged"), n_iterations=data.get("n_iterations"), status="COMPLETED", + timestamp=ts, ) +# ============================================================================ +# Labels, ΔE and mismatch warnings (UI/UX review 2026-12-05, UX-18) +# ============================================================================ + + +def _time_parts(timestamp: str) -> Tuple[str, str, str]: + """``("2026-12-05", "20:54", "20:54:01")`` from a result timestamp.""" + from datetime import datetime + + text = str(timestamp or "") + for fmt in ("%Y-%m-%d_%H-%M-%S-%f", "%Y-%m-%d_%H-%M-%S", "%Y-%m-%dT%H:%M:%S"): + try: + dt = datetime.strptime(text[:26], fmt) + except ValueError: + continue + return dt.strftime("%Y-%m-%d"), dt.strftime("%H:%M"), dt.strftime("%H:%M:%S") + return "", "", "" + + +def short_label( + formula: str, + method: str, + basis: str, + timestamp: str = "", + *, + precision: str = "minute", +) -> str: + """``"H2O · RHF/3-21G · 20:54"``: what a student reads, not a folder ID. + + *precision* ``"second"`` gives ``20:54:01``; ``"date"`` gives + ``2026-12-05 20:54``. + """ + day, hm, hms = _time_parts(timestamp) + when = {"second": hms, "date": f"{day} {hm}" if day else ""}.get(precision, hm) + return f"{formula} · {method}/{basis}" + (f" · {when}" if when else "") + + +def unique_short_labels(summaries: Sequence[CalcSummary]) -> List[str]: + """Short labels for *summaries*; only where two would read the same, the + seconds (same day) or the date are added, then a counter.""" + + def labels(precision: str) -> List[str]: + return [ + short_label(s.formula, s.method, s.basis, s.timestamp, precision=precision) + for s in summaries + ] + + out = labels("minute") + days = {_time_parts(s.timestamp)[0] for s in summaries} + finer = labels("second" if len(days) <= 1 else "date") + out = [f if out.count(o) > 1 else o for o, f in zip(out, finer)] + base = list(out) + seen: dict = {} + for i, lbl in enumerate(base): + if base.count(lbl) > 1: + seen[lbl] = seen.get(lbl, 0) + 1 + out[i] = f"{lbl} ({seen[lbl]})" + return out + + +def relative_energies_kj( + summaries: Sequence[CalcSummary], reference_index: int = 0 +) -> List[Optional[float]]: + """ΔE in kJ/mol relative to ``summaries[reference_index]`` (None if missing).""" + if not summaries: + return [] + ref = summaries[reference_index].energy_hartree + return [ + ( + None + if ref is None or s.energy_hartree is None + else (s.energy_hartree - ref) * HARTREE_TO_KJ_MOL + ) + for s in summaries + ] + + +def comparison_mismatches(summaries: Sequence[CalcSummary]) -> List[str]: + """Plain warnings when the compared results are not like with like. + + Total energies are only directly comparable for the same molecule + (formula) at the same method and basis set. + """ + out: List[str] = [] + formulas = sorted({s.formula for s in summaries}) + levels = sorted({f"{s.method}/{s.basis}" for s in summaries}) + if len(formulas) > 1: + out.append( + f"Different molecules ({', '.join(formulas)}): their total energies " + "are not comparable. A reaction energy needs balanced reactants and " + "products — use Reaction energy below." + ) + if len(levels) > 1: + out.append( + f"Different levels of theory ({', '.join(levels)}): total energies " + "from different methods or basis sets are not directly comparable. " + "Compare energy differences computed at one level instead." + ) + return out + + # ============================================================================ # HTML comparison table # ============================================================================ -def comparison_table_html(summaries: Sequence[CalcSummary]) -> str: +def comparison_table_html( + summaries: Sequence[CalcSummary], *, reference_index: Optional[int] = None +) -> str: """ Return an HTML ```` comparing calculation summaries. - Suitable for ``IPython.display.HTML``. + With *reference_index*, a "ΔE (kJ/mol)" column gives each energy relative + to that row. Suitable for ``IPython.display.HTML``. """ if not summaries: return "

    No calculations to compare.

    " + show_de = reference_index is not None and len(summaries) > 1 + rel = relative_energies_kj(summaries, reference_index or 0) if show_de else [] header = ( "" - "" - "" - "" + "" "" - "" + + ( + "" + if show_de + else "" + ) + + "" "" "" "" ) rows: List[str] = [] - for s in summaries: + for k, s in enumerate(summaries): + de_cell = "" + if show_de: + if k == reference_index: + de_txt = "0 (reference)" + elif rel[k] is None: + de_txt = "—" + else: + de_txt = f"{rel[k]:+.2f}" + de_cell = ( + "" + ) e_str = f"{s.energy_hartree:.8f}" if s.energy_hartree is not None else "—" g_str = f"{s.homo_lumo_gap_ev:.4f}" if s.homo_lumo_gap_ev is not None else "—" c_str = "✅" if s.converged else ("❌" if s.converged is not None else "—") @@ -193,10 +315,13 @@ def comparison_table_html(summaries: Sequence[CalcSummary]) -> str: # on every other row in Dark theme. f"" - f"" - f"" - f"" + # The label names formula, method/basis and time ("H2O · + # RHF/3-21G · 20:54"): one line (table-layout:auto below, as + # Jupyter's table CSS is fixed-layout). + "" f"" + f"{de_cell}" f"" f"" f"" @@ -205,7 +330,8 @@ def comparison_table_html(summaries: Sequence[CalcSummary]) -> str: return ( '
    ' - '
    LabelFormulaMethod / BasisResultEnergy (Ha)HOMO–LUMO gap (eV)ΔE (kJ/mol)HOMO–LUMO gap (eV)ConvergedIterations
    {de_txt}
    {_esc(s.label)}{_esc(s.formula)}{_esc(s.method)} / {_esc(s.basis)}" + f"{_esc(s.label)}{e_str}{g_str}{c_str}{i_str}
    ' + '
    ' "{header}" f"{''.join(rows)}" @@ -306,3 +432,91 @@ def plot_comparison( fig.suptitle(title or "Calculation Comparison", fontsize=14, fontweight="bold") fig.tight_layout() return fig + + +# ============================================================================ +# Plotly comparison chart (in-app; themed by the caller's colours) +# ============================================================================ + + +def plot_comparison_plotly( + summaries: Sequence[CalcSummary], + *, + reference_index: int = 0, + bar_color: str = "#2563eb", + gap_color: str = "#7c3aed", + font_color: Optional[str] = None, + grid_color: Optional[str] = None, + axis_color: Optional[str] = None, +): + """ΔE (kJ/mol, vs ``summaries[reference_index]``) and HOMO–LUMO gap bars. + + Total energies of a few hundred Hartree differ in the third decimal, so + bars of absolute energies all look the same height (UX-18): relative + energies in kJ/mol are what a student can read and compare. Bar labels are + the summaries' short labels. Colours come from the caller (the app passes + theme colours); the defaults suit a light page. + """ + import plotly.graph_objects as go + from plotly.subplots import make_subplots + + labels = [s.label for s in summaries] + rel = relative_energies_kj(summaries, reference_index) + gaps = [s.homo_lumo_gap_ev for s in summaries] + has_e = any(v is not None for v in rel) + has_gap = any(g is not None for g in gaps) + panels = [p for p, ok in (("e", has_e), ("gap", has_gap)) if ok] + ref_label = labels[reference_index] if labels else "" + titles = { + "e": f"ΔE vs {ref_label} (kJ/mol)", + "gap": "HOMO–LUMO gap (eV)", + } + fig = make_subplots( + rows=1, + cols=max(1, len(panels)), + subplot_titles=[titles[p] for p in panels] or ["No energies to compare"], + horizontal_spacing=0.12, + ) + for col, panel in enumerate(panels, start=1): + if panel == "e": + ys = [v if v is not None else 0.0 for v in rel] + text = [f"{v:+.2f}" if v is not None else "n/a" for v in rel] + color = bar_color + hover = "%{x}
    ΔE = %{y:+.2f} kJ/mol" + else: + ys = [g if g is not None else 0.0 for g in gaps] + text = [f"{g:.2f}" if g is not None else "n/a" for g in gaps] + color = gap_color + hover = "%{x}
    gap = %{y:.3f} eV" + fig.add_trace( + go.Bar( + x=labels, + y=ys, + text=text, + textposition="outside", + cliponaxis=False, + marker_color=color, + hovertemplate=hover, + showlegend=False, + ), + row=1, + col=col, + ) + fig.update_layout( + height=360, + margin=dict(l=60, r=20, t=50, b=90), + plot_bgcolor="rgba(0,0,0,0)", + paper_bgcolor="rgba(0,0,0,0)", + bargap=0.35, + ) + if font_color: + fig.update_layout(font=dict(color=font_color)) + fig.update_annotations(font=dict(color=font_color)) + axis = {} + if grid_color: + axis["gridcolor"] = grid_color + if axis_color: + axis.update(linecolor=axis_color, zerolinecolor=axis_color) + fig.update_xaxes(tickangle=-20, automargin=True, **axis) + fig.update_yaxes(automargin=True, zeroline=True, **axis) + return fig diff --git a/quantui/ir_plot.py b/quantui/ir_plot.py index 225c27b3..8452a31b 100644 --- a/quantui/ir_plot.py +++ b/quantui/ir_plot.py @@ -79,10 +79,15 @@ def _default_xrange(freqs_real: tuple) -> List[float]: """ if not freqs_real: return [float(_DEFAULT_XRANGE[0]), float(_DEFAULT_XRANGE[1])] - margin = 100.0 + # At least 100 cm⁻¹, or 4 % of the span: a 4788 cm⁻¹ stick 100 cm⁻¹ from + # the edge of a 4500 cm⁻¹ axis still sat on the frame (UX-20). + span = max(_DEFAULT_XRANGE[1], max(freqs_real)) - min( + _DEFAULT_XRANGE[0], min(freqs_real) + ) + margin = max(100.0, 0.04 * span) lo = min(_DEFAULT_XRANGE[0], min(freqs_real) - margin) hi = max(_DEFAULT_XRANGE[1], max(freqs_real) + margin) - return [float(lo), float(hi)] + return [float(max(0.0, lo)), float(hi)] def _grid_for_range(xrange: List[float]) -> np.ndarray: @@ -190,6 +195,7 @@ def plot_ir_spectrum( scale_factor: float = 1.0, lineshape: str = "lorentzian", yaxis_mode: str = "intensity", + color: str = "#2563eb", ) -> go.Figure: """Return a Plotly figure for the IR absorption spectrum. @@ -214,6 +220,9 @@ def plot_ir_spectrum( and height normalization (see the module docstring). yaxis_mode: ``"intensity"`` (default, km/mol) or ``"transmittance"`` (%T, bands pointing down). + color: Line, stick and marker colour. The app passes the theme's + info accent so the spectrum reads on every palette (UX-20); the + default suits a white page. Returns: :class:`plotly.graph_objects.Figure` ready for display or wrapping @@ -288,7 +297,7 @@ def plot_ir_spectrum( x=_xgrid, y=y_plot, mode="lines", - line=dict(color="#2563eb", width=1.5), + line=dict(color=color, width=1.5), name="IR (broadened)", hovertemplate=hover, ) @@ -311,7 +320,7 @@ def plot_ir_spectrum( x=x_stick, y=y_stick, mode="lines", - line=dict(color="#2563eb", width=2), + line=dict(color=color, width=2), name="IR (stick)", hoverinfo="skip", ) @@ -338,7 +347,7 @@ def plot_ir_spectrum( x=list(freqs_real), y=tips, mode="markers", - marker=dict(color="#1d4ed8", size=6), + marker=dict(color=color, size=6), name="IR (peaks)", showlegend=False, customdata=extra, diff --git a/quantui/molecule.py b/quantui/molecule.py index 7c653c0a..a68444e4 100644 --- a/quantui/molecule.py +++ b/quantui/molecule.py @@ -672,6 +672,86 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: return atoms, coordinates +def _symbol_hint(symbol: str) -> str: + """ " — did you mean 'Cl'?" for a mis-capitalised symbol, else "".""" + for guess in (symbol.capitalize(), symbol.upper()): + if guess != symbol and guess in config.VALID_ATOMS: + return f" — did you mean '{guess}'?" + return "" + + +def xyz_line_problems(xyz_text: str) -> List[str]: + """Every problem in *xyz_text*, one short sentence per bad line. + + :func:`parse_xyz_input` stops at the first error; this lists them all + (UI/UX review 2026-12-05, UX-16), with the same header handling (count + line, optional title, comments). Returns ``[]`` when every atom line + reads, or when the problem is not about individual lines (empty input, + a multi-frame file) — :func:`parse_xyz_input` explains those. + """ + if not xyz_text or not xyz_text.strip(): + return [] + lines = normalize_xyz_text(xyz_text).strip().split("\n") + expected = None + body_start = 0 + for idx, raw in enumerate(lines): + stripped = raw.strip() + if not stripped or stripped.startswith(("#", "!")): + continue + try: + expected = int(stripped) + except ValueError: + break + body_start = idx + 2 if _has_title_line(lines, idx, expected) else idx + 1 + if _count_xyz_frames(lines, idx, expected) > 1: + return [] + break + + problems: List[str] = [] + n_rows = 0 + for offset, raw in enumerate(lines[body_start:]): + num = body_start + offset + 1 + line = raw.strip() + if not line or line.startswith(("#", "!")): + continue + for comment_char in ("#", "!"): + line = line.split(comment_char)[0].strip() + if not line: + continue + n_rows += 1 + parts = line.split() + if len(parts) < 4: + problems.append( + f"Line {num}: needs an element symbol and x, y, z " + f"(found {len(parts)} value{'s' if len(parts) != 1 else ''}: " + f"{line})" + ) + continue + symbol = _xyz_symbol(parts[0]) + if not utils.validate_atom_symbol(symbol): + problems.append( + f"Line {num}: '{parts[0]}' is not an element symbol" + + _symbol_hint(parts[0]) + ) + continue + try: + xyz = [_xyz_float(t) for t in parts[1:4]] + except ValueError: + problems.append( + f"Line {num}: x, y and z must be numbers (got " + f"{' '.join(parts[1:4])})" + ) + continue + if not all(math.isfinite(v) for v in xyz): + problems.append(f"Line {num}: x, y and z must be finite numbers") + if expected is not None and n_rows and n_rows != expected: + problems.append( + f"The count line says {expected} atom{'s' if expected != 1 else ''}, " + f"but {n_rows} atom line{'s were' if n_rows != 1 else ' was'} found" + ) + return problems + + def suggest_multiplicity(atoms: List[str], charge: int) -> int: """ Suggest default spin multiplicity based on molecule composition. diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py index 2da36d76..365c6d64 100644 --- a/quantui/orbital_visualization.py +++ b/quantui/orbital_visualization.py @@ -399,16 +399,33 @@ def count_core_orbitals(info: OrbitalInfo) -> int: return int(sum(1 for e in info.mo_energies_ev[: info.n_occupied] if e < cutoff)) +# Default view of the in-app energy diagram: this many eV below the HOMO and +# above the LUMO. Showing every virtual (up to +95 eV at 3-21G) left HOMO and +# LUMO in a sliver of the plot (UI/UX review 2026-12-05, UX-19). +FRONTIER_WINDOW_EV = 15.0 + + +def _plotly_irrep(label: str) -> str: + """``"4a1"`` → ``"4a1"`` (Plotly text supports ````).""" + from quantui.symmetry import html_irrep + + m = re.fullmatch(r"(\d*)(.+)", str(label)) + if not m: + return _html_escape(str(label)) + return m.group(1) + html_irrep(m.group(2)) + + def plot_orbital_diagram_plotly( info: OrbitalInfo, *, max_orbitals: int = 20, yrange: Optional[Tuple[float, float]] = None, title: Optional[str] = None, - width: int = 560, + width: Optional[int] = 560, height: int = 520, font_scale: float = 1.0, show_core: bool = True, + frontier_window_ev: Optional[float] = None, ): """Interactive Plotly orbital energy-level diagram. @@ -428,7 +445,12 @@ def plot_orbital_diagram_plotly( title: Custom plot title; defaults to ``"Orbital Energy Levels — {formula}"``. width, height: - Figure dimensions in pixels. + Figure dimensions in pixels. ``width=None`` lets the figure fill its + container (the app caps it with CSS). + frontier_window_ev: + With no explicit *yrange*, limit the automatic Y range to this many + eV below the HOMO and above the LUMO; the subtitle says how many + levels are outside it. ``None`` (default) fits every level shown. show_core: When ``False``, leave out core orbitals (:func:`count_core_orbitals`) so the auto Y range frames the valence levels; the subtitle says how @@ -468,7 +490,7 @@ def _window(n_tot: int, n_oc: int, n_core: int) -> Tuple[int, int, int]: irreps = info.irreps if info.irreps and len(info.irreps) == n_total else None def _sym(idx: int) -> str: - return f" ({irreps[idx]})" if irreps else "" + return f" ({_plotly_irrep(irreps[idx])})" if irreps else "" # One column per spin channel. Restricted: a single centred column. # Unrestricted (UHF/UKS): alpha left, beta right, each with its own @@ -609,11 +631,21 @@ def _sym(idx: int) -> str: span = max(shown) - min(shown) margin = max(0.5, span * 0.08 + 0.5) + clipped = False if yrange is None: y_min = min(shown) - margin y_max = max(shown) + margin + if frontier_window_ev is not None and frontier_window_ev > 0: + lo = float(homo_e) - float(frontier_window_ev) + hi = float(lumo_e) + float(frontier_window_ev) + if y_min < lo or y_max > hi: + y_min, y_max = max(y_min, lo), min(y_max, hi) + clipped = True else: y_min, y_max = yrange + # Levels drawn but outside the view: say so rather than hide them + # silently (the default frontier window, or a Y range set by hand). + n_outside = sum(1 for e in shown if e < y_min or e > y_max) subtitles = [] if irreps and info.irrep_caption: @@ -623,10 +655,19 @@ def _sym(idx: int) -> str: subtitles.append( f"{n_core_hidden} core orbital{s_} hidden (tick Show core orbitals)" ) + if n_outside: + s_ = "s" if n_outside > 1 else "" + where = ( + f"beyond ±{frontier_window_ev:g} eV of the gap" + if clipped + else "outside the Y range" + ) + subtitles.append(f"{n_outside} level{s_} {where} not shown (widen Y range)") fig = go.Figure(data=traces) fig.update_layout( width=width, + autosize=width is None, height=height, margin=dict(l=60, r=110, t=50 + 18 * len(subtitles), b=30), title=dict( diff --git a/tests/test_appui_audit_low.py b/tests/test_appui_audit_low.py index de866b77..977fd629 100644 --- a/tests/test_appui_audit_low.py +++ b/tests/test_appui_audit_low.py @@ -63,7 +63,9 @@ def test_in_session_comparison_shows_chart_and_closes_figure(app, shown): app._refresh_comparison() html = _html(shown) assert "Comparison chart" in html - assert "data:image/png;base64," in html + # UX-18: an in-app Plotly figure of ΔE (kJ/mol), not a matplotlib PNG. + assert "quantui-compare-chart" in html + assert "kJ/mol" in html assert plt.get_fignums() == [] diff --git a/tests/test_symmetry.py b/tests/test_symmetry.py index 44cb7bf5..cc142e90 100644 --- a/tests/test_symmetry.py +++ b/tests/test_symmetry.py @@ -405,7 +405,8 @@ def test_diagram_hover_and_caption_carry_labels(self): info.irrep_caption = "Orbital symmetry labels in C2v" fig = plot_orbital_diagram_plotly(info) hovers = " ".join(str(tr.hovertemplate) for tr in fig.data) - assert "(1b1) — HOMO" in hovers + # UX-19: irreps are subscripted, as on the Results card. + assert "(1b1) — HOMO" in hovers assert "C2v" in fig.layout.title.text def test_result_card_point_group_row(self): diff --git a/tests/test_uxrev_results_compare.py b/tests/test_uxrev_results_compare.py new file mode 100644 index 00000000..88cab13e --- /dev/null +++ b/tests/test_uxrev_results_compare.py @@ -0,0 +1,390 @@ +"""M-UXREV UXR.3: Results / Compare / plots (UI/UX review 2026-12-05). + +- UX-15 Results tab empty state. +- UX-16 invalid XYZ: every bad line, error colour, wrapped; table in sync. +- UX-17 Compare empty state; Compare button only with two ticked. +- UX-18 Compare: any pair with mismatch warnings, ΔE in kJ/mol vs the first, + short labels, themed Plotly chart (DEC-035 item 4). +- UX-19 energy-level diagram: responsive width, frontier window. +- UX-20 IR stick colour from the theme; axis padding; option wording. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest +from IPython.display import HTML + +from quantui.app import QuantUIApp +from quantui.comparison import ( + CalcSummary, + comparison_mismatches, + comparison_table_html, + relative_energies_kj, + short_label, + summary_from_saved_result, + unique_short_labels, +) + + +@pytest.fixture +def app(): + return QuantUIApp() + + +# ── UX-15 ──────────────────────────────────────────────────────────────────── + + +class TestResultsEmptyState: + def test_shown_first_before_any_result(self, app): + assert app.results_tab_panel.children[0] is app._results_empty_box + assert app._results_empty_box.layout.display in (None, "") + assert "No result yet" in app._results_empty_html.value + + def test_hidden_once_a_card_is_shown(self, app): + app.result_output.append_display_data(HTML("card")) + assert app._results_empty_box.layout.display == "none" + + def test_says_running_during_a_run(self, app): + from quantui.app_builders import refresh_results_empty_state + + app._calc_running = True + refresh_results_empty_state(app, has_card=False) + assert app._results_empty_box.layout.display == "" + assert "is running" in app._results_empty_html.value + assert app._results_empty_calc_btn.layout.display == "none" + + def test_buttons_go_to_calculate_and_history(self, app): + app.root_tab.selected_index = app._tab_index("results") + app._results_empty_history_btn.click() + assert app.root_tab.selected_index == app._tab_index("history") + app._results_empty_calc_btn.click() + assert app.root_tab.selected_index == app._tab_index("calculate") + + +# ── UX-16 ──────────────────────────────────────────────────────────────────── + +_BAD_XYZ = "3\nwater\nO 0 0 0\nH 0.0 0.76\nXx 0 0 1\n" + + +class TestXyzErrors: + def test_every_bad_line_is_listed(self): + from quantui.molecule import xyz_line_problems + + probs = xyz_line_problems(_BAD_XYZ) + assert probs[0].startswith("Line 4: needs an element symbol and x, y, z") + assert probs[1] == "Line 5: 'Xx' is not an element symbol" + + def test_capitalisation_hint(self): + from quantui.molecule import xyz_line_problems + + assert "did you mean 'Cl'?" in xyz_line_problems("cl 0 0 0")[0] + + def test_count_mismatch_is_reported(self): + from quantui.molecule import xyz_line_problems + + probs = xyz_line_problems("3\ntitle\nH 0 0 0\nH 0 0 0.74\n") + assert probs == ["The count line says 3 atoms, but 2 atom lines were found"] + + def test_valid_text_has_no_problems(self): + from quantui.molecule import xyz_line_problems + + assert xyz_line_problems("O 0 0 0\nH 0 0.76 0.59\nH 0 -0.76 0.59") == [] + + def test_load_shows_a_wrapped_error_list_and_greys_the_table(self, app): + app.xyz_area.value = _BAD_XYZ + app._on_load_xyz(None) + msg = app.xyz_msg.value + assert "var(--q-accent-error)" in msg + assert "2 problems" in msg + assert "Line 4" in msg and "Line 5" in msg + assert "'Xx' is not an element symbol" in msg + assert "quantui-xyz-stale" in app.xyz_table_box._dom_classes + assert "not updated" in app.xyz_table_note.value + + def test_many_problems_are_capped(self, app): + app.xyz_area.value = "\n".join(f"Q{i} 0 0 0" for i in range(12)) + app._on_load_xyz(None) + assert "and 4 more" in app.xyz_msg.value + + def test_successful_load_puts_the_molecule_in_the_table(self, app): + app.xyz_area.value = _BAD_XYZ + app._on_load_xyz(None) + app.xyz_area.value = ( + "N 0 0 0\nH 0 0.94 0.38\nH 0.81 -0.47 0.38\nH -0.81 -0.47 0.38" + ) + app._on_load_xyz(None) + assert [r[0].value for r in app._xyz_table_rows] == ["N", "H", "H", "H"] + assert "quantui-xyz-stale" not in app.xyz_table_box._dom_classes + assert app.xyz_table_note.layout.display == "none" + assert "Loaded H3N" in app.xyz_msg.value or "Loaded NH3" in app.xyz_msg.value + + +# ── UX-17 / UX-18 ──────────────────────────────────────────────────────────── + + +def _saved(tmp: Path, name: str, **data) -> Path: + d = tmp / name + d.mkdir() + base = { + "calc_type": "single_point", + "formula": "H2O", + "method": "RHF", + "basis": "STO-3G", + "energy_hartree": -74.96, + "homo_lumo_gap_ev": 12.0, + "converged": True, + "n_iterations": 6, + "timestamp": name, + } + base.update(data) + (d / "result.json").write_text(json.dumps(base)) + return d + + +class TestCompareControls: + def test_empty_state_without_saved_results(self, app, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + app._populate_compare_list() + assert app._compare_empty_html.layout.display == "" + assert "No saved calculations yet" in app._compare_empty_html.value + assert app.compare_select.layout.display == "none" + assert app.compare_btn.layout.display == "none" + + def test_compare_button_needs_two_ticks(self, app, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + a = _saved(tmp_path, "2026-12-05_20-54-01-692705") + b = _saved(tmp_path, "2026-12-05_20-55-01-692705", basis="3-21G") + app._populate_compare_list() + assert app._compare_empty_html.layout.display == "none" + assert app.compare_btn.layout.display == "none" + assert app._compare_hint_html.layout.display == "" + app.compare_select.value = (str(a),) + assert app.compare_btn.layout.display == "none" + app.compare_select.value = (str(a), str(b)) + assert app.compare_btn.layout.display == "" + assert app._compare_hint_html.layout.display == "none" + + +class TestCompareContent: + def test_short_labels_not_folder_ids(self): + s = summary_from_saved_result( + { + "formula": "H2O", + "method": "RHF", + "basis": "3-21G", + "timestamp": "2026-12-05_20-54-01-692705", + } + ) + assert s.label == "H2O · RHF/3-21G · 20:54" + assert "692705" not in s.label + + def test_repeats_get_the_date(self): + s = [ + CalcSummary("x", "H2O", "RHF", "STO-3G", timestamp="2026-12-05_20-54-01-1"), + CalcSummary("y", "H2O", "RHF", "STO-3G", timestamp="2026-12-06_20-54-01-1"), + ] + assert unique_short_labels(s) == [ + "H2O · RHF/STO-3G · 2026-12-05 20:54", + "H2O · RHF/STO-3G · 2026-12-06 20:54", + ] + + def test_same_day_repeats_get_seconds_then_a_counter(self): + s = [ + CalcSummary("x", "H2O", "RHF", "STO-3G", timestamp="2026-12-05_20-54-01-1"), + CalcSummary("y", "H2O", "RHF", "STO-3G", timestamp="2026-12-05_20-54-40-1"), + CalcSummary("z", "H2O", "RHF", "STO-3G", timestamp="2026-12-05_20-54-40-2"), + CalcSummary("w", "H2O", "RHF", "3-21G", timestamp="2026-12-05_20-54-40-3"), + ] + assert unique_short_labels(s) == [ + "H2O · RHF/STO-3G · 20:54:01", + "H2O · RHF/STO-3G · 20:54:40 (1)", + "H2O · RHF/STO-3G · 20:54:40 (2)", + "H2O · RHF/3-21G · 20:54", + ] + + def test_delta_e_in_kj_mol_vs_the_first(self): + s = [ + CalcSummary("a", "H2O", "RHF", "STO-3G", energy_hartree=-75.0), + CalcSummary("b", "H2O", "RHF", "STO-3G", energy_hartree=-75.001), + ] + rel = relative_energies_kj(s) + assert rel[0] == 0.0 + assert rel[1] == pytest.approx(-2.6255, abs=1e-3) + html = comparison_table_html(s, reference_index=0) + assert "ΔE (kJ/mol)" in html + assert "0 (reference)" in html + assert "-2.63" in html + + def test_no_delta_column_without_a_reference(self): + s = [CalcSummary("a", "H2O", "RHF", "STO-3G", energy_hartree=-75.0)] + assert "ΔE" not in comparison_table_html(s) + + def test_mismatch_warnings(self): + same = [ + CalcSummary("a", "H2O", "RHF", "STO-3G"), + CalcSummary("b", "H2O", "RHF", "STO-3G"), + ] + assert comparison_mismatches(same) == [] + basis = [same[0], CalcSummary("b", "H2O", "RHF", "3-21G")] + (msg,) = comparison_mismatches(basis) + assert "Different levels of theory" in msg and "RHF/3-21G" in msg + mol = [same[0], CalcSummary("b", "CH4", "RHF", "STO-3G")] + (msg,) = comparison_mismatches(mol) + assert "Different molecules" in msg + + def test_compare_view(self, app, tmp_path, monkeypatch): + shown: list = [] + monkeypatch.setattr( + "quantui.app_runflow.display", lambda *a, **k: shown.extend(a) + ) + monkeypatch.setenv("QUANTUI_RESULTS_DIR", str(tmp_path)) + a = _saved(tmp_path, "2026-12-05_20-54-01-692705", energy_hartree=-74.96) + b = _saved( + tmp_path, + "2026-12-05_20-55-01-692705", + basis="3-21G", + energy_hartree=-75.58, + ) + app._populate_compare_list() + app.compare_select.value = (str(a), str(b)) + app._on_compare(None) + html = "\n".join(str(getattr(o, "data", "")) for o in shown) + assert "not directly comparable" in html + assert "Different levels of theory" in html + assert "ΔE (kJ/mol)" in html + assert "2026-12-05_20-54-01-692705" not in html # no raw folder IDs + assert "quantui-compare-chart" in html + + def test_chart_uses_theme_colours(self, app): + from quantui import theme as _theme + from quantui.app_runflow import _comparison_chart_html + from quantui.comparison import plot_comparison_plotly + + s = [ + CalcSummary( + "H2O · RHF/STO-3G", "H2O", "RHF", "STO-3G", energy_hartree=-75.0 + ), + CalcSummary("H2O · RHF/3-21G", "H2O", "RHF", "3-21G", energy_hartree=-75.5), + ] + pal = _theme.get_palette(app.theme_btn.value) + fig = plot_comparison_plotly(s, bar_color=pal.accent_info) + assert fig.data[0].marker.color == pal.accent_info + assert list(fig.data[0].x) == ["H2O · RHF/STO-3G", "H2O · RHF/3-21G"] + assert fig.data[0].y[1] == pytest.approx(-0.5 * 2625.4996394799) + html = _comparison_chart_html(s, app=app) + assert pal.accent_info in html + assert "= info.homo_energy_ev - 15.0 - 1e-9 + assert hi <= info.lumo_energy_ev + 15.0 + 1e-9 + assert "beyond ±15 eV" in fig.layout.title.text + assert fig.layout.width is None and fig.layout.autosize is True + + def test_levels_outside_a_hand_set_range_are_counted(self): + pytest.importorskip("plotly") + from quantui.orbital_visualization import plot_orbital_diagram_plotly + + fig = plot_orbital_diagram_plotly( + _water_321g(), show_core=False, yrange=(-20.0, 20.0) + ) + assert "outside the Y range" in fig.layout.title.text + + def test_library_default_is_unchanged(self): + pytest.importorskip("plotly") + from quantui.orbital_visualization import plot_orbital_diagram_plotly + + fig = plot_orbital_diagram_plotly(_water_321g(), show_core=False) + assert fig.layout.width == 560 + assert fig.layout.yaxis.range[1] > 90 # every level shown + + def test_app_diagram_is_responsive_and_framed(self): + from types import SimpleNamespace + + r = SimpleNamespace( + mo_energy_hartree=np.array( + [-20.4, -1.35, -0.71, -0.56, -0.50, 0.21, 0.30, 1.0, 2.0, 3.5] + ), + mo_occ=np.array([2.0] * 5 + [0.0] * 5), + formula="H2O", + ) + app = QuantUIApp() + app._show_orbital_diagram(r) + fig = app._last_orb_fig + assert fig.layout.width is None + assert app._orb_ymax_input.value < 40 # not +95 eV + payload = "".join( + o.get("data", {}).get("text/html", "") + for o in app._orb_diagram_html.outputs + ) + assert "max-width:900px" in payload + + +# ── UX-20 ──────────────────────────────────────────────────────────────────── + + +class TestIrPlot: + def test_colour_parameter_is_used(self): + from quantui.ir_plot import plot_ir_spectrum + + fig = plot_ir_spectrum([1600.0, 3700.0], [10.0, 20.0], color="#60a5fa") + assert all( + (getattr(t, "line", None) is None or t.line.color in (None, "#60a5fa")) + for t in fig.data + ) + assert fig.data[0].line.color == "#60a5fa" + + def test_high_peak_is_padded_from_the_frame(self): + from quantui.ir_plot import plot_ir_spectrum + + fig = plot_ir_spectrum([1785.6, 4486.7, 4788.3], [1.0, 1.0, 1.0]) + lo, hi = fig.layout.xaxis.range + assert hi - 4788.3 >= 0.035 * (hi - lo) + + def test_app_uses_the_theme_accent_and_neutral_axis_wording(self, app): + from types import SimpleNamespace + + from quantui import theme as _theme + + labels = [lbl for lbl, _ in app._ir_axis_dd.options] + assert labels == ["High → low wavenumber", "Low → high wavenumber"] + r = SimpleNamespace( + frequencies_cm1=[1600.0, 3700.0, 3800.0], + ir_intensities=[50.0, 5.0, 20.0], + formula="H2O", + ) + app._show_ir_spectrum(r) + accent = _theme.get_palette(app.theme_btn.value).accent_info + assert app._last_ir_fig.data[0].line.color == accent From e185481066b4ed9e0efa89b32da2cb38a98fb167 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:04:30 +0000 Subject: [PATCH 07/12] Report Issue: send to the instructor's folder, say who sees it M-UXREV UXR.8 (DEC-035 item 8). - issue_tracker.report_issue saves the report locally as before and, when QUANTUI_ISSUE_DIR names a folder (set by a course deployment, e.g. on NCShare), also writes it there as --.json (description, login, host, session id, session snapshot). A failure to write there is returned, not raised: the local copy exists, and the dialog asks the student to give the instructor the issue number. - The dialog says who sees the report: "your instructor" with a folder set; on an NCShare-style session without one (detected with the existing app_launcher.is_hpc_jupyterlab_session) that it is not sent to anyone; locally that it stays on this computer. The confirmation now stays visible after Submit (the dialog used to close, hiding it); Cancel becomes Close. - Documented: apptainer/README.md "Collecting Report Issue submissions" (drop-box folder recipe), docs/CLI.md and copilot-instructions env-var tables. 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 + CHANGELOG.md | 7 ++ apptainer/README.md | 29 +++++++ docs/CLI.md | 1 + quantui/app.py | 1 + quantui/app_builders.py | 46 ++++++++--- quantui/app_runflow.py | 55 ++++++++++--- quantui/issue_tracker.py | 107 +++++++++++++++++++++++++ tests/test_uxrev_report_issue.py | 129 +++++++++++++++++++++++++++++++ 9 files changed, 357 insertions(+), 19 deletions(-) create mode 100644 tests/test_uxrev_report_issue.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 3c466995..fc26a899 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -794,6 +794,7 @@ Everything incl. the app server and notebook smoke tests: `pip install -e ".[pys | `QUANTUI_LOG_DIR` | `~/.quantui/logs` | Where perf_log and event_log live | | `QUANTUI_FREQ_PARALLEL` | (unset / off) | When truthy (`1`, `true`, `yes`, `on`), fan out IR-intensity finite-difference SCFs across CPU worker processes. Same as the System Settings checkbox; **overrides** the saved setting when set. Reference SCF + Hessian still use gpu4pyscf when available. Requires ≥4 cores and ≥2 atoms. | | `QUANTUI_SETTINGS_PATH` | `~/.quantui/settings.json` | User-preferences file (`user_settings.py`); override for tests | +| `QUANTUI_ISSUE_DIR` | (unset) | Instructor's folder for Report Issue submissions (`issue_tracker.report_issue` writes one JSON per report); the dialog then says "your instructor" sees it (DEC-035 item 8) | | `QUANTUI_DISABLE_GPU` | (unset) | Force CPU even when gpu4pyscf and a device are present | | `QUANTUI_CHECKPOINT_DIR` | `~/.quantui/checkpoints` | Interactive checkpoint/resume store | | `QUANTUI_ENABLE_SLURM` | (unset / off) | Offer the SLURM batch backend (needs `sbatch`) | diff --git a/CHANGELOG.md b/CHANGELOG.md index a1cf96ae..7e4da13d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,13 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht - **IR spectrum:** the sticks use the theme's accent colour (the fixed blue was hard to see on dark themes), the highest band no longer sits on the plot edge, and the axis option reads "High → low wavenumber". +- **Report Issue can reach your instructor.** A course deployment (for + example on NCShare) can set `QUANTUI_ISSUE_DIR` to a folder the instructor + reads; each report is then also saved there, and the dialog says that your + instructor sees it (with your username and a snapshot of the session). + Without it the dialog says the report stays on this computer; on a cluster + session without a folder it asks you to tell your instructor the issue + number. The confirmation now stays visible after Submit. - **One status for the header and the footer.** The status chip in the header and the workspace footer now show the same job state (Idle, Running…, Done, Done — with warnings, Failed); the chip no longer drops back diff --git a/apptainer/README.md b/apptainer/README.md index 77a3e664..10a212c3 100644 --- a/apptainer/README.md +++ b/apptainer/README.md @@ -316,6 +316,35 @@ shielding, 1D PES scan, and Reorganization Energy; PCM implicit solvent --- +## Collecting Report Issue submissions + +Students can report a problem from the app's **Report Issue** button. By +default the report (with a snapshot of the session) is saved only on the +student's own account (`~/.quantui/logs/issues.db`), and the dialog says so. + +For a course deployment, for example on NCShare, point +`QUANTUI_ISSUE_DIR` at a folder you can read and students can write to. +Every report is then also written there as one JSON file +(`--.json`: the description, the login name and the +session snapshot), and the dialog tells students that **their instructor** +sees it. If a student's copy cannot be written there, the dialog says so +and asks them to give you the issue number. + +A drop-box folder lets students add reports without reading each other's: + +```bash +mkdir -p /shared/course/quantui-issues +chmod 1733 /shared/course/quantui-issues # write + enter for all, no listing, sticky +``` + +Set the variable where the students' QuantUI kernel starts, for example in +the Apptainer image (`%environment` in `quantui.def`), with +`apptainer exec --env QUANTUI_ISSUE_DIR=/shared/course/quantui-issues …`, or +in the JupyterHub spawner environment. Students' home folders keep their own +copy either way. + +--- + ## Distributing to students The `.sif` is a single self-contained file — share it however is convenient: diff --git a/docs/CLI.md b/docs/CLI.md index faff72cf..db8ef8da 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -517,6 +517,7 @@ chaining, `--queue-rest`, `check`): | `QUANTUI_ENABLE_SLURM` | Opt in to **SLURM batch (cluster)** on the System Settings → Execution backend dropdown. Requires `sbatch` on PATH. Off by default so student deployments stay in-kernel until an operator enables cluster mode in the Apptainer image, JupyterHub spawner, or shell. Accepted truthy values: `1`, `true`, `yes`, `on`. | | `QUANTUI_MAX_CONCURRENT_JOBS` | Most QuantUI SLURM jobs queued or running at once (app and `quantui submit`; default `2`). | | `QUANTUI_SLURM_SUBMIT_COOLDOWN_S` | Minimum seconds between SLURM submits (default `30`; `0` disables). `quantui submit` waits it out between input files. | +| `QUANTUI_ISSUE_DIR` | Folder where an instructor collects **Report Issue** submissions. When set, each report is also written there as `--.json`, and the dialog tells students that their instructor sees it. Unset: reports stay on the student's computer. See [Collecting Report Issue submissions](https://github.com/The-Schultz-Lab/QuantUI/blob/main/apptainer/README.md#collecting-report-issue-submissions). | | `QUANTUI_FREQ_PARALLEL` | Opt in to parallel **CPU** workers for the IR/Raman finite-difference displacement loops in frequency calculations (`6N` displaced SCFs). Same effect as the **Parallelize IR/Raman displacements (CPU)** checkbox on the System Settings tab; when this env var is set it overrides the saved setting. Reference SCF and Hessian still use gpu4pyscf when available. Requires ≥4 cores and ≥2 atoms. Off by default. Accepted truthy values: `1`, `true`, `yes`, `on`. | --- diff --git a/quantui/app.py b/quantui/app.py index 40a8a12a..a81a6037 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -1719,6 +1719,7 @@ class QuantUIApp: _issue_cancel_btn: Any _issue_overlay: Any _issue_status_html: Any + _issue_intro_html: Any _issue_submit_btn: Any _issue_textarea: Any _cal_accordion: Any diff --git a/quantui/app_builders.py b/quantui/app_builders.py index 37001346..32b4dd10 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -4675,6 +4675,38 @@ def build_help_section(app: Any, *, layout_fn: Any) -> None: app.help_tab_panel.add_class("quantui-drawer") +def issue_intro_html() -> str: + """Report Issue heading plus who will see the report (DEC-035 item 8).""" + from quantui import issue_tracker + + audience = issue_tracker.issue_audience() + if audience == issue_tracker.AUDIENCE_INSTRUCTOR: + who = ( + "Sent to your instructor, with your username and a snapshot " + "of this session (molecule, settings, recent steps). A copy stays " + "on this computer." + ) + elif audience == issue_tracker.AUDIENCE_CLUSTER_LOCAL: + who = ( + "Saved in your own QuantUI folder on this cluster, with a snapshot " + "of this session. It is not sent to anyone automatically: " + "tell your instructor the issue number shown after you submit." + ) + else: + who = ( + "Saved on this computer with a snapshot of the session. " + "It is not sent anywhere." + ) + # Theme tokens, not fixed light-theme browns: on dark palettes the panel + # background follows the theme and #92400e/#78350f text was unreadable. + return ( + '

    ⚐ Report Issue

    ' + f'

    ' + f"{who}

    " + ) + + def build_issue_widgets(app: Any, *, layout_fn: Any) -> None: """Build issue-report widgets shown from the top toolbar.""" app._issue_btn = widgets.Button( @@ -4706,18 +4738,12 @@ def build_issue_widgets(app: Any, *, layout_fn: Any) -> None: ) app._issue_cancel_btn.add_class("quantui-issue-cancel") # Esc target app._issue_status_html = widgets.HTML() + # Says who sees the report: the instructor (collection folder set, e.g. + # on NCShare) or nobody but this computer (DEC-035 item 8). + app._issue_intro_html = widgets.HTML(issue_intro_html()) app._issue_overlay = widgets.VBox( [ - # Theme tokens, not fixed light-theme browns: on dark palettes the - # panel background follows the theme and #92400e/#78350f text was - # nearly unreadable. - widgets.HTML( - '

    ⚐ Report Issue

    ' - f'

    ' - "Saved on this computer with a snapshot of the session, for the " - "developers.

    " - ), + app._issue_intro_html, app._issue_textarea, widgets.HBox( [app._issue_submit_btn, app._issue_cancel_btn], diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index f87bbc39..ac248305 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -2535,6 +2535,11 @@ def on_issue_btn(app: Any, _unused: Any = None) -> None: return app._issue_textarea.value = "" app._issue_status_html.value = "" + app._issue_cancel_btn.description = "Cancel" + # Who sees the report depends on the deployment (DEC-035 item 8). + from quantui.app_builders import issue_intro_html + + app._issue_intro_html.value = issue_intro_html() app._issue_overlay.layout.display = "" @@ -2544,7 +2549,11 @@ def on_issue_cancel(app: Any, _unused: Any = None) -> None: def on_issue_submit(app: Any, *, issue_tracker_mod: Any) -> None: - """Persist issue text and hide overlay on success.""" + """Save the report (and send it to the instructor when configured). + + The dialog stays open with a confirmation that says where the report + went; Cancel becomes Close. + """ text = app._issue_textarea.value.strip() if not text: app._issue_status_html.value = ( @@ -2554,16 +2563,44 @@ def on_issue_submit(app: Any, *, issue_tracker_mod: Any) -> None: return app._issue_submit_btn.disabled = True try: - issue_id = issue_tracker_mod.log_issue( - description=text, - context=app._build_issue_context(), - session_id=app._session_id, - ) + context = app._build_issue_context() + if hasattr(issue_tracker_mod, "report_issue"): + receipt = issue_tracker_mod.report_issue( + description=text, context=context, session_id=app._session_id + ) + issue_id, sent_to, send_error = ( + receipt.issue_id, + receipt.sent_to, + receipt.send_error, + ) + else: # a stand-in module with only log_issue (tests, older callers) + issue_id = issue_tracker_mod.log_issue( + description=text, context=context, session_id=app._session_id + ) + sent_to = send_error = None + if sent_to is not None: + msg, color = ( + f"✓ Issue #{issue_id} sent to your instructor. Thank you!", + _theme.css.ACCENT_SUCCESS, + ) + elif send_error: + msg, color = ( + f"⚠ Issue #{issue_id} was saved on this computer, but it " + "could not be sent to your instructor's folder " + f"({html.escape(send_error)}). Please tell your instructor " + "the issue number.", + _theme.css.ACCENT_WARNING, + ) + else: + msg, color = ( + f"✓ Issue #{issue_id} saved on this computer. Thank you!", + _theme.css.ACCENT_SUCCESS, + ) app._issue_status_html.value = ( - f'' - f"✓ Issue #{issue_id} saved. Thank you!" + f'{msg}' ) - app._issue_overlay.layout.display = "none" + app._issue_textarea.value = "" + app._issue_cancel_btn.description = "Close" except Exception as exc: app._issue_status_html.value = f'Save failed: {html.escape(str(exc))}' finally: diff --git a/quantui/issue_tracker.py b/quantui/issue_tracker.py index b5b551cf..de2253bc 100644 --- a/quantui/issue_tracker.py +++ b/quantui/issue_tracker.py @@ -11,6 +11,13 @@ ``/issues.db`` where ```` is the same directory used by ``calc_log`` (``~/.quantui/logs`` by default, or ``$QUANTUI_LOG_DIR``). +Instructor collection (DEC-035 item 8) +-------------------------------------- +When ``$QUANTUI_ISSUE_DIR`` names a folder (a course deployment sets it, for +example on NCShare), every report is also written there as one JSON file, +so the instructor collects them in one place; the Report Issue dialog then +says "your instructor" sees it. Without it reports stay on this computer. + Public API ---------- ``log_issue(description, context, session_id)`` @@ -21,6 +28,9 @@ ``clear_issues()`` Delete all issue records (drops and recreates the table). + +``report_issue(description, context, session_id)`` + :func:`log_issue`, then a copy to the instructor's folder when set. """ from __future__ import annotations @@ -30,6 +40,7 @@ import sqlite3 import threading from contextlib import contextmanager +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Iterator, Optional @@ -170,6 +181,102 @@ def get_issues(n: int = 50) -> list[dict]: ] +# --------------------------------------------------------------------------- +# Instructor collection (DEC-035 item 8) +# --------------------------------------------------------------------------- + +#: Folder where a course deployment collects reports (one JSON file each). +ISSUE_DIR_ENV = "QUANTUI_ISSUE_DIR" + +#: Who sees a report: the instructor (collection folder set), nobody else +#: yet on an NCShare-style cluster session without one, or this computer. +AUDIENCE_INSTRUCTOR = "instructor" +AUDIENCE_CLUSTER_LOCAL = "cluster-local" +AUDIENCE_LOCAL = "local" + + +def instructor_issue_dir() -> Optional[Path]: + """The instructor's collection folder from ``$QUANTUI_ISSUE_DIR``, or None.""" + raw = os.environ.get(ISSUE_DIR_ENV, "").strip() + return Path(raw).expanduser() if raw else None + + +def issue_audience() -> str: + """Who will see a report filed now (see the ``AUDIENCE_*`` constants).""" + if instructor_issue_dir() is not None: + return AUDIENCE_INSTRUCTOR + try: + from quantui.app_launcher import is_hpc_jupyterlab_session + + if is_hpc_jupyterlab_session(): + return AUDIENCE_CLUSTER_LOCAL + except ImportError: + pass + return AUDIENCE_LOCAL + + +def _reporter() -> str: + """The login name, made safe for a file name ("unknown" if unavailable).""" + import getpass + import re + + try: + name = getpass.getuser() + except (KeyError, OSError): # no passwd entry / no login name + name = "unknown" + return re.sub(r"[^A-Za-z0-9._-]", "_", name)[:40] or "unknown" + + +@dataclass(frozen=True) +class IssueReceipt: + """What :func:`report_issue` did with a report.""" + + issue_id: int + #: The file written to the instructor's folder, or None. + sent_to: Optional[Path] = None + #: Why sending to the instructor's folder failed, or None. + send_error: Optional[str] = None + + +def report_issue( + description: str, + context: Optional[dict] = None, + session_id: Optional[str] = None, +) -> IssueReceipt: + """Save a report locally and, when configured, send it to the instructor. + + The local save (:func:`log_issue`) always happens first. With + ``$QUANTUI_ISSUE_DIR`` set, the report is also written to that folder as + ``--.json``; a failure there is returned (not + raised), since the report is already saved on this computer. + """ + issue_id = log_issue(description, context=context, session_id=session_id) + folder = instructor_issue_dir() + if folder is None: + return IssueReceipt(issue_id) + now = datetime.now(timezone.utc) + user = _reporter() + payload = { + "issue_id": issue_id, + "timestamp": now.isoformat(), + "user": user, + "host": os.uname().nodename if hasattr(os, "uname") else "", + "session_id": session_id, + "description": description, + "context": context or {}, + } + dest = folder / f"{now:%Y%m%dT%H%M%SZ}-{user}-{issue_id}.json" + try: + folder.mkdir(parents=True, exist_ok=True) + dest.write_text( + json.dumps(payload, ensure_ascii=False, indent=2, default=str), + encoding="utf-8", + ) + except OSError as exc: + return IssueReceipt(issue_id, send_error=f"{type(exc).__name__}: {exc}") + return IssueReceipt(issue_id, sent_to=dest) + + def clear_issues() -> None: """Delete all issue records from the database. diff --git a/tests/test_uxrev_report_issue.py b/tests/test_uxrev_report_issue.py new file mode 100644 index 00000000..f27ed0f8 --- /dev/null +++ b/tests/test_uxrev_report_issue.py @@ -0,0 +1,129 @@ +"""M-UXREV UXR.8: Report Issue reaches the instructor (DEC-035 item 8). + +With ``QUANTUI_ISSUE_DIR`` set (a course deployment such as NCShare), each +report is also written to that folder and the dialog says "your instructor" +sees it; locally it says the report stays on this computer. +""" + +from __future__ import annotations + +import json + +import pytest + +from quantui import issue_tracker + + +@pytest.fixture +def logs(tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_LOG_DIR", str(tmp_path / "logs")) + monkeypatch.delenv("QUANTUI_ISSUE_DIR", raising=False) + for key in ( + "APPTAINER_CONTAINER", + "APPTAINER_NAME", + "SINGULARITY_CONTAINER", + "SINGULARITY_NAME", + "JUPYTER_SERVER_URL", + "JUPYTERHUB_SERVICE_URL", + "JUPYTERHUB_USER", + "JPY_SESSION_NAME", + ): + monkeypatch.delenv(key, raising=False) + return tmp_path + + +class TestAudience: + def test_local_by_default(self, logs, monkeypatch): + monkeypatch.setattr( + "quantui.app_launcher.is_hpc_jupyterlab_session", lambda: False + ) + assert issue_tracker.issue_audience() == issue_tracker.AUDIENCE_LOCAL + + def test_instructor_when_a_folder_is_set(self, logs, monkeypatch): + monkeypatch.setenv("QUANTUI_ISSUE_DIR", str(logs / "inbox")) + assert issue_tracker.issue_audience() == issue_tracker.AUDIENCE_INSTRUCTOR + + def test_cluster_session_without_a_folder(self, logs, monkeypatch): + monkeypatch.setattr( + "quantui.app_launcher.is_hpc_jupyterlab_session", lambda: True + ) + assert issue_tracker.issue_audience() == issue_tracker.AUDIENCE_CLUSTER_LOCAL + + +class TestReportIssue: + def test_local_only_without_a_folder(self, logs): + receipt = issue_tracker.report_issue("broken", context={"a": 1}) + assert receipt.sent_to is None and receipt.send_error is None + assert issue_tracker.get_issues()[0]["description"] == "broken" + + def test_writes_one_json_file_to_the_instructor_folder(self, logs, monkeypatch): + inbox = logs / "inbox" + monkeypatch.setenv("QUANTUI_ISSUE_DIR", str(inbox)) + receipt = issue_tracker.report_issue( + "the IR plot is empty", context={"formula": "H2O"}, session_id="s1" + ) + assert receipt.sent_to is not None and receipt.sent_to.parent == inbox + data = json.loads(receipt.sent_to.read_text(encoding="utf-8")) + assert data["description"] == "the IR plot is empty" + assert data["issue_id"] == receipt.issue_id + assert data["context"] == {"formula": "H2O"} + assert data["session_id"] == "s1" + assert data["user"] + # The local copy is kept too. + assert issue_tracker.get_issues()[0]["id"] == receipt.issue_id + + def test_unwritable_folder_is_reported_not_raised(self, logs, monkeypatch): + blocker = logs / "file" + blocker.write_text("x") + monkeypatch.setenv("QUANTUI_ISSUE_DIR", str(blocker / "inbox")) + receipt = issue_tracker.report_issue("x") + assert receipt.sent_to is None + assert receipt.send_error + assert issue_tracker.get_issues()[0]["id"] == receipt.issue_id + + +class TestDialog: + def _app(self): + from quantui.app import QuantUIApp + + return QuantUIApp() + + def test_local_wording(self, logs, monkeypatch): + monkeypatch.setattr( + "quantui.app_launcher.is_hpc_jupyterlab_session", lambda: False + ) + app = self._app() + app._on_issue_btn() + assert "on this computer" in app._issue_intro_html.value + assert "instructor" not in app._issue_intro_html.value + + def test_instructor_wording_and_confirmation(self, logs, monkeypatch): + monkeypatch.setenv("QUANTUI_ISSUE_DIR", str(logs / "inbox")) + app = self._app() + app._on_issue_btn() + assert "your instructor" in app._issue_intro_html.value + app._issue_textarea.value = "Run button does nothing" + app._on_issue_submit() + assert "sent to your instructor" in app._issue_status_html.value + # The confirmation stays visible; Cancel became Close. + assert app._issue_overlay.layout.display == "" + assert app._issue_cancel_btn.description == "Close" + assert len(list((logs / "inbox").glob("*.json"))) == 1 + + def test_cluster_without_folder_says_nobody_is_sent_it(self, logs, monkeypatch): + monkeypatch.setattr( + "quantui.app_launcher.is_hpc_jupyterlab_session", lambda: True + ) + app = self._app() + app._on_issue_btn() + assert "not sent to anyone" in app._issue_intro_html.value + + def test_local_confirmation(self, logs, monkeypatch): + monkeypatch.setattr( + "quantui.app_launcher.is_hpc_jupyterlab_session", lambda: False + ) + app = self._app() + app._on_issue_btn() + app._issue_textarea.value = "x" + app._on_issue_submit() + assert "saved on this computer" in app._issue_status_html.value From 5ef79b51947be75252194b9f6860a4185a9e1178 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:18:33 +0000 Subject: [PATCH 08/12] Copy and polish: formulas, short paths, settings wording, icons, tokens UI/UX review 2026-12-05, UX-26 to UX-33 and UX-35 (M-UXREV UXR.6). The keyboard-order part of UX-26 (status chip out of the Tab order, skip link, tabs before the pane in the DOM) landed with UXR.4/UXR.5. - UX-30: app_formatters.formula_html ( counts) and formula_unicode (H2O as H with a Unicode subscript 2, for dropdowns). Used by every result card, the Calculate summary, the workspace pane caption and footer, the setup-dialog title, the Analysis heading and the History labels (History search still matches on the plain formula). Vibrational-mode options use subscripted irreps like the mode table. - UX-28: utils.short_path / path_html. "Saved - find it in History" with a working-folder or ~-relative path and the full path as a tooltip; the History path line and the Files tab root/current folder likewise. Copy path still copies the full path. - UX-27: System Settings shows a neutral "Not installed (optional)" chip for PyFock, GPU offload and online search, with install hints under "Details for instructors"; GPU present but off says "Not in use"; label cells no longer wrap. - UX-29: the Results menu lists panels by their own titles and says "Available after: Single Point, Geometry Opt" instead of "Needs a NMR Shielding result". - UX-31: Font Awesome icons or text instead of emoji for status in the UI modules (GPU badge, loading/rendering/generating messages, Export Animation, info box, viewer error, History [SLURM ...] and [calibration] markers, Files folders as "name/"). Error texts in molecule.py and pubchem.py are left for the XYZ-error work. - UX-32: inline text/background colours in app_visualization, orbital_visualization and visualization_py3dmol use theme variables (with the old value as fallback for standalone exports). Plot trace colours and app.py's run-error boxes are not changed here. - UX-33: descriptor cards, result cards, the info box and the System Settings cards use a 1 px full border, no 4 px side stripe. - UX-35: theme.logo_css puts a soft light disc behind the header logo on dark palettes. - Help: keyboard use in "Using the menus". Tests updated for the subscripted formulas, menu wording and markers; new tests/test_uxrev_polish.py (notation, paths, settings chip, no emoji in UI string literals, no hard-coded inline colours in the viewer modules, no side stripes, logo backdrop). 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 | 25 +++ quantui/app.py | 25 ++- quantui/app_analysis.py | 10 +- quantui/app_builders.py | 64 +++++-- quantui/app_formatters.py | 50 +++++- quantui/app_menubar.py | 29 +++- quantui/app_runflow.py | 21 ++- quantui/app_setup_dialog.py | 4 +- quantui/app_slurm.py | 4 +- quantui/app_visualization.py | 71 ++++---- quantui/app_workspace.py | 7 +- quantui/benchmarks.py | 2 +- quantui/descriptor_cards.py | 4 +- quantui/help_content.py | 7 +- quantui/orbital_visualization.py | 12 +- quantui/theme.py | 26 ++- quantui/utils.py | 43 +++++ quantui/visualization_py3dmol.py | 15 +- tests/test_app.py | 8 +- tests/test_app_formatters.py | 7 +- tests/test_app_menubar.py | 6 +- tests/test_calibration_save_results.py | 6 +- tests/test_descriptor_cards.py | 6 +- tests/test_jobdirs.py | 2 +- tests/test_mode_irreps.py | 2 +- tests/test_uiaudit_design.py | 2 +- tests/test_uxrev_polish.py | 228 +++++++++++++++++++++++++ 27 files changed, 570 insertions(+), 116 deletions(-) create mode 100644 tests/test_uxrev_polish.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c5e1929..d31fbc3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,31 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht dialog, and the footer note is one line. - **Small molecules fill the viewer** when they open (water was a dot in the middle of the viewer). +- **Formulas are subscripted** (H₂O) in the molecule summary, the workspace + pane, the Results cards, the setup dialog title, the Analysis heading and + History; vibrational-mode labels use a₁ like the mode table. +- **No absolute paths in student views:** "Saved — find it in History" + with a short path (`results/…`, `~/…`); the full path is in its tooltip and + Copy path still copies it. History and the Files tab do the same. +- **System Settings:** optional parts that are not installed (GPU offload, + PyFock, online search) show a neutral "Not installed (optional)" chip + instead of a red cross, with install hints under "Details for + instructors"; labels no longer wrap. +- **Menu wording:** Results → Analysis panels use the panel titles + ("Energy-level Diagram", "Orbital Isosurface"); unavailable items say + "Available after: Single Point, Geometry Opt" (no more "a NMR"). +- **Icons, not emoji,** for status in the UI (GPU badge, loading and + rendering messages, Export Animation, History markers `[SLURM …]` and + `[calibration]`, folders in Files shown as `name/`). +- **Theme colours** replace hard-coded light-theme text colours in the 3D + viewer and orbital modules (rendering and error messages, frame-stepper + buttons). +- **Cards** (descriptor cards, result cards, info boxes, System Settings) + have a thin full border instead of a 4 px side stripe. +- **Logo** sits on a soft light disc in dark palettes, so it no longer + reads as a dim dot. +- **Help → Using the menus** describes keyboard use (focus ring, skip link, + arrow keys in menus). ### Accessibility diff --git a/quantui/app.py b/quantui/app.py index e54dec85..5cd845fc 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -244,6 +244,7 @@ from quantui.app_formatters import ( format_ts_result as _fmt_ts_result, ) +from quantui.app_formatters import formula_html as _formula_html from quantui.app_history import ( build_history_context as _hist_build_history_context, ) @@ -3726,10 +3727,12 @@ def _format_files_root_label(self, root: Path) -> str: except OSError: pass + from quantui.utils import short_path as _short_path + for prefix, known_root in labels: if root == known_root: - return f"{prefix} ({root})" - return str(root) + return f"{prefix} ({_short_path(root)})" + return _short_path(root) def _refresh_file_browser(self) -> None: """Refresh root options and the current directory listing.""" @@ -3817,9 +3820,11 @@ def _update_files_entries(self) -> None: current = Path(self._files_root_dd.value) self._files_current_dir = current + from quantui.utils import path_html as _path_html + self._files_path_html.value = ( f'Current folder: ' - f"{_html.escape(str(current))}" + f"{_path_html(current)}" ) try: @@ -3853,7 +3858,8 @@ def _mtime(p: Path) -> float: options: list[tuple[str, str]] = [] for child in children: if child.is_dir(): - options.append((f"📁 {child.name}", str(child))) + # A trailing slash marks a folder (no emoji; UX-31). + options.append((f"{child.name}/", str(child))) continue try: size_label = self._format_file_size(child.stat().st_size) @@ -6300,7 +6306,7 @@ def _set_molecule( except Exception: # noqa: BLE001 — informational only _frag_str = "" _summary = ( - f'{mol.get_formula()}' + f'{_formula_html(mol.get_formula())}' f' ' f"{len(mol.atoms)} atoms" + (f" • {e_str}" if e_str else "") @@ -6547,9 +6553,14 @@ def _show_result_log(self, saved_dir: Path, log_text: str) -> None: Safe to call from a background thread. """ # Path label + # No absolute path in the student view (UX-28): where to find it, and + # the short path with the full one as its tooltip. + from quantui.utils import path_html as _path_html + self._result_dir_label.value = ( - f'' - f"Saved to: {saved_dir}" + f'' + f' Saved — find it ' + f"in History ({_path_html(saved_dir)})" ) self._result_dir_label.layout.display = "" diff --git a/quantui/app_analysis.py b/quantui/app_analysis.py index a0334fe2..9be1992d 100644 --- a/quantui/app_analysis.py +++ b/quantui/app_analysis.py @@ -115,8 +115,14 @@ def _run_first_text(when: str) -> str: def _analysis_heading_label(ctx: Any) -> str: """Return the analysis heading text aligned with history dropdown labels.""" badge = _CALC_TYPE_BADGES.get(ctx.calc_type, str(ctx.calc_type or "Unknown")) - core = f"[{badge}] {ctx.label}" - from quantui.app_formatters import friendly_timestamp + from quantui.app_formatters import formula_unicode, friendly_timestamp + + label = str(ctx.label) + formula = str(getattr(ctx, "formula", "") or "") + if formula and label.startswith(formula): + # H₂O, as in the point group and irrep labels beside it (UX-30). + label = formula_unicode(formula) + label[len(formula) :] + core = f"[{badge}] {label}" ts = friendly_timestamp(str(getattr(ctx, "timestamp", "") or "").strip()) return f"{ts} · {core}" if ts else core diff --git a/quantui/app_builders.py b/quantui/app_builders.py index 36f34907..34ff6ab4 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -201,6 +201,27 @@ def _ok(flag: bool, extra: str = "") -> str: cross = f'✗' return (tick if flag else cross) + (" " + extra if extra else "") + # Optional parts a lab machine usually lacks (GPU, PyFock) get a neutral + # chip, not a red cross: a missing extra is not a fault (UX-27). Install + # hints sit behind a disclosure for instructors. + def _optional(flag: bool, extra: str = "", details: str = "") -> str: + if flag: + return _ok(True, extra) + chip = ( + f'Not installed (optional)' + ) + if details: + chip += ( + '
    ' + f'' + "Details for instructors" + f'
    ' + f"{details}
    " + ) + return chip + env_badge = ( f'  {_html.escape(env)}' @@ -247,9 +268,14 @@ def _gpu_cell(gpu_state: Any) -> str: ) return cell detail = reason if reason else "not installed or no CUDA device" - return _ok( - False, - f'— {_html.escape(str(detail))}', + from quantui.gpu_offload import _REASON_NOT_INSTALLED + + if detail == _REASON_NOT_INSTALLED or not reason: + return _optional(False, details=_html.escape(str(detail))) + # Installed but not in use (switched off, no device): say so plainly. + return ( + f'Not in use ' + f'— {_html.escape(str(detail))}' ) def _render_status(gpu_state: Any) -> str: @@ -263,25 +289,29 @@ def _render_status(gpu_state: Any) -> str: ), ( "PyFock (Windows SP)", - _ok( + _optional( pyfock_available, - "— Phase-1 PBE" if pyfock_available else "— optional", + "— Phase-1 PBE", + "PyFock is a second quantum engine for native Windows " + "(single points). Install with " + "pip install 'quantui[pyfock]'.", ), ), ("ASE (structure I/O, opt.)", _ok(ase_available)), - ("PubChem search", _ok(pubchem_available)), + ("PubChem search", _optional(pubchem_available)), ("3D viewer (py3Dmol)", _ok(visualization_available)), ("GPU offload (gpu4pyscf)", _gpu_cell(gpu_state)), ("CPU cores / Memory", f"{cores} cores / {mem}"), ] + # Labels on one line (they wrapped: "PyFock (Windows / SP)"). rows = "".join( - f'
    ' for k, v in items ) return ( f'
    ' f'
    ' f"QuantUI {quantui.__version__}" @@ -562,10 +592,8 @@ def _render_status(gpu_state: Any) -> str: layout=layout_fn( margin="8px 0 8px 0", padding="12px 16px", - border_top=f"1px solid {_theme.css.BORDER}", - border_right=f"1px solid {_theme.css.BORDER}", - border_bottom=f"1px solid {_theme.css.BORDER}", - border_left=f"4px solid {_theme.css.TEXT_SUBTLE}", + # One thin border, no side stripe (UX-33). + border=f"1px solid {_theme.css.BORDER}", ), ) @@ -970,7 +998,7 @@ def _sync_recent(_change: Any = None) -> None: # History population (loads every saved result) is deferred to a background # task after the UI paints — see app._start_deferred_startup_tasks. Show a # placeholder until then. - app.past_dd.options = [("⏳ loading saved results…", "")] + app.past_dd.options = [("Loading saved results…", "")] app._refresh_perf_stats() @@ -1253,7 +1281,7 @@ def build_shared_widgets( # loaded; _sync_spin_helper shows it and preselects the metal. layout=layout_fn(display="none"), ) - app.spin_helper_box.set_title(0, "🧲 Spin-state helper (metal complexes)") + app.spin_helper_box.set_title(0, "Spin-state helper (metal complexes)") app.spin_helper_box.selected_index = None # collapsed by default # Classical (MMFF/UFF) pre-optimization is an explicit, transparent tool — # Preview → Keep/Revert — NOT a silent checkbox baked into the run. This @@ -2085,6 +2113,9 @@ def build_welcome_header(app: Any, *, layout_fn: Any = None) -> None: width=44, height=44, ) + # Dark palettes put a soft light disc behind it (theme.logo_css): the + # blue core read as a dim dot on navy (UX-35). + app._welcome_logo.add_class(_theme.LOGO_CLASS) # Text-only HTML. ``_welcome_html`` is kept as a pure HTML widget so # ``app_runflow.on_exit_clicked`` can still ``.value = ...`` it with @@ -2719,7 +2750,8 @@ def _plot_export_row(prefix: str) -> widgets.HBox: # _on_vib_export_animation: plotlymol3d is preferred for export quality, # py3Dmol is the fallback when plotlymol3d isn't installed. app._vib_export_btn = widgets.Button( - description="⬇ Export Animation", + description="Export Animation", + icon="download", tooltip=( "Save the current vibrational mode as a self-contained HTML " "file (PlotlyMol preferred for export quality; py3Dmol " @@ -4219,7 +4251,7 @@ def build_compare_section(app: Any, *, layout_fn: Any, rdkit_available: bool) -> # Deferred to a background startup task (loads every saved result) — see # app._start_deferred_startup_tasks. Placeholder until then. - app.compare_select.options = [("⏳ loading saved results…", "")] + app.compare_select.options = [("Loading saved results…", "")] def build_output_tab(app: Any, *, layout_fn: Any) -> None: diff --git a/quantui/app_formatters.py b/quantui/app_formatters.py index f9dab601..c35e9fac 100644 --- a/quantui/app_formatters.py +++ b/quantui/app_formatters.py @@ -9,6 +9,12 @@ from quantui import theme as _theme +# Font Awesome icon (as the app's buttons use), not an emoji (UX-31). +_GPU_BADGE = ( + f'' + ' GPU' +) + def _converged_color(converged: bool) -> str: return _theme.css.ACCENT_SUCCESS if converged else _theme.css.ACCENT_ERROR_ALT @@ -52,9 +58,31 @@ def _esc(value: Any) -> str: return html.escape(str(value)) +# Digits that follow an element symbol (or a closing bracket) are counts. +_FORMULA_COUNT = re.compile(r"(?<=[A-Za-z)\]])(\d+)") +_SUBSCRIPT_DIGITS = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") + + +def formula_html(formula: Any) -> str: + """:func:`display_formula` for HTML, counts as ````: H2O. + + One notation everywhere a formula is shown, matching the subscripted + point groups (C₂ᵥ) and irreps (a₁) beside it (UX-30). + """ + return _FORMULA_COUNT.sub(r"\1", _esc(display_formula(formula))) + + +def formula_unicode(formula: Any) -> str: + """:func:`display_formula` with Unicode subscripts (H₂O), for plain text + such as dropdown options, which cannot hold markup.""" + return _FORMULA_COUNT.sub( + lambda m: m.group(1).translate(_SUBSCRIPT_DIGITS), display_formula(formula) + ) + + def _formula_html(formula: Any) -> str: - """:func:`display_formula`, escaped for HTML.""" - return _esc(display_formula(formula)) + """:func:`display_formula`, escaped for HTML, counts subscripted.""" + return formula_html(formula) def friendly_timestamp(ts: Any) -> str: @@ -116,8 +144,10 @@ def _homo_lumo_gap_label(scf_variant: str | None) -> str: def _result_card_open(*, accent: str | None = None, extra_style: str = "") -> str: border = accent or _theme.css.ACCENT_SUCCESS_ALT style = ( - f"background:{_theme.css.BG_PANEL};border:1px solid {_theme.css.BORDER};" - f"border-left:4px solid {border};padding:10px 14px;border-radius:4px;" + # A full 1 px border in the card's status colour, not a 4 px side + # stripe (UX-33). + f"background:{_theme.css.BG_PANEL};border:1px solid {border};" + f"padding:10px 14px;border-radius:4px;" f"margin:6px 0" ) if extra_style: @@ -272,10 +302,10 @@ def _num(label: str, value: str) -> str: if bool(get("gpu_used", False)): _name = get("gpu_name") _device = ( - f'🚀 GPU' + f"{_GPU_BADGE}" f' — {_esc(_name)}' if _name - else f'🚀 GPU' + else _GPU_BADGE ) else: _device = f'CPU' @@ -1635,7 +1665,7 @@ def format_reorg_result(r: Any) -> str: def slurm_history_marker(data: dict[str, Any]) -> str: - """Short History-list marker for a SLURM result, e.g. ``🖥 SLURM 812345·a2 ``. + """Short History-list marker for a SLURM result, e.g. ``[SLURM 812345·a2] ``. Empty for local results and for results saved before SLURM provenance was recorded. @@ -1645,12 +1675,14 @@ def slurm_history_marker(data: dict[str, Any]) -> str: info = data.get("slurm") or {} job_id = info.get("job_id") attempt = info.get("attempt") - text = "🖥 SLURM" + # Plain text in brackets, like the calibration marker: dropdown options + # cannot hold icons, and the emoji read as decoration (UX-31). + text = "SLURM" if job_id: text += f" {job_id}" if attempt: text += f"·a{attempt}" - return text + " " + return f"[{text}] " def _slurm_provenance_row(data: dict[str, Any]) -> str: diff --git a/quantui/app_menubar.py b/quantui/app_menubar.py index f822cc09..81a6db3a 100644 --- a/quantui/app_menubar.py +++ b/quantui/app_menubar.py @@ -382,11 +382,34 @@ def _reason(app: Any) -> Optional[str]: if name in getattr(app, "_ana_available", set()): return None when = getattr(app, "_ana_when_map", {}).get(name, "") - return f"Needs a {when} result" if when else "No data for this result" + # "Available after: Single Point, Geometry Opt" — no article to get + # wrong ("a NMR"), and the list reads as a list (UX-29). + return ( + "Available after: " + when.replace(" / ", ", ") + if when + else "No data for this result" + ) return _reason +def panel_title(app: Any, name: str) -> str: + """The panel's own title ("Energy-level Diagram"), for menu items. + + The menu used the short internal names (Energies, Isosurface), which did + not match the panels they open (UX-29). + """ + from quantui.app_analysis import _base_title + + names = list(getattr(app, "_ana_panel_names", []) or []) + accs = list(getattr(app, "_ana_accordions", []) or []) + if name in names: + title = _base_title(accs[names.index(name)]).strip() + if title: + return title + return name + + # --------------------------------------------------------------------------- # Actions (each calls an existing handler) # --------------------------------------------------------------------------- @@ -728,10 +751,10 @@ def menu_definitions(app: Any) -> List[Tuple[str, List[MenuEntry]]]: panel_items: List[MenuEntry] = [ MenuItem( f"panel_{i}", - name, + panel_title(app, name), "angle-right", _jump(name), - tip=f"Open the {name} panel on the Analysis tab", + tip=f"Open the {panel_title(app, name)} panel on the Analysis tab", reason=_panel_reason(name), ) for i, name in enumerate(getattr(app, "_ana_panel_names", [])) diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index 97dfff9a..4bf6bd26 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -1482,7 +1482,7 @@ def _refresh_seed_options( n_imag = sum(1 for f in ir.get("frequencies_cm1") or [] if f < 0) imag_note = f", {n_imag} imag" if n_imag else "" label = ( - f"📈 Freq · {data['formula']} " + f"Freq · {data['formula']} " f"{data['method']}/{data['basis']}{imag_note} — {ts}" ) options.append((label, f"{FREQ_SEED_PREFIX}{d}")) @@ -1800,7 +1800,7 @@ def on_preopt_preview(app: Any, btn: Any = None) -> None: app.preopt_reset_btn.disabled = True app.preopt_preview_box.layout.display = "" app.preopt_preview_status.value = _preopt_small( - "⏳ Pre-optimizing — watch it relax below…" + "Pre-optimizing — watch it relax below…" ) try: app._activity_begin("Previewing pre-optimization…", kind="ui") @@ -2074,16 +2074,19 @@ def on_copy_results_path(app: Any, btn: Any) -> None: display(Javascript(f"navigator.clipboard.writeText('{path_str}')")) # The kernel cannot see whether the browser allowed the clipboard write # (it needs a secure context), so do not claim success outright. + from quantui.utils import path_html + app.results_path_lbl.value = ( - '' - f"Copied to clipboard (if the browser allowed it): {html.escape(str(p))}" + f'' + f"Copied to clipboard (if the browser allowed it): {path_html(p)}" "" ) def _reset() -> None: time.sleep(3) app.results_path_lbl.value = ( - f'{p}' + f'' + f"{path_html(p)}" ) try: @@ -3178,6 +3181,7 @@ def refresh_results_browser(app: Any) -> None: return from quantui.app_formatters import ( display_formula, + formula_unicode, friendly_timestamp, slurm_history_marker, ) @@ -3186,10 +3190,11 @@ def refresh_results_browser(app: Any) -> None: entry_date, refresh_history_facet_options, ) + from quantui.utils import path_html app.results_path_lbl.value = ( f'' - f"{app._get_results_dir()}" + f"{path_html(app._get_results_dir())}" ) dirs = list_results() if not dirs: @@ -3209,7 +3214,7 @@ def refresh_results_browser(app: Any) -> None: # can tell them apart from user-initiated calcs. The marker # comes from result.json's ``calibration_run_id`` extras field # written by the worker. - calib_marker = "🔧 " if data.get("calibration_run_id") else "" + calib_marker = "[calibration] " if data.get("calibration_run_id") else "" # SLURM batch results carry job id + attempt. slurm_marker = slurm_history_marker(data) formula = display_formula(data.get("formula", "?")) @@ -3217,7 +3222,7 @@ def refresh_results_browser(app: Any) -> None: basis = data.get("basis", "?") label = ( f"{friendly_timestamp(ts)} · [{calc_badge}] " - f"{calib_marker}{slurm_marker}{formula} " + f"{calib_marker}{slurm_marker}{formula_unicode(formula)} " f"{method}/{basis}" ) entries.append( diff --git a/quantui/app_setup_dialog.py b/quantui/app_setup_dialog.py index b0c85c26..e20afc94 100644 --- a/quantui/app_setup_dialog.py +++ b/quantui/app_setup_dialog.py @@ -21,13 +21,13 @@ from __future__ import annotations -import html as _html import logging from typing import Any, Optional, Tuple import ipywidgets as widgets from quantui import theme as _theme +from quantui.app_formatters import formula_html logger = logging.getLogger(__name__) @@ -116,7 +116,7 @@ def _title_html(app: Any) -> str: mol = getattr(app, "_molecule", None) what = ( f' — ' - f"{_html.escape(mol.get_formula())}" + f"{formula_html(mol.get_formula())}" if mol is not None else "" ) diff --git a/quantui/app_slurm.py b/quantui/app_slurm.py index 67244fc7..328218fb 100644 --- a/quantui/app_slurm.py +++ b/quantui/app_slurm.py @@ -322,7 +322,7 @@ def submit_slurm_run(app: Any) -> None: app.run_status.value = f"Submitted to SLURM (job {slurm_id}). Monitoring…" _append_run_stdout( app, - f"\n📤 Submitted batch job {slurm_id} (request {request_id})\n" + f"\nSubmitted batch job {slurm_id} (request {request_id})\n" f"Job directory: {(record.job_dir or record.staging_dir) if record else '?'}\n", ) threading.Thread( @@ -1019,7 +1019,7 @@ def _ingest_success(app: Any, record: Any) -> None: app.run_status.value = ( f"SLURM {calc_type.replace('_', ' ')} complete — saved to {saved_dir.name}." ) - _append_run_stdout(app, f"\n✅ Result saved to {saved_dir}\n") + _append_run_stdout(app, f"\nResult saved to {saved_dir}\n") app.result_output.append_display_data( HTML(completion_summary_html(saved_dir, payload)) ) diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index e9533264..592ad259 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -28,7 +28,11 @@ viewer_render_kwargs, ) from quantui.downloads import download_link_html as _download_link_html -from quantui.orbital_visualization import _GENERIC_CAPTURE_JS, _png_capture_controls +from quantui.orbital_visualization import ( + _GENERIC_CAPTURE_JS, + _png_capture_controls, + pretty_irrep, +) from quantui.plotly_embed import figure_html as _plotly_figure_html from quantui.symmetry import html_irrep from quantui.viz_assets import fit_zoom, fit_zoom_js, orient_js, orient_view @@ -65,7 +69,7 @@ def _show_plot_error(app: Any, out: Any, what: str, exc: BaseException) -> None: try: app._set_html_output( out, - f'

    ⚠ {html.escape(what)} could ' + f'

    ⚠ {html.escape(what)} could ' f"not be plotted: {detail}

    ", ) except Exception: # noqa: BLE001 — error display must never raise @@ -275,7 +279,7 @@ def on_traj_expand(app: Any, change: dict[str, Any]) -> None: app.traj_output.children = ( widgets.HTML( value=( - '

    ' + '

    ' "Loading trajectory viewer…

    " ) ), @@ -298,7 +302,7 @@ def on_traj_expand(app: Any, change: dict[str, Any]) -> None: app.traj_output.children = ( widgets.HTML( value=( - f'

    ' + f'

    ' f"⚠ Trajectory rendering failed: {html.escape(str(exc))}

    " ) ), @@ -340,7 +344,7 @@ def _is_stale() -> bool: app.traj_output.children = ( widgets.HTML( value=( - '

    ' + '

    ' "No trajectory data available (single-frame result).

    " ) ), @@ -435,7 +439,7 @@ def _on_traj_png_captured(change: dict) -> None: "output_type": "display_data", "data": { "text/html": ( - '

    ' + '

    ' f"Trajectory viewer failed: {_escape(str(exc))}

    " ) }, @@ -455,7 +459,7 @@ def _on_traj_png_captured(change: dict) -> None: def _on_export(_btn) -> None: _btn.disabled = True export_status.value = ( - f'' + f'' f"Generating {n}-frame animation, please wait…" ) @@ -492,7 +496,7 @@ def _do_export() -> None: export_status, "value", ( - f'' + f'' f"✓ Saved: {_escape(str(out_path))} " + _download_link_html(out_path) ), @@ -502,7 +506,7 @@ def _do_export() -> None: setattr, export_status, "value", - 'Export failed: ' + 'Export failed: ' f"{_escape(str(exc))}", ) finally: @@ -720,7 +724,8 @@ def show_vib_animation(app: Any, freq_result: Any, molecule: Any) -> bool: else f"Mode {i}: {freq_val:.1f} cm⁻¹ (imaginary, TS?)" ) sym = irreps.labels[i - 1] if irreps is not None else None - options.append((f"{label} · {sym}" if sym else label, i)) + # a₁, not a1: the mode table beside it subscripts the irreps (UX-30). + options.append((f"{label} · {pretty_irrep(sym)}" if sym else label, i)) if not options: return False @@ -768,8 +773,10 @@ def show_vib_animation(app: Any, freq_result: Any, molecule: Any) -> bool: token = app._vib_render_token _swap_vib_output( app, - _VIB_CAMERA_RESET_JS + f'

    ' - f"⏳ Rendering vibrational animation ({first_label})…

    ", + _VIB_CAMERA_RESET_JS + + f'

    ' + f' ' + f"Rendering vibrational animation ({first_label})…

    ", ) _start_daemon( app._render_vib_mode, vib_data, molecule, first_mode, render_token=token @@ -2132,7 +2139,7 @@ def _show_timeout() -> None: btn.description = "Generate Isosurface" app._set_html_output( app._orb_iso_output, - '

    ' + '

    ' "⚠ Orbital isosurface timed out after 180 s. " "Try a smaller basis set or a smaller molecule.

    ", ) @@ -2316,7 +2323,7 @@ def _show_range_err() -> None: return app._set_html_output( app._orb_iso_output, - '

    ' + '

    ' f"⚠ Orbital number out of range. This calculation has " f"{n_total} molecular orbitals (valid MO numbers 1–" f"{n_total}; HOMO = MO {n_occ}).

    ", @@ -2508,7 +2515,7 @@ def _show_range_err() -> None: def _show_err(msg: str = err_msg) -> None: app._set_html_output( app._orb_iso_output, - f'

    ' + f'

    ' f"⚠ Orbital isosurface failed: {html.escape(msg)}

    ", ) @@ -2583,7 +2590,7 @@ def _show_msg(msg: str) -> None: app._set_html_output, app._orb_iso_output, # Plain text: messages carry exception text (audit VIZ-12). - f'

    ⚠ {html.escape(msg)}

    ', + f'

    ⚠ {html.escape(msg)}

    ', ) mo_coeff = getattr(app, "_last_orb_mo_coeff", None) @@ -2702,7 +2709,7 @@ def _show_msg(msg: str) -> None: html_str = _plotly_figure_html(fig, full_html=False) if mode == "esp": html_str = ( - '

    ESP colouring ' + '

    ESP colouring ' "needs the py3Dmol backend; showing the density surface " "only.

    " + html_str ) @@ -2757,7 +2764,8 @@ def _vib_err(app: Any, msg: str) -> None: Escaped: callers pass exception text (audit VIZ-12).""" _swap_vib_output( - app, f'

    ⚠ {html.escape(msg)}

    ' + app, + f'

    ⚠ {html.escape(msg)}

    ', ) @@ -3372,7 +3380,9 @@ def on_iso_cancel(app: Any, btn: Any = None) -> None: pass status = getattr(app, "_iso_export_status", None) if status is not None: - status.value = 'Cancelled.' + status.value = ( + 'Cancelled.' + ) def iso_bridge_update(app: Any, **opts: Any) -> None: @@ -3437,7 +3447,7 @@ def update_iso_enclosed_label(app: Any) -> None: "" if frac is None else ( - f'encloses ' + f'encloses ' f"{frac * 100:.1f}% {what}" ) ) @@ -3616,8 +3626,9 @@ def on_vib_mode_changed(app: Any, change: dict[str, Any]) -> None: token = app._vib_render_token _swap_vib_output( app, - f'

    ' - f"⏳ Rendering vibrational animation ({label})…

    ", + f'

    ' + f' ' + f"Rendering vibrational animation ({label})…

    ", ) _start_daemon( app._render_vib_mode, vib_data, molecule, mode_number, render_token=token @@ -3626,7 +3637,7 @@ def on_vib_mode_changed(app: Any, change: dict[str, Any]) -> None: _STEPPER_BTN_STYLE = ( f"padding:2px 9px;border:1px solid {_theme.css.BORDER};border-radius:4px;" - "background:#f8fafc;color:#334155;cursor:pointer;font-size:13px;line-height:1.4;" + "background:var(--q-bg-panel,#f8fafc);color:var(--q-text-body,#334155);cursor:pointer;font-size:13px;line-height:1.4;" ) # Reorg geometry Save-PNG bridge: appends the active stepper slug after the URI @@ -3769,7 +3780,7 @@ def _frame_stepper_controls( f"{ab_html}" "
    " f'
    ' + 'style="font-size:12px;color:var(--q-text-secondary,#64748b);margin:0 0 4px 2px;">' f"{initial_label}
    " ) js = ( @@ -3828,7 +3839,7 @@ def build_reorg_geometry_viewer_html( from quantui.viz_assets import make_view if not geometries: - return '

    No geometries available.

    ' + return '

    No geometries available.

    ' blocks = [] for g in geometries: @@ -3896,7 +3907,7 @@ def build_reorg_geometry_viewer_html( 1000, # unused: loop=False and Play is not the point here label_js=( 'var s=""+LBL[i]+"";' - 'if(NOTE[i]) s+="
    "+NOTE[i]+"";' + 'if(NOTE[i]) s+="
    "+NOTE[i]+"";' "return s;" ), initial_label=geometries[0].get("label", "Geometry 1"), @@ -4008,13 +4019,13 @@ def _xyz(g: dict) -> str: ) legend = ( '
    ' - '━ ' + '━ ' f'{reference.get("label", "reference").split(" — ")[0]}' ' ━ ' f'{other.get("label", "other").split(" — ")[0]}' ' ⟶ ' f"displacement ({moved}){scale_note}" - '
    Shown as computed, not superimposed — ' + '
    Shown as computed, not superimposed — ' "the displacement is the quantity of interest." "
    " ) @@ -5201,7 +5212,7 @@ def on_orbital_gallery(app: Any, btn: Any = None) -> None: button.description = "Building gallery…" app._set_html_output( app._orb_gallery_output, - f'

    ⏳ Computing {2 * each_side} ' + f'

    Computing {2 * each_side} ' "orbitals…

    ", ) @@ -5210,7 +5221,7 @@ def _work() -> None: html_str = build_gallery_for_app(app, each_side) except Exception as exc: # noqa: BLE001 — shown in the panel html_str = ( - '

    ⚠ Orbital gallery failed: ' + '

    ⚠ Orbital gallery failed: ' f"{html.escape(f'{type(exc).__name__}: {exc}')}

    " ) diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 7744c75e..cb171266 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -48,6 +48,7 @@ import ipywidgets as widgets from quantui import theme as _theme +from quantui.app_formatters import formula_html from quantui.app_measurement import MEASURE_INBOX_CLASS from quantui.app_pick_mode import ( PICK_BANNER_CSS, @@ -501,7 +502,7 @@ def footer_html(app: Any) -> str: tag = {"result": "result", "input": "input"}.get(str(source), "") parts.append( f'' - f"{_html.escape(mol.get_formula())} · {n} atom" + f"{formula_html(mol.get_formula())} · {n} atom" f"{'s' if n != 1 else ''} · charge {int(getattr(mol, 'charge', 0))} · " f"mult {int(getattr(mol, 'multiplicity', 1))}" + ( @@ -539,12 +540,12 @@ def caption_html(app: Any) -> str: 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 " + f"Input structure {formula_html(mol.get_formula())}, as set up " "on the Calculate tab." ) elif source == "input": text = ( - f"Input structure {_html.escape(mol.get_formula())} — run a " + f"Input structure {formula_html(mol.get_formula())} — run a " "calculation to analyse it." ) else: diff --git a/quantui/benchmarks.py b/quantui/benchmarks.py index becd8999..34c25296 100644 --- a/quantui/benchmarks.py +++ b/quantui/benchmarks.py @@ -850,7 +850,7 @@ def _save_calibration_step( - ``save_result`` — base dir + result.json + pyscf.log. The ``extras={"calibration_run_id": ...}`` tag lets the History - dropdown render a 🔧 marker beside calibration entries. + dropdown render a "[calibration]" marker beside calibration entries. - ``save_thumbnail`` — the card shown in the History dropdown. - For GeoOpt: ``save_trajectory`` (so the Trajectory panel works). - For SP/GeoOpt/Freq with MO data: ``save_orbitals`` (so the diff --git a/quantui/descriptor_cards.py b/quantui/descriptor_cards.py index 0fd74475..5e2635e1 100644 --- a/quantui/descriptor_cards.py +++ b/quantui/descriptor_cards.py @@ -155,7 +155,9 @@ def _card_html(*, fg: str, bg: str, icon: str, title: str, body: str) -> str: """Assemble one descriptor card (icon + title + one-line body).""" return ( f'
    ' f'' f"{icon}" diff --git a/quantui/help_content.py b/quantui/help_content.py index 480e62be..d8341cc1 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -1253,7 +1253,7 @@ "Resubmit runs a job again (for example after it ran out of " "time), and Remove clears a finished job from the list." "
  • Finished jobs appear in History (marked " - "🖥 SLURM), where you open them like any other " + "[SLURM …]), where you open them like any other " "result.
  • " "
  • A resubmitted Geometry Opt, Frequency, PES Scan, Transition State " "or Reorganization Energy job continues from its checkpoint instead " @@ -1506,6 +1506,11 @@ "dialog and shows the live output on the Calculate tab. To pick " "scan atoms by clicking the structure (PES Scan), close the " "dialog first.

    " + "

    Keyboard: Tab moves between controls (a ring shows " + "where you are; the first Tab offers Skip to molecule " + "input). On a menu title, the arrow keys open the menu and " + "move through its items, left and right move between menus, Enter " + "chooses and Esc closes.

    " "

    The menu bar can be turned off in System Settings " "(Menu bar); the tabs work the same either way.

    " ), diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py index 2da36d76..c21dff81 100644 --- a/quantui/orbital_visualization.py +++ b/quantui/orbital_visualization.py @@ -676,7 +676,7 @@ def orbital_summary_html(info: OrbitalInfo) -> str: """ a = " (α)" if _is_unrestricted(info) else "" # counts below are alpha-only return ( - '
    ' f"Orbital Summary — {_html_escape(info.formula)}
    " f"Occupied MOs{a}: {info.n_occupied}  |  " @@ -1827,7 +1827,7 @@ def esp_legend_html(esp_range: float) -> str: "border:1px solid #999;border-radius:3px;" 'background:linear-gradient(to right,#ff0000,#ffffff,#0000ff)">' f"+{esp_range:.3f} a.u.
    (+{kcal:.0f} kcal/mol)
    " - 'red: electron-rich (attracts a + charge) · ' + 'red: electron-rich (attracts a + charge) · ' "blue: electron-poor
    " ) @@ -1935,7 +1935,7 @@ def _build_iso_viewer( m = re.search(r"3dmolviewer_(\w+)", view_html) if m is None: logger.error("could not find py3Dmol viewer id; isosurface unavailable") - return '

    Viewer could not be built.

    ' + return '

    Viewer could not be built.

    ' uid = m.group(1) js = ( @@ -1962,8 +1962,8 @@ def _build_iso_viewer( busy = ( f'" + 'font-size:13px;color:var(--q-text-body,#334155);font-style:italic;pointer-events:none">' + ' Generating…
  • ' ) # position:relative on the wrapper so the overlay is placed against the # viewer rather than the page. @@ -1983,7 +1983,7 @@ def _build_iso_viewer( # this module, and importing back would close the cycle. _ORB_BTN_STYLE = ( f"padding:2px 9px;border:1px solid {_theme.css.BORDER};border-radius:4px;" - "background:#f8fafc;color:#334155;cursor:pointer;font-size:13px;line-height:1.4;" + "background:var(--q-bg-panel,#f8fafc);color:var(--q-text-body,#334155);cursor:pointer;font-size:13px;line-height:1.4;" ) # JS->kernel bridge for "save what I am looking at". diff --git a/quantui/theme.py b/quantui/theme.py index 75f590dc..cddf7cfd 100644 --- a/quantui/theme.py +++ b/quantui/theme.py @@ -456,8 +456,8 @@ def _widget_chrome_css() -> str: ".quantui-info-box " f"{{ background: {surface} !important; " "color: var(--q-text-body) !important; " - "border: 1px solid var(--q-border) !important; " - "border-left: 4px solid var(--q-accent-info) !important; " + # One thin accent border, no 4 px side stripe (UX-33). + "border: 1px solid var(--q-accent-info) !important; " "padding: 10px; border-radius: 5px; margin-bottom: 10px; }\n" ".quantui-info-box small " "{ color: var(--q-text-muted) !important; }\n" @@ -736,6 +736,24 @@ def get_palette(palette_id: str) -> ThemePalette: return PALETTES.get(palette_id, PALETTES[DEFAULT_PALETTE_ID]) +LOGO_CLASS = "quantui-logo" + + +def logo_css(palette: ThemePalette) -> str: + """Header logo backdrop: a soft light disc on dark palettes (UX-35). + + The logo's blue core is drawn for light backgrounds; on navy it was a dim + dot. Light palettes need nothing. + """ + if not palette.is_dark: + return f".{LOGO_CLASS} {{ background: none !important; }}\n" + return ( + f".{LOGO_CLASS} {{ border-radius: 50% !important; background: " + "radial-gradient(circle at center, rgba(241,245,249,0.92) 0, " + "rgba(241,245,249,0.92) 30%, rgba(241,245,249,0) 62%) !important; }\n" + ) + + def theme_css_block(palette_id: str) -> str: """Inject CSS custom properties for *palette_id*.""" palette = get_palette(palette_id) @@ -744,7 +762,7 @@ def theme_css_block(palette_id: str) -> str: merged.update(palette.jupyterlab_variables()) lines = [f" {k}: {v};" for k, v in merged.items()] vars_block = "\n".join(lines) - chrome = _widget_chrome_css() + chrome = _widget_chrome_css() + logo_css(palette) css_text = ":root {\n" f"{vars_block}\n" "}\n" f"{chrome}" return theme_injection_html(css_text) @@ -879,6 +897,8 @@ def frame_viewer_html(view_html: str, *, width: int, controls: str = "") -> str: "disabled_button_css", "focus_ring_css", "frame_viewer_html", + "LOGO_CLASS", + "logo_css", "get_palette", "plotly_colors", "theme_css_block", diff --git a/quantui/utils.py b/quantui/utils.py index 55d0f849..ae486cd9 100644 --- a/quantui/utils.py +++ b/quantui/utils.py @@ -217,6 +217,49 @@ def format_file_size(size_bytes: int) -> str: return f"{size:.1f} TB" +def short_path(path: "os.PathLike[str] | str") -> str: + """A short, readable form of *path* for student-facing text. + + Relative to the working folder when inside it, ``~/…`` when inside the + home folder, otherwise ``…//``. Show the full path in a + tooltip (:func:`path_html`): absolute paths such as + ``/tmp/…/results-a/2026-…_H2O_RHF_STO-3G`` were noise for students + (UI/UX review 2026-12-05, UX-28). + """ + p = Path(path) + try: + full = p.resolve() + except (OSError, RuntimeError): + full = p + for base, prefix in ((Path.cwd(), ""), (Path.home(), "~/")): + try: + root = base.resolve() + if len(root.parts) <= 1: + continue # "/" as the base would shorten nothing + rel = full.relative_to(root) + except (ValueError, OSError, RuntimeError): + continue + text = rel.as_posix() + if text in ("", "."): + return prefix.rstrip("/") or "." + return f"{prefix}{text}" + parts = full.parts + if len(parts) <= 3: + return full.as_posix() + return "…/" + "/".join(parts[-2:]) + + +def path_html(path: "os.PathLike[str] | str") -> str: + """:func:`short_path` as HTML, with the full path as its tooltip.""" + import html as _html + + full = str(path) + return ( + f'' + f"{_html.escape(short_path(path))}" + ) + + def get_timestamp() -> str: """ Get current timestamp in ISO format. diff --git a/quantui/visualization_py3dmol.py b/quantui/visualization_py3dmol.py index 1f12a29e..083d94e1 100644 --- a/quantui/visualization_py3dmol.py +++ b/quantui/visualization_py3dmol.py @@ -553,7 +553,8 @@ def _info_box_html(molecule, backend: str) -> str: selected = backend if backend != "auto" else (backends[0] if backends else "") return ( '
    ' - "📊 Molecule Information
    " + ' ' + "Molecule Information
    " f"Formula: {molecule.get_formula()} | " f"Atoms: {len(molecule.atoms)} | " f"Electrons: {molecule.get_electron_count()} | " @@ -568,7 +569,7 @@ def _info_box_html(molecule, backend: str) -> str: def _unavailable_html(molecule) -> str: """HTML fallback when no 3D visualization backend is installed.""" return ( - '
    ' + '
    ' "

    ⚠️ 3D visualization not available.

    " "

    To enable visualization, install one of:

    " "
    • pip install py3dmol (recommended)
    • " @@ -680,8 +681,9 @@ class in the whole page, not scoped to which button was clicked). except Exception as e: logger.error(f"Render failed for {molecule.get_formula()}: {e}") parts.append( - '
      ' - f"❌ Visualization failed: {_html.escape(str(e))}
      " + '
      ' + ' ' + f"Visualization failed: {_html.escape(str(e))}
      " ) # Frame the fragment at the viewer's own width — see theme.frame_viewer_html # for why the border cannot live on the hosting Output widget's CSS class. @@ -744,7 +746,8 @@ def display_molecule( info_html = ( '
      ' - "📊 Molecule Information
      " + ' ' + "Molecule Information
      " f"Formula: {molecule.get_formula()} | " f"Atoms: {len(molecule.atoms)} | " f"Electrons: {molecule.get_electron_count()} | " @@ -776,7 +779,7 @@ def display_molecule( logger.info(f"Successfully displayed {molecule.get_formula()}") except Exception as e: - print(f"❌ Visualization failed: {e}") + print(f"Visualization failed: {e}") logger.error(f"Display failed for {molecule.get_formula()}: {e}") diff --git a/tests/test_app.py b/tests/test_app.py index 8f73473d..9fa8a12f 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -292,7 +292,8 @@ def test_export_btn_enabled_after_set_molecule(self): def test_mol_info_html_updated(self): app = QuantUIApp() app._set_molecule(_water()) - assert "H2O" in app.mol_info_html.value + # Counts are subscripted (UX-30). + assert "H2O" in app.mol_info_html.value def test_expand_restores_expanded_view(self): app = QuantUIApp() @@ -1607,7 +1608,7 @@ def test_returns_string(self): def test_contains_formula(self): app = QuantUIApp() html = app._format_nmr_result(self._make_nmr()) - assert "H2O" in html + assert "H2O" in html def test_contains_method_and_basis(self): app = QuantUIApp() @@ -3553,7 +3554,8 @@ def test_analysis_heading_matches_history_label_shape(self): # Same readable timestamp as the History label (audit D16). assert "2026-05-14 10:11" in heading assert "[Frequency Analysis]" in heading - assert "H2O B3LYP/6-31G" in heading + # Unicode subscripts, as in the History labels (UX-30). + assert "H₂O B3LYP/6-31G" in heading assert "(from History)" in heading diff --git a/tests/test_app_formatters.py b/tests/test_app_formatters.py index 37e8b807..e37ccd06 100644 --- a/tests/test_app_formatters.py +++ b/tests/test_app_formatters.py @@ -155,7 +155,8 @@ def test_live_and_history_cards_share_the_same_extra_rows(): "MP2 correlation", "Solvent (PCM)", "Compute device", - "🚀 GPU", + "fa-bolt", + "GPU", "NVIDIA A100", "Dipole moment", "1.8500 D", @@ -185,7 +186,7 @@ def test_history_card_graceful_on_pre_parity_result(): ) assert "Compute device" in html assert "CPU" in html - assert "🚀 GPU" not in html + assert "fa-bolt" not in html assert "Dipole moment" not in html assert "Mulliken charges" not in html @@ -301,7 +302,7 @@ def test_format_past_result_contains_calc_type_badge(): } html = format_past_result(data) assert "Single Point" in html - assert "H2O" in html + assert "H2O" in html def test_format_past_result_renders_ccsd_breakdown(): diff --git a/tests/test_app_menubar.py b/tests/test_app_menubar.py index 589813e2..064ddba6 100644 --- a/tests/test_app_menubar.py +++ b/tests/test_app_menubar.py @@ -192,7 +192,9 @@ def test_analysis_panels_unavailable_until_a_result(self, app): mb.open_menu(app, "Results") name = app._ana_panel_names[0] btn = _item(app, "panel_0") - assert btn.disabled and "Needs a" in btn.tooltip + assert btn.disabled and "Available after:" in btn.tooltip + # Menu items carry the panel's own title (UX-29). + assert btn.description == "Energy-level Diagram" app._ana_available.add(name) mb.open_menu(app, "Results") assert not _item(app, "panel_0").disabled @@ -431,7 +433,7 @@ def test_run_from_the_dialog_does_nothing_when_run_is_unavailable(self, app): def test_title_names_the_molecule(self, app): app._set_molecule(Molecule(["O", "H", "H"], WATER), "water") open_setup_dialog(app) - assert "H2O" in app._sd_title.value + assert "H2O" in app._sd_title.value def test_close_button_is_the_esc_target(self, app): assert DIALOG_CLOSE_CLASS in app._sd_close_btn._dom_classes diff --git a/tests/test_calibration_save_results.py b/tests/test_calibration_save_results.py index 43886cd1..a69e4353 100644 --- a/tests/test_calibration_save_results.py +++ b/tests/test_calibration_save_results.py @@ -314,7 +314,7 @@ def test_refresh_results_browser_emits_calibration_marker(self): from quantui import app_runflow src = inspect.getsource(app_runflow.refresh_results_browser) - # The 🔧 marker is rendered when calibration_run_id is present - # on the saved result.json. + # The "[calibration]" marker is rendered when calibration_run_id is + # present on the saved result.json. assert "calibration_run_id" in src - assert "🔧" in src or "calib_marker" in src + assert "[calibration]" in src and "calib_marker" in src diff --git a/tests/test_descriptor_cards.py b/tests/test_descriptor_cards.py index 7c1b45d8..8bc927c0 100644 --- a/tests/test_descriptor_cards.py +++ b/tests/test_descriptor_cards.py @@ -72,9 +72,11 @@ def test_title_includes_family_descriptor(self): class TestCardStructure: - def test_card_uses_left_border_accent_like_result_cards(self): + def test_card_uses_a_full_thin_border_not_a_side_stripe(self): + # UI/UX review 2026-12-05, UX-33. html = method_card_html("RHF") - assert "border-left:4px solid" in html + assert "border:1px solid" in html + assert "border-left:4px" not in html def test_no_cdn_or_external_asset(self): # Offline-safe: inline SVG only, never an / CDN link. diff --git a/tests/test_jobdirs.py b/tests/test_jobdirs.py index 0279c6f3..4fb22c0c 100644 --- a/tests/test_jobdirs.py +++ b/tests/test_jobdirs.py @@ -518,7 +518,7 @@ def test_history_marker_and_card_row(self): "attempt_dir": "/scratch/u/run/attempt-02_job812345", }, } - assert slurm_history_marker(data) == "🖥 SLURM 812345·a2 " + assert slurm_history_marker(data) == "[SLURM 812345·a2] " card = format_past_result(data) assert "Ran on" in card assert "job 812345 · attempt 2" in card diff --git a/tests/test_mode_irreps.py b/tests/test_mode_irreps.py index a64c15d9..732d6482 100644 --- a/tests/test_mode_irreps.py +++ b/tests/test_mode_irreps.py @@ -237,7 +237,7 @@ def test_mode_dropdown_names_the_irrep(self, tmp_path, monkeypatch): mol = Molecule([a for a, _ in m["atoms"]], [xyz for _, xyz in m["atoms"]]) app._show_vib_animation(self._nh3_result(), mol) labels = [lbl for lbl, _ in app.vib_mode_dd.options] - assert labels[0] == "Mode 1: 1090.5 cm⁻¹ · a1" + assert labels[0] == "Mode 1: 1090.5 cm⁻¹ · a₁" # as in the table assert labels[1].endswith("· e") def test_history_stub_carries_modes_and_geometry(self): diff --git a/tests/test_uiaudit_design.py b/tests/test_uiaudit_design.py index 8bf35322..dab49e94 100644 --- a/tests/test_uiaudit_design.py +++ b/tests/test_uiaudit_design.py @@ -155,7 +155,7 @@ def test_title_has_no_nested_parentheses(self): from quantui.app_formatters import format_freq_result html = format_freq_result(self._result()) - assert "H2O · B3LYP/6-31G* (RKS)" in html + assert "H2O · B3LYP/6-31G* (RKS)" in html assert "(B3LYP/6-31G* (RKS))" not in html def test_thermo_shows_corrections_not_absolute_kj(self): diff --git a/tests/test_uxrev_polish.py b/tests/test_uxrev_polish.py new file mode 100644 index 00000000..af10b3ad --- /dev/null +++ b/tests/test_uxrev_polish.py @@ -0,0 +1,228 @@ +"""Copy and polish from the UI/UX review 2026-12-05 (M-UXREV UXR.6): +formula notation, short paths, System Settings wording, icons instead of +emoji, theme colours in the viewer modules, no side stripes, logo backdrop. +""" + +from __future__ import annotations + +import os +import pathlib +import re + +import pytest + +from quantui import theme + +PKG = pathlib.Path(theme.__file__).parent + + +class TestFormulaNotation: + def test_html_subscripts_counts(self): + from quantui.app_formatters import formula_html + + assert formula_html("H2O") == "H2O" + assert formula_html("C6H6") == "C6H6" + assert formula_html("H3N") == "NH3" # display order kept + assert formula_html("") == "<b>" + + def test_unicode_for_plain_text(self): + from quantui.app_formatters import formula_unicode + + assert formula_unicode("H2O") == "H₂O" + assert formula_unicode("Fe(CO)5") == "Fe(CO)₅" + assert formula_unicode("") == "" + + def test_result_cards_subscript(self): + from quantui.app_formatters import format_past_result + + html = format_past_result( + { + "calc_type": "single_point", + "formula": "CH4", + "method": "RHF", + "basis": "STO-3G", + "energy_hartree": -40.0, + "converged": True, + } + ) + assert "CH4" in html + + +class TestShortPaths: + def test_inside_the_working_folder(self, tmp_path, monkeypatch): + from quantui.utils import short_path + + monkeypatch.chdir(tmp_path) + assert short_path(tmp_path / "results" / "run1") == "results/run1" + assert short_path(tmp_path) == "." + + def test_inside_home(self, tmp_path, monkeypatch): + from quantui.utils import short_path + + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.chdir("/") + target = tmp_path / "home" / ".quantui" / "results" + assert short_path(target) == "~/.quantui/results" + + def test_elsewhere_keeps_the_last_two_parts(self, monkeypatch): + from quantui.utils import short_path + + monkeypatch.chdir("/") + monkeypatch.setenv("HOME", "/nonexistent-home") + assert short_path("/srv/data/quantui/results-a/2026_H2O") == ( + "…/results-a/2026_H2O" + ) + + def test_full_path_is_the_tooltip(self): + from quantui.utils import path_html + + html = path_html("/srv/a/b/c") + assert 'title="/srv/a/b/c"' in html + assert ">…/b/c<" in html + + def test_results_label_has_no_absolute_path(self, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(tmp_path / "s.json")) + monkeypatch.chdir(tmp_path) + from quantui.app import QuantUIApp + + app = QuantUIApp() + saved = tmp_path / "results" / "2026-12-05_H2O_RHF_STO-3G" + saved.mkdir(parents=True) + app._show_result_log(saved, "") + value = app._result_dir_label.value + visible = re.sub(r'title="[^"]*"', "", value) + assert str(tmp_path) not in visible + assert "History" in value + assert f'title="{saved}"' in value + + +class TestSystemSettings: + @pytest.fixture + def app(self, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(tmp_path / "s.json")) + from quantui.app import QuantUIApp + + return QuantUIApp() + + def test_missing_gpu_is_neutral_with_details(self, app): + from quantui.gpu_offload import _REASON_NOT_INSTALLED + + html = app._render_status_html((False, None, _REASON_NOT_INSTALLED)) + row = html.split("GPU offload (gpu4pyscf)", 1)[1].split("", 1)[0] + assert "Not installed (optional)" in row + assert "Details for instructors" in row + assert "✗" not in row # no red cross + + def test_gpu_switched_off_says_not_in_use(self, app): + html = app._render_status_html((False, None, "QUANTUI_DISABLE_GPU is set")) + row = html.split("GPU offload (gpu4pyscf)", 1)[1].split("", 1)[0] + assert "Not in use" in row + + def test_labels_do_not_wrap_and_no_side_stripe(self, app): + html = app._render_status_html(None) + assert "white-space:nowrap" in html + assert "border-left:4px" not in html + + +class TestIconsNotEmoji: + # Colour emoji used as status icons in the app's own UI modules (UX-31). + # (molecule.py / pubchem.py error texts are left to the XYZ-error work.) + FILES = ( + "app_formatters.py", + "app_builders.py", + "app_runflow.py", + "app_visualization.py", + "app_slurm.py", + "visualization_py3dmol.py", + "orbital_visualization.py", + "app.py", + ) + # (The plain arrow glyph on the viewers' Save PNG buttons stays: those + # buttons also live in standalone exports, which have no icon font.) + EMOJI = re.compile("[\U0001f300-\U0001faff\u23f3\u2705\u274c]") + + @pytest.mark.parametrize("name", FILES) + def test_no_status_emoji_in_string_literals(self, name): + import ast + + tree = ast.parse((PKG / name).read_text(encoding="utf-8")) + docstrings = set() + for node in ast.walk(tree): + body = getattr(node, "body", None) + if isinstance(body, list) and body: + first = body[0] + if isinstance(first, ast.Expr) and isinstance( + first.value, ast.Constant + ): + docstrings.add(id(first.value)) + offenders = [ + f"{name}:{node.lineno}: {node.value[:50]!r}" + for node in ast.walk(tree) + if isinstance(node, ast.Constant) + and isinstance(node.value, str) + and id(node) not in docstrings + and self.EMOJI.search(node.value) + ] + assert offenders == [] + + def test_slurm_and_calibration_markers_are_text(self): + from quantui.app_formatters import slurm_history_marker + + data = {"execution_backend": "slurm", "slurm": {"job_id": "1", "attempt": 1}} + assert slurm_history_marker(data) == "[SLURM 1·a1] " + + +class TestThemeColoursInViewerModules: + FILES = ( + "app_visualization.py", + "orbital_visualization.py", + "visualization_py3dmol.py", + ) + # Data colours on a diverging scale (charge differences), not chrome. + ALLOWED = {"2166ac", "b2182b"} + + @pytest.mark.parametrize("name", FILES) + def test_inline_text_colours_use_tokens(self, name): + text = (PKG / name).read_text(encoding="utf-8") + found = { + m.group(1).lower() + for m in re.finditer( + r"(?:color|background)\s*:\s*#([0-9a-fA-F]{3,6})\b", text + ) + } + assert found <= self.ALLOWED, f"{name}: {sorted(found - self.ALLOWED)}" + + +class TestNoSideStripes: + def test_descriptor_card(self): + from quantui.descriptor_cards import basis_card_html + + assert "border-left:4px" not in basis_card_html("STO-3G") + + def test_result_card_and_info_box(self): + from quantui.app_formatters import _result_card_open + + assert "border-left:4px" not in _result_card_open() + assert "border-left: 4px" not in theme._widget_chrome_css() + + +class TestLogo: + def test_dark_palettes_get_a_backdrop(self): + for pid in theme.PALETTE_IDS: + p = theme.get_palette(pid) + css = theme.logo_css(p) + assert f".{theme.LOGO_CLASS}" in css + assert ("radial-gradient" in css) is p.is_dark + assert css in theme._widget_chrome_css() + css # well-formed + assert css in theme.theme_css_block(pid).replace("\\n", "\n") + + def test_logo_widget_carries_the_class(self, tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(tmp_path / "s.json")) + from quantui.app import QuantUIApp + + app = QuantUIApp() + assert theme.LOGO_CLASS in app._welcome_logo._dom_classes + + +def test_env_home_untouched(): + assert "HOME" in os.environ From dcf520a2209e25502c3ad9f3682904e939cbf907 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:19:18 +0000 Subject: [PATCH 09/12] Type fixes for CI's mypy in the pane views and setup dialog Two narrowings mypy asked for after the UXR.4 changes: the setup panel is checked for None before its children are read, and the isosurface banner label is read once into a local. 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_pane_views.py | 5 +++-- quantui/app_setup_dialog.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/quantui/app_pane_views.py b/quantui/app_pane_views.py index 339c625e..3fc79f71 100644 --- a/quantui/app_pane_views.py +++ b/quantui/app_pane_views.py @@ -459,8 +459,9 @@ def _push_iso_appearance(app: Any) -> None: def _banner_label(app: Any, name: str) -> str: label = PANE_VIEWS[name][1] - if name == ISOSURFACE and getattr(app, "_pv_iso_label", ""): - return f"{label}: {app._pv_iso_label}" + iso_label = getattr(app, "_pv_iso_label", None) + if name == ISOSURFACE and iso_label: + return f"{label}: {iso_label}" if name == "Vibrational": dd = getattr(app, "vib_mode_dd", None) for text, value in getattr(dd, "options", ()) or (): diff --git a/quantui/app_setup_dialog.py b/quantui/app_setup_dialog.py index e20afc94..b9860c78 100644 --- a/quantui/app_setup_dialog.py +++ b/quantui/app_setup_dialog.py @@ -227,7 +227,7 @@ def build_setup_dialog(app: Any, *, layout_fn: Any, enabled: bool = True) -> Non setup = getattr(app, "calc_setup_panel", None) host = _find_parent(getattr(app, "_calculate_tab_panel", None), setup) heading = _setup_heading(setup) - if enabled and host is not None and heading is not None: + if enabled and setup is not None and host is not None and heading is not None: heading.layout.flex = "1 1 auto" app._sd_open_row = widgets.HBox( [heading, app._sd_open_btn], From d8d8167850ee99d6a70a4de60fdd2d9904bd0723 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:37:29 +0000 Subject: [PATCH 10/12] Warm default theme; Light renamed Bright; Raman follows theme switches New Warm palette (cream page #fffaf0, warm charcoal text, deep teal accent) becomes the default, replacing Dark. It was picked from four warm candidates that all meet WCAG AA for text, button text and the focus ring; the palette contrast test now covers it. The former Light palette is renamed Bright. Old ids still resolve (theme.resolve_palette_id / PALETTE_ALIASES), and a saved "Light" in settings.json loads as Bright. 3D and plot scenes on light palettes use the lighter of page and panel, so Warm viewers sit on the cream page. Fixes found while making the mock-ups: the Raman spectrum is now re-rendered on a theme switch (it kept the run-time palette, hiding its axis titles on light themes), and the gold minimum star on PES plots gets an outline so it stays visible on light backgrounds. 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 | 12 +++++ README.md | 4 +- quantui/app.py | 7 +++ quantui/app_builders.py | 1 + quantui/app_visualization.py | 12 ++++- quantui/pes_scan_2d_plot.py | 7 ++- quantui/theme.py | 93 +++++++++++++++++++++++++++++++--- quantui/user_settings.py | 13 ++++- tests/test_app.py | 2 +- tests/test_app_menubar.py | 6 +-- tests/test_theme_contrast.py | 5 +- tests/test_uiaudit_design.py | 4 +- tests/test_user_settings.py | 2 +- tests/test_viz_audit_medium.py | 4 +- tests/test_warm_palette.py | 81 +++++++++++++++++++++++++++++ 15 files changed, 229 insertions(+), 24 deletions(-) create mode 100644 tests/test_warm_palette.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 64469df3..b63d8e73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ### Changed +- **New default theme: Warm.** A cream page with warm charcoal text and a + deep teal accent replaces Dark as the default; every text, button and + focus-ring colour meets WCAG AA. The former Light theme is now called + **Bright**; a saved "Light" choice opens as Bright. 3D viewers and plots on + light themes sit on the page colour instead of pure white. + - **Frequency calculations optimize the geometry first by default.** "Geometry optimization before calculation" now starts ticked for Frequency (other calculation types keep it unticked, and each type @@ -125,6 +131,12 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ### Fixed +- The Raman spectrum follows a theme switch; it used to keep the colours of + the theme active when the calculation ran, which hid its axis titles on + light themes. +- The gold "minimum" star on PES scan plots has an outline, so it stays + visible on light backgrounds and on the light end of the 2-D colour scale. + - The run status line next to Cancel wraps instead of being cut off at the panel edge. - Internal lines are hidden from the on-screen run log again (checkpoint diff --git a/README.md b/README.md index f27cd3c7..2ee0bdf3 100644 --- a/README.md +++ b/README.md @@ -146,8 +146,8 @@ Real output from QuantUI, straight from the app: - **Timing calibration** — one-click benchmark suite populates the time estimator with real machine data so predictions are accurate from the first run - **Voilà app mode** — serve the notebook as a polished widget-only UI (no - code visible), with six colour themes (Light, Dark, Midnight, Dark Blue, - Hot Pink, Dark Maroon), a dedicated output log, and an + code visible), with seven colour themes (Warm, the default; Bright, Dark, + Midnight, Dark Blue, Hot Pink, Dark Maroon), a dedicated output log, and an in-app bug-report form --- diff --git a/quantui/app.py b/quantui/app.py index 636c8dbe..957147ff 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -4525,6 +4525,13 @@ def _rerender_plotly_theme(self) -> None: self._ir_mode_toggle.value, self._ir_fwhm_slider.value, ) + # Raman bakes the palette's axis colours in too: without this it kept + # the theme active when the calculation ran (UI/UX review 2026-12-05). + if getattr(self, "_last_raman_acts", None): + self._update_raman_figure( + self._raman_mode_toggle.value, + self._raman_fwhm_slider.value, + ) if getattr(self, "_last_uv_wavelengths_nm", None): self._update_uv_vis_figure( self._uv_mode_toggle.value, diff --git a/quantui/app_builders.py b/quantui/app_builders.py index 68c35279..c64ea9a6 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -2030,6 +2030,7 @@ def build_theme_selector(app: Any, *, layout_fn: Any) -> None: if default_palette is not None else _theme.DEFAULT_PALETTE_ID ) + initial = _theme.resolve_palette_id(initial) if initial not in _theme.PALETTE_IDS: initial = _theme.DEFAULT_PALETTE_ID app.theme_btn = widgets.Dropdown( diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index 93493669..b58e765b 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -4945,7 +4945,17 @@ def show_pes_scan_result(app: Any, result: Any) -> bool: y=[valid_y[star_idx]], mode="markers", name=star_name.replace(" energy", ""), - marker=dict(size=14, color="#ca8a04", symbol="star"), + # Gold star with a text-coloured outline, so its edge + # keeps 3:1 contrast on light and dark palettes. + marker=dict( + size=14, + color="#ca8a04", + symbol="star", + line=dict( + width=1.5, + color=app._plotly_theme_colors()["font_color"], + ), + ), hovertext=[valid_hover[star_idx] + f"
      {star_name}"], hoverinfo="text", ) diff --git a/quantui/pes_scan_2d_plot.py b/quantui/pes_scan_2d_plot.py index c1d111d1..1b9464b8 100644 --- a/quantui/pes_scan_2d_plot.py +++ b/quantui/pes_scan_2d_plot.py @@ -105,7 +105,12 @@ def build_pes_2d_figure(result: Any, *, link_hint: bool = True) -> go.Figure: mode="markers", name="Minimum", marker=dict( - size=16, color="#ca8a04", symbol="star", line=dict(width=1) + # Dark outline: the gold star alone is lost on the + # light end of the colour scale. + size=16, + color="#ca8a04", + symbol="star", + line=dict(width=1.5, color="#1c1915"), ), hovertext=[ok_hover[best] + "
      Minimum energy"], hoverinfo="text", diff --git a/quantui/theme.py b/quantui/theme.py index cddf7cfd..2a000cf9 100644 --- a/quantui/theme.py +++ b/quantui/theme.py @@ -465,9 +465,10 @@ def _widget_chrome_css() -> str: def _light_palette() -> ThemePalette: + """Bright: white page, slate text, blue accent (called "Light" before 0.14).""" return ThemePalette( - palette_id="Light", - display_name="Light", + palette_id="Bright", + display_name="Bright", is_dark=False, page_bg=PAGE_BG, border=BORDER, @@ -715,9 +716,57 @@ def _dark_maroon_palette() -> ThemePalette: ) +def _warm_palette() -> ThemePalette: + """Warm (default): cream page, warm charcoal text, deep teal accent. + + Every text token is at least 4.5:1 on ``page_bg``, ``bg_panel`` and + ``surface_muted_bg``; button text (``page_bg``) at least 4.5:1 on each + accent fill; borders and ``accent_info`` (focus ring) at least 3:1. + """ + return ThemePalette( + palette_id="Warm", + display_name="Warm", + is_dark=False, + page_bg="#fffaf0", + border="#8a7b66", + border_strong="#776953", + border_legacy="#ddd3c2", + bg_panel="#fbf4e6", + text_heading="#1c1915", + text_label="#46403a", + text_secondary="#4d4640", + text_muted="#625a52", + text_muted_light="#655d55", + text_faint="#69615a", + text_subtle="#69615a", + text_body="#34302b", + text_strong="#25221e", + text_slate="#625a52", + text_slate_dark="#4d4640", + accent_error="#b4231b", + accent_error_alt="#a8201a", + accent_success="#2c6e3a", + accent_success_bg="#eaf3e3", + accent_success_alt="#35733f", + accent_warning="#9a4b00", + accent_warning_light="#985c06", + accent_info="#0d6a6c", + accent_purple="#6b3fa0", + accent_teal="#0f6b5c", + surface_info_bg="#e2f0ec", + surface_purple_bg="#f2ebf6", + surface_warning_bg="#fbefd6", + surface_teal_bg="#e3f1ea", + surface_green_bg="#e9f3e2", + surface_orange_bg="#fcecdc", + surface_muted_bg="#efe6d6", + ) + + PALETTES: Dict[str, ThemePalette] = { p.palette_id: p for p in ( + _warm_palette(), _light_palette(), _dark_palette(), _midnight_palette(), @@ -728,12 +777,20 @@ def _dark_maroon_palette() -> ThemePalette: } PALETTE_IDS: Tuple[str, ...] = tuple(PALETTES.keys()) -DEFAULT_PALETTE_ID = "Dark" +DEFAULT_PALETTE_ID = "Warm" + +# Old palette ids still accepted (saved settings, scripts): old id → current id. +PALETTE_ALIASES: Dict[str, str] = {"Light": "Bright"} + + +def resolve_palette_id(palette_id: str) -> str: + """Map an old palette id to its current name; unknown ids pass through.""" + return PALETTE_ALIASES.get(palette_id, palette_id) def get_palette(palette_id: str) -> ThemePalette: - """Return a palette by id, falling back to the default.""" - return PALETTES.get(palette_id, PALETTES[DEFAULT_PALETTE_ID]) + """Return a palette by id (old ids accepted), falling back to the default.""" + return PALETTES.get(resolve_palette_id(palette_id), PALETTES[DEFAULT_PALETTE_ID]) LOGO_CLASS = "quantui-logo" @@ -791,6 +848,19 @@ def theme_injection_html(css_text: str, *, style_id: str = "quantui-theme-css") ) +def _lighter(a: str, b: str) -> str: + """Return whichever of two ``#rrggbb`` colours has the higher luminance.""" + + def lum(h: str) -> float: + h = h.lstrip("#") + if len(h) == 3: + h = "".join(c * 2 for c in h) + r, g, b_ = (int(h[i : i + 2], 16) / 255 for i in (0, 2, 4)) + return 0.2126 * r + 0.7152 * g + 0.0722 * b_ + + return a if lum(a) >= lum(b) else b + + def plotly_colors(palette_id: str) -> dict: """Plotly layout colours for the selected palette.""" palette = get_palette(palette_id) @@ -804,9 +874,14 @@ def plotly_colors(palette_id: str) -> dict: # blue-gray meant for white backgrounds). "axis_line_color": palette.border_strong, # Dark palettes: the panel colour rather than pure black, so 3D - # viewers sit in the page instead of punching a black hole in it - # Light palettes keep a white scene. - "scene_bgcolor": palette.bg_panel if palette.is_dark else "#ffffff", + # viewers sit in the page instead of punching a black hole in it. + # Light palettes use the lighter of page and panel (white for Bright, + # the cream page for Warm) so plotted colours keep their contrast. + "scene_bgcolor": ( + palette.bg_panel + if palette.is_dark + else _lighter(palette.page_bg, palette.bg_panel) + ), } @@ -878,6 +953,7 @@ def frame_viewer_html(view_html: str, *, width: int, controls: str = "") -> str: "BORDER_LEGACY", "BORDER_STRONG", "DEFAULT_PALETTE_ID", + "PALETTE_ALIASES", "PAGE_BG", "PALETTE_IDS", "PALETTES", @@ -900,6 +976,7 @@ def frame_viewer_html(view_html: str, *, width: int, controls: str = "") -> str: "LOGO_CLASS", "logo_css", "get_palette", + "resolve_palette_id", "plotly_colors", "theme_css_block", "theme_injection_html", diff --git a/quantui/user_settings.py b/quantui/user_settings.py index 6550389e..5eaa0402 100644 --- a/quantui/user_settings.py +++ b/quantui/user_settings.py @@ -68,7 +68,8 @@ _VALID_QUANTUM_ENGINES = ("auto", "pyscf", "pyfock") _VALID_THEME_PALETTES = ( - "Light", + "Warm", + "Bright", "Dark", "Midnight", "Dark Blue", @@ -76,6 +77,9 @@ "Hot Pink", ) +# Old palette names in saved settings → current names. +_PALETTE_RENAMES = {"Light": "Bright"} + # Default settings path. The QUANTUI_SETTINGS_PATH env var overrides for tests. DEFAULT_SETTINGS_PATH = Path.home() / ".quantui" / "settings.json" @@ -101,7 +105,7 @@ class VizSettings: class ThemeSettings: """Visual theme preferences (preset palette selection).""" - palette: str = "Dark" + palette: str = "Warm" @dataclass @@ -300,6 +304,11 @@ def _from_dict(cls, data: object) -> UserSettings: theme = ThemeSettings() candidate_palette = theme_section.get("palette", theme.palette) + # Palettes renamed in 0.14 ("Light" is now "Bright"). + if isinstance(candidate_palette, str): + candidate_palette = _PALETTE_RENAMES.get( + candidate_palette, candidate_palette + ) if ( isinstance(candidate_palette, str) and candidate_palette in _VALID_THEME_PALETTES diff --git a/tests/test_app.py b/tests/test_app.py index cb5400f5..db8dbe77 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -135,7 +135,7 @@ def test_calc_type_default(self): def test_theme_default(self): app = QuantUIApp() - assert app.theme_btn.value == "Dark" + assert app.theme_btn.value == "Warm" # DEC-035: Warm is the default def test_charge_default(self): from quantui.config import DEFAULT_CHARGE diff --git a/tests/test_app_menubar.py b/tests/test_app_menubar.py index 064ddba6..4fd9029e 100644 --- a/tests/test_app_menubar.py +++ b/tests/test_app_menubar.py @@ -255,10 +255,10 @@ def test_labels_and_workspace_toggles(self, app): assert app._ws_enabled is (not ws) def test_theme_item_sets_the_theme_dropdown(self, app): - _choose(app, "theme_Light") - assert app.theme_btn.value == "Light" + _choose(app, "theme_Bright") + assert app.theme_btn.value == "Bright" mb.open_menu(app, "View") - assert _item(app, "theme_Light").icon == "dot-circle-o" + assert _item(app, "theme_Bright").icon == "dot-circle-o" def test_load_molecule_and_upload_open_the_input_sub_tabs(self, app): _choose(app, "upload_structure") diff --git a/tests/test_theme_contrast.py b/tests/test_theme_contrast.py index f8576d3e..a62d51e8 100644 --- a/tests/test_theme_contrast.py +++ b/tests/test_theme_contrast.py @@ -58,7 +58,8 @@ def test_identical_colours_have_no_contrast(self): class TestPaletteRegistry: def test_presets_ship(self): assert set(theme.PALETTE_IDS) == { - "Light", + "Warm", + "Bright", "Dark", "Midnight", "Dark Blue", @@ -112,7 +113,7 @@ def test_strong_border_clears_ui_bar_on_panel_and_page(self, palette_id): ), palette_id def test_strong_is_actually_stronger_than_default_on_light(self): - palette = theme.get_palette("Light") + palette = theme.get_palette("Bright") assert _contrast( _hex_rgb(palette.border_strong), _hex_rgb(palette.bg_panel) ) > _contrast(_hex_rgb(palette.border), _hex_rgb(palette.bg_panel)) diff --git a/tests/test_uiaudit_design.py b/tests/test_uiaudit_design.py index 0fdd5f49..93fea566 100644 --- a/tests/test_uiaudit_design.py +++ b/tests/test_uiaudit_design.py @@ -254,7 +254,9 @@ def test_dark_viewer_background_is_the_panel_colour(self): dark = theme.get_palette("Dark") assert theme.plotly_colors("Dark")["scene_bgcolor"] == dark.bg_panel - assert theme.plotly_colors("Light")["scene_bgcolor"] == "#ffffff" + assert theme.plotly_colors("Bright")["scene_bgcolor"] == "#ffffff" + # Warm: the cream page (lighter than its panel), not pure white. + assert theme.plotly_colors("Warm")["scene_bgcolor"] == "#fffaf0" def test_unavailable_panels_say_what_they_need(self, app): titles = { diff --git a/tests/test_user_settings.py b/tests/test_user_settings.py index d23738b1..2394efe1 100644 --- a/tests/test_user_settings.py +++ b/tests/test_user_settings.py @@ -254,7 +254,7 @@ def test_save_then_load_preserves_values(self, tmp_path): @pytest.mark.parametrize( "palette", - ["Light", "Dark", "Midnight", "Dark Blue", "Dark Maroon", "Hot Pink"], + ["Warm", "Bright", "Dark", "Midnight", "Dark Blue", "Dark Maroon", "Hot Pink"], ) def test_theme_palette_round_trips(self, tmp_path, palette): path = tmp_path / "settings.json" diff --git a/tests/test_viz_audit_medium.py b/tests/test_viz_audit_medium.py index d1b51689..62b84eb8 100644 --- a/tests/test_viz_audit_medium.py +++ b/tests/test_viz_audit_medium.py @@ -94,13 +94,13 @@ def test_vib_cache_is_keyed_on_background( app._last_result_dir = tmp_path app._vib_single_viewer_active = False - app.theme_btn.value = "Light" + app.theme_btn.value = "Bright" _render_vib_mode_py3dmol(app, water_mol, mode_number=1) light = _vib_html(app) app.theme_btn.value = "Dark" _render_vib_mode_py3dmol(app, water_mol, mode_number=1) dark = _vib_html(app) - app.theme_btn.value = "Light" + app.theme_btn.value = "Bright" _render_vib_mode_py3dmol(app, water_mol, mode_number=1) light_again = _vib_html(app) diff --git a/tests/test_warm_palette.py b/tests/test_warm_palette.py new file mode 100644 index 00000000..8cfedcf5 --- /dev/null +++ b/tests/test_warm_palette.py @@ -0,0 +1,81 @@ +"""Warm default palette and the Light → Bright rename (0.14).""" + +from __future__ import annotations + +import json + +from quantui import theme +from quantui.user_settings import ThemeSettings, UserSettings + + +def test_warm_is_the_default(): + assert theme.DEFAULT_PALETTE_ID == "Warm" + assert ThemeSettings().palette == "Warm" + assert theme.PALETTE_IDS[0] == "Warm" + assert theme.get_palette("no-such-palette").palette_id == "Warm" + + +def test_light_is_now_bright(): + assert "Light" not in theme.PALETTE_IDS + assert theme.resolve_palette_id("Light") == "Bright" + assert theme.get_palette("Light").palette_id == "Bright" + assert theme.plotly_colors("Light") == theme.plotly_colors("Bright") + + +def test_saved_light_setting_loads_as_bright(tmp_path): + path = tmp_path / "settings.json" + path.write_text(json.dumps({"_schema_version": 1, "theme": {"palette": "Light"}})) + assert UserSettings.load(path).theme.palette == "Bright" + + +def test_warm_is_light_and_cream(): + warm = theme.get_palette("Warm") + assert warm.is_dark is False + assert warm.page_bg == "#fffaf0" + assert warm.accent_info == "#0d6a6c" + + +def test_saved_light_opens_the_app_on_bright(tmp_path, monkeypatch): + import pytest + + pytest.importorskip("pyscf") + path = tmp_path / "settings.json" + path.write_text(json.dumps({"_schema_version": 1, "theme": {"palette": "Light"}})) + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(path)) + from quantui.app import QuantUIApp + + app = QuantUIApp() + assert app.theme_btn.value == "Bright" + + +def test_raman_plot_follows_a_theme_switch(): + import pytest + + pytest.importorskip("pyscf") + from quantui.app import QuantUIApp + + app = QuantUIApp() + app.theme_btn.value = "Dark" + app._last_raman_freqs = [1600.0, 3700.0, 3800.0] + app._last_raman_acts = [5.0, 80.0, 30.0] + app._last_raman_labels = None + app._update_raman_figure("Stick", 20.0) + dark_font = app._last_raman_fig.layout.font.color + app.theme_btn.value = "Bright" + assert app._last_raman_fig.layout.font.color == theme.plotly_colors("Bright")[ + "font_color" + ] + assert app._last_raman_fig.layout.font.color != dark_font + + + +def test_pes_minimum_star_has_an_outline(): + import pytest + + pytest.importorskip("plotly") + from quantui.pes_scan_2d_plot import build_pes_2d_figure + from tests.test_pes_scan_2d import _fake_result + + fig = build_pes_2d_figure(_fake_result()) + star = next(t for t in fig.data if t.name == "Minimum") + assert star.marker.line.width >= 1.5 From a076009c9da2718e56c95b3c770f14d7e0f6d743 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:38:56 +0000 Subject: [PATCH 11/12] Release 0.14.0 Version 0.14.0; CHANGELOG [0.14.0] - 2026-12-05 (UI/UX review fixes: Frequency pre-optimization by default, completed-with-warnings signals, summary-first run log, Compare dE with mismatch warnings, one pane viewer, accessibility and contrast, course preset, Report Issue to the instructor, Warm default theme) and compare links. 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 | 5 ++++- pyproject.toml | 2 +- quantui/__init__.py | 2 +- tests/test_warm_palette.py | 8 ++++---- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b63d8e73..1a87c79d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +## [0.14.0] - 2026-12-05 + ### Added - **Course preset for instructors.** An optional preset trims the Method and @@ -1915,7 +1917,8 @@ Initial public scaffolding of the QuantUI package: `quantui` package with `calculator.py`, basic notebook launcher, Apptainer container definition, MIT license, and project metadata. -[Unreleased]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.2...HEAD +[Unreleased]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.14.0...HEAD +[0.14.0]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.2...v0.14.0 [0.13.2]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.1...v0.13.2 [0.13.1]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.0...v0.13.1 [0.13.0]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.12.0...v0.13.0 diff --git a/pyproject.toml b/pyproject.toml index eaff0fb6..6649468d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ build-backend = "setuptools.build_meta" [project] name = "quantui" -version = "0.13.2" +version = "0.14.0" description = "An open-source frontend for DFT and post-HF quantum chemistry with PySCF" readme = "README.md" requires-python = ">=3.9" diff --git a/quantui/__init__.py b/quantui/__init__.py index d6dbd037..24b238ed 100644 --- a/quantui/__init__.py +++ b/quantui/__init__.py @@ -7,7 +7,7 @@ PySCF requires Linux/macOS/WSL. Windows users should use the Apptainer container. """ -__version__ = "0.13.2" +__version__ = "0.14.0" import logging from typing import Any diff --git a/tests/test_warm_palette.py b/tests/test_warm_palette.py index 8cfedcf5..0a5c3861 100644 --- a/tests/test_warm_palette.py +++ b/tests/test_warm_palette.py @@ -62,13 +62,13 @@ def test_raman_plot_follows_a_theme_switch(): app._update_raman_figure("Stick", 20.0) dark_font = app._last_raman_fig.layout.font.color app.theme_btn.value = "Bright" - assert app._last_raman_fig.layout.font.color == theme.plotly_colors("Bright")[ - "font_color" - ] + assert ( + app._last_raman_fig.layout.font.color + == theme.plotly_colors("Bright")["font_color"] + ) assert app._last_raman_fig.layout.font.color != dark_font - def test_pes_minimum_star_has_an_outline(): import pytest From cc0e0beb3a1425431c59da3d300d9033b7ab4dfa Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:47:25 +0000 Subject: [PATCH 12/12] Short-path tests: patch Path.home instead of HOME (Windows CI) On Windows Path.home() reads USERPROFILE, not HOME, so setting HOME in the tests did not move the home folder and pytest's tmp_path (under AppData) shortened to "~/AppData/...". The tests now patch Path.home directly and chdir to the filesystem anchor; the leftover HOME-in-env check becomes a check that the patch does not leak. Contributions: - Claude (Opus 5.5): code edits, review, and conceptual discussion - Jonathan Schultz: overall vision, planning, review, and orchestration Co-authored-by: Jonathan Schultz --- tests/test_uxrev_polish.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/tests/test_uxrev_polish.py b/tests/test_uxrev_polish.py index af10b3ad..86fad31f 100644 --- a/tests/test_uxrev_polish.py +++ b/tests/test_uxrev_polish.py @@ -57,18 +57,26 @@ def test_inside_the_working_folder(self, tmp_path, monkeypatch): assert short_path(tmp_path) == "." def test_inside_home(self, tmp_path, monkeypatch): + from pathlib import Path + from quantui.utils import short_path - monkeypatch.setenv("HOME", str(tmp_path / "home")) - monkeypatch.chdir("/") - target = tmp_path / "home" / ".quantui" / "results" + home = tmp_path / "home" + # Patch Path.home itself: Windows reads USERPROFILE, not HOME. + monkeypatch.setattr(Path, "home", classmethod(lambda cls: home)) + monkeypatch.chdir(Path(tmp_path.anchor)) + target = home / ".quantui" / "results" assert short_path(target) == "~/.quantui/results" def test_elsewhere_keeps_the_last_two_parts(self, monkeypatch): + from pathlib import Path + from quantui.utils import short_path - monkeypatch.chdir("/") - monkeypatch.setenv("HOME", "/nonexistent-home") + monkeypatch.chdir(Path.cwd().anchor) + monkeypatch.setattr( + Path, "home", classmethod(lambda cls: Path("/nonexistent-home")) + ) assert short_path("/srv/data/quantui/results-a/2026_H2O") == ( "…/results-a/2026_H2O" ) @@ -224,5 +232,8 @@ def test_logo_widget_carries_the_class(self, tmp_path, monkeypatch): assert theme.LOGO_CLASS in app._welcome_logo._dom_classes -def test_env_home_untouched(): - assert "HOME" in os.environ +def test_home_patch_does_not_leak(): + from pathlib import Path + + # The Path.home patch above is undone after its test. + assert Path.home() == Path(os.path.expanduser("~"))
    ' + f'
    ' f'{k}{v}