diff --git a/quantui/app.py b/quantui/app.py index 580fc77f..9e46d078 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -14,8 +14,10 @@ from __future__ import annotations import asyncio +import copy import html as _html import io +import logging import re import threading import time @@ -424,6 +426,9 @@ from quantui.app_runflow import ( resolve_ts_product as _run_resolve_ts_product, ) +from quantui.app_runflow import ( + seed_with_run_charge as _run_seed_with_run_charge, +) from quantui.app_runflow import ( update_estimate as _run_update_estimate, ) @@ -669,7 +674,7 @@ freq_parallel_opt_in, ) from quantui.help_content import HELP_TOPICS, VIEWER_HELP_TOPICS -from quantui.molecule import Molecule, parse_xyz_input +from quantui.molecule import Molecule from quantui.progress import StepProgress from quantui.user_settings import UserSettings from quantui.utils import get_session_resources @@ -681,6 +686,8 @@ select_backend, ) +logger = logging.getLogger(__name__) + # ── Availability flags (computed once at import, not per-instantiation) ─────── try: from quantui.ase_bridge import ASE_AVAILABLE @@ -741,7 +748,10 @@ RDKIT_AVAILABLE as _PUBCHEM_RDKIT_AVAILABLE, ) from quantui.structure_providers import ( - resolve_structure_with_message as _resolve_structure_with_message, + molecule_from_resolved as _molecule_from_resolved, + ) + from quantui.structure_providers import ( + resolve_structure_with_details as _resolve_structure_with_details, ) from quantui.structure_providers import ( search_candidates as _struct_search_candidates, @@ -754,7 +764,8 @@ except ImportError: PUBCHEM_AVAILABLE = False _student_friendly_resolve = None # type: ignore[assignment] - _resolve_structure_with_message = None # type: ignore[assignment] + _resolve_structure_with_details = None # type: ignore[assignment] + _molecule_from_resolved = None # type: ignore[assignment] _struct_search_candidates = None # type: ignore[assignment] @@ -4829,13 +4840,19 @@ def _apply_pubchem_search_result( def _resolve_and_apply(self, query: str, loop) -> None: """Resolve a single query (background thread) and apply on the main loop.""" try: - xyz_str, _msg, source, _is_offline = _resolve_structure_with_message(query) - if xyz_str is None: + resolved, _msg = _resolve_structure_with_details(query) + if resolved is None: raise ValueError(_msg) - atoms, coords = parse_xyz_input(xyz_str) - mol = Molecule(atoms=atoms, coordinates=coords) + # Keep the resolver's charge and multiplicity: rebuilt from the + # coordinates alone, an ion or radical loaded as a neutral + # singlet or failed the electron-count check (audit DATA-1). + mol = _molecule_from_resolved(resolved) loop.call_soon_threadsafe( - self._apply_pubchem_search_result, query, mol, None, source + self._apply_pubchem_search_result, + query, + mol, + None, + resolved.source, ) except Exception as exc: loop.call_soon_threadsafe( @@ -5932,7 +5949,8 @@ def _set_molecule( ) -> None: """Update shared state and refresh dependent widgets.""" self._molecule = mol - self.run_btn.disabled = False + # Loading a molecule mid-run must not re-arm Run (audit APP-4). + self.run_btn.disabled = bool(getattr(self, "_calc_running", False)) self.export_btn.disabled = False self.export_xyz_btn.disabled = False self.export_mol_btn.disabled = not _RDKIT_AVAILABLE @@ -6388,12 +6406,121 @@ def _on_vib_next_clicked(self, _btn) -> None: self.vib_mode_dd.value = opts[i + 1][1] return + # ── Run lock: one calculation at a time, setup frozen while it runs ── + + def _run_input_widgets(self) -> List[Any]: + """Every control whose value a run reads (the Calculation Setup panel, + the molecule's charge/multiplicity, the calculation type).""" + found: List[Any] = [] + seen: set = set() + help_buttons = { + id(w) + for name, w in vars(self).items() + if name.endswith("_help_btn") and w is not None + } + + def _walk(w: Any) -> None: + if w is None or id(w) in seen: + return + seen.add(id(w)) + children = getattr(w, "children", None) + if children: + for child in children: + _walk(child) + return + if hasattr(w, "disabled") and id(w) not in help_buttons: + found.append(w) + + _walk(getattr(self, "calc_setup_panel", None)) + for name in ("charge_si", "mult_si", "calc_type_dd"): + _walk(getattr(self, name, None)) + return found + + def _freeze_run_inputs(self) -> None: + """Disable the run's input controls, remembering their prior state.""" + frozen = getattr(self, "_frozen_run_inputs", None) or {} + for w in self._run_input_widgets(): + if id(w) in frozen: + continue + try: + frozen[id(w)] = (w, bool(w.disabled)) + w.disabled = True + except Exception: # noqa: BLE001 — a widget without the trait + frozen.pop(id(w), None) + self._frozen_run_inputs = frozen + + def _restore_run_inputs(self) -> None: + """Re-enable what :meth:`_freeze_run_inputs` disabled.""" + frozen = getattr(self, "_frozen_run_inputs", None) or {} + self._frozen_run_inputs = {} + for w, was_disabled in frozen.values(): + try: + w.disabled = was_disabled + except Exception: # noqa: BLE001 — closed widget + pass + + def _begin_run_lock(self) -> None: + """Mark a run in flight (main thread, before the worker starts).""" + self._calc_running = True + self.run_btn.disabled = True + self._freeze_run_inputs() + + def _end_run_lock(self) -> None: + """Release the run lock taken by :meth:`_begin_run_lock`.""" + self._calc_running = False + self.run_btn.disabled = False + self._restore_run_inputs() + + def _run_in_thread(self) -> None: + """Worker-thread entry: :meth:`_do_run`, plus a guaranteed unlock. + + ``_do_run`` releases the run state in its own ``finally``, but that + block starts after its setup; an error before it (an unwritable log + directory, say) used to leave Run disabled for the session. + """ + error: Optional[BaseException] = None + try: + self._do_run() + except Exception as exc: # noqa: BLE001 — reported below + logger.exception("Calculation run failed before it started") + error = exc + finally: + if getattr(self, "_calc_running", False): + self._cancel_event.clear() + self.cancel_btn.disabled = True + self.log_clear_btn.disabled = False + try: + self._stop_elapsed_ticker() + self._activity_end(kind="compute") + except Exception: # noqa: BLE001 — teardown is best-effort + pass + self._end_run_lock() + self.run_status.value = ( + f"The run could not start: {error}" + if error is not None + else "The run stopped unexpectedly." + ) + else: + self._restore_run_inputs() + def _do_run(self) -> None: """Main calculation dispatch — runs in a background thread.""" - mol = self._molecule - if mol is None: + if self._molecule is None: self.run_status.value = "Load a molecule first." + self._end_run_lock() return + # Everything the run depends on is read once, here. The run lasts + # minutes and the setup widgets (and the active molecule, whose + # charge/multiplicity the Charge/Multiplicity fields write into) + # stay live: a later read would mix two levels of theory in one + # saved result (audit APP-2). + mol = copy.deepcopy(self._molecule) + _run_method = self.method_dd.value + _run_basis = self.basis_dd.value + _run_solvent_opt = self.solvent_dd.value if self.solvent_cb.value else None + _run_fmax = self.fmax_fi.value + _run_max_steps = self.max_steps_si.value + _run_preopt = bool(self._freq_preopt_cb.value) self._activity_begin( "Running compute operations...", kind="compute", @@ -6412,7 +6539,7 @@ def _do_run(self) -> None: _calc_log.log_event( "calc_start", - f"{self.method_dd.value}/{self.basis_dd.value} on {mol.get_formula()}", + f"{_run_method}/{_run_basis} on {mol.get_formula()}", n_atoms=len(mol.atoms), ) _run_wall_t = time.perf_counter() @@ -6432,9 +6559,7 @@ def _do_run(self) -> None: _predicted_run_confidence: str = "unknown" try: _ct_for_est = _run_calc_type_key(self) - _nb_for_est = _calc_log.count_basis_functions( - mol.atoms, self.basis_dd.value - ) + _nb_for_est = _calc_log.count_basis_functions(mol.atoms, _run_basis) # Match _update_estimate's GPU-prediction logic so the # recorded predicted_s is what the user SAW in the UI # before they hit Run. @@ -6448,7 +6573,7 @@ def _do_run(self) -> None: ) _gpu_avail, _ = is_gpu_available() - if _gpu_avail and self.method_dd.value.upper() not in _GPU_NO: + if _gpu_avail and _run_method.upper() not in _GPU_NO: _predicted_gpu_used = True else: _predicted_gpu_used = False @@ -6460,7 +6585,7 @@ def _do_run(self) -> None: # references are never fitted, so predict False for them. _predicted_density_fit: Optional[bool] = None try: - if self.method_dd.value.upper() in ("MP2", "CCSD", "CCSD(T)"): + if _run_method.upper() in ("MP2", "CCSD", "CCSD(T)"): _predicted_density_fit = False else: _predicted_density_fit = bool( @@ -6472,8 +6597,8 @@ def _do_run(self) -> None: _est = _calc_log.estimate_time( n_atoms=len(mol.atoms), n_electrons=mol.get_electron_count(), - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, n_basis=_nb_for_est, calc_type=_ct_for_est, gpu_used=_predicted_gpu_used, @@ -6516,7 +6641,7 @@ def _run_required_final_single_point(target_mol, reason: str): """Run a required post-optimization single point on target geometry.""" from quantui.engines import EnginePreference, EngineRequest, run_calc - _solvent = self.solvent_dd.value if self.solvent_cb.value else None + _solvent = _run_solvent_opt self.run_status.value = ( "Running required single-point on optimized geometry..." ) @@ -6528,8 +6653,8 @@ def _run_required_final_single_point(target_mol, reason: str): EngineRequest( request_id=_uuid.uuid4().hex, calc_type="single_point", - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, charge=int(target_mol.charge), multiplicity=int(target_mol.multiplicity), molecule={ @@ -6621,7 +6746,7 @@ def _run_required_final_single_point(target_mol, reason: str): ct = self.calc_type_dd.value # PCM solvent for this run (None = gas phase). The checkbox is # disabled for calc types without solvent support. - _run_solvent = self.solvent_dd.value if self.solvent_cb.value else None + _run_solvent = _run_solvent_opt result: Any = None result_html: str = "" save_spectra: dict = {} @@ -6632,7 +6757,7 @@ def _run_required_final_single_point(target_mol, reason: str): # 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 self._freq_preopt_cb.value and ct not in ( + if _run_preopt and ct not in ( "Geometry Opt", "Frequency", "UV-Vis (TD-DFT)", @@ -6656,8 +6781,8 @@ def _run_required_final_single_point(target_mol, reason: str): try: _pre_opt = optimize_geometry( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, ) @@ -6697,7 +6822,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _geo_seed_traj, _ = load_trajectory(Path(_geo_seed_path)) - calc_mol = _geo_seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_geo_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: " f"{Path(_geo_seed_path).name}\n" @@ -6711,20 +6836,18 @@ def _run_required_final_single_point(target_mol, reason: str): # History-based expected step count → "step k/~N" + a floor # for the live progress fraction. None on cold history. - _expected_steps = _calc_log.estimate_opt_steps( - self.method_dd.value, self.basis_dd.value - ) + _expected_steps = _calc_log.estimate_opt_steps(_run_method, _run_basis) log.opt_expected_steps = ( int(round(_expected_steps)) if _expected_steps else None ) - log.opt_fmax_target = float(self.fmax_fi.value) + log.opt_fmax_target = float(_run_fmax) log.opt_fmax0 = None result = run_calc( EngineRequest( request_id=_uuid.uuid4().hex, calc_type="geometry_opt", - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, charge=int(calc_mol.charge), multiplicity=int(calc_mol.multiplicity), molecule={ @@ -6732,8 +6855,8 @@ def _run_required_final_single_point(target_mol, reason: str): "coordinates": [list(c) for c in calc_mol.coordinates], }, options={ - "fmax": self.fmax_fi.value, - "steps": self.max_steps_si.value, + "fmax": _run_fmax, + "steps": _run_max_steps, "expected_steps": ( int(round(_expected_steps)) if _expected_steps else None ), @@ -6816,15 +6939,15 @@ def _run_required_final_single_point(target_mol, reason: str): check_search_possible, ) - check_search_possible(self.method_dd.value) + check_search_possible(_run_method) self.run_status.value = ( "Building a transition-state guess from reactant + product…" ) _ts_guess = build_ts_guess( calc_mol, _ts_product, - self.method_dd.value, - self.basis_dd.value, + _run_method, + _run_basis, n_images=int(self._ts_n_images_si.value), solvent=_run_solvent, progress_stream=log, # type: ignore[arg-type] @@ -6835,10 +6958,10 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Searching for a transition state…" result = run_ts_search( calc_mol, - self.method_dd.value, - self.basis_dd.value, + _run_method, + _run_basis, fmax=float(self._ts_fmax_fi.value), - steps=int(self.max_steps_si.value), + steps=int(_run_max_steps), progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, cancel_check=self._cancel_event.is_set, @@ -6886,9 +7009,9 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Following the reaction path…" result = run_irc( calc_mol, - self.method_dd.value, - self.basis_dd.value, - steps=int(self.max_steps_si.value), + _run_method, + _run_basis, + steps=int(_run_max_steps), progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, cancel_check=self._cancel_event.is_set, @@ -6917,7 +7040,7 @@ def _run_required_final_single_point(target_mol, reason: str): # any failure log to the user log, keep ``calc_mol`` as # the input geometry, and proceed to the freq analysis — # the user can iterate if their input was actually wrong. - if self._freq_preopt_cb.value: + if _run_preopt: from quantui import optimize_geometry from quantui.optimizer import FREQ_PREOPT_FMAX @@ -6930,8 +7053,8 @@ def _run_required_final_single_point(target_mol, reason: str): try: _pre_opt = optimize_geometry( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, fmax=FREQ_PREOPT_FMAX, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, @@ -6964,7 +7087,7 @@ def _run_required_final_single_point(target_mol, reason: str): ) # ── Step 3: frequency analysis ──────────────────────────────── - if _run_solvent and not self._freq_preopt_cb.value: + if _run_solvent and not _run_preopt: log.write( f"\nNote: PCM ({_run_solvent}) frequencies are only " "meaningful at a geometry optimized in the same " @@ -6976,8 +7099,8 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Computing frequencies (SCF + Hessian)…" result = run_freq_calc( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] # The app opens _ckpt and resolves _resume # above (used by Geometry Opt / PES Scan / Reorganization @@ -7009,8 +7132,8 @@ def _run_required_final_single_point(target_mol, reason: str): _retried = retry_frequency_off_saddle( calc_mol, result, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, solvent=_run_solvent, progress_stream=log, # type: ignore[arg-type] ) @@ -7037,7 +7160,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _seed_traj, _ = load_trajectory(Path(_tddft_seed_path)) - calc_mol = _seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: {Path(_tddft_seed_path).name}\n" f" Formula: {calc_mol.get_formula()} " @@ -7047,7 +7170,7 @@ def _run_required_final_single_point(target_mol, reason: str): # ── Step 2: optional geometry optimization ──────────────────── # Renamed from # "pre-optimisation" — DFT geom-opt is just geom-opt. - if self._freq_preopt_cb.value: + if _run_preopt: from quantui import optimize_geometry self.run_status.value = ( @@ -7063,8 +7186,8 @@ def _run_required_final_single_point(target_mol, reason: str): try: _pre_opt = optimize_geometry( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, ) @@ -7097,8 +7220,8 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Running TD-DFT excited states..." result = run_tddft_calc( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, nstates=self.nstates_si.value, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, @@ -7127,7 +7250,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _nmr_seed_traj, _ = load_trajectory(Path(_nmr_seed_path)) - calc_mol = _nmr_seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_nmr_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: {Path(_nmr_seed_path).name}\n" f" Formula: {calc_mol.get_formula()} " @@ -7139,8 +7262,8 @@ def _run_required_final_single_point(target_mol, reason: str): result = run_nmr_calc( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] ) result_html = self._format_nmr_result(result) @@ -7179,7 +7302,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _seed_traj, _ = load_trajectory(Path(_scan_seed.value)) if _seed_traj: - calc_mol = _seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: " f"{Path(_scan_seed.value).name}\n" @@ -7199,16 +7322,16 @@ def _run_required_final_single_point(target_mol, reason: str): result = run_pes_scan( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, scan_type=_st, atom_indices=_atom_idx, start=self._scan_start.value, stop=self._scan_stop.value, steps=self._scan_steps.value, grid=str(getattr(self._scan_grid_dd, "value", "linear")), - fmax=self.fmax_fi.value, - max_opt_steps=self.max_steps_si.value, + fmax=_run_fmax, + max_opt_steps=_run_max_steps, progress_stream=log, # type: ignore[arg-type] checkpoint=_ckpt, resume=_resume, @@ -7229,14 +7352,14 @@ def _run_required_final_single_point(target_mol, reason: str): run_reorganization_energy, ) - _solvent = self.solvent_dd.value if self.solvent_cb.value else None + _solvent = _run_solvent_opt result = run_reorganization_energy( molecule=calc_mol, mode=self._reorg_mode_dd.value, - method=self.method_dd.value, - basis=self.basis_dd.value, - fmax=self.fmax_fi.value, - steps=self.max_steps_si.value, + method=_run_method, + basis=_run_basis, + fmax=_run_fmax, + steps=_run_max_steps, progress_stream=log, # type: ignore[arg-type] solvent=_solvent, checkpoint=_ckpt, @@ -7250,7 +7373,7 @@ def _run_required_final_single_point(target_mol, reason: str): from quantui.engines import EnginePreference, EngineRequest, run_calc # MP2 heavy-atom warning - if self.method_dd.value.upper() == "MP2": + if _run_method.upper() == "MP2": _n_heavy = sum(1 for a in calc_mol.atoms if a != "H") if _n_heavy > 20: self.result_output.append_display_data( @@ -7262,13 +7385,13 @@ def _run_required_final_single_point(target_mol, reason: str): ) ) - _solvent = self.solvent_dd.value if self.solvent_cb.value else None + _solvent = _run_solvent_opt engine_result = run_calc( EngineRequest( request_id=_uuid.uuid4().hex, calc_type="single_point", - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, charge=int(calc_mol.charge), multiplicity=int(calc_mol.multiplicity), molecule={ @@ -7345,8 +7468,8 @@ def _run_required_final_single_point(target_mol, reason: str): _ana_ctx = _AnalysisContext( calc_type=save_type, formula=result.formula, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, live_result=result, molecule=calc_mol, spectra_data=save_spectra, @@ -7507,7 +7630,7 @@ def _run_required_final_single_point(target_mol, reason: str): self._queue_main_thread_callback( self._update_log_panel, log.getvalue(), - f"{result.formula} {self.method_dd.value}/{self.basis_dd.value}", + f"{result.formula} {_run_method}/{_run_basis}", ) self._queue_main_thread_callback( self._show_result_log, @@ -7680,7 +7803,7 @@ def _run_required_final_single_point(target_mol, reason: str): try: _calc_log.log_event( "calc_cancelled", - f"{mol.get_formula()} {self.method_dd.value}/{self.basis_dd.value}", + f"{mol.get_formula()} {_run_method}/{_run_basis}", elapsed_s=round(_elapsed, 2), ) except OSError: @@ -7723,8 +7846,8 @@ def _run_required_final_single_point(target_mol, reason: str): _log_dir.mkdir(parents=True, exist_ok=True) _ts = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") _formula = mol.get_formula() if mol is not None else "unknown" - _method = self.method_dd.value - _basis = self.basis_dd.value + _method = _run_method + _basis = _run_basis with open(_log_dir / "error_log.txt", "a") as _ef: _ef.write( f"\n{'='*60}\n" @@ -7755,6 +7878,7 @@ def _run_required_final_single_point(target_mol, reason: str): finally: self.run_btn.disabled = False + self._restore_run_inputs() # Disarm Cancel, re-enable Clear, clear run-in-flight state. self._calc_running = False self._cancel_event.clear() diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index c314f4a0..d2ce6825 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -126,6 +126,12 @@ def _set_run_output(app: Any, outputs: tuple) -> None: def on_run_clicked(app: Any, btn: Any) -> None: """Reset result panes and start the background run thread.""" + # One run at a time. The button is disabled while a run is in flight, + # but a double-click (or a click queued before the disable reached the + # browser) still lands here; two runs would share the cancel flag, the + # live log and the checkpoint directory (audit APP-4). + if getattr(app, "_calc_running", False): + return # Pre-run guard: catch a basis with no parameters for an # element (e.g. 6-31G on Pt) or a charge/multiplicity inconsistent with the # electron count, and explain it here — on the main thread, before anything @@ -220,7 +226,10 @@ def on_run_clicked(app: Any, btn: Any) -> None: submit_slurm_run(app) return - threading.Thread(target=app._do_run, daemon=True).start() + # Claim the run on this (main) thread, before the worker starts: the + # worker used to set the flag itself, leaving a window for a second run. + app._begin_run_lock() + threading.Thread(target=app._run_in_thread, daemon=True).start() _FREQ_PREOPT_DESC_DEFAULT = "Geometry optimization before calculation (QM, slower)" @@ -1134,8 +1143,29 @@ def _update_freq_perturb_seed_ui(app: Any, path_str: str) -> None: box.layout.display = "none" +def seed_with_run_charge(seed_mol: Any, base_mol: Any) -> Any: + """*seed_mol*'s geometry with *base_mol*'s charge and multiplicity. + + A seed is a saved result's geometry, and its ``trajectory.json`` carries + the charge and multiplicity of *that* run. The run being set up decides + the electronic state: the classic "cation at the neutral's optimized + geometry" must not silently recompute the neutral (audit APP-3). + """ + from quantui.molecule import Molecule + + return Molecule( + list(seed_mol.atoms), + [list(map(float, c)) for c in seed_mol.coordinates], + charge=int(base_mol.charge), + multiplicity=int(base_mol.multiplicity), + ) + + def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> Any: - """Apply seed geometry (geo-opt final frame or freq mode perturbation).""" + """Apply seed geometry (geo-opt final frame or freq mode perturbation). + + The returned molecule keeps *base_mol*'s charge and multiplicity. + """ from quantui.backends.dispatch import load_seed_molecule, seed_path_from_app from quantui.freq_calc import ( VIB_MODE_DISPLAY_AMPLITUDE_ANGSTROM, @@ -1157,6 +1187,7 @@ def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> mode_number, fraction=fraction, ) + mol = seed_with_run_charge(mol, base_mol) if log is not None: freq_raw = meta.get("frequency_cm1") freq_val = float(freq_raw) if isinstance(freq_raw, (int, float)) else None @@ -1170,7 +1201,7 @@ def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> ) return mol - mol = load_seed_molecule(seed_path) + mol = seed_with_run_charge(load_seed_molecule(seed_path), base_mol) if log is not None: log.write( f"\nSeed geometry loaded from: {Path(seed_path).name}\n" diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index 5a838fca..d1d4444f 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -25,6 +25,7 @@ from quantui.orbital_visualization import _GENERIC_CAPTURE_JS, _png_capture_controls from quantui.symmetry import html_irrep from quantui.viz_assets import orient_js, orient_view +from quantui.viz_assets import script_json as _script_json logger = logging.getLogger(__name__) @@ -3116,11 +3117,10 @@ def iso_bridge_update(app: Any, **opts: Any) -> None: bridge = getattr(app, "_iso_js_bridge", None) if bridge is None: return - import json from IPython.display import Javascript, display - payload = json.dumps(opts) + payload = _script_json(opts) # Retry-until-present mirrors _vib_bridge_set_mode: at the moment a slider # fires, the viewer may still be loading its async 3Dmol bundle. js = ( @@ -3446,7 +3446,6 @@ def _frame_stepper_controls( (e.g. per-frame energy arrays). ``loop`` makes Play cycle forever, else it runs once and stops on the last frame. """ - import json btn = _STEPPER_BTN_STYLE start = (n - 1) if start_index is None else start_index @@ -3483,8 +3482,8 @@ def _frame_stepper_controls( .replace("__IV__", str(interval_ms)) .replace("__LOOP__", "1" if loop else "0") .replace("__START__", str(start)) - .replace("__AB_START__", json.dumps(ab_at_start or "")) - .replace("__AB_OTHER__", json.dumps(ab_other or "")) + .replace("__AB_START__", _script_json(ab_at_start or "")) + .replace("__AB_OTHER__", _script_json(ab_other or "")) .replace("__EXTRA__", extra_decls) .replace("__LABEL_BODY__", label_js) ) @@ -3520,7 +3519,6 @@ def build_reorg_geometry_viewer_html( the isosurface viewer's capture bridge but with a uid-scoped capture function — see ``_GENERIC_CAPTURE_JS``. Empty omits the button. """ - import json import re from quantui.viz_assets import make_view @@ -3549,7 +3547,7 @@ def build_reorg_geometry_viewer_html( return _theme.frame_viewer_html(view_html, width=width) uid = m.group(1) - slugs = json.dumps( + slugs = _script_json( [ g.get("label", f"geometry_{i + 1}").split(" — ")[0] for i, g in enumerate(geometries) @@ -3561,7 +3559,7 @@ def build_reorg_geometry_viewer_html( capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) bridge_js = ( _REORG_PNG_BRIDGE_JS.replace("__UID__", uid) @@ -3583,10 +3581,10 @@ def build_reorg_geometry_viewer_html( if len(geometries) < 2: return _theme.frame_viewer_html(view_html, width=width) - labels = json.dumps( + labels = _script_json( [g.get("label", f"Geometry {i + 1}") for i, g in enumerate(geometries)] ) - notes = json.dumps([g.get("note", "") for g in geometries]) + notes = _script_json([g.get("note", "") for g in geometries]) controls = _frame_stepper_controls( uid, len(geometries), @@ -3826,7 +3824,6 @@ def build_trajectory_viewer_html( displayed in it — nothing trajectory-specific needed). Empty omits the button. """ - import json import re from quantui.viz_assets import make_view @@ -3850,7 +3847,7 @@ def build_trajectory_viewer_html( capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) view_html = ( view_html @@ -3864,9 +3861,9 @@ def build_trajectory_viewer_html( return _theme.frame_viewer_html(view_html, width=width) interval_ms = max(1, int(round(1000.0 / max(1, fps)))) - eabs = json.dumps([float(e) for e in energies]) if energies else "null" - erel = json.dumps([float(e) for e in rel_e]) if rel_e else "null" - fjs = json.dumps(formula or "") + eabs = _script_json([float(e) for e in energies]) if energies else "null" + erel = _script_json([float(e) for e in rel_e]) if rel_e else "null" + fjs = _script_json(formula or "") label_js = ( 'var s="Step "+i+" / "+(N-1);' f'if({fjs}) s+=" \\u00b7 "+{fjs};' @@ -4022,7 +4019,6 @@ def build_vib_viewer_html( equivalent client-side capture global, same reasoning as the main molecule viewer. """ - import json import re import numpy as np @@ -4056,14 +4052,14 @@ def build_vib_viewer_html( interval_ms = max(1, int(round(1000.0 / max(1, fps)))) js = ( _VIB_VIEWER_JS.replace("__UID__", uid) - .replace("__SYM__", json.dumps(atoms)) - .replace("__BASE__", json.dumps(base.tolist())) - .replace("__DISPL__", json.dumps(displ_map)) + .replace("__SYM__", _script_json(atoms)) + .replace("__BASE__", _script_json(base.tolist())) + .replace("__DISPL__", _script_json(displ_map)) .replace("__NAT__", str(n_atoms)) .replace("__NF__", str(int(n_frames))) .replace("__AMP__", repr(float(amplitude))) .replace("__IV__", str(interval_ms)) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) .replace("__INIT__", str(int(initial_mode))) .replace("__ARROWS__", "true" if arrows else "false") .replace("__ORIENT__", orient_js("v", base)) @@ -4074,7 +4070,7 @@ def build_vib_viewer_html( capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) body = ( body diff --git a/quantui/backends/slurm.py b/quantui/backends/slurm.py index b1e5569b..0a6d48df 100644 --- a/quantui/backends/slurm.py +++ b/quantui/backends/slurm.py @@ -38,6 +38,7 @@ SlurmJobAccounting, default_job_name, estimate_slurm_resources, + normalize_slurm_state, parse_sacct_accounting, parse_sacct_states, parse_slurm_job_id, @@ -54,8 +55,19 @@ "TIMEOUT", "NODE_FAIL", "OUT_OF_MEMORY", + # Also final for this job id: a preempted job is not requeued + # under it unless the site requeues (then squeue reports it again). + "PREEMPTED", + "BOOT_FAIL", + "DEADLINE", + "REVOKED", } ) +# Non-terminal states that are not literally PENDING/RUNNING. +_RUNNING_LIKE_SLURM = frozenset({"COMPLETING", "SUSPENDED", "STOPPED", "RESIZING"}) +_PENDING_LIKE_SLURM = frozenset( + {"PENDING", "CONFIGURING", "REQUEUED", "REQUEUE_HOLD", "REQUEUE_FED"} +) _TERMINAL_RECORD = frozenset({"success", "error", "cancelled"}) _ACTIVE_RECORD = frozenset({"queued", "pending", "running", "submitted"}) # A request id (uuid hex / job-name style) or a numeric SLURM job id. @@ -463,8 +475,8 @@ def _squeue_status(self, slurm_job_id: str) -> str | None: ): return None - status = result.stdout.strip() - return status.upper() if status else None + status = normalize_slurm_state(result.stdout) + return status or None def _sacct_status(self, slurm_job_id: str) -> str | None: batch = self._batch_sacct([slurm_job_id]) @@ -566,8 +578,8 @@ def _batch_squeue(self, slurm_job_ids: List[str]) -> Dict[str, str]: ) for line in result.stdout.splitlines(): parts = line.strip().split() - if len(parts) == 2: - statuses[parts[0]] = parts[1] + if len(parts) >= 2: + statuses[parts[0]] = normalize_slurm_state(" ".join(parts[1:])) except ( subprocess.TimeoutExpired, FileNotFoundError, @@ -746,8 +758,8 @@ def cancel(self, request_id: str) -> bool: ) if status in _TERMINAL_SLURM: return self._finalize_cancel_from_slurm_state(record, status) - if status and status not in ("PENDING", "RUNNING", "CONFIGURING"): - return self._finalize_cancel_from_slurm_state(record, status) + # Anything else (PENDING, RUNNING, COMPLETING, ...) is still on + # its way to CANCELLED: keep waiting until the deadline. time.sleep(cfg.CANCEL_POLL_INTERVAL_SECONDS) self._record_cancel_failure( @@ -812,10 +824,10 @@ def _is_within(path: Path, parent: Path) -> bool: def _map_slurm_status(slurm_status: str) -> str: - upper = slurm_status.upper() - if upper in ("PENDING", "CONFIGURING"): + upper = normalize_slurm_state(slurm_status) + if upper in _PENDING_LIKE_SLURM: return "pending" - if upper == "RUNNING": + if upper == "RUNNING" or upper in _RUNNING_LIKE_SLURM: return "running" if upper in _TERMINAL_SLURM: if upper == "COMPLETED": diff --git a/quantui/backends/slurm_utils.py b/quantui/backends/slurm_utils.py index eaf85776..484bba02 100644 --- a/quantui/backends/slurm_utils.py +++ b/quantui/backends/slurm_utils.py @@ -105,6 +105,18 @@ def parse_slurm_job_id(sbatch_output: str) -> Optional[str]: return None +def normalize_slurm_state(state: str) -> str: + """Reduce a SLURM state string to its bare upper-case state name. + + ``sacct`` reports a cancel as ``CANCELLED by `` and may append ``+`` + to a state (``CANCELLED+``); ``squeue`` long forms can carry a reason in + the same way. Every consumer compares against bare names + (``CANCELLED``, ``COMPLETED``, ...), so the extra text is dropped here. + """ + parts = str(state or "").strip().upper().split() + return parts[0].rstrip("+") if parts else "" + + def parse_sacct_accounting(sacct_output: str) -> Dict[str, SlurmJobAccounting]: """Parse ``sacct -P --format=JobID,State,ExitCode,Elapsed`` output.""" rows: Dict[str, SlurmJobAccounting] = {} @@ -116,7 +128,7 @@ def parse_sacct_accounting(sacct_output: str) -> Dict[str, SlurmJobAccounting]: if len(parts) < 2: continue job_id = parts[0].strip() - state = parts[1].strip().upper() + state = normalize_slurm_state(parts[1]) if not job_id or not state or "." in job_id: continue exit_code = parts[2].strip() if len(parts) > 2 else "" diff --git a/quantui/calculator.py b/quantui/calculator.py index cb40b451..acabd3de 100644 --- a/quantui/calculator.py +++ b/quantui/calculator.py @@ -144,6 +144,11 @@ def generate_calculation_script( calc_type, solvent=solvent, density_fit=density_fit, nstates=nstates ) script_content = config.PYSCF_SCRIPT_TEMPLATE.format( + chg_dispersion_block=( + chg_dispersion_script_block() + if self.method.upper() == "WB97X-D" + else "" + ), job_name=job_name, method=self.method, basis=self.basis, @@ -295,6 +300,25 @@ def create_calculation( } +def chg_dispersion_script_block() -> str: + """Source of :mod:`quantui.chg_dispersion` for a standalone script. + + The exported script must reproduce wB97X-D's dispersion term without + importing QuantUI, so the (numpy + pyscf only) module is pasted in. + """ + import inspect + + from . import chg_dispersion + + src = inspect.getsource(chg_dispersion) + # A __future__ import is only legal at the top of a file. + src = src.replace("from __future__ import annotations\n", "") + return ( + "\n\n# ---- wB97X-D dispersion term (copy of quantui/chg_dispersion.py)" + " ----\n" + src + "# ---- end of wB97X-D dispersion term ----\n" + ) + + def script_sections( calc_type: str = "single_point", *, diff --git a/quantui/chg_dispersion.py b/quantui/chg_dispersion.py new file mode 100644 index 00000000..d8d183ba --- /dev/null +++ b/quantui/chg_dispersion.py @@ -0,0 +1,200 @@ +"""ωB97X-D's empirical dispersion term (Chai & Head-Gordon 2008). + +ωB97X-D is the ωB97X range-separated hybrid *plus* an atom-pair dispersion +correction with Chai–Head-Gordon ("CHG") damping: + + E_disp = - sum_{i (C6 / J nm^6 mol^-1, R0 / Angstrom). +# Same values as ASE's ase.calculators.vdwcorrection.vdWDB_Grimme06jcc. +_D2 = { + "H": (0.14, 1.001), + "He": (0.08, 1.012), + "Li": (1.61, 0.825), + "Be": (1.61, 1.408), + "B": (3.13, 1.485), + "C": (1.75, 1.452), + "N": (1.23, 1.397), + "O": (0.70, 1.342), + "F": (0.75, 1.287), + "Ne": (0.63, 1.243), + "Na": (5.71, 1.144), + "Mg": (5.71, 1.364), + "Al": (10.79, 1.639), + "Si": (9.23, 1.716), + "P": (7.84, 1.705), + "S": (5.57, 1.683), + "Cl": (5.07, 1.639), + "Ar": (4.61, 1.595), + "K": (10.80, 1.485), + "Ca": (10.80, 1.474), + "Ga": (16.99, 1.650), + "Ge": (17.10, 1.727), + "As": (16.37, 1.760), + "Se": (12.64, 1.771), + "Br": (12.47, 1.749), + "Kr": (12.01, 1.727), + "Rb": (24.67, 1.628), + "Sr": (24.67, 1.606), + "In": (37.32, 1.672), + "Sn": (38.71, 1.804), + "Sb": (38.44, 1.881), + "Te": (31.74, 1.892), + "I": (31.50, 1.892), + "Xe": (29.99, 1.881), +} +for _el in ("Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn"): + _D2[_el] = (10.80, 1.562) +for _el in ("Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd"): + _D2[_el] = (24.67, 1.639) + +_DAMP_A = 6.0 +_BOHR_ANG = 0.52917721092 +# J nm^6 mol^-1 -> Hartree Bohr^6 +_C6_TO_AU = (10.0 / _BOHR_ANG) ** 6 / 2625499.639 + + +def _params(symbols): + missing = sorted({s for s in symbols if s not in _D2}) + if missing: + raise ValueError( + "wB97X-D dispersion (Grimme D2 parameters) is defined for H-Xe " + f"only; no parameters for {', '.join(missing)}. Choose another " + "functional for this molecule." + ) + c6 = np.array([_D2[s][0] for s in symbols]) * _C6_TO_AU + r0 = np.array([_D2[s][1] for s in symbols]) / _BOHR_ANG + return c6, r0 + + +def _symbols(mol): + from pyscf.data.elements import _std_symbol + + return [_std_symbol(mol.atom_pure_symbol(i)) for i in range(mol.natm)] + + +def chg_dispersion(mol, deriv=0): + """CHG dispersion for a PySCF ``Mole``: energy, gradient or Hessian. + + ``deriv=0`` returns the energy (Hartree); ``1`` the gradient + ``(natm, 3)`` in Hartree/Bohr; ``2`` the Hessian ``(natm, natm, 3, 3)`` + in Hartree/Bohr^2 (PySCF's Hessian layout). + """ + coords = np.asarray(mol.atom_coords(), dtype=float) # Bohr + c6, r0 = _params(_symbols(mol)) + n = len(coords) + energy = 0.0 + grad = np.zeros((n, 3)) + hess = np.zeros((n, n, 3, 3)) + for i in range(n): + for j in range(i + 1, n): + d = coords[i] - coords[j] + r = float(np.sqrt(d @ d)) + cij = float(np.sqrt(c6[i] * c6[j])) + b = _DAMP_A * float(r0[i] + r0[j]) ** 12 + # E = -C6 / D(r), D = r^6 + b r^-6 (= r^6 (1 + a (r/Rr)^-12)) + dd0 = r**6 + b * r**-6 + energy -= cij / dd0 + if deriv == 0: + continue + dd1 = 6.0 * r**5 - 6.0 * b * r**-7 + de = cij * dd1 / dd0**2 # dE/dr + u = d / r + grad[i] += de * u + grad[j] -= de * u + if deriv == 1: + continue + dd2 = 30.0 * r**4 + 42.0 * b * r**-8 + d2e = cij * (dd2 * dd0 - 2.0 * dd1**2) / dd0**3 # d2E/dr2 + uu = np.outer(u, u) + block = d2e * uu + (de / r) * (np.eye(3) - uu) + hess[i, i] += block + hess[j, j] += block + hess[i, j] -= block + hess[j, i] -= block + if deriv == 0: + return energy + if deriv == 1: + return grad + return hess + + +def _uses_chg(mf): + return getattr(mf, "disp", None) == CHG_DISP + + +def install(): + """Hook :func:`chg_dispersion` into PySCF (idempotent). + + Wraps the four dispersion entry points PySCF's SCF, gradient and Hessian + drivers call (``do_disp`` / ``get_dispersion``); objects whose + ``disp`` is not :data:`CHG_DISP` go through PySCF's own code unchanged. + """ + from pyscf import grad, hessian, scf + from pyscf.grad import dispersion as _gd # noqa: F401 — sets PySCF's hook first + from pyscf.hessian import dispersion as _hd # noqa: F401 + from pyscf.hessian import rhf as _hrhf + + scf_cls = scf.hf.SCF + if getattr(scf_cls, "_quantui_chg_installed", False): + return + grad_cls = grad.rhf.GradientsBase + hess_cls = _hrhf.HessianBase + _ = hessian # imported for the side effect of registering hessian modules + + orig_do_disp = scf_cls.do_disp + orig_scf_disp = scf_cls.get_dispersion + orig_grad_disp = grad_cls.get_dispersion + orig_hess_disp = hess_cls.get_dispersion + + def do_disp(mf, *args, **kwargs): + if _uses_chg(mf): + return True + return orig_do_disp(mf, *args, **kwargs) + + def scf_get_dispersion(mf, *args, **kwargs): + if _uses_chg(mf): + return chg_dispersion(mf.mol, 0) + return orig_scf_disp(mf, *args, **kwargs) + + def grad_get_dispersion(mf_grad, *args, **kwargs): + if _uses_chg(mf_grad.base): + return chg_dispersion(mf_grad.mol, 1) + return orig_grad_disp(mf_grad, *args, **kwargs) + + def hess_get_dispersion(hessobj, *args, **kwargs): + if _uses_chg(hessobj.base): + return chg_dispersion(hessobj.mol, 2) + return orig_hess_disp(hessobj, *args, **kwargs) + + scf_cls.do_disp = do_disp + scf_cls.get_dispersion = scf_get_dispersion + grad_cls.get_dispersion = grad_get_dispersion + hess_cls.get_dispersion = hess_get_dispersion + scf_cls._quantui_chg_installed = True diff --git a/quantui/config.py b/quantui/config.py index b4499ecd..10f4f3f0 100644 --- a/quantui/config.py +++ b/quantui/config.py @@ -103,11 +103,12 @@ "type": "dft", "label": "wB97X-D — Range-Separated Hybrid + Built-in Dispersion", "description": ( - "Range-separated hybrid functional (Chai & Head-Gordon, 2008) with its " - "own empirical dispersion correction baked into the fit — not an " - "externally applied Grimme D3 correction. Excellent for non-covalent " - "interactions, charge-transfer excitations, and systems where " - "long-range exchange matters." + "Range-separated hybrid functional (Chai & Head-Gordon, 2008) fitted " + "together with its own atom-pair dispersion correction (Grimme-2006 " + "C6 coefficients, Chai–Head-Gordon damping) — not Grimme D3. QuantUI " + "adds that term to energies, forces and frequencies. Good for " + "non-covalent interactions, charge-transfer excitations, and systems " + "where long-range exchange matters. Dispersion parameters cover H–Xe." ), "use_for": "Non-covalent interactions, excited states, large organic molecules.", }, @@ -273,18 +274,24 @@ def pople_notation_alias(basis: str) -> str: # TMS isotropic shielding reference constants for NMR chemical shift computation. # Key: "method/basis" → {element: σ_TMS (ppm)}. δ = σ_TMS − σ_molecule. -# Source: Cheeseman et al., J. Chem. Phys. 104 (1996) 5497; CCCBDB. +# Computed with QuantUI itself (run_nmr_calc, PySCF GIAO) on TMS optimized at +# the same level (optimize_geometry, fmax 0.01 eV/Å; Td), so TMS comes out at +# δ = 0 and the table is consistent with the shieldings it is subtracted from. +# The previous literature-style values did not match this GIAO code: TMS gave +# δ(13C) = −7.7 ppm at B3LYP/6-31G* and −52 ppm at RHF/STO-3G (audit SCF-1). +# Recompute every row if the NMR code, PySCF or pyscf-properties changes the +# shieldings (tests/test_nmr_tms_reference.py checks the RHF/STO-3G row). NMR_REFERENCE_SHIELDINGS: Dict[str, Dict[str, float]] = { - "B3LYP/6-31G*": {"H": 31.72, "C": 183.71}, - "B3LYP/6-311G**": {"H": 31.60, "C": 188.94}, - "B3LYP/cc-pVDZ": {"H": 31.54, "C": 186.12}, - "B3LYP/def2-SVP": {"H": 31.65, "C": 184.20}, - "RHF/6-31G*": {"H": 32.00, "C": 196.00}, - "RHF/STO-3G": {"H": 30.50, "C": 195.00}, - "PBE0/6-31G*": {"H": 31.60, "C": 184.50}, - "PBE/6-31G*": {"H": 31.50, "C": 185.00}, + "B3LYP/6-31G*": {"H": 32.19, "C": 190.22}, + "B3LYP/6-311G**": {"H": 32.01, "C": 184.49}, + "B3LYP/cc-pVDZ": {"H": 31.31, "C": 192.19}, + "B3LYP/def2-SVP": {"H": 31.37, "C": 189.07}, + "RHF/6-31G*": {"H": 32.93, "C": 202.04}, + "RHF/STO-3G": {"H": 33.75, "C": 249.43}, + "PBE0/6-31G*": {"H": 32.12, "C": 195.06}, + "PBE/6-31G*": {"H": 31.75, "C": 189.09}, } -NMR_DEFAULT_REFERENCE: Dict[str, float] = {"H": 31.72, "C": 183.71} # B3LYP/6-31G* +NMR_DEFAULT_REFERENCE: Dict[str, float] = dict(NMR_REFERENCE_SHIELDINGS["B3LYP/6-31G*"]) # Default calculation settings DEFAULT_METHOD = "RHF" @@ -646,7 +653,7 @@ def electron_count(atoms: Any, charge: int) -> int: from pathlib import Path from pyscf import gto, scf, dft import numpy as np - +{chg_dispersion_block} def _run_scf_with_rescue(mf): # Standalone copy of QuantUI's shared SCF-rescue helper @@ -715,9 +722,10 @@ def main(): # Display name → PySCF xc string + external D3 dispersion where # needed. Matches quantui/session_calc.py resolve_xc + maybe_apply_d3. # wB97X-D maps to its full LibXC name (the actual Chai/Head-Gordon - # 2008 functional, built-in dispersion) because PySCF's short-alias - # parser black-lists 'wb97x-d'/'wb97x_d' as ambiguous; PBE-D3 adds - # zero-damping Grimme D3 through mf.disp (needs pyscf-dispersion). + # 2008 functional) because PySCF's short-alias parser black-lists + # 'wb97x-d'/'wb97x_d'; its own dispersion term is added below. + # PBE-D3 adds zero-damping Grimme D3 through mf.disp (needs + # pyscf-dispersion). _XC_ALIAS = {{ 'M06-L': 'm06l', 'wB97X-D': 'hyb_gga_xc_wb97x_d', @@ -752,6 +760,12 @@ def main(): "WARNING: pyscf-dispersion not installed; " "running {{method}} without D3 dispersion." ) + if method == 'wB97X-D': + # LibXC's wb97x_d is only the XC part: add the functional's + # own atom-pair dispersion term (defined at the top of this + # script, a copy of quantui/chg_dispersion.py). + install() + mf.disp = CHG_DISP {density_fit_block}{solvent_block} energy = _run_scf_with_rescue(mf) diff --git a/quantui/freq_calc.py b/quantui/freq_calc.py index 4cc0c488..e3375f10 100644 --- a/quantui/freq_calc.py +++ b/quantui/freq_calc.py @@ -621,9 +621,9 @@ def _status(msg: str) -> None: mf = scf.UHF(mol) scf_variant = type(mf).__name__ else: - # Route through resolve_xc + maybe_apply_d3 so - # methods like wB97X-D (PySCF rejects "wb97x-d") map to the - # bare functional + external D3 dispersion. + # Route through resolve_xc + maybe_apply_d3: display names map to + # LibXC (PySCF rejects "wb97x-d"), PBE-D3 gets D3, and wB97X-D gets + # its own dispersion term (quantui.chg_dispersion) in the Hessian. from .session_calc import maybe_apply_d3, resolve_xc mf = dft.RKS(mol) if mol.spin == 0 else dft.UKS(mol) @@ -800,6 +800,7 @@ def _status(msg: str) -> None: from .config import BOHR_TO_ANGSTROM as _BOHR_TO_ANG from .freq_displacement_ids import ( displacement_id, + displacement_set_name, parse_displacement_id, ) @@ -835,7 +836,17 @@ def _status(msg: str) -> None: # assembly step itself a proper gate: it only runs # once every required id is present here, regardless of how # it got there. - _ITEM_SET_NAME = "freq_displacements" + # Named for this reference geometry and SCF setup, so a + # resume never reuses dipoles displaced from anything else. + _ITEM_SET_NAME = displacement_set_name( + "freq_displacements", + mol, + xc=_xc, + density_fit=_density_fit_used, + solvent=_pcm_solvent, + delta_bohr=_DELTA, + unrestricted=_dm0_is_unrestricted, + ) _dipoles: dict = {} if checkpoint is not None and resume: for _item_id, _payload in checkpoint.completed_items( diff --git a/quantui/freq_displacement_ids.py b/quantui/freq_displacement_ids.py index 61a52764..3fb50eba 100644 --- a/quantui/freq_displacement_ids.py +++ b/quantui/freq_displacement_ids.py @@ -20,7 +20,9 @@ from __future__ import annotations -from typing import List, Tuple +import hashlib +import json +from typing import Any, List, Optional, Tuple _AXIS_LABELS = ("x", "y", "z") _SIGN_LABELS = {1: "+", -1: "-"} @@ -76,3 +78,50 @@ def required_displacement_ids(n_atoms: int) -> List[str]: ids.append(displacement_id(atom_index, axis, 1)) ids.append(displacement_id(atom_index, axis, -1)) return ids + + +def displacement_set_name( + prefix: str, + mol: Any, + *, + xc: Optional[str], + density_fit: bool, + solvent: Optional[str], + delta_bohr: float, + unrestricted: bool, +) -> str: + """Checkpoint item-set name for one reference geometry and setup. + + The ids above say *which* displacement a banked result is, not *what it + was displaced from*. A resumed Frequency run whose reference geometry + changed (pre-optimization ticked on the second attempt, a different + seed or mode displacement) or whose SCF setup changed (density fitting, + functional, solvent) used to splice the old geometry's dipoles into the + new finite difference, giving wrong IR intensities with no warning. The + set name now carries a digest of everything a displaced SCF depends on, + so results banked for anything else are simply not found. + + *mol* is the PySCF ``Mole`` of the reference SCF. + """ + coords = [ + [round(float(v), 6) + 0.0 for v in row] for row in mol.atom_coords().tolist() + ] + basis = mol.basis if isinstance(mol.basis, str) else repr(mol.basis) + ecp = mol.ecp if isinstance(mol.ecp, str) else repr(sorted(dict(mol.ecp or {}))) + key = { + "atoms": [mol.atom_symbol(i) for i in range(mol.natm)], + "coords_bohr": coords, + "charge": int(mol.charge), + "spin": int(mol.spin), + "basis": basis, + "ecp": ecp, + "xc": xc, + "density_fit": bool(density_fit), + "solvent": solvent, + "delta_bohr": float(delta_bohr), + "unrestricted": bool(unrestricted), + } + digest = hashlib.sha256( + json.dumps(key, sort_keys=True, default=str).encode("utf-8") + ).hexdigest()[:16] + return f"{prefix}-{digest}" diff --git a/quantui/gpu_offload.py b/quantui/gpu_offload.py index 584cf2aa..c74ff5a7 100644 --- a/quantui/gpu_offload.py +++ b/quantui/gpu_offload.py @@ -58,7 +58,10 @@ # short-circuits BEFORE the migration. # - Double-hybrids would belong here too, but QuantUI doesn't expose # any double-hybrid methods today. -_GPU_UNSUPPORTED_METHODS: frozenset = frozenset({"MP2", "CCSD", "CCSD(T)"}) +# - wB97X-D: its dispersion term is QuantUI's own PySCF hook +# (quantui.chg_dispersion), which gpu4pyscf objects do not carry, so a +# GPU run would silently drop it. +_GPU_UNSUPPORTED_METHODS: frozenset = frozenset({"MP2", "CCSD", "CCSD(T)", "WB97X-D"}) # Datacenter GPU families with usable double-precision throughput (FP64 at # roughly 1/2 of FP32). Everything else — GeForce, RTX/Quadro workstation, the diff --git a/quantui/help_content.py b/quantui/help_content.py index 69bef50d..fc0d1b9c 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -624,7 +624,9 @@ "