Compute¶
The compute module contains algorithms for calculating various molecular properties.
MCD (Molecular Connectivity Diagram)¶
Mean Displacement Correlation (MCD) computation for diffusion analysis.
This module implements the MCD method for computing self and distinct displacement correlations (MSD) from molecular dynamics trajectories.
Adapted from the tame library (https://github.com/Roy-Kid/tame).
MCDCompute ¶
MCDCompute(tags, max_dt, dt, center_of_mass=None)
Bases: Compute['Trajectory', MCDResult]
Compute Mean Displacement Correlations (MSD) for diffusion analysis.
This class implements the MCD method which computes time correlation functions of particle displacements. It returns raw MSD values without fitting. It supports:
- Self diffusion: MSD_i = <(r_i(t+dt) - r_i(t))²>
- Distinct diffusion: <(r_i(t+dt) - r_i(t)) · (r_j(t+dt) - r_j(t))>
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tags
|
list[str]
|
List of atom type specifications. Each tag can be: - Single integer (e.g., "3"): Self-diffusion MSD of type 3 - Two integers separated by comma (e.g., "3,4"): Distinct diffusion correlation between types 3 and 4 |
required |
max_dt
|
float
|
Maximum time lag in ps |
required |
dt
|
float
|
Timestep in ps |
required |
center_of_mass
|
dict[int, float] | None
|
Optional dict mapping element types to masses for COM removal. Format: {element_type: mass}, e.g., {1: 1.008, 6: 12.011} |
None
|
Examples:
>>> from molpy.io import read_h5_trajectory
>>> traj = read_h5_trajectory("trajectory.h5")
>>>
>>> # Compute self-diffusion MSD of atom type 3
>>> mcd = MCDCompute(tags=["3"], max_dt=30.0, dt=0.01)
>>> result = mcd(traj)
>>> print(result.correlations["3"]) # MSD values at each time lag
>>>
>>> # Compute distinct diffusion between types 3 and 4
>>> mcd = MCDCompute(tags=["3,4"], max_dt=30.0, dt=0.01)
>>> result = mcd(traj)
>>> print(result.correlations["3,4"]) # Correlation values
Source code in src/molpy/compute/mcd.py
57 58 59 60 61 62 63 64 65 66 67 68 | |
compute ¶
compute(input)
Compute MCD from trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
'Trajectory'
|
Input trajectory object |
required |
Returns:
| Type | Description |
|---|---|
MCDResult
|
MCDResult containing correlation functions (MSD values) |
Source code in src/molpy/compute/mcd.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
PMSD (Periodic Minimum Square Displacement)¶
Polarization Mean Square Displacement (PMSD) computation.
This module implements the PMSD method for computing polarization fluctuations in ionic systems from molecular dynamics trajectories.
Adapted from the tame library (https://github.com/Roy-Kid/tame).
PMSDCompute ¶
PMSDCompute(cation_type, anion_type, max_dt, dt)
Bases: Compute['Trajectory', PMSDResult]
Compute Polarization Mean Square Displacement for ionic systems.
This class computes the PMSD which measures polarization fluctuations in ionic systems. The polarization is defined as:
P(t) = Σ_cations r_i(t) - Σ_anions r_j(t)
And the PMSD is:
PMSD(dt) = <(P(t+dt) - P(t))²>_t
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cation_type
|
int
|
Atom type index for cations |
required |
anion_type
|
int
|
Atom type index for anions |
required |
max_dt
|
float
|
Maximum time lag in ps |
required |
dt
|
float
|
Timestep in ps |
required |
Examples:
>>> from molpy.io import read_h5_trajectory
>>> traj = read_h5_trajectory("ionic_liquid.h5")
>>>
>>> # Compute PMSD for Li+ (type 1) and PF6- (type 2)
>>> pmsd = PMSDCompute(cation_type=1, anion_type=2, max_dt=30.0, dt=0.01)
>>> result = pmsd(traj)
>>>
>>> # Plot results
>>> import matplotlib.pyplot as plt
>>> plt.plot(result.time, result.pmsd)
>>> plt.xlabel("Time lag (ps)")
>>> plt.ylabel("PMSD (Ų)")
>>> plt.show()
Source code in src/molpy/compute/pmsd.py
58 59 60 61 62 63 64 65 66 67 68 69 | |
compute ¶
compute(trajectory)
Compute PMSD from trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
'Trajectory'
|
Input trajectory object |
required |
Returns:
| Type | Description |
|---|---|
PMSDResult
|
PMSDResult containing time points and PMSD values |
Source code in src/molpy/compute/pmsd.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
RDKit Integration¶
RDKit-based compute operations for RDKitAdapter.
This module provides compute nodes that operate on RDKitAdapter instances to perform RDKit-based molecular operations like 3D coordinate generation and geometry optimization.
Generate3D
dataclass
¶
Generate3D(add_hydrogens=True, sanitize=True, embed=True, optimize=True, max_embed_attempts=10, embed_random_seed=0, max_opt_iters=200, forcefield='UFF', update_internal=True)
Bases: Compute[RDKitAdapter, RDKitAdapter]
RDKit-based 3D generation pipeline for RDKitAdapter.
This compute node performs a configurable sequence of RDKit operations on a RDKitAdapter: - Add explicit hydrogens (optional) - Sanitize molecule (optional) - Generate 3D coordinates via embedding (optional) - Optimize geometry with force field (optional)
The node mutates the passed RDKitAdapter, updating both the external Chem.Mol and optionally the internal Atomistic structure.
Attributes:
| Name | Type | Description |
|---|---|---|
add_hydrogens |
bool
|
Whether to add explicit hydrogens before embedding |
sanitize |
bool
|
Whether to sanitize the molecule |
embed |
bool
|
Whether to perform 3D coordinate embedding |
optimize |
bool
|
Whether to optimize geometry after embedding |
max_embed_attempts |
int
|
Maximum number of embedding attempts |
embed_random_seed |
int | None
|
Random seed for embedding (None for random) |
max_opt_iters |
int
|
Maximum optimization iterations |
forcefield |
str
|
Force field to use ("UFF" or "MMFF94") |
update_internal |
bool
|
Whether to sync internal structure after modifications |
Examples:
>>> from molpy.adapter.rdkit import RDKitAdapter
>>> from molpy.compute.rdkit import Generate3D
>>> from molpy import Atomistic
>>>
>>> # Create adapter from Atomistic
>>> atomistic = Atomistic()
>>> # ... add atoms and bonds ...
>>> adapter = RDKitAdapter(internal=atomistic)
>>>
>>> # Generate 3D coordinates
>>> op = Generate3D(
... add_hydrogens=True,
... sanitize=True,
... embed=True,
... optimize=True
... )
>>> adapter = op(adapter) # Mutates adapter
>>>
>>> # Access updated structure
>>> updated_atomistic = adapter.get_internal()
compute ¶
compute(input)
Execute the 3D generation pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
RDKitAdapter
|
RDKitAdapter to process |
required |
Returns:
| Type | Description |
|---|---|
RDKitAdapter
|
The same RDKitAdapter instance (mutated) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If adapter has no external representation and sync fails |
RuntimeError
|
If embedding or optimization fails |
Source code in src/molpy/compute/rdkit.py
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | |
OptimizeGeometry
dataclass
¶
OptimizeGeometry(max_opt_iters=200, forcefield='UFF', update_internal=True, raise_on_failure=False)
Bases: Compute[RDKitAdapter, RDKitAdapter]
RDKit-based geometry optimization for RDKitAdapter.
This compute node optimizes the geometry of a molecule using RDKit's force field methods (UFF or MMFF94).
Attributes:
| Name | Type | Description |
|---|---|---|
max_opt_iters |
int
|
Maximum optimization iterations |
forcefield |
str
|
Force field to use ("UFF" or "MMFF94") |
update_internal |
bool
|
Whether to sync internal structure after optimization |
raise_on_failure |
bool
|
Whether to raise exception on optimization failure (default: False) If False, warnings are issued but optimization continues |
Examples:
>>> from molpy.adapter.rdkit import RDKitAdapter
>>> from molpy.compute.rdkit import OptimizeGeometry
>>>
>>> adapter = RDKitAdapter(internal=atomistic)
>>> optimizer = OptimizeGeometry(forcefield="UFF", max_opt_iters=200)
>>> adapter = optimizer(adapter)
compute ¶
compute(input)
Execute geometry optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
RDKitAdapter
|
RDKitAdapter to process |
required |
Returns:
| Type | Description |
|---|---|
RDKitAdapter
|
The same RDKitAdapter instance (mutated) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no conformer found |
RuntimeError
|
If optimization fails and raise_on_failure=True |
Source code in src/molpy/compute/rdkit.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
Result¶
Result classes for compute operations.
This module defines result types returned by compute operations.
MCDResult
dataclass
¶
MCDResult(meta=dict(), time=(lambda: np.array([]))(), correlations=dict())
Bases: TimeSeriesResult
Results from Mean Displacement Correlation calculation.
Attributes:
| Name | Type | Description |
|---|---|---|
time |
NDArray[float64]
|
Time lag values (in ps) |
correlations |
dict[str, NDArray[float64]]
|
Dictionary mapping tag names to correlation function arrays (MSD values). Each array has shape (n_time_lags,) |
PMSDResult
dataclass
¶
PMSDResult(meta=dict(), time=(lambda: np.array([]))(), pmsd=(lambda: np.array([]))())
Bases: TimeSeriesResult
Results from Polarization Mean Square Displacement calculation.
Attributes:
| Name | Type | Description |
|---|---|---|
time |
NDArray[float64]
|
Time lag values (in ps) |
pmsd |
NDArray[float64]
|
Polarization MSD values at each time lag, shape (n_time_lags,) |
Result
dataclass
¶
Result(meta=dict())
Base class for computation results.
Subclasses should define specific fields for their result data.
to_dict ¶
to_dict()
Convert result to dictionary representation.
Source code in src/molpy/compute/result.py
24 25 26 | |
Time Series¶
Time-series analysis operations for trajectory data.
This module provides utilities for computing time-correlation functions, mean squared displacements, and other time-series statistics commonly used in molecular dynamics trajectory analysis.
Adapted from the tame library (https://github.com/Roy-Kid/tame).
TimeAverage ¶
TimeAverage(shape, dtype=np.float64, dropnan='partial')
Compute running time average with NaN handling.
This class accumulates data over time and computes the average, with options for handling NaN values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Shape of data arrays to average |
required |
dtype
|
dtype
|
Data type for accumulated arrays |
float64
|
dropnan
|
Literal['none', 'partial', 'all']
|
How to handle NaN values: - 'none': Include NaN values in average (result may be NaN) - 'partial': Ignore individual NaN entries - 'all': Skip entire frame if any NaN is present |
'partial'
|
Examples:
>>> avg = TimeAverage(shape=(10,), dropnan='partial')
>>> avg.update(np.array([1.0, 2.0, np.nan, 4.0]))
>>> avg.update(np.array([2.0, 3.0, 3.0, 5.0]))
>>> result = avg.get() # [1.5, 2.5, 3.0, 4.5]
Source code in src/molpy/compute/time_series.py
102 103 104 105 106 107 108 109 110 111 112 113 | |
get ¶
get()
Get current time-averaged value.
Returns:
| Type | Description |
|---|---|
NDArray
|
Time-averaged data array |
Source code in src/molpy/compute/time_series.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
reset ¶
reset()
Reset accumulator to initial state.
Source code in src/molpy/compute/time_series.py
162 163 164 165 166 167 168 169 | |
update ¶
update(new_data)
Add new data to running average.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_data
|
NDArray
|
New data array to include in average |
required |
Source code in src/molpy/compute/time_series.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
TimeCache ¶
TimeCache(cache_size, shape, dtype=np.float64, default_val=np.nan)
Cache previous N frames of trajectory data for correlation calculations.
This class maintains a rolling buffer of the most recent N frames of data, which is essential for computing time-correlation functions like MSD and ACF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_size
|
int
|
Number of frames to cache (maximum time lag) |
required |
shape
|
tuple[int, ...]
|
Shape of data arrays to cache (e.g., (n_atoms, 3) for coordinates) |
required |
dtype
|
dtype
|
Data type for cached arrays |
float64
|
default_val
|
float
|
Default value to fill cache initially (default: NaN) |
nan
|
Examples:
>>> cache = TimeCache(cache_size=100, shape=(10, 3))
>>> coords = np.random.randn(10, 3)
>>> cache.update(coords)
>>> cached_data = cache.get() # Shape: (100, 10, 3)
Source code in src/molpy/compute/time_series.py
37 38 39 40 41 42 43 44 45 46 47 48 49 | |
get ¶
get()
Get cached data array.
Returns:
| Type | Description |
|---|---|
NDArray
|
Cached data with shape (cache_size, *data_shape) |
Source code in src/molpy/compute/time_series.py
67 68 69 70 71 72 73 | |
reset ¶
reset()
Reset cache to initial state.
Source code in src/molpy/compute/time_series.py
75 76 77 78 | |
update ¶
update(new_data)
Add new frame to cache, shifting older frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_data
|
NDArray
|
New data array to add (shape must match self.shape) |
required |
Source code in src/molpy/compute/time_series.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
compute_acf ¶
compute_acf(data, cache_size, dropnan='partial')
Compute autocorrelation function over trajectory.
Calculates:
The particle dimension is averaged, and the time dimension is accumulated using a rolling cache to compute correlations at different time lags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
NDArray
|
Trajectory data with shape (n_frames, n_particles, n_dim) |
required |
cache_size
|
int
|
Maximum time lag (dt) to compute, in frames |
required |
dropnan
|
Literal['none', 'partial', 'all']
|
How to handle NaN values in averaging |
'partial'
|
Returns:
| Type | Description |
|---|---|
NDArray
|
ACF array with shape (cache_size,) containing ACF at each time lag |
Examples:
>>> # Velocity autocorrelation
>>> n_frames, n_particles = 1000, 100
>>> velocities = np.random.randn(n_frames, n_particles, 3)
>>> acf = compute_acf(velocities, cache_size=100)
Source code in src/molpy/compute/time_series.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
compute_msd ¶
compute_msd(data, cache_size, dropnan='partial')
Compute mean squared displacement over trajectory.
Calculates: <(r_i(t+dt) - r_i(t))^2>_{i,t}
The particle dimension is averaged, and the time dimension is accumulated using a rolling cache to compute correlations at different time lags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
NDArray
|
Trajectory data with shape (n_frames, n_particles, n_dim) |
required |
cache_size
|
int
|
Maximum time lag (dt) to compute, in frames |
required |
dropnan
|
Literal['none', 'partial', 'all']
|
How to handle NaN values in averaging |
'partial'
|
Returns:
| Type | Description |
|---|---|
NDArray
|
MSD array with shape (cache_size,) containing MSD at each time lag |
Examples:
>>> # Simple 1D random walk
>>> n_frames, n_particles = 1000, 100
>>> positions = np.cumsum(np.random.randn(n_frames, n_particles, 1), axis=0)
>>> msd = compute_msd(positions, cache_size=100)
>>> # MSD should grow linearly with time for random walk
Source code in src/molpy/compute/time_series.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | |