Steered MD¶
autopath.pulling.steered_md.SteeredMD ¶
Steered molecular dynamics: pull a ligand along a COM-COM reaction coordinate using a moving harmonic restraint.
Parameter design
Three orthogonal knobs control a sweep:
max_displacement(nm): total RC range to traverse.pulling_speed(nm/ps): physical pulling rate — varied across replicas in the sweep (passed to :meth:run).dx_per_move(nm): RC grid spacing — how far the spring center r0 advances per Python-side update. Held fixed across the sweep.
From these, the runtime derives::
steps_per_move = round(dx_per_move / (pulling_speed * dt))
sMD_moves = max_displacement / dx_per_move
total MD steps = max_displacement / (pulling_speed * dt)
Note the total MD step count does not depend on dx_per_move.
dx_per_move is purely an analysis-grid / log-resolution knob: it
controls how many rows are written to sMD_{run_id}.dat and the
DCD frame cadence, but does not change the physics. Holding it
constant across the sweep gives every speed the same protocol grid,
which is what :class:SMDAnalysis expects when comparing speeds.
Choosing dx_per_move
Upper bound — keep it small vs. the thermal sigma of the spring,
sigma_thermal = sqrt(kT/k). A rule of thumb is
dx_per_move <= sigma_thermal / 10 so the system sees an
effectively continuous bias rather than discrete jumps. The
constructor logs the ratio and warns if dx_per_move > 0.5 * sigma.
Lower bound — at the fastest sweep speed you don't want
steps_per_move to clip; keep
dx_per_move >= ~2 * v_max * dt (typically ~1e-4 nm with default
timestep). Going smaller buys nothing physical and only inflates the
.dat row count and per-move Python overhead. :meth:run warns when
steps_per_move rounds below 1.5 or when the realized speed
differs from the requested speed by more than 5%.
Choosing sMD_spring_cte
Stiffer springs give tighter tracking but smaller sigma_thermal,
which in turn tightens the upper bound on dx_per_move (and
eventually the lower bound on steps_per_move). For a typical
ligand the per-atom convention k = N_ha * k_per_atom (used in
:mod:autopath_core) keeps the thermal sigma roughly invariant to
ligand size.
Seeding
seed=None leaves OpenMM's random seeds unset (every run differs).
With an integer seed each :meth:run seeds the Langevin integrator
and the initial velocities with :meth:run_seed of (seed, run_id),
so pulls with different run_id or speed differ and the same pull
is reproducible regardless of call order. Reproducibility therefore
needs an explicit run_id and a deterministic platform (Reference/CPU).
pull_single_direction ¶
pull_single_direction(simulation, run_id: int, direction: str = 'forward', lambda0=None)
Main pulling loop for a single replica in one direction.
Advances the spring centre r0 by dx_per_move each iteration and
integrates steps_per_move MD steps. At each move the method records
the within-move time-averaged restraint force force (with its SEM),
the incremental protocol work dW_protocol (energy change due to the
r0 shift before MD relaxation — distinct from the cumulative work),
and, every save_freq moves, the soft contact count NC.
NC autostop: the loop halts early when NC drops below
autostop_nc × NC_initial for autostop_nc_window consecutive
samples and the cumulative displacement exceeds
autostop_min_displacement.
Output
The spring schedule starts at lambda0 (a length Quantity, required), the spring
centre the replica was equilibrated at by run.
Writes {out_dir}/sMD_{run_id}.dat with a # key=value metadata
header (spring_constant, requested/realized speed, steps_per_move,
force_n_samples, lambda0_nm, r_start_nm) followed by columns:
step, time, r_target, r_before, r_after, force, force_sem,
U_cvpack, dW_protocol
force is the coherent quantity for the estimators: the within-move
mean restraint force sampled from the dynamics under the current
r_target (with force_sem its standard error). This is what feeds
Feq / friction / the mean-force-TI PMF. The pre-step "kick"
-k*(r_before - r_target) is intentionally NOT logged (it is the
wrong ensemble for the mean force, and is trivially reconstructable
from r_before, r_target and the header spring_constant if needed).
The instantaneous lag r_target - r_after is likewise not logged: it
is a finite-speed, single-endpoint quantity (equilibrium lag + friction
drag γv/k + thermal noise), derivable from the two position columns. The
coordinate deconvolution uses the equilibrium lag Feq/k instead.
run_seed ¶
run_seed(run_id)
OpenMM seed of one run: hash of (seed, run_id) in [1, 2**31 - 1); None if unseeded.
run_id is the full replica name (replica-<id>_v<speed>_<direction>).
run ¶
run(pulling_speed: float = 0.001, pulling_direction: str = 'forward', run_id: str = None, checkpoint_file: str = None, pdb_file: str = None, state_xml_file: str = None, lambda0_nm: float | None = None)
Run one steered MD replica at the requested speed.
The replica is equilibrated for 50 ps with the spring held at lambda0 and then pulled from lambda0. lambda0_nm=None uses the COM distance of the input structure, which is shared by replicas started from the same structure; pass it explicitly when starting structures differ.
Sweep-fixed parameters (dx_per_move, max_displacement, sMD_spring_cte, save_freq) are set in init. Only the speed-dependent bookkeeping (steps_per_move, realized_speed) is computed here.
adapt_speed_from_meff
staticmethod
¶
adapt_speed_from_meff(m_eff_dalton, dx_target_nm=0.01, gammaL_ps=2.0, v_min=0.0005, v_max=0.01)
Heuristically adapt the pulling speed from the ligand effective mass.
Uses v = dx_target * gammaL / m_eff (Einstein–Smoluchowski scaling) then clamps the result to [v_min, v_max]. Useful for choosing a speed that keeps the ligand near equilibrium during the pull.
autopath.pulling.SMDData.SMDData ¶
Container and preprocessor for steered MD log files.
Wraps one or more .dat log files produced by a dcTMD/SMD run.
On construction the logs are loaded, filtered, and augmented with
cumulative work and analysis-coordinate columns; the result is stored
in self.raw_data. Estimator results are accumulated later via
:meth:add_estimator_results and stored in self.results.
Coordinate conventions
r_target is the theoretical protocol grid — the ideal constraint
position at each step, used by dcTMD. Because it follows a fixed
schedule it is identical across replicas and suitable for grouping.
r_before is the actual ligand distance measured before the
constraint force is applied. It reflects stochastic fluctuations, so
different replicas land on different grids; it requires binning before
it can be used as an analysis coordinate.
Parameters (selected)
completion_threshold_nm : float Distance threshold (nm) used to drop trajectories that did not reach their end state (default 0.1 nm).
load_logs ¶
load_logs() -> pd.DataFrame
Read all log files and return a concatenated DataFrame.
Each file is read with pd.read_csv (comment lines starting
with # are skipped). The columns trajname, speed,
and repid are appended from the filename. Files that cannot
be parsed are skipped with an error log.
After this call self.raw_data does not yet exist — the
returned DataFrame is passed through further processing steps in
__init__ before being assigned to self.raw_data.
build_protocol_grids ¶
build_protocol_grids(raw_data: DataFrame) -> dict[float, pd.DataFrame]
Reconstruct the ideal protocol grid per speed analytically.
Returns:
| Name | Type | Description |
|---|---|---|
protocol_grids |
dict
|
protocol_grids[speed] = DataFrame with columns: ['step', 'r_target_protocol'] |
build_analysis_coord ¶
build_analysis_coord(raw_data: DataFrame) -> pd.DataFrame
Attach r_coord: the per-(speed, step) median of r_target.
r_target should in theory match across replicas at a given speed, but tiny numerical differences (mostly from r0 not being exact) mean it doesn't; the median gives one shared coordinate for analysis/plotting.
integrate_force_dx ¶
integrate_force_dx(raw_data: DataFrame, r_column: str, work_mode: str = 'auto', protocol_work_column: str = 'dW_protocol') -> pd.DataFrame
Build cumulative work per trajectory.
Modes
- 'force_dx': legacy definition using trapezoidal integration of force over r_column.
- 'protocol': cumulative sum of per-move protocol increments (default column dW_protocol).
- 'auto': use 'protocol' when the column is present, else fallback to 'force_dx'.
filter_by_r_range ¶
filter_by_r_range(r_range, r_column) -> None
Restrict self.raw_data to rows where r_column falls within r_range.
Modifies self.raw_data in-place and returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_range
|
tuple[float, float]
|
|
required |
r_column
|
str
|
Column name to filter on (typically |
required |
parse_log_trailer
staticmethod
¶
parse_log_trailer(fn: str) -> dict
Parse trailing # key=value lines (stop bookkeeping) of an sMD .dat file.
Reads only the file tail. Values are coerced to float where possible. Returns an empty dict for logs without a trailer.
parse_log_metadata
staticmethod
¶
parse_log_metadata(fn) -> dict
Parse leading # key=value comment lines from an sMD .dat file.
These carry per-replica constants written by
:class:SteeredMD (spring_constant_kJ_mol_nm2, requested/realized
speed, steps_per_move, force_n_samples). Values are coerced to float
where possible. Returns an empty dict for older logs without a header.
get_trace_features ¶
get_trace_features(features: list[str] = ['work', 'lag', 'r_before'], stride: int = 1, rescale_by_speed: bool = False, zscore_by_speed: bool = False) -> pd.DataFrame
Build a feature table from trace-like quantities (force, lag, work, ...), organized in r-space (x_col) for each trajectory. Optional rescaling/normalization by speed (in case of clustering multi-speed data).
calculate_pocket_distances ¶
calculate_pocket_distances(group_A: str = None, group_B: str = None, recompute: bool = False, stride: int = 2) -> pd.DataFrame
Compute (or load) pocket-ligand distance features.
Persisted per speed to {outdir}/{sysname}_pocketDistances_v{speed}.csv
— check_convergence calls this once per speed with per-speed SMDData
instances sharing the same outdir. Results for all requested speeds are
concatenated on return.
Each cache starts with a # JSON header recording the selections,
stride and trajectory names it was computed for. A cache is reused only
when all of these match the request; otherwise (including caches written
before the header existed, whose step is the DCD frame index, and the
legacy combined {sysname}_pocketDistances.csv) it is recomputed with
a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_A
|
str
|
MDAnalysis selection string for the pocket atoms. |
None
|
group_B
|
str
|
MDAnalysis selection string for the ligand atoms. |
None
|
recompute
|
bool
|
If False (default), reuse each speed's cache file when it matches and only compute the rest. If True, recompute and overwrite all. |
False
|
stride
|
int
|
Frame stride for trajectory reading (default 2). |
2
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns |
merge_feature_sets
staticmethod
¶
merge_feature_sets(*feature_dfs: DataFrame, tolerance_ps: float | None = None) -> pd.DataFrame
Merge N feature DataFrames via a nearest-time asof merge per trajectory.
The first DataFrame is the reference (left side); the rest are merged
onto it one by one, e.g. combining trace features, pocket distances,
and ligand shape descriptors into one feature table for clustering.
All DataFrames must have trajname and time columns; shared
metadata columns are taken from the reference to avoid duplicates.
tolerance_ps caps the allowed asof time gap (ps); None always
keeps the nearest match regardless of gap size.
build_merged_features
staticmethod
¶
build_merged_features(trace_df: DataFrame, geom_df: DataFrame, tolerance_ps: float | None = None) -> pd.DataFrame
Merge geometry and trace feature DataFrames.
Convenience wrapper around :meth:merge_feature_sets that preserves
the original two-argument signature. The geometry DataFrame is used
as the reference (left side) and trace features are merged onto it.
merge_geom_features
staticmethod
¶
merge_geom_features(trace_df: DataFrame, geom_df: DataFrame, mode: str = 'impute') -> pd.DataFrame
Merge geom sidecar features onto trace features.
mode='impute' : merge_feature_sets nearest-fill (no NaN, full rows). mode='aligned' : keep only exact (trajname, time) matches.
load_geom_features ¶
load_geom_features() -> pd.DataFrame
Load per-run geom sidecars (sMD_*_geom.dat) for the loaded logs.
Returns an empty DataFrame when no sidecars are present; never raises on missing files. Columns: trajname, speed, step, time, geom_*.
add_estimator_results ¶
add_estimator_results(estimator_name: str, results_df: DataFrame)
Append per-(speed, path, step) estimator output to self.results.
Tags results_df with an 'estimator' column set to
estimator_name, then concatenates into self.results.
Multiple calls accumulate results from different estimators.
get_p_neq ¶
get_p_neq(byspeed: bool = True) -> dict[str, float]
p_neq Non-equilibrium path probabilities from sMD analysis. Returns a dictionary mapping path labels to p_neq values.
choose_reference_estimator
staticmethod
¶
choose_reference_estimator(results: DataFrame) -> str
Robustness-selected reference estimator for shared path weighting.
autopath.pulling.AnalysisSMD.SMDAnalysis ¶
Orchestrates the full dcTMD/SMD post-processing pipeline.
Pipeline stages
- Load SMD traces from log files via :class:
SMDData. - Cluster trajectories into unbinding paths using DTW
(:class:
DTWPathModel) or a user-supplied path model. - Estimate ΔG and W_diss per (speed, path, step) using Jarzynski and/or Cumulant estimators.
- Combine per-path profiles into a mixture PMF (
path_combination), then extrapolate to v→0 when multiple speeds are present. - Compute friction (γ) from the dissipative work profile and estimate k_off via Kramers/Pontryagin MFPT.
- Write CSV outputs and optional diagnostic plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replica_imbalance_threshold
|
float
|
Warn when the max/min replica count ratio across paths exceeds this
value (default 3.0). Logged in :meth: |
3.0
|
path_combination
|
str
|
How per-path profiles are combined, in both :meth: |
'eq21'
|
friction_model
|
(mixed, ols)
|
Regression for the force friction slope (default |
'mixed'
|
friction_source_work
|
(auto, derivative, force, regression)
|
Friction the Kramers MFPT uses for all estimators. |
'auto'
|
run ¶
run(sMDDdata: SMDData, r_range: tuple[float, float] | None = None, group_A: str = None, group_B: str = None, merge_features: bool = True, cluster_across_speeds: bool = True, features: list[str] | None = None, ligand_sdf: str | None = None, geom_features: bool = True, geom_merge: str = 'aligned', plateau_frac: float = 0.4, cluster_to_boundary: bool = True, boundary_buffer_frac: float = 0.1, recompute_distances: bool = False, kramers_abs: str = 'end', kramers_bound: str = 'mirror') -> SMDData
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cluster_across_speeds
|
bool
|
Cluster all speeds together (default; features standardised within
each speed) so each path spans every speed, as per-path force
|
True
|
features
|
list[str] | None
|
Flat list of clustering feature names to compute. Each name must
be in |
None
|
ligand_sdf
|
str | None
|
Path to an SDF with the ligand and correct bond orders.
Required if any RDKit feature is in |
None
|
kramers_abs
|
(end, force_plateau)
|
Kramers absorbing boundary: end of the pulled range ( |
"end"
|
kramers_bound
|
(mirror, none)
|
Bound-state population below the pull start
(:meth: |
"mirror"
|
check_convergence ¶
check_convergence(logs: list[str], speeds: list[float] = None, quantities: list[str] = ['dG_weighted'], estimator_name: str = 'cumulant', group_A: str = None, group_B: str = None, features: list | None = None, merge_features: bool = False, ligand_sdf: str | None = None, geom_features: bool = True, geom_merge: str = 'aligned', min_replicas: int = 5, trace_min_replicas: int = 3, tol_rmsd: float = 4.0, tol_barrier: float = 3.0, tol_r_ts: float = 0.1, trim_fraction: float = 0.1, min_common_points: int = 5, conv_window: int = 5, boundary_method: str = 'force_plateau', plateau_frac: float = 0.4, restrict_rmsd_to_boundary: bool = True, cluster_to_boundary: bool = True, boundary_buffer_frac: float = 0.1, min_samples_per_step_conv: int = 3, min_trajs_per_path_conv: int = 2, recompute_distances: bool = False, trace_per_path: bool = False)
Check PMF convergence as replica count grows, per pulling speed.
For each speed, replicas are added one at a time in sorted order.
After every addition the mixture PMF is rebuilt from the running
estimator statistics. PMF(k) is compared against a reference formed
by averaging over the last conv_window rungs (conv_window=1
reduces to the previous rung) on three criteria: RMSD over the
common r-range, change in barrier height, and change in
transition-state position.
Returns:
| Name | Type | Description |
|---|---|---|
convergence_df |
DataFrame
|
One row per (speed, k) with columns: |
traces_df |
DataFrame
|
Long-form PMF traces — one row per (speed, k, step) — for
plotting PMF evolution with increasing replica count. Contains
only |
path_weights ¶
path_weights(sMDDdata: SMDData, estimator: str = 'auto') -> dict
Path weights per speed (see :meth:_path_weights).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sMDDdata
|
SMDData
|
Data object with fitted estimator results. |
required |
estimator
|
str
|
Estimator whose dG gates the paths ('auto', 'cumulant', 'jarzynski', ...). |
'auto'
|
Returns:
| Type | Description |
|---|---|
dict
|
|
autopath.pulling.PathModel.DTWPathModel ¶
Bases: PathModel
Cluster trajectories using Dynamic Time Warping (DTW) and k-medoids. For more information on DTW see: https://doi.org/10.1073/pnas.231354212 https://dtaidistance.readthedocs.io/en/latest/index.html
fit_transform ¶
fit_transform(feature_df: DataFrame, r_range: tuple = None, n_paths: int = None, cluster_across_speeds: bool = True, reference_pdb: str = None, ligand_select: str = None, pocket_select: str = None, trajectory_files: dict = None, persist_medoids: bool = True) -> dict
Fit and transform trajectory clustering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_range
|
tuple or float
|
If a tuple (low, high), filter trajectories to that r_coord range before clustering. If a float in (0, 1], use the first r_range fraction of each trajectory for clustering (e.g. 0.8 uses the first 80% of frames). Plots always reflect the full trajectory regardless. |
None
|
cluster_across_speeds
|
bool
|
If True (default), cluster all trajectories together, standardising
features within each speed; labels are |
True
|
reference_pdb
|
str
|
Path to reference PDB file for unbinding path visualization. |
None
|
ligand_select
|
str
|
MDAnalysis selection string for ligand atoms. |
None
|
trajectory_files
|
dict
|
Dictionary mapping trajectory names to (topology, trajectory) tuples for unbinding path visualization. |
None
|
persist_medoids
|
bool
|
Merge this call's medoids into |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Mapping of trajectory name → path label ( |
Notes
Feature handling (merged feature mode):
When both geometric features (columns starting with
geom_feature_prefix) and trace features are present,
a PCA is applied to the geometric features before DTW distance
computation, reducing them to n_geom_pcs principal components.
This equalises their dimensionality contribution relative to the
trace features; without it, large numbers of pairwise-distance
columns would dominate the DTW metric.
merge_small_paths ¶
merge_small_paths(path_mappings: dict, min_pulls: int, speeds: dict = None)
Merge small (speed, path) groups into surviving paths.
A group with fewer than min_pulls pulls at a speed moves, pull by
pull, to the path with at least min_pulls pulls at that speed whose
medoid is nearest in DTW distance. If none qualifies, all pulls at that
speed go to the largest path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path_mappings
|
dict
|
trajname -> path label, as returned by :meth: |
required |
min_pulls
|
int
|
Minimum pulls per speed for a path to survive. |
required |
speeds
|
dict
|
trajname -> speed. Needed when paths were clustered across speeds; without it each clustering group counts as one speed. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
mappings |
dict
|
Updated trajname -> path label. |
merges |
list of dict
|
Records with keys |
plot_distance_matrix ¶
plot_distance_matrix(distmatrix: ndarray = None)
Save the DTW distance matrix and the as-clustered path labels.
Subclasses may override this to capture the inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distmatrix
|
ndarray
|
Square (N_traj x N_traj) DTW distance matrix, in |
None
|
plot_elbow ¶
plot_elbow(scores: dict, K: int)
Save the selected K and the per-k scores to path_model_v*.json.
Subclasses may override this to capture the inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
dict
|
Mapping of k to silhouette score; empty when K is fixed. |
required |
K
|
int
|
Selected number of paths. |
required |
plot_clusters_PCA ¶
plot_clusters_PCA(feature_df: DataFrame = None, path_mapping_dic: dict = None, vectors_stacked_scaled: list = None, feature_names: list = None, pca_model=None, pca_feature_names: list = None)
Save the 2-D PCA scores and loadings of the scaled trajectory features.
Subclasses may override this to capture the inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_df
|
DataFrame
|
Feature DataFrame for the current group (defines trajectory order). |
None
|
path_mapping_dic
|
dict
|
Mapping of trajectory name to path label. |
None
|
vectors_stacked_scaled
|
list of np.ndarray
|
Scaled (and optionally PCA-reduced) feature arrays, one per trajectory. |
None
|
feature_names
|
list of str
|
Names of the columns of |
None
|
pca_model
|
PCA
|
Fitted PCA whose scores the vectors already are. |
None
|
pca_feature_names
|
list of str
|
Original feature names for |
None
|
autopath.pulling.readouts ¶
Scalar ΔG readouts of sMD free-energy profiles for ranking several ligands.
Two readouts, both label-free:
- profile readout: ΔG at the most prominent PMF peak for the cumulant (argmax if none), the profile maximum for Jarzynski and force.
- rupture readout: ΔG at d*, the median over the ligand set of each ligand's force-peak displacement (argmax of the running mean of the mean pulling force).
profile_readouts ¶
profile_readouts(pmfs: DataFrame, kBT: float = KBT) -> pd.DataFrame
Profile readout of one system's mixture_pmfs.csv.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pmfs
|
DataFrame
|
Columns |
required |
kBT
|
float
|
Thermal energy (kJ/mol) for the peak prominence threshold. |
KBT
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
rupture_displacement ¶
rupture_displacement(processed: DataFrame, smooth: int = RUPTURE_SMOOTH) -> dict
{speed: force-peak displacement (nm)} from one system's traces (autopath.pulling.outputs.load_traces).
Steps not reached by every pull are dropped, so the profile ends with the shortest pull.
rupture_readouts ¶
rupture_readouts(pmfs: dict, ruptures: dict) -> pd.DataFrame
Rupture readout of a ligand set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pmfs
|
dict
|
|
required |
ruptures
|
dict
|
|
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|