溶剂化 API¶
配置¶
MC 溶剂化模拟的配置数据类。
提供冻结(不可变)的分子配置、QPE 参数和溶剂化模拟设置。采用三模式哈密顿量框架(hf_corrected / fixed / dynamic)。
- class q2m3.solvation.config.MoleculeConfig(name, symbols, coords, charge, active_electrons=2, active_orbitals=2, basis='sto-3g')[源代码]¶
基类:
object溶剂化模拟的分子体系配置。
- 参数:
name (str)
symbols (list[str])
coords (list[list[float]])
charge (int)
active_electrons (int)
active_orbitals (int)
basis (str)
- name¶
便于阅读的标识符
- 类型:
str
- symbols¶
原子符号(例如 ["H", "H"])
- 类型:
list[str]
- coords¶
原子坐标,单位为埃,形状为 (n_atoms, 3)
- 类型:
list[list[float]]
- charge¶
分子总电荷(必填,无默认值)
- 类型:
int
- active_electrons¶
QPE 活性空间中的活性电子数
- 类型:
int
- active_orbitals¶
QPE 活性空间中的活性轨道数
- 类型:
int
- basis¶
基组名称
- 类型:
str
- property coords_array: ndarray¶
以形状为 (n_atoms, 3) 的 numpy 数组表示的坐标。
- class q2m3.solvation.config.QPEConfig(n_estimation_wires=4, n_trotter_steps=10, n_shots=0, device_seed=None, target_resolution=0.003, energy_range=0.2, qpe_interval=10)[源代码]¶
基类:
objectQPE(量子相位估计)参数。
- 参数:
n_estimation_wires (int)
n_trotter_steps (int)
n_shots (int)
device_seed (int | None)
target_resolution (float)
energy_range (float)
qpe_interval (int)
- n_estimation_wires¶
相位估计寄存器的量子比特数
- 类型:
int
- n_trotter_steps¶
时间演化的 Trotter 步数
- 类型:
int
- n_shots¶
测量次数(0 = 解析计算,>0 = 采样)
- 类型:
int
- device_seed¶
用于复现设备采样结果的可选随机种子
- 类型:
int | None
- target_resolution¶
目标能量分辨率,单位为 Hartree
- 类型:
float
- energy_range¶
平移后 QPE 的能量范围,单位为 Hartree
- 类型:
float
- qpe_interval¶
两次 QPE 评估之间的 MC 步数间隔(hf_corrected 模式)
- 类型:
int
- class q2m3.solvation.config.SolvationConfig(molecule, qpe_config=<factory>, hamiltonian_mode='dynamic', embedding_mode='diagonal', n_waters=10, n_mc_steps=500, temperature=300.0, translation_step=0.3, rotation_step=0.2618, initial_water_distance=4.0, random_seed=42, verbose=True, ir_cache_dir=None, ir_cache_enabled=True, ir_cache_force_recompile=False)[源代码]¶
基类:
object完整的 MC 溶剂化模拟配置。
- hamiltonian_mode 字段选择能量评估策略:
"hf_corrected":E_HF + delta_corr_pol(快速,近似)
"fixed":仅编译一次的真空哈密顿量(速度中等)
"dynamic":每步使用 MM 嵌入哈密顿量(慢,最完整)
- embedding_mode 字段选择 MM 嵌入算符的支持范围:
"diagonal":更新单位算符/Z 算符系数的兼容模式
"full_oneelectron":支持固定 MO 的完整单电子算符,仅适用于 hamiltonian_mode="fixed"
- 参数:
molecule (MoleculeConfig)
qpe_config (QPEConfig)
hamiltonian_mode (Literal['hf_corrected', 'fixed', 'dynamic'])
embedding_mode (Literal['diagonal', 'full_oneelectron'])
n_waters (int)
n_mc_steps (int)
temperature (float)
translation_step (float)
rotation_step (float)
initial_water_distance (float)
random_seed (int)
verbose (bool)
ir_cache_dir (str | None)
ir_cache_enabled (bool)
ir_cache_force_recompile (bool)
- molecule¶
分子体系配置
- qpe_config¶
QPE 参数
- hamiltonian_mode¶
能量评估策略
- 类型:
Literal['hf_corrected', 'fixed', 'dynamic']
- embedding_mode¶
构建 QPE 哈密顿量时使用的 MM 嵌入模式
- 类型:
Literal['diagonal', 'full_oneelectron']
- n_waters¶
TIP3P 水分子数
- 类型:
int
- n_mc_steps¶
MC 采样总步数
- 类型:
int
- temperature¶
模拟温度,单位为开尔文
- 类型:
float
- translation_step¶
每次 MC 移动的最大平移量,单位为埃
- 类型:
float
- rotation_step¶
每次 MC 移动的最大旋转角,单位为弧度
- 类型:
float
- initial_water_distance¶
初始水分子环半径,单位为埃
- 类型:
float
- random_seed¶
用于复现结果的随机种子
- 类型:
int
- verbose¶
打印进度信息
- 类型:
bool
- ir_cache_dir¶
Catalyst LLVM IR 缓存目录;设为 None 时使用默认缓存路径
- 类型:
str | None
- ir_cache_enabled¶
启用 Catalyst LLVM IR 缓存复用
- 类型:
bool
- ir_cache_force_recompile¶
忽略缓存的 IR 并强制重新编译
- 类型:
bool
- property n_qpe_evaluations: int¶
根据模式计算预期的 QPE 评估次数。
- property kt: float¶
热能 kT,单位为 Hartree。
流程编排器¶
MC 溶剂化流程编排器。
由 QPE 驱动的蒙特卡洛溶剂化模拟的端到端工作流。支持三种哈密顿量模式:
hf_corrected:使用 E_HF + E_MM 判定是否接受,按间隔执行 QPE 诊断
fixed:真空哈密顿量仅编译一次,每步执行 QPE
dynamic:每步使用 MM 嵌入哈密顿量,每步执行 QPE
用法:
from q2m3.solvation import SolvationConfig, MoleculeConfig, run_solvation
config = SolvationConfig(
molecule=MoleculeConfig(name="H2", symbols=["H","H"],
coords=[[0,0,0],[0,0,0.74]], charge=0),
hamiltonian_mode="fixed",
n_waters=10,
n_mc_steps=100,
)
result = run_solvation(config, show_plots=False)
- q2m3.solvation.orchestrator.run_solvation(config, show_plots=True)[源代码]¶
执行完整的 MC 溶剂化工作流。
工作流:1. 验证配置 2. 初始化溶剂环 3. 计算真空 HF 能量 4. 构建 QPE 电路(build_qpe_circuit -> QPECircuitBundle)5. 预计算真空缓存 6. 创建步回调(取决于模式)7. 计算初始能量(首次调用 step_callback -> 触发 @qjit)8. 创建 MC 循环(create_mc_loop)9. 执行 MC 循环 10. 计算 Mulliken 电荷(诊断)11. 打印统计信息并绘图(如有请求)12. 返回结果字典
- 参数:
config (SolvationConfig) -- 完整的溶剂化模拟配置
show_plots (bool) -- 是否显示能量轨迹图
- 返回:
包含第 1 层(MCResult)和第 2 层(流程编排器)字段的 dict
- 返回类型:
dict[str, Any]
- q2m3.solvation.orchestrator.replay_quantum_trajectory(config, trajectory_solvent_states)[源代码]¶
在保存的溶剂轨迹上重放 fixed 或 dynamic 模式的量子评估。
- 参数:
config (SolvationConfig)
trajectory_solvent_states (ndarray)
- 返回类型:
dict[str, Any]
电路构建器¶
MC 溶剂化模拟的 QPE 电路构建器。
构建由 @qjit 编译的参数化 QPE 电路。电路将哈密顿量系数作为运行时参数接收。仅编译一次后,每个 MC 步用不同系数调用,避免每步重新编译所需的 67 秒。
Catalyst 的关键约束(已通过概念验证):- 使用 X 门代替 qml.BasisState(Catalyst @qjit + ctrl() 存在缺陷)- TrotterProduct 必须设置 check_hermitian=False(与 JAX tracer 不兼容)- MAX_TROTTER_STEPS_RUNTIME 限制 Trotter 步数,以避免 MLIR 内存不足 - 量子比特采用最高有效位在前的顺序(与 PennyLane QFT 约定一致)
- class q2m3.solvation.circuit_builder.QPECircuitBundle(compiled_circuit, base_coeffs, ops, base_time, op_index_map, energy_shift, n_estimation_wires, n_system_qubits, active_orbitals, n_trotter_steps, measurement_mode, is_fixed_circuit=False, embedding_mode='diagonal')[源代码]¶
基类:
objectQPE 电路编译产生的全部对象。
- 参数:
compiled_circuit (Callable)
base_coeffs (ndarray)
ops (list)
base_time (float)
op_index_map (dict)
energy_shift (float)
n_estimation_wires (int)
n_system_qubits (int)
active_orbitals (int)
n_trotter_steps (int)
measurement_mode (str)
is_fixed_circuit (bool)
embedding_mode (str)
- compiled_circuit¶
@qjit 函数:() → result(fixed)或 (coeffs_arr) → result(dynamic)
- 类型:
collections.abc.Callable
- base_coeffs¶
初始真空系数加平移系数
- 类型:
numpy.ndarray
- ops¶
PennyLane 算符(编译时常量)
- 类型:
list
- base_time¶
用于将相位转换为能量的演化时间
- 类型:
float
- op_index_map¶
{"identity_idx": int, "z_wire_idx": {wire: idx}}
- 类型:
dict
- energy_shift¶
施加于哈密顿量的 E_HF 平移量
- 类型:
float
- n_estimation_wires¶
QPE 估计量子比特数
- 类型:
int
- n_system_qubits¶
系统量子比特数(= 2 * active_orbitals)
- 类型:
int
- active_orbitals¶
活性空间轨道数
- 类型:
int
- n_trotter_steps¶
实际 Trotter 步数(可能受上限限制)
- 类型:
int
- measurement_mode¶
"probs" 或 "shots"
- 类型:
str
- is_fixed_circuit¶
零参数电路(fixed 模式)为 True;接收 coeffs_arr 的电路为 False。
- 类型:
bool
- embedding_mode¶
构建固定算符支撑集所用的 MM 嵌入模式
- 类型:
str
- q2m3.solvation.circuit_builder.build_qpe_circuit(config, qm_coords, hf_energy, *, _keep_intermediate=False)[源代码]¶
构建接收运行时系数的参数化 QPE 电路。
电路构建器构造基础哈密顿量,并将其分解为系数和 PennyLane 算符。它施加 HF 能量平移并推导平移后的 QPE 参数。必要时限制运行时 Trotter 深度,并返回
QPECircuitBundle。在 diagonal 模式下,基础哈密顿量采用真空算符支撑集。在full_oneelectron模式下,它采用固定 MM 算符。- 参数:
config (SolvationConfig) -- 溶剂化配置
qm_coords (ndarray) -- QM 区域坐标,单位为埃,形状为 (n_atoms, 3)
hf_energy (float) -- 用于能量平移和 base_time 计算的 HF 能量
_keep_intermediate (bool)
- 返回:
包含已编译电路和元数据的 QPECircuitBundle
- 返回类型:
- q2m3.solvation.circuit_builder.decompose_hamiltonian(H)¶
从 PennyLane Sum/Hamiltonian 中提取 (coeffs, ops)。
在 PennyLane 0.44+ 中,qml.qchem.molecular_hamiltonian 返回由 SProd 组成的 Sum。qml.dot(coeffs, ops) 需要分别传入系数和算符。
- 参数:
H -- PennyLane 哈密顿量(由 SProd 算符组成的 Sum)
- 返回:
(coefficients, operators) 元组,其中系数为浮点数,算符为 PennyLane 算符实例。
- 返回类型:
tuple[list[float], list]
- q2m3.solvation.circuit_builder.build_operator_index_map(ops, n_system_qubits, coeffs)¶
扫描 ops,查找 Identity 和单 Z(wire) 的索引,以更新 MM 系数。
如果 range(n_system_qubits) 中任一 wire 缺少 Z(wire),则追加 coeff=0.0 的占位项,确保所有自旋轨道都能接收 MM 修正。
- 参数:
ops (list) -- PennyLane 算符列表(来自 decompose_hamiltonian)
n_system_qubits (int) -- 系统量子比特数(= 2 * active_orbitals)
coeffs (list[float]) -- 对应的系数列表(可能会扩展)
- 返回:
index_map: {"identity_idx": int, "z_wire_idx": {wire: idx, ...}}
extended_coeffs: 追加缺失 Z 项后的系数
extended_ops: 追加缺失 Z 项后的算符
- 返回类型:
Tuple of (index_map, extended_coeffs, extended_ops) where
能量回调¶
MC 溶剂化模拟的能量计算模块。
提供真空缓存、三模式系数回调和步回调工厂,用于由 QPE 驱动的蒙特卡洛溶剂化能量评估。
- 三种哈密顿量模式:
hf_corrected:使用 HF 能量判定 MC 是否接受,按间隔执行 QPE 诊断
fixed:真空系数仅编译一次,每步执行 QPE
dynamic:每步使用 MM 嵌入哈密顿量,每步执行 QPE
所有步回调均为纯 Python 函数(未使用 @qjit);它们在内部调用预编译的 @qjit 电路(ADR-003)。
- class q2m3.solvation.energy.StepResult(e_qpe, e_mm_sol_sol, e_hf_ref, callback_time, qpe_time)[源代码]¶
基类:
object一次 MC 步的能量计算结果。
- 参数:
e_qpe (float)
e_mm_sol_sol (float)
e_hf_ref (float)
callback_time (float)
qpe_time (float)
- q2m3.solvation.energy.precompute_vacuum_cache(config)[源代码]¶
运行一次真空 SCF,并缓存结果供 MC 循环使用。
- 参数:
config (SolvationConfig) -- 包含分子定义的溶剂化配置
- 返回:
h_core_vac, mo_coeff, mo_coeff_active, energy_nuc_vac, e_vacuum, active_idx
- 返回类型:
Dictionary with cached vacuum SCF data
- q2m3.solvation.energy.create_coefficient_callback(config, circuit_bundle, vacuum_cache)[源代码]¶
工厂:为配置的模式创建系数更新回调。
对于 "hf_corrected" / "fixed":返回未修改的 base_coeffs。对于 "dynamic":运行溶剂化 SCF,计算差值并更新系数。
- 参数:
config (SolvationConfig) -- 溶剂化配置
circuit_bundle (QPECircuitBundle) -- 包含 base_coeffs 和 op_index_map 的 QPE 电路对象包
vacuum_cache (dict) -- 预计算的真空数据
- 返回:
(solvent_states, qm_coords_flat) -> np.ndarray[n_terms]
- 返回类型:
Callable
- q2m3.solvation.energy.create_step_callback(circuit_bundle, config, vacuum_cache)[源代码]¶
工厂:创建每步能量计算回调(fixed/dynamic 模式)。
内部流程:1. coefficient_callback → new_coeffs 2. compiled_circuit(jnp.array(new_coeffs)) → measurement_result 3. phase_extraction(measurement_result) → e_qpe 4. compute_mm_energy(solvents) → e_mm_sol_sol 5. 返回 StepResult
- 参数:
circuit_bundle (QPECircuitBundle) -- 包含已编译电路的 QPE 电路对象包
config (SolvationConfig) -- 溶剂化配置
vacuum_cache (dict) -- 预计算的真空数据
- 返回:
(solvent_states, qm_coords_flat) -> StepResult
- 返回类型:
Callable
- q2m3.solvation.energy.create_hf_corrected_step_callback(config, vacuum_cache, qm_coords, e_vacuum, circuit_bundle=None)[源代码]¶
工厂:创建延迟编译的 hf_corrected 模式步回调。
每步:PySCF QMMM → e_hf_ref;compute_mm_energy → e_mm。每隔 qpe_interval 步:额外运行 QPE 电路进行诊断。
如果 circuit_bundle 为 None,则在首个 QPE 步按需构建 QPE 电路(延迟编译,避免启动时的编译开销)。
非 QPE 步返回 StepResult(e_qpe=NaN, qpe_time=0.0)。
- 参数:
config (SolvationConfig) -- 溶剂化配置
vacuum_cache (dict) -- 预计算的真空数据
qm_coords (np.ndarray) -- 用于构建电路的 QM 坐标数组
e_vacuum (float) -- 用于能量平移的真空 HF 能量
circuit_bundle (QPECircuitBundle | None) -- 可选的预构建电路对象包(None = 延迟构建)
- 返回:
(solvent_states, qm_coords_flat) -> StepResult
- 返回类型:
Callable
- q2m3.solvation.energy.compute_hf_energy_vacuum(molecule)[源代码]¶
计算 QM 区域的真空 HF 能量。
- 参数:
molecule (MoleculeConfig) -- 分子体系配置
- 返回:
真空 HF 能量,单位为 Hartree
- 返回类型:
float
- q2m3.solvation.energy.compute_hf_energy_solvated(molecule, solvent_molecules)[源代码]¶
计算含 MM 静电嵌入的溶剂化 HF 能量。
- 参数:
molecule (MoleculeConfig) -- QM 区域的分子配置
solvent_molecules (Sequence[SolventMolecule]) -- 溶剂分子列表(MM 区域)
- 返回:
溶剂化 HF 能量,单位为 Hartree
- 返回类型:
float
- q2m3.solvation.energy.compute_mulliken_charges(molecule, solvent_states=None)[源代码]¶
计算真空或溶剂化构型的 Mulliken 电荷。
- 参数:
molecule (MoleculeConfig) -- QM 区域的分子配置
solvent_states (ndarray | None) -- 可选的溶剂状态数组 (n_mol, 6)。真空情况使用 None。
- 返回:
mulliken_charge},例如 {"O0": -0.45, "H1": +0.22}
- 返回类型:
Dictionary {atom_label
蒙特卡洛循环¶
由 QPE 驱动的溶剂化模拟的蒙特卡洛循环。
实现纯 Python 的 Metropolis MC 循环(ADR-003:不使用 @qjit),将能量评估交给预编译的步回调。
- 三种哈密顿量模式决定接受判据所用的能量:
hf_corrected:E_HF_ref + E_MM(sol-sol)(快速,近似)
fixed / dynamic:E_QPE + E_MM(sol-sol)(完整量子计算)
- class q2m3.solvation.mc_loop.MCResult(initial_energy, final_energy, best_energy, best_qpe_energy, acceptance_rate, avg_energy, quantum_energies, hf_energies, callback_times, quantum_times, final_solvent_states, best_solvent_states, best_qpe_solvent_states, trajectory_solvent_states, n_quantum_evaluations, n_accepted)[源代码]¶
基类:
object完整的 MC 模拟结果。
- 参数:
initial_energy (float)
final_energy (float)
best_energy (float)
best_qpe_energy (float)
acceptance_rate (float)
avg_energy (float)
quantum_energies (ndarray)
hf_energies (ndarray)
callback_times (ndarray)
quantum_times (ndarray)
final_solvent_states (ndarray)
best_solvent_states (ndarray)
best_qpe_solvent_states (ndarray)
trajectory_solvent_states (ndarray)
n_quantum_evaluations (int)
n_accepted (int)
- q2m3.solvation.mc_loop.create_mc_loop(config, step_callback)[源代码]¶
工厂:创建由 QPE 驱动的 MC 循环(纯 Python)。
返回使用 Metropolis 接受准则运行 MC 模拟的闭包。
- 参数:
config (SolvationConfig) -- 溶剂化模拟配置。
step_callback (Callable[[ndarray, ndarray], StepResult]) -- 每次 MC 尝试的能量评估函数。签名:(solvent_states, qm_coords) -> StepResult
- 返回:
mc_loop(initial_solvents, qm_coords, seed, initial_energy) -> MCResult
- 返回类型:
Callable[[...], MCResult]
相位提取¶
从 QPE 测量结果中提取相位的工具。
纯 NumPy 实现,不依赖 PennyLane、Catalyst 或 JAX。
- 两种提取模式:
解析模式(probs):计算概率加权的预期分箱索引。与 argmax(4 位 QPE 约为 12 mHa)相比,可保留小于分箱宽度的灵敏度(约 0.1 mHa)。
采样模式(samples):将每个比特串解码为分箱索引,再计算各次测量的能量统计量。
- 共用的核心公式:
phase = expected_bin / n_bins energy = -2π · phase / base_time + energy_shift
- q2m3.solvation.phase_extraction.extract_energy_from_probs(probs, base_time, energy_shift, n_estimation_wires)[源代码]¶
从解析概率分布中提取能量。
使用分箱索引的概率加权平均值。平均值可以位于整数分箱索引之间。
- 参数:
probs (ndarray) -- 形状为 (2^n_estimation_wires,) 的概率数组。
base_time (float) -- 用于将相位转换为能量的基本演化时间。
energy_shift (float) -- 施加于哈密顿量的能量偏移量。
n_estimation_wires (int) -- QPE 估计量子比特数。
- 返回:
估计能量,单位为 Hartree。
- 返回类型:
float
- q2m3.solvation.phase_extraction.extract_energy_from_shots(samples, base_time, energy_shift, n_estimation_wires, return_statistics=False)[源代码]¶
从测量采样中提取能量。
samples 的每一行都是一个编码分箱索引的比特串(最高有效位在前)。计算每次测量的能量后,返回平均值或统计字典。
- 参数:
samples (ndarray) -- 形状为 (n_shots, n_estimation_wires) 的二进制数组。
base_time (float) -- 用于将相位转换为能量的基本演化时间。
energy_shift (float) -- 施加于哈密顿量的能量偏移量。
n_estimation_wires (int) -- QPE 估计量子比特数。
return_statistics (bool) -- 如果为 True,则返回包含 mean、std、sem 和 n_shots 的字典。
- 返回:
平均能量(float)或统计字典。
- 抛出:
ValueError -- samples 为空时。
- 返回类型:
float | dict
溶剂模型¶
QM/MM 模拟的显式溶剂模型
本模块提供数据驱动的溶剂模型定义,供 PySCF 的 qmmm 模块使用。主要包括:1. 溶剂几何结构和部分电荷(用于 pyscf.qmmm.mm_charge)2. 刚体坐标变换 3. 溶剂间相互作用的经典 MM 能量(用于 MC 接受判定)
- 设计原则:
数据驱动:使用数据类定义溶剂模型,便于扩展
兼容 PySCF:为 qmmm.mm_charge 输出以埃为单位的坐标
最小实现:仅实现 PySCF 未直接提供的功能
- 与 PySCF 配合使用:
from pyscf import qmmm
model = TIP3P_WATER molecules = [SolventMolecule(model, pos, angles) for ...] mm_coords, mm_charges = get_mm_embedding_data(molecules)
# Convert to Bohr for PySCF mm_coords_bohr = mm_coords * ANGSTROM_TO_BOHR mf = qmmm.mm_charge(mf, mm_coords_bohr, mm_charges)
- class q2m3.solvation.solvent.SolventAtom(symbol, local_coord, charge, lj_sigma=0.0, lj_epsilon=0.0)[源代码]¶
基类:
object溶剂模型中的单个原子。
- 参数:
symbol (str)
local_coord (tuple[float, float, float])
charge (float)
lj_sigma (float)
lj_epsilon (float)
- symbol¶
原子符号(例如 "O"、"H")
- 类型:
str
- local_coord¶
分子固定坐标系中的位置(埃)
- 类型:
tuple[float, float, float]
- charge¶
部分电荷(以元电荷为单位)
- 类型:
float
- lj_sigma¶
Lennard-Jones sigma 参数(埃);无 LJ 时为 0
- 类型:
float
- lj_epsilon¶
Lennard-Jones epsilon 参数(kcal/mol);无 LJ 时为 0
- 类型:
float
- class q2m3.solvation.solvent.SolventModel(name, atoms, reference='')[源代码]¶
基类:
object包含几何结构、电荷和 LJ 参数的溶剂模型定义。
这是定义溶剂类型的不可变数据结构。实际的溶剂分子实例由 SolventMolecule 表示。
- 参数:
name (str)
atoms (tuple[SolventAtom, ...])
reference (str)
- name¶
模型标识符(例如 "TIP3P"、"SPC/E")
- 类型:
str
- atoms¶
定义分子结构的 SolventAtom 元组
- 类型:
tuple[q2m3.solvation.solvent.SolventAtom, ...]
- reference¶
模型参数的文献引用
- 类型:
str
- property local_coords: ndarray¶
以 (n_atoms, 3) 数组表示的局部坐标。
- class q2m3.solvation.solvent.SolventMolecule(model, position=<factory>, euler_angles=<factory>)[源代码]¶
基类:
object具有位置和取向的溶剂分子实例。
- 参数:
model (SolventModel)
position (ndarray)
euler_angles (ndarray)
- model¶
溶剂模型(定义几何结构和参数)
- position¶
质心位置,单位为埃
- 类型:
numpy.ndarray
- euler_angles¶
以 (roll, pitch, yaw) 表示的取向,单位为弧度
- 类型:
numpy.ndarray
- classmethod from_state_vector(model, state)[源代码]¶
从状态向量创建分子。
- 参数:
model (SolventModel)
state (ndarray)
- 返回类型:
- q2m3.solvation.solvent.get_mm_embedding_data(molecules)[源代码]¶
为 pyscf.qmmm.mm_charge() 提取 MM 嵌入数据。
- 参数:
molecules (Sequence[SolventMolecule]) -- SolventMolecule 实例序列
- 返回:
coords: 原子坐标,单位为埃,形状为 (n_total_atoms, 3)
charges: 部分电荷,形状为 (n_total_atoms,)
- 返回类型:
Tuple of
- 与 PySCF 配合使用:
coords, charges = get_mm_embedding_data(molecules) coords_bohr = coords * ANGSTROM_TO_BOHR mf = qmmm.mm_charge(mf, coords_bohr, charges)
- q2m3.solvation.solvent.get_mm_embedding_data_bohr(molecules)[源代码]¶
获取坐标以 Bohr 为单位的 MM 嵌入数据(可直接用于 PySCF)。
此便捷函数将坐标转换为 Bohr,即 pyscf.qmmm.mm_charge() 所需的单位。
- 返回:
(coords_bohr, charges) 元组
- 参数:
molecules (Sequence[SolventMolecule])
- 返回类型:
tuple[ndarray, ndarray]
- q2m3.solvation.solvent.compute_mm_energy(molecules)[源代码]¶
计算溶剂分子之间的经典 MM 能量。
计算所有溶剂分子对之间的 Lennard-Jones 和库仑相互作用,用于 MC 接受准则。
注意:这是简单的成对计算实现。大型体系的实际计算可考虑使用 OpenMM 或其他优化库。
- 参数:
molecules (Sequence[SolventMolecule]) -- SolventMolecule 实例序列
- 返回:
总 MM 能量,单位为 Hartree。不同分子的原子完全重合时,将该构型视为违反硬核约束的无效构型,并返回 +inf。
- 返回类型:
float
- q2m3.solvation.solvent.initialize_solvent_ring(model, n_molecules, center, radius, random_seed=42)[源代码]¶
将溶剂分子初始化为环形排列。
分子等间距排列在 x-y 平面的环上,初始取向随机。
- 参数:
model (SolventModel) -- 使用的溶剂模型
n_molecules (int) -- 分子数
center (ndarray) -- 环中心(通常为溶质中心)
radius (float) -- 环半径,单位为埃
random_seed (int) -- 用于复现取向的随机种子
- 返回:
SolventMolecule 实例列表
- 返回类型:
list[SolventMolecule]
- q2m3.solvation.solvent.molecules_to_state_array(molecules)[源代码]¶
将分子列表转换为形状为 (n_mol, 6) 的状态数组。
- 参数:
molecules (Sequence[SolventMolecule])
- 返回类型:
ndarray
- q2m3.solvation.solvent.state_array_to_molecules(model, states)[源代码]¶
将状态数组转换为分子列表。
- 参数:
model (SolventModel)
states (ndarray)
- 返回类型:
list[SolventMolecule]
IR 缓存¶
用于 QPE 电路编译的 Catalyst LLVM IR 缓存。
- 实现两阶段编译缓存:
阶段 A(缓存未命中):子进程完整运行 @qjit(keep_intermediate=True) -> 保存 LLVM IR 阶段 B(缓存命中):replace_ir + jit_compile -> 跳过 MLIR 流水线(速度约为原来的 5 倍)
缓存键仅包含电路拓扑参数。运行时哈密顿量系数不影响 LLVM IR 结构,因此为 n_waters=5 编译的 IR 也适用于 n_waters=20。固定的完整单电子嵌入可能改变算符支撑集,因此 embedding_mode 是缓存键的一部分。
- q2m3.solvation.ir_cache.compute_cache_key(config)[源代码]¶
根据电路拓扑参数生成确定性的缓存键。
缓存键编码影响 LLVM IR 结构的参数:- 分子标识(名称、基组、活性空间)- QPE 电路参数(估计量子线、Trotter 步数、测量次数)- 哈密顿量电路形式及嵌入算符支撑集
仅影响运行时系数值的参数(n_waters、temperature、coordinates)不包含在内。
- 参数:
config (SolvationConfig)
- 返回类型:
str
- q2m3.solvation.ir_cache.cache_path_for_config(config)[源代码]¶
返回缓存 IR 文件的完整路径。
- 参数:
config (SolvationConfig)
- 返回类型:
Path
- q2m3.solvation.ir_cache.is_cache_available(config)[源代码]¶
检查此配置是否存在有效缓存文件。
- 参数:
config (SolvationConfig)
- 返回类型:
bool
- q2m3.solvation.ir_cache.resolve_compiled_circuit(config, bundle)[源代码]¶
根据缓存状态确定 QPE 电路的编译方式。
缓存命中时:replace_ir + jit_compile(数秒)缓存未命中时:子进程完整编译 -> 保存 IR -> replace_ir + jit_compile
replace_ir 会原位修改对象包的 compiled_circuit。
- 参数:
config (SolvationConfig) -- 包含缓存设置的溶剂化配置
bundle (QPECircuitBundle) -- 来自 build_qpe_circuit() 的 QPECircuitBundle
- 返回:
(bundle, cache_stats);bundle 仍为同一个对象(replace_ir 原位修改)
- 返回类型:
tuple[QPECircuitBundle, dict[str, Any]]
分析¶
δ_corr-pol 及相关统计量的溶剂化分析函数。
纯 NumPy 模块,不依赖 Catalyst 或 JAX。所有公共函数均为纯函数:接收 NumPy 数组,返回冻结数据类。
- class q2m3.solvation.analysis.DeltaCorrPolResult(mean_ha, std_ha, sem_ha, t_statistic, n_samples, is_significant, per_step_delta)[源代码]¶
基类:
objectδ_corr-pol 分析结果。
注意:frozen=True 防止对字段重新赋值,但不能防止修改 np.ndarray 等可变字段(例如仍可执行 obj.per_step_delta[0] = 999)。这是已接受的权衡。frozen 表达不可变的设计意图,并使简单字段可哈希。为避免大数组的性能开销,读取 ndarray 时不强制复制。使用者应将所有字段视为只读。
- 参数:
mean_ha (float)
std_ha (float)
sem_ha (float)
t_statistic (float)
n_samples (int)
is_significant (bool)
per_step_delta (ndarray)
- class q2m3.solvation.analysis.EnergyPhaseResult(early_mean, early_std, late_mean, late_std, n_per_phase)[源代码]¶
基类:
object能量趋势阶段分析结果(早期与晚期阶段)。
- 参数:
early_mean (float)
early_std (float)
late_mean (float)
late_std (float)
n_per_phase (int)
- class q2m3.solvation.analysis.QPEHFConsistencyResult(mean_offset_mha, pearson_correlation, early_offset_mha, late_offset_mha, offset_drift_mha, n_samples)[源代码]¶
基类:
objectQPE-HF 轨迹一致性指标。
- 参数:
mean_offset_mha (float)
pearson_correlation (float)
early_offset_mha (float)
late_offset_mha (float)
offset_drift_mha (float)
n_samples (int)
- class q2m3.solvation.analysis.EquilibrationResult(frac_decreasing, n_windows, qpe_drift_mha, is_monotonic)[源代码]¶
基类:
object平衡诊断结果(基于窗口的单调性)。
- 参数:
frac_decreasing (float)
n_windows (int)
qpe_drift_mha (float)
is_monotonic (bool)
- class q2m3.solvation.analysis.ModeComparisonResult(delta_corr_pol, energy_phases, qpe_hf_consistency, equilibration, energy_distributions, trotter_bias_mha)[源代码]¶
基类:
object完整的三模式比较分析结果。
- 参数:
delta_corr_pol (DeltaCorrPolResult)
energy_phases (dict[str, EnergyPhaseResult])
qpe_hf_consistency (QPEHFConsistencyResult | None)
equilibration (EquilibrationResult | None)
energy_distributions (dict[str, dict])
trotter_bias_mha (float)
- q2m3.solvation.analysis.compute_delta_corr_pol(quantum_energies_fixed, quantum_energies_dynamic)[源代码]¶
从成对的 fixed/dynamic QPE 能量计算每步 δ_corr-pol。
- δ_corr-pol(R) = E_QPE(dynamic, R) - E_QPE(fixed, R)
≈ E_corr(solvated, R) - E_corr(vacuum)
- 参数:
quantum_energies_fixed (ndarray) -- fixed 哈密顿量模式的 QPE 能量。
quantum_energies_dynamic (ndarray) -- dynamic 哈密顿量模式的 QPE 能量。长度必须与 quantum_energies_fixed 相同。
- 返回:
包含配对样本统计量的 DeltaCorrPolResult。
- 返回类型:
- q2m3.solvation.analysis.analyze_energy_phases(quantum_energies, n_phases=3)[源代码]¶
分析 MC 采样阶段的早期/晚期能量趋势。
将能量轨迹等分为 n_phases 段,并比较首段(早期)和末段(晚期)。
- 参数:
quantum_energies (ndarray) -- 由 QPE 驱动的 MC 模拟的能量轨迹。
n_phases (int) -- 将轨迹划分的阶段数。
- 返回:
包含早期和晚期阶段均值及标准差的 EnergyPhaseResult。
- 返回类型:
- q2m3.solvation.analysis.compute_qpe_hf_consistency(quantum_energies, hf_energies)[源代码]¶
计算 QPE-HF 轨迹一致性指标。
衡量 QPE 和 HF 能量轨迹的同步变化程度。较高的正 Pearson 相关系数表明趋势一致。
- 参数:
quantum_energies (ndarray) -- QPE 能量轨迹。
hf_energies (ndarray) -- HF 能量轨迹(长度与 quantum_energies 相同)。
- 返回:
包含偏移量和相关统计量的 QPEHFConsistencyResult。
- 返回类型:
- q2m3.solvation.analysis.detect_equilibration(quantum_energies, min_samples=10)[源代码]¶
用于 MC 平衡判断的窗口单调性诊断。
将能量等分为 5 个窗口,检查窗口均值是否单调递减(提示尚未达到平衡)。
- 参数:
quantum_energies (ndarray) -- QPE 能量轨迹。
min_samples (int) -- 所需的最少样本数。如果 len(quantum_energies) < min_samples,则返回 None。
- 返回:
EquilibrationResult;样本不足时返回 None。
- 返回类型:
EquilibrationResult | None
- q2m3.solvation.analysis.run_mode_comparison(result_fixed, result_dynamic, result_hf_corrected=None, e_vacuum=0.0)[源代码]¶
编排完整的三模式比较分析。
组合底层分析函数,根据 run_solvation() 返回的字典生成完整的 ModeComparisonResult。
- 参数:
result_fixed (dict) -- fixed 哈密顿量模式的 run_solvation() 结果字典。
result_dynamic (dict) -- dynamic 哈密顿量模式的 run_solvation() 结果字典。
result_hf_corrected (dict | None) -- 可选的 hf_corrected 模式结果字典。
e_vacuum (float) -- 用于计算 Trotter 偏差的真空参考能量(Ha)。
- 返回:
所有分析字段均已填充的 ModeComparisonResult。
- 抛出:
ValueError -- 任一结果字典缺少必需键时。
- 返回类型:
结构分析¶
用于有限溶剂壳层输出的内部结构分析工具。
本模块中的例程是纯 NumPy/CSV 工具,用于处理 q2m3.solvation.run_solvation() 已返回的溶剂状态数组。这些例程支持可选的后处理工作流,而非主要溶剂化 API,因此不加入 q2m3.solvation.__init__。
- class q2m3.solvation.structure_analysis.RadialProfile(bin_edges, counts, shell_volumes, density_per_a3, mean_count_per_frame, cumulative_coordination, n_frames)[源代码]¶
基类:
object溶质中心周围有限溶剂壳层中的氧原子径向密度分布。
- 参数:
bin_edges (ndarray)
counts (ndarray)
shell_volumes (ndarray)
density_per_a3 (ndarray)
mean_count_per_frame (ndarray)
cumulative_coordination (ndarray)
n_frames (int)
- property bin_centers: ndarray¶
分箱中心,单位为埃。
- q2m3.solvation.structure_analysis.validate_state_trajectory(states)[源代码]¶
返回形状为
(n_steps, n_waters, 6)的浮点轨迹数组。- 参数:
states (ndarray)
- 返回类型:
ndarray
- q2m3.solvation.structure_analysis.write_state_trajectory_csv(path, states)[源代码]¶
将溶剂状态写为长格式 CSV,以支持确定性的往返读写。
- 参数:
path (Path)
states (ndarray)
- 返回类型:
None
- q2m3.solvation.structure_analysis.load_state_trajectory_csv(path)[源代码]¶
加载溶剂状态轨迹 CSV。
首选模式是长格式
step,water_index,x,y,z,roll,pitch,yaw。为兼容临时 notebook 导出,也接受包含water_0_x或w0_x等列的紧凑宽格式。- 参数:
path (Path)
- 返回类型:
ndarray
- q2m3.solvation.structure_analysis.solute_center(solute_coords)[源代码]¶
返回溶质坐标的算术中心。
- 参数:
solute_coords (ndarray)
- 返回类型:
ndarray
- q2m3.solvation.structure_analysis.water_oxygen_distances(states, solute_coords)[源代码]¶
返回每帧中每个水分子的氧原子中心到溶质中心的距离。
- 参数:
states (ndarray)
solute_coords (ndarray)
- 返回类型:
ndarray
- q2m3.solvation.structure_analysis.radial_density_profile(states, solute_coords, bin_edges, *, start=0)[源代码]¶
计算有限溶剂壳层中的氧原子径向密度和累积配位数。
- 参数:
states (ndarray)
solute_coords (ndarray)
bin_edges (ndarray)
start (int)
- 返回类型:
- q2m3.solvation.structure_analysis.shell_counts_per_frame(states, solute_coords, cutoff, *, start=0)[源代码]¶
返回每帧中距离不超过
cutoff埃的水分子数。- 参数:
states (ndarray)
solute_coords (ndarray)
cutoff (float)
start (int)
- 返回类型:
ndarray
- q2m3.solvation.structure_analysis.coordination_by_cutoff(states, solute_coords, cutoffs, *, start=0)[源代码]¶
返回每个截断距离的平均配位数。
- 参数:
states (ndarray)
solute_coords (ndarray)
cutoffs (ndarray)
start (int)
- 返回类型:
ndarray
- q2m3.solvation.structure_analysis.select_representative_snapshot_indices(states, solute_coords, *, n_snapshots=3, cutoff=3.5, start=0)[源代码]¶
确定性地选择初始舍弃期后的快照,使其覆盖壳层占据情况。
- 参数:
states (ndarray)
solute_coords (ndarray)
n_snapshots (int)
cutoff (float)
start (int)
- 返回类型:
list[int]
- q2m3.solvation.structure_analysis.select_random_snapshot_indices(states, *, n_snapshots=3, start=0, stop=None, random_seed=42)[源代码]¶
从轨迹窗口中选择可复现的随机快照索引。
- 参数:
states (ndarray)
n_snapshots (int)
start (int)
stop (int | None)
random_seed (int)
- 返回类型:
list[int]
- q2m3.solvation.structure_analysis.state_to_symbols_coords(solute_symbols, solute_coords, solvent_state)[源代码]¶
将一帧溶剂状态转换为合并的溶质和 TIP3P 原子数组。
- 参数:
solute_symbols (list[str])
solute_coords (ndarray)
solvent_state (ndarray)
- 返回类型:
tuple[list[str], ndarray]
- q2m3.solvation.structure_analysis.write_xyz_snapshot(path, solute_symbols, solute_coords, solvent_state, *, comment='')[源代码]¶
将一帧溶质与溶剂壳层写为 XYZ 文件。
- 参数:
path (Path)
solute_symbols (list[str])
solute_coords (ndarray)
solvent_state (ndarray)
comment (str)
- 返回类型:
None
- q2m3.solvation.structure_analysis.xyz_atom_count(path)[源代码]¶
返回 XYZ 文件声明的原子数。
- 参数:
path (Path)
- 返回类型:
int
- q2m3.solvation.structure_analysis.radial_profile_to_rows(profile)[源代码]¶
将径向分布转换为可写入 CSV 的字典。
- 参数:
profile (RadialProfile)
- 返回类型:
list[dict[str, Any]]
统计与绘图¶
MC 溶剂化模拟的时间统计格式化。
使用 Rich 库在控制台输出表格和面板。支持三种哈密顿量模式:hf_corrected / fixed / dynamic。
- class q2m3.solvation.statistics.TimingData(quantum_compile_time=0.0, mc_loop_time=0.0, hf_times=<factory>, quantum_times=<factory>, n_mc_steps=0, n_quantum_evals=0, hamiltonian_mode='')[源代码]¶
基类:
object模拟计时数据容器。
- 参数:
quantum_compile_time (float)
mc_loop_time (float)
hf_times (ndarray)
quantum_times (ndarray)
n_mc_steps (int)
n_quantum_evals (int)
hamiltonian_mode (str)
- q2m3.solvation.statistics.create_timing_table(timing)[源代码]¶
为执行阶段计时创建 Rich 表格。
- 参数:
timing (TimingData)
- 返回类型:
Table
- q2m3.solvation.statistics.print_time_statistics(timing, console=None)[源代码]¶
向控制台打印格式化的计时统计。
- 参数:
timing (TimingData) -- TimingData 实例
console (Console | None) -- Rich Console(如果为 None 则新建)
- 返回类型:
None
- q2m3.solvation.statistics.create_timing_data_from_result(result, compile_time, loop_time, hamiltonian_mode='')[源代码]¶
从 MC 循环结果字典创建 TimingData。
- 参数:
result (dict)
compile_time (float)
loop_time (float)
hamiltonian_mode (str)
- 返回类型:
MC 溶剂化模拟的绘图工具。
提供能量轨迹可视化和接受率分析图。
- q2m3.solvation.plotting.plot_energy_trajectory(mc_steps, hf_energies, quantum_steps=None, quantum_energies=None, reference_energy=None, title='Energy Trajectory', output_path=None, show=True)[源代码]¶
绘制能量随 MC 步数变化的轨迹。
- 参数:
mc_steps (Sequence[int]) -- HF 能量对应的 MC 步索引
hf_energies (Sequence[float]) -- 每步的 HF(或总 QM/MM)能量
quantum_steps (Sequence[int] | None) -- 执行量子评估的 MC 步索引
quantum_energies (Sequence[float] | None) -- 量子算法的能量估计值
reference_energy (float | None) -- 绘制相对值所用的参考能量(例如真空能量)
title (str) -- 图标题
output_path (str | Path | None) -- 图像保存路径(None = 不保存)
show (bool) -- 是否显示图像
- 返回:
Matplotlib Figure 对象
- 返回类型:
Figure
- q2m3.solvation.plotting.plot_acceptance_rate(mc_steps, cumulative_accepted, window_size=50, title='MC Acceptance Rate', output_path=None, show=True)[源代码]¶
绘制累积接受率和窗口接受率。
- 参数:
mc_steps (Sequence[int]) -- MC 步索引
cumulative_accepted (Sequence[int]) -- 已接受移动的累积次数
window_size (int) -- 滚动接受率的窗口大小
title (str) -- 图标题
output_path (str | Path | None) -- 图像保存路径
show (bool) -- 是否显示
- 返回:
Matplotlib Figure 对象
- 返回类型:
Figure