工具模块 (utils)
本模块提供各种辅助工具和实用函数。
通用工具
工具模块
包含 TensorConverter 类用于张量与 Voigt 表示之间的转换,DataCollector 类用于收集模拟过程中的数据, 及一些常用的单位转换常量
- class thermoelasticsim.utils.utils.TensorConverter[源代码]
基类:
object张量转换工具类,支持应力和应变张量的 Voigt 与 3x3 矩阵表示之间的相互转换。
- class thermoelasticsim.utils.utils.DataCollector(capacity=None, save_interval=1000, use_threading=False, output_file='trajectory.h5')[源代码]
基类:
object数据收集器,用于记录和分析模拟轨迹
提供了系统状态的收集、统计和保存功能,支持异步数据处理和自动保存。
- 参数:
常量
优化器
分子动力学模拟优化器模块
提供多种优化算法用于原子结构优化,包括: - GradientDescentOptimizer: 带动量项的梯度下降 - BFGSOptimizer: 基于scipy.optimize.minimize的BFGS - LBFGSOptimizer: 改进的L-BFGS(有限内存BFGS)
- class thermoelasticsim.utils.optimizers.Atom(id, symbol, mass_amu, position, velocity=None)[源代码]
基类:
object原子对象,分子动力学模拟的基本单元
表示一个原子的完整状态,包括位置、速度、受力等物理属性。 在MD模拟中,原子遵循牛顿运动方程:
\[m \frac{d^2\mathbf{r}}{dt^2} = \mathbf{F}\]- 参数:
- id
原子唯一标识符
- Type:
- symbol
元素符号
- Type:
- mass_amu
原始质量 (amu)
- Type:
- mass
转换后的质量 (eV·fs²/Ų)
- Type:
- position
当前位置向量 (3,)
- Type:
- velocity
当前速度向量 (3,)
- Type:
- force
当前受力向量 (3,)
- Type:
备注
质量与常数采用全局统一定义(参见
thermoelasticsim.utils.utils模块):AMU_TO_EVFSA2质量单位转换常量(amu → eV·fs²/Ų)。
KB_IN_EV玻尔兹曼常数(eV/K)。
示例
创建铝原子:
>>> atom = Atom(id=1, symbol="Al", mass_amu=26.98, position=[0, 0, 0]) >>> atom.velocity = np.array([1.0, 0.0, 0.0]) # 设置速度 >>> print(f"动能: {0.5 * atom.mass * np.dot(atom.velocity, atom.velocity):.4f} eV")
- __init__(id, symbol, mass_amu, position, velocity=None)[源代码]
- accelerate_by(velocity_change)[源代码]
通过速度增量改变原子速度
- 参数:
velocity_change (numpy.ndarray | array_like) -- 速度增量向量,形状为 (3,)
- 抛出:
ValueError -- 如果速度增量不是3D向量
- 返回类型:
None
示例
>>> atom = Atom(1, 'H', 1.0, [0, 0, 0]) >>> atom.accelerate_by([0.1, 0.2, 0.3]) >>> print(atom.velocity) [0.1 0.2 0.3]
- copy()[源代码]
创建 Atom 的深拷贝
- 返回:
新的 Atom 对象,包含当前原子的所有属性的副本
- 返回类型:
示例
>>> atom1 = Atom(1, 'H', 1.0, [0, 0, 0]) >>> atom2 = atom1.copy() >>> atom2.id == atom1.id True >>> atom2.position is atom1.position False
- move_by(displacement)[源代码]
通过位置增量移动原子
- 参数:
displacement (numpy.ndarray | array_like) -- 位置增量向量,形状为 (3,)
- 抛出:
ValueError -- 如果位置增量不是3D向量
- 返回类型:
None
示例
>>> atom = Atom(1, 'H', 1.0, [0, 0, 0]) >>> atom.move_by([0.1, 0.2, 0.3]) >>> print(atom.position) [0.1 0.2 0.3]
- class thermoelasticsim.utils.optimizers.Cell(lattice_vectors, atoms, pbc_enabled=True)[源代码]
基类:
object晶胞对象,管理原子集合和晶格结构
晶胞是分子动力学模拟的基本容器,定义了模拟盒子的几何形状 和其中包含的原子。支持周期性边界条件和最小镜像约定。
晶格矢量定义为行向量:
\[\begin{split}\mathbf{L} = \begin{pmatrix} \mathbf{a}_1 \\ \mathbf{a}_2 \\ \mathbf{a}_3 \end{pmatrix}\end{split}\]晶胞体积计算:
\[V = |\mathbf{a}_1 \cdot (\mathbf{a}_2 \times \mathbf{a}_3)|\]- 参数:
- lattice_vectors
晶格矢量矩阵 (3, 3)
- Type:
- volume
晶胞体积 (ų)
- Type:
- pbc_enabled
周期性边界条件标志
- Type:
- lattice_locked
晶格锁定标志(用于内部弛豫)
- Type:
- lattice_inv
晶格逆矩阵,用于坐标转换
- Type:
- num_atoms
原子数量(属性)
- Type:
- apply_periodic_boundary(positions)[源代码]
应用周期性边界条件
- minimum_image(displacement)[源代码]
计算最小镜像位移
备注
分数/笛卡尔坐标转换(列向量记号):
\[\mathbf{r} = \mathbf{L}\,\mathbf{s},\qquad \mathbf{s} = \mathbf{L}^{-1}\,\mathbf{r}\]实现采用“行向量右乘”的等价式:
\[\mathbf{s}^{\top} = \mathbf{r}^{\top}\,\mathbf{L}^{-1},\qquad \mathbf{r}^{\top} = \mathbf{s}^{\top}\,\mathbf{L}^{\top}\]示例
创建FCC铝晶胞:
>>> a = 4.05 # 晶格常数 >>> lattice = a * np.eye(3) # 立方晶格 >>> atoms = [ ... Atom(0, "Al", 26.98, [0, 0, 0]), ... Atom(1, "Al", 26.98, [a/2, a/2, 0]), ... Atom(2, "Al", 26.98, [a/2, 0, a/2]), ... Atom(3, "Al", 26.98, [0, a/2, a/2]) ... ] >>> cell = Cell(lattice, atoms) >>> print(f"晶胞体积: {cell.volume:.2f} ų")
- __init__(lattice_vectors, atoms, pbc_enabled=True)[源代码]
- apply_deformation(deformation_matrix)[源代码]
对晶格与原子坐标施加形变矩阵 \(\mathbf{F}\)
- 参数:
deformation_matrix (numpy.ndarray) -- 形变矩阵 \(\mathbf{F}\),形状为 (3, 3)
- 返回类型:
None
备注
采用列向量约定的连续介质力学记号:
晶格未锁定(允许变胞)时:
\[\mathbf{L}_{\text{new}} = \mathbf{F}\, \mathbf{L}_{\text{old}},\qquad \mathbf{r}_{\text{new}} = \mathbf{F}\, \mathbf{r}_{\text{old}}\]晶格已锁定(固定胞形)时:
\[\mathbf{L}_{\text{new}} = \mathbf{L}_{\text{old}},\qquad \mathbf{r}_{\text{new}} = \mathbf{F}\, \mathbf{r}_{\text{old}}\]
实现细节:本实现使用“行向量右乘”形式,等价写法为
\[\mathbf{r}_{\text{new}}^{\top} = \mathbf{r}_{\text{old}}^{\top} \mathbf{F}^{\top}.\]示例
>>> import numpy as np >>> F = np.array([[1.01, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> cell.apply_deformation(F)
- apply_periodic_boundary(positions)[源代码]
应用周期性边界条件
将原子位置映射回主晶胞内,使用标准的最小镜像约定。
算法(列向量记号):
\[\mathbf{s} = \mathbf{L}^{-1}\,\mathbf{r},\qquad \mathbf{s}' = \mathbf{s} - \lfloor \mathbf{s} + 0.5 \rfloor,\qquad \mathbf{r}' = \mathbf{L}\,\mathbf{s}'\]- 参数:
positions (numpy.ndarray) -- 原子位置坐标,形状为 (3,) 或 (N, 3)
- 返回:
应用PBC后的位置,保持输入形状
- 返回类型:
- 抛出:
ValueError -- 如果位置数组形状不正确或包含非有限值
备注
该实现使用分数坐标进行周期性映射,确保数值稳定性。 对于三斜晶系也能正确处理。
示例
>>> # 单个原子位置 >>> pos = np.array([5.0, 6.0, 7.0]) >>> new_pos = cell.apply_periodic_boundary(pos) >>> # 批量处理 >>> positions = np.random.randn(100, 3) * 10 >>> new_positions = cell.apply_periodic_boundary(positions)
- build_supercell(repetition)[源代码]
构建超胞,返回一个新的 Cell 对象。
采用更简单、更健壮的算法,直接在笛卡尔坐标系下操作。
- calculate_kinetic_energy()[源代码]
计算当前系统的总动能
- 返回:
系统总动能,单位为 \(\mathrm{eV}\)
- 返回类型:
备注
计算所有原子的动能总和,包含质心运动
示例
>>> cell = Cell(lattice_vectors, atoms) >>> kinetic = cell.calculate_kinetic_energy() >>> print(f"系统动能: {kinetic:.6f} eV")
- calculate_stress_tensor(potential)[源代码]
计算应力张量
- 参数:
potential (Potential) -- 用于计算应力的势能对象
- 返回:
3×3 应力张量矩阵 (eV/ų)
- 返回类型:
- calculate_temperature()[源代码]
计算系统的瞬时温度
使用均分定理计算温度,扣除质心运动贡献:
\[T = \frac{2 E_{kin}}{k_B \cdot N_{dof}}\]其中动能(扣除质心):
\[E_{kin} = \sum_i \frac{1}{2} m_i |\mathbf{v}_i - \mathbf{v}_{cm}|^2\]自由度数定义:
\[\begin{split}N_{\mathrm{dof}} = \begin{cases} 3N - 3, & N > 1, \\ 3, & N = 1. \end{cases}\end{split}\]- 返回:
系统温度,单位为 \(\mathrm{K}\)
- 返回类型:
备注
瞬时温度会有涨落,通常需要时间平均来获得稳定值。 对于NVE系综,温度是守恒量的函数。
示例
>>> temp = cell.calculate_temperature() >>> print(f"瞬时温度: {temp:.1f} K") >>> # 计算时间平均温度 >>> temps = [cell.calculate_temperature() for _ in range(1000)] >>> avg_temp = np.mean(temps)
参见
calculate_kinetic_energy计算总动能(含质心运动)
- copy()[源代码]
创建 Cell 的深拷贝
- get_box_lengths()[源代码]
返回模拟盒子在 x、y、z 方向的长度
- 返回:
包含三个方向长度的数组 (Å)
- 返回类型:
- get_com_position()[源代码]
计算系统质心位置。
- 返回:
质心位置向量
- 返回类型:
- get_com_velocity()[源代码]
计算系统质心速度。
- 返回:
质心速度向量
- 返回类型:
- get_forces()[源代码]
获取所有原子的力信息
- 返回:
原子力数组,形状为 (num_atoms, 3)
- 返回类型:
- get_fractional_coordinates()[源代码]
获取所有原子的分数坐标
- 返回:
原子分数坐标数组,形状为(num_atoms, 3)
- 返回类型:
备注
坐标关系(列向量记号):
\[\mathbf{s} = \mathbf{L}^{-1}\,\mathbf{r}\]代码实现采用行向量右乘:\(\mathbf{s}^{\top} = \mathbf{r}^{\top}\,\mathbf{L}^{-1}\)。
- get_positions()[源代码]
获取所有原子的位置信息
- 返回:
原子位置数组,形状为 (num_atoms, 3)
- 返回类型:
示例
>>> positions = cell.get_positions() >>> print(f"原子数量: {positions.shape[0]}")
- get_velocities()[源代码]
获取所有原子的速度信息
- 返回:
原子速度数组,形状为 (num_atoms, 3)
- 返回类型:
- get_volume()[源代码]
计算晶胞体积
- 返回:
晶胞体积 (ų)
- 返回类型:
备注
体积通过晶格矢量的标量三重积计算:
\[V = \left|\, \mathbf{a} \cdot (\mathbf{b} \times \mathbf{c}) \,\right|\]
- lock_lattice_vectors()[源代码]
锁定晶格向量,防止在优化过程中被修改
备注
锁定后,晶格向量将不能被修改,直到调用
unlock_lattice_vectors()。- 返回类型:
None
- minimum_image(displacement)[源代码]
计算最小镜像位移向量
根据最小镜像约定,找到最近的周期镜像之间的位移。 这对于正确计算周期性系统中的距离和力至关重要。
数学原理(列向量记号):
\[\mathbf{d}_{\min} = \mathbf{d} - \mathbf{L}\, \operatorname{round}(\mathbf{L}^{-1} \mathbf{d})\]- 参数:
displacement (numpy.ndarray) -- 原始位移向量 (3,)
- 返回:
最小镜像位移向量 (3,)
- 返回类型:
- 抛出:
ValueError -- 如果位移向量不是3D或包含非有限值
备注
该方法确保返回的位移向量长度最小,对应于最近的周期镜像。 在计算原子间相互作用时必须使用此方法。
示例
>>> # 计算两原子间的最小距离 >>> r12 = atom2.position - atom1.position >>> r12_min = cell.minimum_image(r12) >>> distance = np.linalg.norm(r12_min)
参见
apply_periodic_boundary应用周期性边界条件
- property num_atoms
返回原子数量
- remove_com_motion()[源代码]
移除系统的质心运动。
该方法计算并移除系统的净平动,保证总动量为零。 在应用恒温器和恒压器时应该调用此方法。
- scale_lattice(scale_factor)[源代码]
按给定因子等比例缩放晶格
- 参数:
scale_factor (float) -- 缩放因子,>1放大,<1缩小
- 返回类型:
None
备注
这个方法只缩放晶格矢量,不改变原子坐标。 通常与原子坐标的相应缩放一起使用。
示例
>>> cell.scale_lattice(1.1) # 放大10% >>> # 同时需要缩放原子坐标以保持相对位置 >>> for atom in cell.atoms: ... atom.position *= 1.1
- set_fractional_coordinates(fractional_coords)[源代码]
根据分数坐标设置所有原子的笛卡尔坐标
- 参数:
fractional_coords (numpy.ndarray) -- 分数坐标数组,形状为(num_atoms, 3)
- 返回类型:
None
备注
坐标关系(列向量记号):
\[\mathbf{r} = \mathbf{L}\,\mathbf{s}\]代码实现采用行向量右乘:\(\mathbf{r}^{\top} = \mathbf{s}^{\top}\,\mathbf{L}^{\top}\)。
- set_lattice_vectors(lattice_vectors)[源代码]
设置新的晶格矢量并更新相关属性。
- 参数:
lattice_vectors (np.ndarray) -- 新的 3x3 晶格矢量矩阵。
- set_positions(positions)[源代码]
设置所有原子的笛卡尔坐标
- 参数:
positions (numpy.ndarray) -- 笛卡尔坐标数组,形状为(num_atoms, 3)
- 返回类型:
None
- set_velocities(velocities)[源代码]
设置所有原子的速度
- 参数:
velocities (numpy.ndarray) -- 速度数组,形状为 (num_atoms, 3)
- 抛出:
ValueError -- 当输入数组形状与原子数不匹配时抛出
- 返回类型:
None
- unlock_lattice_vectors()[源代码]
解锁晶格向量,允许在需要时修改
备注
解锁后,晶格向量可以被修改,直到再次调用
lock_lattice_vectors()。- 返回类型:
None
- class thermoelasticsim.utils.optimizers.Potential(parameters, cutoff)[源代码]
基类:
ABC势能计算的抽象基类。
提供原子间势能模型的统一接口,约定最小方法集以支持分子动力学 (MD) 中的力与能量评估。
备注
所有具体势能模型至少需实现
calculate_forces与calculate_energy。单位约定:能量 eV,长度 Å,力 eV/Å。
- __init__(parameters, cutoff)[源代码]
- abstractmethod calculate_energy(cell, neighbor_list)[源代码]
计算系统的总势能。
- 参数:
cell (Cell) -- 晶胞与原子集合。
neighbor_list (NeighborList) -- 邻居列表(按模型需要使用)。
- 返回:
系统总势能,单位 eV。
- 返回类型:
备注
抽象方法,必须由子类实现。
- abstractmethod calculate_forces(cell, neighbor_list)[源代码]
计算系统中所有原子的作用力。
- 参数:
cell (Cell) -- 晶胞与原子集合。
neighbor_list (NeighborList) -- 邻居列表(按模型需要使用)。
- 返回类型:
None
备注
需就地写入
force(单位 eV/Å)。抽象方法,必须由子类实现。
- class thermoelasticsim.utils.optimizers.Optimizer[源代码]
基类:
object优化器抽象基类,定义优化方法的接口
子类需要实现optimize()方法来执行具体的优化算法。
- optimize(cell, potential)[源代码]
执行优化算法,需子类实现
- class thermoelasticsim.utils.optimizers.GradientDescentOptimizer(maxiter=10000, tol=0.001, step_size=0.001, energy_tol=0.0001, beta=0.9)[源代码]
基类:
Optimizer带动量项的梯度下降优化器
- 参数:
- converged
优化是否收敛的标志
- Type:
- trajectory
记录优化轨迹的列表
- Type:
- __init__(maxiter=10000, tol=0.001, step_size=0.001, energy_tol=0.0001, beta=0.9)[源代码]
初始化带动量项的梯度下降优化器
- class thermoelasticsim.utils.optimizers.BFGSOptimizer(tol=1e-06, maxiter=10000)[源代码]
基类:
OptimizerBFGS准牛顿优化器
- converged
优化是否收敛的标志
- Type:
- trajectory
记录优化轨迹的列表
- Type:
备注
使用scipy.optimize.minimize的BFGS实现 适用于中等规模系统优化
- __init__(tol=1e-06, maxiter=10000)[源代码]
初始化 BFGS 优化器
- class thermoelasticsim.utils.optimizers.CGOptimizer(tol=1e-06, maxiter=10000)[源代码]
基类:
Optimizer共轭梯度优化器(分数坐标),对剪切后的浅谷更稳健。
- 参数:
- class thermoelasticsim.utils.optimizers.LBFGSOptimizer(ftol=1e-08, gtol=1e-06, maxiter=1000, supercell_dims=None, **kwargs)[源代码]
基类:
OptimizerL-BFGS优化器(有限内存BFGS)
该优化器能够处理两种模式: 1. 仅优化原子位置 (默认)。 2. 同时优化原子位置和晶胞形状 (完全弛豫)。
- 参数:
- __init__(ftol=1e-08, gtol=1e-06, maxiter=1000, supercell_dims=None, **kwargs)[源代码]
轨迹记录
轨迹存储和管理系统
基于H5MD (HDF5 for Molecular Dynamics) 标准的轨迹存储系统。 提供高效的数据压缩、并行I/O支持和丰富的元数据管理功能。
主要特性: - HDF5格式的高效存储 - 支持大规模轨迹数据 - 灵活的压缩选项 - 增量式写入支持 - 丰富的元数据记录
Author: Gilbert Young Created: 2025-08-15
- class thermoelasticsim.utils.trajectory.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])[源代码]
基类:
dateThe year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.
- astimezone()
tz -> convert to local time in new timezone tz
- classmethod combine()
date, time -> datetime with same date and time fields
- ctime()
Return ctime() style string.
- date()
Return date object with same year, month and day.
- dst()
Return self.tzinfo.dst(self).
- fold
- classmethod fromisoformat()
string -> datetime from a string in most ISO 8601 formats
- classmethod fromtimestamp()
timestamp[, tz] -> tz's local time from POSIX timestamp.
- hour
- isoformat()
[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to 'T'. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds' and 'microseconds'.
- max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
- microsecond
- min = datetime.datetime(1, 1, 1, 0, 0)
- minute
- classmethod now(tz=None)
Returns new datetime object representing current time local to tz.
- tz
Timezone object.
If no tz is specified, uses local timezone.
- replace()
Return datetime with new specified fields.
- resolution = datetime.timedelta(microseconds=1)
- second
- classmethod strptime()
string, format -> new datetime parsed from a string (like time.strptime()).
- time()
Return time object with same time but with tzinfo=None.
- timestamp()
Return POSIX timestamp as float.
- timetuple()
Return time tuple, compatible with time.localtime().
- timetz()
Return time object with same time and tzinfo.
- tzinfo
- tzname()
Return self.tzinfo.tzname(self).
- classmethod utcfromtimestamp()
Construct a naive UTC datetime from a POSIX timestamp.
- classmethod utcnow()
Return a new datetime representing UTC day and time.
- utcoffset()
Return self.tzinfo.utcoffset(self).
- utctimetuple()
Return UTC time tuple, compatible with time.localtime().
- class thermoelasticsim.utils.trajectory.Path(*args, **kwargs)[源代码]
基类:
PurePathPurePath subclass that can make system calls.
Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.
- absolute()[源代码]
Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.
Use resolve() to get the canonical path to a file.
- chmod(mode, *, follow_symlinks=True)[源代码]
Change the permissions of the path, like os.chmod().
- classmethod cwd()[源代码]
Return a new path pointing to the current working directory (as returned by os.getcwd()).
- exists()[源代码]
Whether this path exists.
- expanduser()[源代码]
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
- glob(pattern)[源代码]
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.
- group()[源代码]
Return the group name of the file gid.
- hardlink_to(target)[源代码]
Make this path a hard link pointing to the same file as target.
Note the order of arguments (self, target) is the reverse of os.link's.
- classmethod home()[源代码]
Return a new path pointing to the user's home directory (as returned by os.path.expanduser('~')).
- is_block_device()[源代码]
Whether this path is a block device.
- is_char_device()[源代码]
Whether this path is a character device.
- is_dir()[源代码]
Whether this path is a directory.
- is_fifo()[源代码]
Whether this path is a FIFO.
- is_file()[源代码]
Whether this path is a regular file (also True for symlinks pointing to regular files).
- is_mount()[源代码]
Check if this path is a POSIX mount point
- is_socket()[源代码]
Whether this path is a socket.
- is_symlink()[源代码]
Whether this path is a symbolic link.
- iterdir()[源代码]
Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'.
- lchmod(mode)[源代码]
Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's.
- link_to(target)[源代码]
Make the target path a hard link pointing to this path.
Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.
Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.
- lstat()[源代码]
Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's.
- mkdir(mode=511, parents=False, exist_ok=False)[源代码]
Create a new directory at this given path.
- open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[源代码]
Open the file pointed by this path and return a file object, as the built-in open() function does.
- owner()[源代码]
Return the login name of the file owner.
- read_bytes()[源代码]
Open the file in bytes mode, read it, and close the file.
- read_text(encoding=None, errors=None)[源代码]
Open the file in text mode, read it, and close the file.
- readlink()[源代码]
Return the path to which the symbolic link points.
- rename(target)[源代码]
Rename this path to the target path.
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.
Returns the new Path instance pointing to the target path.
- replace(target)[源代码]
Rename this path to the target path, overwriting if that path exists.
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.
Returns the new Path instance pointing to the target path.
- resolve(strict=False)[源代码]
Make the path absolute, resolving all symlinks on the way and also normalizing it.
- rglob(pattern)[源代码]
Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.
- rmdir()[源代码]
Remove this directory. The directory must be empty.
- samefile(other_path)[源代码]
Return whether other_path is the same or not as this file (as returned by os.path.samefile()).
- stat(*, follow_symlinks=True)[源代码]
Return the result of the stat() system call on this path, like os.stat() does.
- symlink_to(target, target_is_directory=False)[源代码]
Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.
- touch(mode=438, exist_ok=True)[源代码]
Create this file with the given access mode, if it doesn't exist.
- unlink(missing_ok=False)[源代码]
Remove this file or link. If the path is a directory, use rmdir() instead.
- write_bytes(data)[源代码]
Open the file in bytes mode, write to it, and close the file.
- write_text(data, encoding=None, errors=None, newline=None)[源代码]
Open the file in text mode, write to it, and close the file.
- class thermoelasticsim.utils.trajectory.Any(*args, **kwargs)[源代码]
基类:
objectSpecial type indicating an unconstrained type.
Any is compatible with every type.
Any assumed to have all methods.
All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.
- class thermoelasticsim.utils.trajectory.TrajectoryWriter(filename, mode='w', compression='gzip', compression_opts=4, chunk_size=100)[源代码]
基类:
objectH5MD格式轨迹文件写入器
遵循H5MD v1.1规范,提供高效的分子动力学轨迹存储。
- 参数:
示例
>>> writer = TrajectoryWriter('trajectory.h5', compression='gzip') >>> writer.initialize(n_atoms=100, n_frames_estimate=1000) >>> writer.write_frame(positions, box, time=0.0, step=0) >>> writer.close()
- __init__(filename, mode='w', compression='gzip', compression_opts=4, chunk_size=100)[源代码]
- open()[源代码]
打开HDF5文件
- initialize(n_atoms, n_frames_estimate=1000, atom_types=None, metadata=None)[源代码]
初始化H5MD文件结构
- write_frame(positions, box=None, time=None, step=None, velocities=None, forces=None, stress=None, energy=None, temperature=None, **kwargs)[源代码]
写入单帧数据
- 参数:
positions (np.ndarray) -- 原子位置 (n_atoms, 3)
box (np.ndarray, optional) -- 晶格矢量 (3, 3)
time (float, optional) -- 时间(ps)
step (int, optional) -- MD步数
velocities (np.ndarray, optional) -- 速度 (n_atoms, 3)
forces (np.ndarray, optional) -- 力 (n_atoms, 3)
stress (np.ndarray, optional) -- 应力张量 (3, 3)
energy (float, optional) -- 总能量
temperature (float, optional) -- 温度
**kwargs -- 其他观测量
- close()[源代码]
关闭文件
- class thermoelasticsim.utils.trajectory.TrajectoryReader(filename, mode='r', cache_size=100)[源代码]
基类:
objectH5MD格式轨迹文件读取器
提供高效的轨迹数据读取和分析功能。
示例
>>> reader = TrajectoryReader('trajectory.h5') >>> reader.open() >>> for frame_idx in range(reader.n_frames): ... frame = reader.read_frame(frame_idx) ... process_frame(frame) >>> reader.close()
- open()[源代码]
打开HDF5文件
- read_frames(start=0, stop=None, stride=1)[源代码]
批量读取多帧
- close()[源代码]
关闭文件
- thermoelasticsim.utils.trajectory.save_trajectory(filename, positions_list, boxes_list=None, times=None, **kwargs)[源代码]
便捷函数:保存轨迹数据
- thermoelasticsim.utils.trajectory.load_trajectory(filename, start=0, stop=None, stride=1)[源代码]
便捷函数:加载轨迹数据
带轨迹记录的优化器扩展
为现有优化器添加轨迹记录功能,在优化过程中自动捕获原子位置、 晶格矢量、能量、应力等信息并保存到HDF5文件。
Author: Gilbert Young Created: 2025-08-15
- class thermoelasticsim.utils.trajectory_recorder.Path(*args, **kwargs)[源代码]
基类:
PurePathPurePath subclass that can make system calls.
Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.
- absolute()[源代码]
Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.
Use resolve() to get the canonical path to a file.
- chmod(mode, *, follow_symlinks=True)[源代码]
Change the permissions of the path, like os.chmod().
- classmethod cwd()[源代码]
Return a new path pointing to the current working directory (as returned by os.getcwd()).
- exists()[源代码]
Whether this path exists.
- expanduser()[源代码]
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
- glob(pattern)[源代码]
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.
- group()[源代码]
Return the group name of the file gid.
- hardlink_to(target)[源代码]
Make this path a hard link pointing to the same file as target.
Note the order of arguments (self, target) is the reverse of os.link's.
- classmethod home()[源代码]
Return a new path pointing to the user's home directory (as returned by os.path.expanduser('~')).
- is_block_device()[源代码]
Whether this path is a block device.
- is_char_device()[源代码]
Whether this path is a character device.
- is_dir()[源代码]
Whether this path is a directory.
- is_fifo()[源代码]
Whether this path is a FIFO.
- is_file()[源代码]
Whether this path is a regular file (also True for symlinks pointing to regular files).
- is_mount()[源代码]
Check if this path is a POSIX mount point
- is_socket()[源代码]
Whether this path is a socket.
- is_symlink()[源代码]
Whether this path is a symbolic link.
- iterdir()[源代码]
Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'.
- lchmod(mode)[源代码]
Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's.
- link_to(target)[源代码]
Make the target path a hard link pointing to this path.
Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.
Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.
- lstat()[源代码]
Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's.
- mkdir(mode=511, parents=False, exist_ok=False)[源代码]
Create a new directory at this given path.
- open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[源代码]
Open the file pointed by this path and return a file object, as the built-in open() function does.
- owner()[源代码]
Return the login name of the file owner.
- read_bytes()[源代码]
Open the file in bytes mode, read it, and close the file.
- read_text(encoding=None, errors=None)[源代码]
Open the file in text mode, read it, and close the file.
- readlink()[源代码]
Return the path to which the symbolic link points.
- rename(target)[源代码]
Rename this path to the target path.
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.
Returns the new Path instance pointing to the target path.
- replace(target)[源代码]
Rename this path to the target path, overwriting if that path exists.
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.
Returns the new Path instance pointing to the target path.
- resolve(strict=False)[源代码]
Make the path absolute, resolving all symlinks on the way and also normalizing it.
- rglob(pattern)[源代码]
Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.
- rmdir()[源代码]
Remove this directory. The directory must be empty.
- samefile(other_path)[源代码]
Return whether other_path is the same or not as this file (as returned by os.path.samefile()).
- stat(*, follow_symlinks=True)[源代码]
Return the result of the stat() system call on this path, like os.stat() does.
- symlink_to(target, target_is_directory=False)[源代码]
Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.
- touch(mode=438, exist_ok=True)[源代码]
Create this file with the given access mode, if it doesn't exist.
- unlink(missing_ok=False)[源代码]
Remove this file or link. If the path is a directory, use rmdir() instead.
- write_bytes(data)[源代码]
Open the file in bytes mode, write to it, and close the file.
- write_text(data, encoding=None, errors=None, newline=None)[源代码]
Open the file in text mode, write to it, and close the file.
- class thermoelasticsim.utils.trajectory_recorder.Any(*args, **kwargs)[源代码]
基类:
objectSpecial type indicating an unconstrained type.
Any is compatible with every type.
Any assumed to have all methods.
All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.
- class thermoelasticsim.utils.trajectory_recorder.Cell(lattice_vectors, atoms, pbc_enabled=True)[源代码]
基类:
object晶胞对象,管理原子集合和晶格结构
晶胞是分子动力学模拟的基本容器,定义了模拟盒子的几何形状 和其中包含的原子。支持周期性边界条件和最小镜像约定。
晶格矢量定义为行向量:
\[\begin{split}\mathbf{L} = \begin{pmatrix} \mathbf{a}_1 \\ \mathbf{a}_2 \\ \mathbf{a}_3 \end{pmatrix}\end{split}\]晶胞体积计算:
\[V = |\mathbf{a}_1 \cdot (\mathbf{a}_2 \times \mathbf{a}_3)|\]- 参数:
- lattice_vectors
晶格矢量矩阵 (3, 3)
- Type:
- volume
晶胞体积 (ų)
- Type:
- pbc_enabled
周期性边界条件标志
- Type:
- lattice_locked
晶格锁定标志(用于内部弛豫)
- Type:
- lattice_inv
晶格逆矩阵,用于坐标转换
- Type:
- num_atoms
原子数量(属性)
- Type:
- apply_periodic_boundary(positions)[源代码]
应用周期性边界条件
- minimum_image(displacement)[源代码]
计算最小镜像位移
备注
分数/笛卡尔坐标转换(列向量记号):
\[\mathbf{r} = \mathbf{L}\,\mathbf{s},\qquad \mathbf{s} = \mathbf{L}^{-1}\,\mathbf{r}\]实现采用“行向量右乘”的等价式:
\[\mathbf{s}^{\top} = \mathbf{r}^{\top}\,\mathbf{L}^{-1},\qquad \mathbf{r}^{\top} = \mathbf{s}^{\top}\,\mathbf{L}^{\top}\]示例
创建FCC铝晶胞:
>>> a = 4.05 # 晶格常数 >>> lattice = a * np.eye(3) # 立方晶格 >>> atoms = [ ... Atom(0, "Al", 26.98, [0, 0, 0]), ... Atom(1, "Al", 26.98, [a/2, a/2, 0]), ... Atom(2, "Al", 26.98, [a/2, 0, a/2]), ... Atom(3, "Al", 26.98, [0, a/2, a/2]) ... ] >>> cell = Cell(lattice, atoms) >>> print(f"晶胞体积: {cell.volume:.2f} ų")
- __init__(lattice_vectors, atoms, pbc_enabled=True)[源代码]
- apply_deformation(deformation_matrix)[源代码]
对晶格与原子坐标施加形变矩阵 \(\mathbf{F}\)
- 参数:
deformation_matrix (numpy.ndarray) -- 形变矩阵 \(\mathbf{F}\),形状为 (3, 3)
- 返回类型:
None
备注
采用列向量约定的连续介质力学记号:
晶格未锁定(允许变胞)时:
\[\mathbf{L}_{\text{new}} = \mathbf{F}\, \mathbf{L}_{\text{old}},\qquad \mathbf{r}_{\text{new}} = \mathbf{F}\, \mathbf{r}_{\text{old}}\]晶格已锁定(固定胞形)时:
\[\mathbf{L}_{\text{new}} = \mathbf{L}_{\text{old}},\qquad \mathbf{r}_{\text{new}} = \mathbf{F}\, \mathbf{r}_{\text{old}}\]
实现细节:本实现使用“行向量右乘”形式,等价写法为
\[\mathbf{r}_{\text{new}}^{\top} = \mathbf{r}_{\text{old}}^{\top} \mathbf{F}^{\top}.\]示例
>>> import numpy as np >>> F = np.array([[1.01, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> cell.apply_deformation(F)
- apply_periodic_boundary(positions)[源代码]
应用周期性边界条件
将原子位置映射回主晶胞内,使用标准的最小镜像约定。
算法(列向量记号):
\[\mathbf{s} = \mathbf{L}^{-1}\,\mathbf{r},\qquad \mathbf{s}' = \mathbf{s} - \lfloor \mathbf{s} + 0.5 \rfloor,\qquad \mathbf{r}' = \mathbf{L}\,\mathbf{s}'\]- 参数:
positions (numpy.ndarray) -- 原子位置坐标,形状为 (3,) 或 (N, 3)
- 返回:
应用PBC后的位置,保持输入形状
- 返回类型:
- 抛出:
ValueError -- 如果位置数组形状不正确或包含非有限值
备注
该实现使用分数坐标进行周期性映射,确保数值稳定性。 对于三斜晶系也能正确处理。
示例
>>> # 单个原子位置 >>> pos = np.array([5.0, 6.0, 7.0]) >>> new_pos = cell.apply_periodic_boundary(pos) >>> # 批量处理 >>> positions = np.random.randn(100, 3) * 10 >>> new_positions = cell.apply_periodic_boundary(positions)
- build_supercell(repetition)[源代码]
构建超胞,返回一个新的 Cell 对象。
采用更简单、更健壮的算法,直接在笛卡尔坐标系下操作。
- calculate_kinetic_energy()[源代码]
计算当前系统的总动能
- 返回:
系统总动能,单位为 \(\mathrm{eV}\)
- 返回类型:
备注
计算所有原子的动能总和,包含质心运动
示例
>>> cell = Cell(lattice_vectors, atoms) >>> kinetic = cell.calculate_kinetic_energy() >>> print(f"系统动能: {kinetic:.6f} eV")
- calculate_stress_tensor(potential)[源代码]
计算应力张量
- 参数:
potential (Potential) -- 用于计算应力的势能对象
- 返回:
3×3 应力张量矩阵 (eV/ų)
- 返回类型:
- calculate_temperature()[源代码]
计算系统的瞬时温度
使用均分定理计算温度,扣除质心运动贡献:
\[T = \frac{2 E_{kin}}{k_B \cdot N_{dof}}\]其中动能(扣除质心):
\[E_{kin} = \sum_i \frac{1}{2} m_i |\mathbf{v}_i - \mathbf{v}_{cm}|^2\]自由度数定义:
\[\begin{split}N_{\mathrm{dof}} = \begin{cases} 3N - 3, & N > 1, \\ 3, & N = 1. \end{cases}\end{split}\]- 返回:
系统温度,单位为 \(\mathrm{K}\)
- 返回类型:
备注
瞬时温度会有涨落,通常需要时间平均来获得稳定值。 对于NVE系综,温度是守恒量的函数。
示例
>>> temp = cell.calculate_temperature() >>> print(f"瞬时温度: {temp:.1f} K") >>> # 计算时间平均温度 >>> temps = [cell.calculate_temperature() for _ in range(1000)] >>> avg_temp = np.mean(temps)
参见
calculate_kinetic_energy计算总动能(含质心运动)
- copy()[源代码]
创建 Cell 的深拷贝
- get_box_lengths()[源代码]
返回模拟盒子在 x、y、z 方向的长度
- 返回:
包含三个方向长度的数组 (Å)
- 返回类型:
- get_com_position()[源代码]
计算系统质心位置。
- 返回:
质心位置向量
- 返回类型:
- get_com_velocity()[源代码]
计算系统质心速度。
- 返回:
质心速度向量
- 返回类型:
- get_forces()[源代码]
获取所有原子的力信息
- 返回:
原子力数组,形状为 (num_atoms, 3)
- 返回类型:
- get_fractional_coordinates()[源代码]
获取所有原子的分数坐标
- 返回:
原子分数坐标数组,形状为(num_atoms, 3)
- 返回类型:
备注
坐标关系(列向量记号):
\[\mathbf{s} = \mathbf{L}^{-1}\,\mathbf{r}\]代码实现采用行向量右乘:\(\mathbf{s}^{\top} = \mathbf{r}^{\top}\,\mathbf{L}^{-1}\)。
- get_positions()[源代码]
获取所有原子的位置信息
- 返回:
原子位置数组,形状为 (num_atoms, 3)
- 返回类型:
示例
>>> positions = cell.get_positions() >>> print(f"原子数量: {positions.shape[0]}")
- get_velocities()[源代码]
获取所有原子的速度信息
- 返回:
原子速度数组,形状为 (num_atoms, 3)
- 返回类型:
- get_volume()[源代码]
计算晶胞体积
- 返回:
晶胞体积 (ų)
- 返回类型:
备注
体积通过晶格矢量的标量三重积计算:
\[V = \left|\, \mathbf{a} \cdot (\mathbf{b} \times \mathbf{c}) \,\right|\]
- lock_lattice_vectors()[源代码]
锁定晶格向量,防止在优化过程中被修改
备注
锁定后,晶格向量将不能被修改,直到调用
unlock_lattice_vectors()。- 返回类型:
None
- minimum_image(displacement)[源代码]
计算最小镜像位移向量
根据最小镜像约定,找到最近的周期镜像之间的位移。 这对于正确计算周期性系统中的距离和力至关重要。
数学原理(列向量记号):
\[\mathbf{d}_{\min} = \mathbf{d} - \mathbf{L}\, \operatorname{round}(\mathbf{L}^{-1} \mathbf{d})\]- 参数:
displacement (numpy.ndarray) -- 原始位移向量 (3,)
- 返回:
最小镜像位移向量 (3,)
- 返回类型:
- 抛出:
ValueError -- 如果位移向量不是3D或包含非有限值
备注
该方法确保返回的位移向量长度最小,对应于最近的周期镜像。 在计算原子间相互作用时必须使用此方法。
示例
>>> # 计算两原子间的最小距离 >>> r12 = atom2.position - atom1.position >>> r12_min = cell.minimum_image(r12) >>> distance = np.linalg.norm(r12_min)
参见
apply_periodic_boundary应用周期性边界条件
- property num_atoms
返回原子数量
- remove_com_motion()[源代码]
移除系统的质心运动。
该方法计算并移除系统的净平动,保证总动量为零。 在应用恒温器和恒压器时应该调用此方法。
- scale_lattice(scale_factor)[源代码]
按给定因子等比例缩放晶格
- 参数:
scale_factor (float) -- 缩放因子,>1放大,<1缩小
- 返回类型:
None
备注
这个方法只缩放晶格矢量,不改变原子坐标。 通常与原子坐标的相应缩放一起使用。
示例
>>> cell.scale_lattice(1.1) # 放大10% >>> # 同时需要缩放原子坐标以保持相对位置 >>> for atom in cell.atoms: ... atom.position *= 1.1
- set_fractional_coordinates(fractional_coords)[源代码]
根据分数坐标设置所有原子的笛卡尔坐标
- 参数:
fractional_coords (numpy.ndarray) -- 分数坐标数组,形状为(num_atoms, 3)
- 返回类型:
None
备注
坐标关系(列向量记号):
\[\mathbf{r} = \mathbf{L}\,\mathbf{s}\]代码实现采用行向量右乘:\(\mathbf{r}^{\top} = \mathbf{s}^{\top}\,\mathbf{L}^{\top}\)。
- set_lattice_vectors(lattice_vectors)[源代码]
设置新的晶格矢量并更新相关属性。
- 参数:
lattice_vectors (np.ndarray) -- 新的 3x3 晶格矢量矩阵。
- set_positions(positions)[源代码]
设置所有原子的笛卡尔坐标
- 参数:
positions (numpy.ndarray) -- 笛卡尔坐标数组,形状为(num_atoms, 3)
- 返回类型:
None
- set_velocities(velocities)[源代码]
设置所有原子的速度
- 参数:
velocities (numpy.ndarray) -- 速度数组,形状为 (num_atoms, 3)
- 抛出:
ValueError -- 当输入数组形状与原子数不匹配时抛出
- 返回类型:
None
- unlock_lattice_vectors()[源代码]
解锁晶格向量,允许在需要时修改
备注
解锁后,晶格向量可以被修改,直到再次调用
lock_lattice_vectors()。- 返回类型:
None
- class thermoelasticsim.utils.trajectory_recorder.Potential(parameters, cutoff)[源代码]
基类:
ABC势能计算的抽象基类。
提供原子间势能模型的统一接口,约定最小方法集以支持分子动力学 (MD) 中的力与能量评估。
备注
所有具体势能模型至少需实现
calculate_forces与calculate_energy。单位约定:能量 eV,长度 Å,力 eV/Å。
- __init__(parameters, cutoff)[源代码]
- abstractmethod calculate_energy(cell, neighbor_list)[源代码]
计算系统的总势能。
- 参数:
cell (Cell) -- 晶胞与原子集合。
neighbor_list (NeighborList) -- 邻居列表(按模型需要使用)。
- 返回:
系统总势能,单位 eV。
- 返回类型:
备注
抽象方法,必须由子类实现。
- abstractmethod calculate_forces(cell, neighbor_list)[源代码]
计算系统中所有原子的作用力。
- 参数:
cell (Cell) -- 晶胞与原子集合。
neighbor_list (NeighborList) -- 邻居列表(按模型需要使用)。
- 返回类型:
None
备注
需就地写入
force(单位 eV/Å)。抽象方法,必须由子类实现。
- class thermoelasticsim.utils.trajectory_recorder.LBFGSOptimizer(ftol=1e-08, gtol=1e-06, maxiter=1000, supercell_dims=None, **kwargs)[源代码]
基类:
OptimizerL-BFGS优化器(有限内存BFGS)
该优化器能够处理两种模式: 1. 仅优化原子位置 (默认)。 2. 同时优化原子位置和晶胞形状 (完全弛豫)。
- 参数:
- __init__(ftol=1e-08, gtol=1e-06, maxiter=1000, supercell_dims=None, **kwargs)[源代码]
- class thermoelasticsim.utils.trajectory_recorder.TrajectoryWriter(filename, mode='w', compression='gzip', compression_opts=4, chunk_size=100)[源代码]
基类:
objectH5MD格式轨迹文件写入器
遵循H5MD v1.1规范,提供高效的分子动力学轨迹存储。
- 参数:
示例
>>> writer = TrajectoryWriter('trajectory.h5', compression='gzip') >>> writer.initialize(n_atoms=100, n_frames_estimate=1000) >>> writer.write_frame(positions, box, time=0.0, step=0) >>> writer.close()
- __init__(filename, mode='w', compression='gzip', compression_opts=4, chunk_size=100)[源代码]
- close()[源代码]
关闭文件
- initialize(n_atoms, n_frames_estimate=1000, atom_types=None, metadata=None)[源代码]
初始化H5MD文件结构
- open()[源代码]
打开HDF5文件
- write_frame(positions, box=None, time=None, step=None, velocities=None, forces=None, stress=None, energy=None, temperature=None, **kwargs)[源代码]
写入单帧数据
- 参数:
positions (np.ndarray) -- 原子位置 (n_atoms, 3)
box (np.ndarray, optional) -- 晶格矢量 (3, 3)
time (float, optional) -- 时间(ps)
step (int, optional) -- MD步数
velocities (np.ndarray, optional) -- 速度 (n_atoms, 3)
forces (np.ndarray, optional) -- 力 (n_atoms, 3)
stress (np.ndarray, optional) -- 应力张量 (3, 3)
energy (float, optional) -- 总能量
temperature (float, optional) -- 温度
**kwargs -- 其他观测量
- class thermoelasticsim.utils.trajectory_recorder.TrajectoryRecorder(output_file, record_interval=1, record_forces=True, record_stress=True, record_energy=True, compression='gzip', compression_opts=4)[源代码]
基类:
object轨迹记录器
可以作为回调函数集成到优化器中,自动记录优化轨迹。
- 参数:
示例
>>> recorder = TrajectoryRecorder('optimization.h5') >>> optimizer = LBFGSOptimizerWithTrajectory(recorder=recorder) >>> optimizer.optimize(cell, potential)
- __init__(output_file, record_interval=1, record_forces=True, record_stress=True, record_energy=True, compression='gzip', compression_opts=4)[源代码]
- initialize(cell, metadata=None)[源代码]
初始化记录器
- record(cell, potential, step=None)[源代码]
记录当前状态
- finalize()[源代码]
完成记录并关闭文件
- class thermoelasticsim.utils.trajectory_recorder.LBFGSOptimizerWithTrajectory(recorder=None, trajectory_file=None, record_interval=1, **kwargs)[源代码]
基类:
LBFGSOptimizer带轨迹记录功能的L-BFGS优化器
在原有L-BFGS优化器基础上添加轨迹记录功能。
- 参数:
- __init__(recorder=None, trajectory_file=None, record_interval=1, **kwargs)[源代码]
- thermoelasticsim.utils.trajectory_recorder.create_optimizer_with_trajectory(optimizer_type='L-BFGS', trajectory_file=None, record_interval=1, **optimizer_params)[源代码]
创建带轨迹记录的优化器
绘图与可视化(可选)
备注
可视化相关模块依赖较多第三方库,且与文档构建关系不大。为降低构建复杂度,本节默认不自动展开 API。需要详细说明时,可在本地环境中查看源码注释或启用相应模块文档。