q2m3 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- q2m3/__init__.py +75 -0
- q2m3/constants.py +35 -0
- q2m3/core/__init__.py +62 -0
- q2m3/core/device_utils.py +232 -0
- q2m3/core/hamiltonian_utils.py +88 -0
- q2m3/core/qmmm_system.py +163 -0
- q2m3/core/qpe.py +603 -0
- q2m3/core/quantum_qmmm.py +497 -0
- q2m3/core/quantum_solver.py +66 -0
- q2m3/core/rdm.py +503 -0
- q2m3/core/resource_estimation.py +301 -0
- q2m3/interfaces/__init__.py +21 -0
- q2m3/interfaces/fixed_mo_embedding.py +357 -0
- q2m3/interfaces/pyscf_pennylane.py +758 -0
- q2m3/molecule.py +77 -0
- q2m3/profiling/__init__.py +60 -0
- q2m3/profiling/catalyst_ir.py +89 -0
- q2m3/profiling/memory.py +249 -0
- q2m3/profiling/orchestrator.py +390 -0
- q2m3/profiling/qpe_profiler.py +384 -0
- q2m3/profiling/timing.py +145 -0
- q2m3/sampling/__init__.py +35 -0
- q2m3/sampling/mc_moves.py +117 -0
- q2m3/sampling/metropolis.py +130 -0
- q2m3/sampling/mm_forcefield.py +134 -0
- q2m3/sampling/water_molecule.py +158 -0
- q2m3/solvation/__init__.py +58 -0
- q2m3/solvation/analysis.py +352 -0
- q2m3/solvation/circuit_builder.py +388 -0
- q2m3/solvation/config.py +188 -0
- q2m3/solvation/energy.py +510 -0
- q2m3/solvation/ir_cache.py +345 -0
- q2m3/solvation/mc_loop.py +197 -0
- q2m3/solvation/orchestrator.py +439 -0
- q2m3/solvation/phase_extraction.py +102 -0
- q2m3/solvation/plotting.py +152 -0
- q2m3/solvation/solvent.py +453 -0
- q2m3/solvation/statistics.py +170 -0
- q2m3/solvation/structure_analysis.py +340 -0
- q2m3/utils/__init__.py +16 -0
- q2m3/utils/io.py +152 -0
- q2m3/utils/plotting.py +76 -0
- q2m3/version.py +52 -0
- q2m3-0.1.1.dist-info/METADATA +389 -0
- q2m3-0.1.1.dist-info/RECORD +48 -0
- q2m3-0.1.1.dist-info/WHEEL +5 -0
- q2m3-0.1.1.dist-info/licenses/LICENSE +21 -0
- q2m3-0.1.1.dist-info/top_level.txt +1 -0
q2m3/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Copyright (c) 2026 Ye Jun <yjmaxpayne@hotmail.com>
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Quantum-QM/MM POC Framework
|
|
6
|
+
|
|
7
|
+
A hybrid quantum-classical framework for QM/MM calculations using QPE algorithms.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .version import __version__
|
|
11
|
+
|
|
12
|
+
__author__ = "Ye Jun <yjmaxpayne@hotmail.com>"
|
|
13
|
+
|
|
14
|
+
from .constants import (
|
|
15
|
+
ANGSTROM_TO_BOHR,
|
|
16
|
+
CHEMICAL_ACCURACY_HA,
|
|
17
|
+
HARTREE_TO_KCAL_MOL,
|
|
18
|
+
KCAL_TO_HARTREE,
|
|
19
|
+
TIP3P_HYDROGEN_CHARGE,
|
|
20
|
+
TIP3P_OXYGEN_CHARGE,
|
|
21
|
+
)
|
|
22
|
+
from .core import (
|
|
23
|
+
CATALYST_VERSION,
|
|
24
|
+
HAS_CATALYST,
|
|
25
|
+
HAS_JAX_CUDA,
|
|
26
|
+
HAS_LIGHTNING_GPU,
|
|
27
|
+
HAS_LIGHTNING_QUBIT,
|
|
28
|
+
JAX_DEFAULT_BACKEND,
|
|
29
|
+
QMMMSystem,
|
|
30
|
+
QPEEngine,
|
|
31
|
+
QuantumQMMM,
|
|
32
|
+
get_best_available_device,
|
|
33
|
+
get_catalyst_effective_backend,
|
|
34
|
+
)
|
|
35
|
+
from .interfaces import (
|
|
36
|
+
FixedMOEmbeddingDiagnostics,
|
|
37
|
+
FixedMOEmbeddingResult,
|
|
38
|
+
PySCFPennyLaneConverter,
|
|
39
|
+
UnifiedDensityMatrix,
|
|
40
|
+
build_fixed_mo_embedding_integrals,
|
|
41
|
+
)
|
|
42
|
+
from .molecule import MoleculeConfig
|
|
43
|
+
from .utils import load_xyz, save_json_results
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"__version__",
|
|
47
|
+
"QuantumQMMM",
|
|
48
|
+
"QPEEngine",
|
|
49
|
+
"QMMMSystem",
|
|
50
|
+
"FixedMOEmbeddingDiagnostics",
|
|
51
|
+
"FixedMOEmbeddingResult",
|
|
52
|
+
"PySCFPennyLaneConverter",
|
|
53
|
+
"UnifiedDensityMatrix",
|
|
54
|
+
"build_fixed_mo_embedding_integrals",
|
|
55
|
+
"load_xyz",
|
|
56
|
+
"save_json_results",
|
|
57
|
+
# Molecule config
|
|
58
|
+
"MoleculeConfig",
|
|
59
|
+
# Constants
|
|
60
|
+
"HARTREE_TO_KCAL_MOL",
|
|
61
|
+
"KCAL_TO_HARTREE",
|
|
62
|
+
"ANGSTROM_TO_BOHR",
|
|
63
|
+
"CHEMICAL_ACCURACY_HA",
|
|
64
|
+
"TIP3P_OXYGEN_CHARGE",
|
|
65
|
+
"TIP3P_HYDROGEN_CHARGE",
|
|
66
|
+
# Device utilities
|
|
67
|
+
"HAS_LIGHTNING_GPU",
|
|
68
|
+
"HAS_LIGHTNING_QUBIT",
|
|
69
|
+
"HAS_JAX_CUDA",
|
|
70
|
+
"JAX_DEFAULT_BACKEND",
|
|
71
|
+
"HAS_CATALYST",
|
|
72
|
+
"CATALYST_VERSION",
|
|
73
|
+
"get_best_available_device",
|
|
74
|
+
"get_catalyst_effective_backend",
|
|
75
|
+
]
|
q2m3/constants.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Copyright (c) 2026 Ye Jun <yjmaxpayne@hotmail.com>
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Centralized physical constants for quantum chemistry and QM/MM simulations.
|
|
6
|
+
|
|
7
|
+
All values are Python floats (NOT JAX scalars) for compatibility with both
|
|
8
|
+
pure Python and @qjit compiled code.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
# =============================================================================
|
|
12
|
+
# Unit Conversion Constants
|
|
13
|
+
# =============================================================================
|
|
14
|
+
HARTREE_TO_KCAL_MOL = 627.5094
|
|
15
|
+
KCAL_TO_HARTREE = 1.0 / HARTREE_TO_KCAL_MOL
|
|
16
|
+
ANGSTROM_TO_BOHR = 1.8897259886
|
|
17
|
+
BOLTZMANN_CONSTANT = 3.1668114e-6 # Hartree/K
|
|
18
|
+
COULOMB_CONSTANT = 332.0637 # kcal/mol * Angstrom / e^2
|
|
19
|
+
|
|
20
|
+
# =============================================================================
|
|
21
|
+
# TIP3P Water Model Parameters
|
|
22
|
+
# Reference: Jorgensen et al., J. Chem. Phys. 79, 926 (1983)
|
|
23
|
+
# =============================================================================
|
|
24
|
+
TIP3P_OH_BOND_LENGTH = 0.9572 # Angstrom
|
|
25
|
+
TIP3P_HOH_ANGLE = 104.52 # degrees
|
|
26
|
+
TIP3P_OXYGEN_CHARGE = -0.834 # e
|
|
27
|
+
TIP3P_HYDROGEN_CHARGE = 0.417 # e
|
|
28
|
+
TIP3P_SIGMA_OO = 3.15061 # Angstrom (Lennard-Jones sigma)
|
|
29
|
+
TIP3P_EPSILON_OO = 0.152 # kcal/mol (Lennard-Jones epsilon)
|
|
30
|
+
|
|
31
|
+
# =============================================================================
|
|
32
|
+
# Accuracy Thresholds
|
|
33
|
+
# =============================================================================
|
|
34
|
+
CHEMICAL_ACCURACY_HA = 0.0016 # ~1 kcal/mol
|
|
35
|
+
RELAXED_ACCURACY_HA = 0.016 # ~10 kcal/mol
|
q2m3/core/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Copyright (c) 2026 Ye Jun <yjmaxpayne@hotmail.com>
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Core module for Quantum-QM/MM calculations.
|
|
6
|
+
|
|
7
|
+
Contains the main computational engines and system builders.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .device_utils import (
|
|
11
|
+
CATALYST_VERSION,
|
|
12
|
+
HAS_CATALYST,
|
|
13
|
+
HAS_JAX_CUDA,
|
|
14
|
+
HAS_LIGHTNING_GPU,
|
|
15
|
+
HAS_LIGHTNING_QUBIT,
|
|
16
|
+
JAX_DEFAULT_BACKEND,
|
|
17
|
+
get_best_available_device,
|
|
18
|
+
get_catalyst_effective_backend,
|
|
19
|
+
select_device,
|
|
20
|
+
)
|
|
21
|
+
from .hamiltonian_utils import build_operator_index_map, decompose_hamiltonian
|
|
22
|
+
from .qmmm_system import QMMMSystem
|
|
23
|
+
from .qpe import QPEEngine
|
|
24
|
+
from .quantum_qmmm import QuantumQMMM
|
|
25
|
+
from .rdm import RDMEstimator, measure_rdm_from_qpe_state
|
|
26
|
+
from .resource_estimation import (
|
|
27
|
+
EFTQCResources,
|
|
28
|
+
EmbeddingDiagnostics,
|
|
29
|
+
ResourceComparisonResult,
|
|
30
|
+
compare_vacuum_solvated,
|
|
31
|
+
derive_t_resources,
|
|
32
|
+
estimate_eftqc_runtime,
|
|
33
|
+
estimate_resources,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"decompose_hamiltonian",
|
|
38
|
+
"build_operator_index_map",
|
|
39
|
+
# Resource estimation
|
|
40
|
+
"EFTQCResources",
|
|
41
|
+
"EmbeddingDiagnostics",
|
|
42
|
+
"ResourceComparisonResult",
|
|
43
|
+
"estimate_resources",
|
|
44
|
+
"compare_vacuum_solvated",
|
|
45
|
+
"derive_t_resources",
|
|
46
|
+
"estimate_eftqc_runtime",
|
|
47
|
+
"QPEEngine",
|
|
48
|
+
"QMMMSystem",
|
|
49
|
+
"QuantumQMMM",
|
|
50
|
+
"RDMEstimator",
|
|
51
|
+
"measure_rdm_from_qpe_state",
|
|
52
|
+
# Device utilities
|
|
53
|
+
"select_device",
|
|
54
|
+
"get_best_available_device",
|
|
55
|
+
"get_catalyst_effective_backend",
|
|
56
|
+
"HAS_LIGHTNING_GPU",
|
|
57
|
+
"HAS_LIGHTNING_QUBIT",
|
|
58
|
+
"HAS_JAX_CUDA",
|
|
59
|
+
"JAX_DEFAULT_BACKEND",
|
|
60
|
+
"HAS_CATALYST",
|
|
61
|
+
"CATALYST_VERSION",
|
|
62
|
+
]
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# Copyright (c) 2026 Ye Jun <yjmaxpayne@hotmail.com>
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Quantum device selection and management utilities.
|
|
6
|
+
|
|
7
|
+
Provides unified device selection logic for QPE and RDM modules,
|
|
8
|
+
with GPU acceleration support and Catalyst compatibility.
|
|
9
|
+
|
|
10
|
+
IMPORTANT: There are TWO separate GPU support systems in q2m3:
|
|
11
|
+
|
|
12
|
+
1. PennyLane Lightning GPU (cuQuantum/CUDA):
|
|
13
|
+
- Used by standard QPE circuits (without @qjit)
|
|
14
|
+
- Detected by HAS_LIGHTNING_GPU flag
|
|
15
|
+
- Requires: pennylane-lightning[gpu], cuQuantum, CUDA
|
|
16
|
+
|
|
17
|
+
2. JAX/Catalyst GPU (jaxlib[cuda]):
|
|
18
|
+
- Used by Catalyst @qjit compiled circuits
|
|
19
|
+
- Detected by HAS_JAX_CUDA flag
|
|
20
|
+
- Requires: jax[cuda11_pip] or jax[cuda12_pip]
|
|
21
|
+
|
|
22
|
+
When Catalyst @qjit is enabled, even with lightning.gpu device,
|
|
23
|
+
the actual execution backend is determined by JAX, NOT PennyLane.
|
|
24
|
+
If JAX lacks CUDA support, Catalyst runs on CPU regardless of device name.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import warnings
|
|
28
|
+
from typing import Literal
|
|
29
|
+
|
|
30
|
+
import pennylane as qml
|
|
31
|
+
|
|
32
|
+
# =============================================================================
|
|
33
|
+
# Device Availability Detection (executed once at module import)
|
|
34
|
+
# =============================================================================
|
|
35
|
+
|
|
36
|
+
# 1. PennyLane Lightning GPU availability (for standard QPE)
|
|
37
|
+
HAS_LIGHTNING_GPU = False
|
|
38
|
+
try:
|
|
39
|
+
_test_dev = qml.device("lightning.gpu", wires=1)
|
|
40
|
+
del _test_dev
|
|
41
|
+
HAS_LIGHTNING_GPU = True
|
|
42
|
+
except Exception as e:
|
|
43
|
+
# Device "lightning.gpu" not available or failed to initialize; ignore and continue.
|
|
44
|
+
warnings.warn(f'Could not initialize "lightning.gpu" device: {e}', stacklevel=2)
|
|
45
|
+
|
|
46
|
+
HAS_LIGHTNING_QUBIT = False
|
|
47
|
+
try:
|
|
48
|
+
_test_dev = qml.device("lightning.qubit", wires=1)
|
|
49
|
+
del _test_dev
|
|
50
|
+
HAS_LIGHTNING_QUBIT = True
|
|
51
|
+
except Exception as e:
|
|
52
|
+
# Device "lightning.qubit" not available or failed to initialize; ignore and continue.
|
|
53
|
+
warnings.warn(f'Could not initialize "lightning.qubit" device: {e}', stacklevel=2)
|
|
54
|
+
|
|
55
|
+
# 2. JAX/Catalyst GPU availability (for @qjit compiled circuits)
|
|
56
|
+
# This is SEPARATE from PennyLane Lightning GPU!
|
|
57
|
+
HAS_JAX_CUDA = False
|
|
58
|
+
JAX_DEFAULT_BACKEND = "cpu"
|
|
59
|
+
try:
|
|
60
|
+
import jax
|
|
61
|
+
|
|
62
|
+
JAX_DEFAULT_BACKEND = jax.default_backend()
|
|
63
|
+
# JAX backend is "cuda" or "gpu" when GPU is available
|
|
64
|
+
HAS_JAX_CUDA = JAX_DEFAULT_BACKEND in ("cuda", "gpu")
|
|
65
|
+
except ImportError:
|
|
66
|
+
# JAX not installed, which is fine for non-Catalyst usage
|
|
67
|
+
pass
|
|
68
|
+
except Exception:
|
|
69
|
+
# Other JAX initialization errors
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
# 3. Catalyst availability (for reporting/display purposes)
|
|
73
|
+
# NOTE: qpe.py and rdm.py maintain their own HAS_CATALYST + no-op fallback
|
|
74
|
+
# for graceful degradation. This detection is for display/reporting only.
|
|
75
|
+
HAS_CATALYST = False
|
|
76
|
+
CATALYST_VERSION = "N/A"
|
|
77
|
+
try:
|
|
78
|
+
import catalyst
|
|
79
|
+
|
|
80
|
+
HAS_CATALYST = True
|
|
81
|
+
CATALYST_VERSION = catalyst.__version__
|
|
82
|
+
except ImportError:
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
# Type alias for supported device types
|
|
86
|
+
DeviceType = Literal["auto", "default.qubit", "lightning.qubit", "lightning.gpu"]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def get_best_available_device() -> str:
|
|
90
|
+
"""
|
|
91
|
+
Return the name of the best available device.
|
|
92
|
+
|
|
93
|
+
Priority: lightning.gpu > lightning.qubit > default.qubit
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
Device name string
|
|
97
|
+
"""
|
|
98
|
+
if HAS_LIGHTNING_GPU:
|
|
99
|
+
return "lightning.gpu"
|
|
100
|
+
elif HAS_LIGHTNING_QUBIT:
|
|
101
|
+
return "lightning.qubit"
|
|
102
|
+
else:
|
|
103
|
+
return "default.qubit"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def get_catalyst_backend_info() -> dict:
|
|
107
|
+
"""
|
|
108
|
+
Get detailed information about Catalyst execution backend.
|
|
109
|
+
|
|
110
|
+
IMPORTANT: Catalyst @qjit uses JAX as its execution backend, which is
|
|
111
|
+
SEPARATE from PennyLane device selection. Even if device="lightning.gpu",
|
|
112
|
+
Catalyst will run on CPU if JAX lacks CUDA support.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Dictionary with:
|
|
116
|
+
- jax_backend: JAX default backend ("cpu", "cuda", "gpu")
|
|
117
|
+
- has_jax_cuda: Whether JAX has CUDA support
|
|
118
|
+
- effective_device: Actual execution device for Catalyst
|
|
119
|
+
- warning: Optional warning message if GPU expected but unavailable
|
|
120
|
+
"""
|
|
121
|
+
result = {
|
|
122
|
+
"jax_backend": JAX_DEFAULT_BACKEND,
|
|
123
|
+
"has_jax_cuda": HAS_JAX_CUDA,
|
|
124
|
+
"effective_device": "GPU" if HAS_JAX_CUDA else "CPU",
|
|
125
|
+
"warning": None,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
# Add warning if Lightning GPU is available but JAX GPU is not
|
|
129
|
+
if HAS_LIGHTNING_GPU and not HAS_JAX_CUDA:
|
|
130
|
+
result["warning"] = (
|
|
131
|
+
"PennyLane lightning.gpu is available, but Catalyst @qjit will run on CPU "
|
|
132
|
+
"because JAX lacks CUDA support. To enable Catalyst GPU, install: "
|
|
133
|
+
"pip install 'jax[cuda12]' (or cuda11 for older CUDA versions)"
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
return result
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_effective_catalyst_device_label() -> str:
|
|
140
|
+
"""
|
|
141
|
+
Get the effective device label for Catalyst execution.
|
|
142
|
+
|
|
143
|
+
Unlike get_best_available_device() which returns the PennyLane device name,
|
|
144
|
+
this returns what Catalyst actually runs on (CPU/GPU based on JAX backend).
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
Human-readable label like "lightning.gpu (JAX: CPU)" or "lightning.gpu (JAX: GPU)"
|
|
148
|
+
"""
|
|
149
|
+
pennylane_device = get_best_available_device()
|
|
150
|
+
jax_backend = "GPU" if HAS_JAX_CUDA else "CPU"
|
|
151
|
+
return f"{pennylane_device} (JAX: {jax_backend})"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def get_catalyst_effective_backend() -> str:
|
|
155
|
+
"""Get human-readable Catalyst execution backend label.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
String like "GPU (JAX CUDA)" or "CPU (JAX)"
|
|
159
|
+
"""
|
|
160
|
+
if HAS_JAX_CUDA:
|
|
161
|
+
return "GPU (JAX CUDA)"
|
|
162
|
+
return "CPU (JAX)"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def select_device(
|
|
166
|
+
device_type: str,
|
|
167
|
+
n_wires: int,
|
|
168
|
+
use_catalyst: bool = False,
|
|
169
|
+
seed: int | None = None,
|
|
170
|
+
):
|
|
171
|
+
"""
|
|
172
|
+
Select quantum device based on device_type parameter.
|
|
173
|
+
|
|
174
|
+
NOTE: As of PennyLane v0.43, setting shots on device is deprecated.
|
|
175
|
+
Use qml.set_shots() transform on QNode instead.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
device_type: Device selection strategy:
|
|
179
|
+
- "auto": Auto-select best available (GPU > lightning.qubit > default.qubit)
|
|
180
|
+
- "default.qubit": Standard PennyLane simulator
|
|
181
|
+
- "lightning.qubit": High-performance CPU simulator
|
|
182
|
+
- "lightning.gpu": GPU-accelerated simulator (requires cuQuantum)
|
|
183
|
+
n_wires: Number of qubits
|
|
184
|
+
use_catalyst: If True, ensure Catalyst-compatible fallback
|
|
185
|
+
(lightning.qubit instead of default.qubit)
|
|
186
|
+
seed: Optional device seed for reproducible shot-based sampling
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
PennyLane device instance
|
|
190
|
+
"""
|
|
191
|
+
device_kwargs = {"wires": n_wires}
|
|
192
|
+
if seed is not None:
|
|
193
|
+
device_kwargs["seed"] = seed
|
|
194
|
+
|
|
195
|
+
# Determine fallback device based on Catalyst compatibility
|
|
196
|
+
# Catalyst only supports lightning.qubit and lightning.gpu, not default.qubit
|
|
197
|
+
fallback_device = (
|
|
198
|
+
"lightning.qubit" if (use_catalyst and HAS_LIGHTNING_QUBIT) else "default.qubit"
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
if device_type == "auto":
|
|
202
|
+
# Auto-select: GPU > lightning.qubit > default.qubit
|
|
203
|
+
if HAS_LIGHTNING_GPU:
|
|
204
|
+
return qml.device("lightning.gpu", **device_kwargs)
|
|
205
|
+
elif HAS_LIGHTNING_QUBIT:
|
|
206
|
+
return qml.device("lightning.qubit", **device_kwargs)
|
|
207
|
+
else:
|
|
208
|
+
return qml.device("default.qubit", **device_kwargs)
|
|
209
|
+
|
|
210
|
+
elif device_type == "lightning.gpu":
|
|
211
|
+
if not HAS_LIGHTNING_GPU:
|
|
212
|
+
warnings.warn(
|
|
213
|
+
f"lightning.gpu not available, falling back to {fallback_device}",
|
|
214
|
+
UserWarning,
|
|
215
|
+
stacklevel=3,
|
|
216
|
+
)
|
|
217
|
+
return qml.device(fallback_device, **device_kwargs)
|
|
218
|
+
return qml.device("lightning.gpu", **device_kwargs)
|
|
219
|
+
|
|
220
|
+
elif device_type == "lightning.qubit":
|
|
221
|
+
if not HAS_LIGHTNING_QUBIT:
|
|
222
|
+
warnings.warn(
|
|
223
|
+
"lightning.qubit not available, falling back to default.qubit",
|
|
224
|
+
UserWarning,
|
|
225
|
+
stacklevel=3,
|
|
226
|
+
)
|
|
227
|
+
return qml.device("default.qubit", **device_kwargs)
|
|
228
|
+
return qml.device("lightning.qubit", **device_kwargs)
|
|
229
|
+
|
|
230
|
+
else:
|
|
231
|
+
# default.qubit or any unrecognized value
|
|
232
|
+
return qml.device("default.qubit", **device_kwargs)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Copyright (c) 2026 Ye Jun <yjmaxpayne@hotmail.com>
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""
|
|
4
|
+
PennyLane Hamiltonian operator utilities.
|
|
5
|
+
|
|
6
|
+
Provides helper functions for decomposing PennyLane Sum/Hamiltonian objects
|
|
7
|
+
(PennyLane 0.44+ compatible) and building operator index maps for efficient
|
|
8
|
+
coefficient updates in QM/MM simulations.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import pennylane as qml
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def decompose_hamiltonian(H) -> tuple[list[float], list]:
|
|
15
|
+
"""
|
|
16
|
+
Extract (coeffs, ops) from PennyLane Sum/Hamiltonian.
|
|
17
|
+
|
|
18
|
+
PennyLane 0.44+ returns Sum of SProd from qml.qchem.molecular_hamiltonian.
|
|
19
|
+
We need separate coefficients and operators for qml.dot(coeffs, ops).
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
H: PennyLane Hamiltonian (Sum of SProd operators)
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Tuple of (coefficients, operators) where coefficients are floats
|
|
26
|
+
and operators are PennyLane operator instances.
|
|
27
|
+
"""
|
|
28
|
+
coeffs = []
|
|
29
|
+
ops = []
|
|
30
|
+
for op in H.operands:
|
|
31
|
+
if isinstance(op, qml.ops.SProd):
|
|
32
|
+
coeffs.append(float(op.scalar))
|
|
33
|
+
ops.append(op.base)
|
|
34
|
+
else:
|
|
35
|
+
coeffs.append(1.0)
|
|
36
|
+
ops.append(op)
|
|
37
|
+
return coeffs, ops
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_operator_index_map(
|
|
41
|
+
ops: list,
|
|
42
|
+
n_system_qubits: int,
|
|
43
|
+
coeffs: list[float],
|
|
44
|
+
) -> tuple[dict, list[float], list]:
|
|
45
|
+
"""
|
|
46
|
+
Scan ops to find Identity and single-Z(wire) indices for MM coefficient updates.
|
|
47
|
+
|
|
48
|
+
If any Z(wire) for wire in range(n_system_qubits) is missing, appends a
|
|
49
|
+
coeff=0.0 placeholder to ensure all spin orbitals can receive MM corrections.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
ops: List of PennyLane operators (from decompose_hamiltonian)
|
|
53
|
+
n_system_qubits: Number of system qubits (= 2 * active_orbitals)
|
|
54
|
+
coeffs: Corresponding coefficient list (may be extended)
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
Tuple of (index_map, extended_coeffs, extended_ops) where:
|
|
58
|
+
- index_map: {"identity_idx": int, "z_wire_idx": {wire: idx, ...}}
|
|
59
|
+
- extended_coeffs: coefficients with any missing Z terms appended
|
|
60
|
+
- extended_ops: operators with any missing Z terms appended
|
|
61
|
+
"""
|
|
62
|
+
coeffs = list(coeffs)
|
|
63
|
+
ops = list(ops)
|
|
64
|
+
|
|
65
|
+
identity_idx = None
|
|
66
|
+
z_wire_idx = {}
|
|
67
|
+
|
|
68
|
+
for i, op in enumerate(ops):
|
|
69
|
+
# Detect multi-wire Identity (matches qml.Identity(wires=[0,1,...]))
|
|
70
|
+
if isinstance(op, qml.Identity):
|
|
71
|
+
identity_idx = i
|
|
72
|
+
# Detect single-qubit PauliZ
|
|
73
|
+
elif isinstance(op, qml.PauliZ) and len(op.wires) == 1:
|
|
74
|
+
wire = op.wires[0]
|
|
75
|
+
z_wire_idx[wire] = i
|
|
76
|
+
|
|
77
|
+
# Ensure all spin-orbital wires have a Z entry
|
|
78
|
+
for wire in range(n_system_qubits):
|
|
79
|
+
if wire not in z_wire_idx:
|
|
80
|
+
z_wire_idx[wire] = len(ops)
|
|
81
|
+
coeffs.append(0.0)
|
|
82
|
+
ops.append(qml.PauliZ(wires=wire))
|
|
83
|
+
|
|
84
|
+
if identity_idx is None:
|
|
85
|
+
raise ValueError("Hamiltonian has no Identity term — cannot apply MM corrections")
|
|
86
|
+
|
|
87
|
+
index_map = {"identity_idx": identity_idx, "z_wire_idx": z_wire_idx}
|
|
88
|
+
return index_map, coeffs, ops
|
q2m3/core/qmmm_system.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# Copyright (c) 2026 Ye Jun <yjmaxpayne@hotmail.com>
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
QM/MM system builder for molecular simulations.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Atom:
|
|
16
|
+
"""Represents an atom with position and properties."""
|
|
17
|
+
|
|
18
|
+
symbol: str
|
|
19
|
+
position: np.ndarray # 3D coordinates in Angstrom
|
|
20
|
+
charge: float = 0.0
|
|
21
|
+
is_qm: bool = True
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class QMMMSystem:
|
|
25
|
+
"""
|
|
26
|
+
Build and manage QM/MM system for H3O+ in water environment.
|
|
27
|
+
|
|
28
|
+
Handles the partitioning of QM and MM regions, and sets up
|
|
29
|
+
the embedding potential for quantum calculations.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
qm_atoms: list[Atom],
|
|
35
|
+
mm_model: str = "tip3p",
|
|
36
|
+
solvation_shells: int = 1,
|
|
37
|
+
num_waters: int = 8,
|
|
38
|
+
):
|
|
39
|
+
"""
|
|
40
|
+
Initialize QM/MM system.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
qm_atoms: List of atoms in QM region (H3O+)
|
|
44
|
+
mm_model: Water model for MM region
|
|
45
|
+
solvation_shells: Number of solvation shells
|
|
46
|
+
num_waters: Number of water molecules in MM region
|
|
47
|
+
"""
|
|
48
|
+
self.qm_atoms = qm_atoms
|
|
49
|
+
self.mm_model = mm_model
|
|
50
|
+
self.solvation_shells = solvation_shells
|
|
51
|
+
self.num_waters = num_waters
|
|
52
|
+
self.mm_atoms = []
|
|
53
|
+
|
|
54
|
+
# Initialize system
|
|
55
|
+
self._setup_mm_environment()
|
|
56
|
+
|
|
57
|
+
def _setup_mm_environment(self) -> None:
|
|
58
|
+
"""
|
|
59
|
+
Generate MM water molecules around QM region.
|
|
60
|
+
|
|
61
|
+
Creates a simple spherical solvation shell around the QM region
|
|
62
|
+
using TIP3P water geometry.
|
|
63
|
+
"""
|
|
64
|
+
if self.num_waters == 0:
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
# TIP3P water geometry constants (Angstrom)
|
|
68
|
+
OH_BOND_LENGTH = 0.9572
|
|
69
|
+
SOLVATION_RADIUS = 3.0
|
|
70
|
+
|
|
71
|
+
# Calculate center of QM region
|
|
72
|
+
qm_center = self._calculate_qm_center()
|
|
73
|
+
|
|
74
|
+
for i in range(self.num_waters):
|
|
75
|
+
water_atoms = self._create_water_molecule(
|
|
76
|
+
i, qm_center, SOLVATION_RADIUS, OH_BOND_LENGTH
|
|
77
|
+
)
|
|
78
|
+
self.mm_atoms.extend(water_atoms)
|
|
79
|
+
|
|
80
|
+
def _create_water_molecule(
|
|
81
|
+
self, index: int, center: np.ndarray, radius: float, bond_length: float
|
|
82
|
+
) -> list[Atom]:
|
|
83
|
+
"""
|
|
84
|
+
Create a single water molecule at spherical position.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
index: Water molecule index
|
|
88
|
+
center: Center point for placement
|
|
89
|
+
radius: Distance from center
|
|
90
|
+
bond_length: O-H bond length
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
List of three atoms (O, H, H)
|
|
94
|
+
"""
|
|
95
|
+
# TIP3P partial charges
|
|
96
|
+
OXYGEN_CHARGE = -0.834
|
|
97
|
+
HYDROGEN_CHARGE = 0.417
|
|
98
|
+
|
|
99
|
+
# Calculate spherical position
|
|
100
|
+
theta = np.pi * (index + 0.5) / self.num_waters
|
|
101
|
+
phi = 2 * np.pi * index / self.num_waters
|
|
102
|
+
|
|
103
|
+
o_pos = center + radius * np.array(
|
|
104
|
+
[np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# Create water atoms (simplified orientation)
|
|
108
|
+
o_atom = Atom("O", o_pos, charge=OXYGEN_CHARGE, is_qm=False)
|
|
109
|
+
h1_pos = o_pos + np.array([bond_length, 0, 0])
|
|
110
|
+
h2_pos = o_pos + np.array([-bond_length, 0, 0])
|
|
111
|
+
|
|
112
|
+
h1_atom = Atom("H", h1_pos, charge=HYDROGEN_CHARGE, is_qm=False)
|
|
113
|
+
h2_atom = Atom("H", h2_pos, charge=HYDROGEN_CHARGE, is_qm=False)
|
|
114
|
+
|
|
115
|
+
return [o_atom, h1_atom, h2_atom]
|
|
116
|
+
|
|
117
|
+
def _calculate_qm_center(self) -> np.ndarray:
|
|
118
|
+
"""Calculate geometric center of QM region."""
|
|
119
|
+
positions = np.array([atom.position for atom in self.qm_atoms])
|
|
120
|
+
return np.mean(positions, axis=0)
|
|
121
|
+
|
|
122
|
+
def get_embedding_potential(self) -> tuple[np.ndarray, np.ndarray]:
|
|
123
|
+
"""
|
|
124
|
+
Calculate embedding potential from MM charges.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
Tuple of (charges, coordinates) for MM point charges
|
|
128
|
+
"""
|
|
129
|
+
if not self.mm_atoms:
|
|
130
|
+
return np.array([]), np.array([])
|
|
131
|
+
|
|
132
|
+
charges = np.array([atom.charge for atom in self.mm_atoms])
|
|
133
|
+
coords = np.array([atom.position for atom in self.mm_atoms])
|
|
134
|
+
|
|
135
|
+
return charges, coords
|
|
136
|
+
|
|
137
|
+
def get_total_charge(self) -> int:
|
|
138
|
+
"""Get total system charge."""
|
|
139
|
+
return sum(atom.charge for atom in self.qm_atoms)
|
|
140
|
+
|
|
141
|
+
def get_qm_coords(self) -> np.ndarray:
|
|
142
|
+
"""Get QM atom coordinates as numpy array."""
|
|
143
|
+
return np.array([atom.position for atom in self.qm_atoms])
|
|
144
|
+
|
|
145
|
+
def to_pyscf_mol(self) -> dict[str, Any]:
|
|
146
|
+
"""
|
|
147
|
+
Convert to PySCF molecule format.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Dictionary with atom positions and basis set info
|
|
151
|
+
"""
|
|
152
|
+
atom_str = []
|
|
153
|
+
for atom in self.qm_atoms:
|
|
154
|
+
atom_str.append(
|
|
155
|
+
f"{atom.symbol} {atom.position[0]:.6f} {atom.position[1]:.6f} {atom.position[2]:.6f}"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
"atom": "\n".join(atom_str),
|
|
160
|
+
"charge": self.get_total_charge(),
|
|
161
|
+
"basis": "sto-3g",
|
|
162
|
+
"unit": "Angstrom",
|
|
163
|
+
}
|