# Analyzing Molecular Change along a Trajectory

Source: https://ml-biomat.com/tutorials/python-scientific/s06/en/
Language: en

Separate global motion from internal change in an actual ubiquitin trajectory, linking structures, time traces, and residue fluctuations.

## A molecule moves; does its shape change too?

A loose knot in water can drift as a whole, rotate, and move its free ends. A point marked on the knot may occupy very different positions in two photographs even when the knot has barely changed shape. Molecular dynamics trajectories present the same problem: atomic coordinates change continually, but how much of that change comes from the motion of the whole molecule, and how much comes from internal rearrangement? This chapter uses MDAnalysis to read a ubiquitin trajectory and separate these contributions. We will calculate structural differences, molecular size, and residue-specific fluctuations, keeping the atom selection, units, reference, and time interval attached to every result.

A protein is a chain of amino-acid residues. A residue is the structural unit that remains when an amino acid becomes part of the chain. Each usually contains a backbone carbon called Cα, or alpha carbon. Connecting neighboring Cα positions gives a simplified trace of the backbone, useful for following bends and changes of shape. Side chains, hydrogen atoms, and surrounding water carry additional local detail. Ubiquitin in this example has 76 residues and 1231 protein atoms in the simulation model. We use its 76 Cα atoms to compare shape and the masses of all protein atoms to calculate size. These choices address different questions and remain explicitly identified in the figures.

The move from static structure to atomic motion has a concrete scientific history. In 1977, McCammon, Gelin, and Karplus studied bovine pancreatic trypsin inhibitor, BPTI, using forces from an empirical potential in equations of motion. Their work examined fluctuations around an average structure: a folded protein could still possess substantial internal motion. A structural picture therefore benefits from being read alongside coordinates recorded over time. The figure below presents that question with the present ubiquitin trajectory. The gray first-frame reference stays fixed, the blue backbone changes in the same projection, and orange marks the terminal Gly76. The lower plot turns motion at two positions into quantitative, time-resolved records.

![The 1977 BPTI study examined atomic fluctuations in a folded protein. This figure explores the same type of question with the present fitted ubiquitin trajectory: three times at a shared scale, and three-dimensional distances of Gly76 and Ile23 from their own full-window means.](https://ml-biomat.com/static/tutorials/python-scientific/figures/0c406eaa622a4a76aaf67fdd.svg?v=0c406eaa622a)

Figure 1The 1977 BPTI study examined atomic fluctuations in a folded protein. This figure explores the same type of question with the present fitted ubiquitin trajectory: three times at a shared scale, and three-dimensional distances of Gly76 and Ile23 from their own full-window means.

The frames here come from classical molecular dynamics. Their coordinates were generated by a specified molecular model and numerical integration, rather than by taking successive microscope images. The starting protein structure is PDB 1UBQ. The simulated system uses AMBER99SB-ILDN protein parameters, TIP3P water, and 17 sodium and 17 chloride ions, with temperature and pressure control targets of 300 K and 1 bar. Our analysis describes conformational changes of that model over 0–1000 ps. A project about bond-making reactions, proton transfer, or much slower conformational transitions calls for corresponding choices of physical model and observation time.

## Connect atom identities to a changing time record

A trajectory mainly stores coordinates in the same atom order at each recorded frame. It often lacks enough information to identify every atom, its residue, and its mass. A topology file supplies that identity table. An MDAnalysis `Universe` connects the two: `reference.tpr` provides atom identities, masses, and connectivity, while `ubiquitin-5ps.xtc` provides changing coordinates and simulation boxes. Despite the topology filename, the structural comparison in this chapter uses the first trajectory frame as its reference, rather than the minimized coordinates also stored in the TPR. A file can contain several kinds of information; the calculation must still specify which of them it uses.

The complete system contains 18869 atoms, including protein, water, and ions. `u.select_atoms('protein')` returns an `AtomGroup`, which you can imagine as a selected set of rows in the identity table. The selection `'protein and name CA'` narrows it to atoms named CA within the protein. CA here is the alpha-carbon atom name, and the protein condition supplies its molecular context. An atom group keeps its connection to the original trajectory, so changing the frame also changes the positions returned for those atoms. Before comparing structures, the program checks the total atom count, protein atom count, Cα count, and residue numbering.

Think of `u.trajectory[20]` as moving the reader to the twenty-first photograph. Array indexing starts at zero; frame index 20 corresponds to 100 ps in this dataset. A loop over `u.trajectory` advances the reader, and `ts.time` gives the current physical time. When storing coordinates, `.copy()` creates an independent numerical snapshot. A reader that manages a current frame may otherwise update a shared underlying buffer during later reads. Iteration can also return the reader to its first frame afterward, so times and values needed later are collected explicitly inside the loop.

Units are standardized at the input boundary. MDAnalysis reads these coordinates in ångströms, Å. One ångström equals 0.1 nm, so the program divides by 10 when constructing its analysis arrays, and every plotted length uses nm. Times are read in ps, with 1000 ps equal to 1 ns. This subset retains every fifth frame from a trajectory originally saved every 1 ps: 0, 5, 10, through 1000 ps, giving 201 frames. The molecular dynamics integration step was 0.002 ps, or 2 fs. The 5 ps sampling interval spans 2500 integration steps. Keeping fewer snapshots does not change the integration step, but faster motion cannot be reconstructed from this subset; a frequency analysis would need output with appropriate temporal resolution.

The input has already undergone whole-molecule reconstruction and protein centering. Periodic boundaries describe space by repeating a simulation cell: an atom crossing a cell edge remains part of the same molecule in a neighboring equivalent image. Treating atoms across that edge as separated by a whole box length can distort both molecular size and alignment. Here the protein has been reconstructed into a continuous molecular image. With another trajectory, use box vectors and molecular connectivity to restore whole molecules before this geometrical analysis. Showing a whole molecule, following its displacement across many cells, and removing global rotation serve different questions and require appropriately chosen operations.

## Compare the molecule in a shared frame of reference

Imagine tracing two protein backbones on transparent sheets. The outlines may initially lie far apart. Moving their centers together and rotating one sheet can bring much of the backbone into closer agreement. Rigid-body fitting performs the three-dimensional version of that operation, with “closer agreement” expressed as a precise minimization objective. A rigid transformation applies one translation and one rotation to every atom in a frame, preserving all distances within that frame. It does not pull an individual residue toward the reference merely to lower the error.

Every frame here is fitted to the first frame using the same 76 Cα atoms, in the same order, with equal weights. Averaging each Cartesian coordinate gives their geometrical center; subtracting it removes translation. The calculation then finds the three-dimensional rotation that minimizes the sum of squared distances between corresponding points. Squaring means a more distant pair contributes more strongly to this objective. The geometrical center is appropriate because all selected atoms contribute equally. If a future analysis uses mass-weighted fitting, both centering and the error calculation must use the corresponding mass weights.

The complete program uses `AlignTraj` for the actual fitting. To keep the data relationship clear, `Merge(ca)` creates an object containing just these 76 atom identities, and `load_new` attaches an array organized as 201 frames × 76 atoms × 3 coordinates. A reference object holds the first-frame positions; a mobile object holds every frame. Only this backbone subset needs to be loaded into memory. Water and ions remain in the original trajectory, and the full protein identities and masses remain available for calculating molecular size.

Assess fitting with both geometry and numbers. At 1000 ps, the unfitted Cα root mean square deviation is 0.362319 nm. Removing translation reduces it to 0.345529 nm; removing global rotation as well gives 0.107340 nm. These values use the same atoms, time, and reference. Their differences show that much of the direct coordinate change comes from overall orientation. The remaining fitted difference describes changes of shape relative to the first frame for this atom selection. For a protein with two domains that rotate relative to one another, fitting the entire protein or a single domain establishes different viewing frames for internal motion; choose the fitting region to match the research question.

![Three coordinate treatments share the first-frame reference and 76 Cα atoms. Lower left: mass-weighted Rg of 1231 protein atoms. Lower right: first frame in gray, unfitted 1000 ps in orange, and fitted 1000 ps in blue, projected onto fixed x and z axes.](https://ml-biomat.com/static/tutorials/python-scientific/figures/3390a9e3ef7807e6a38af023.svg?v=3390a9e3ef78)

Figure 2Three coordinate treatments share the first-frame reference and 76 Cα atoms. Lower left: mass-weighted Rg of 1231 protein atoms. Lower right: first frame in gray, unfitted 1000 ps in orange, and fitted 1000 ps in blue, projected onto fixed x and z axes.

## Build a structural difference from paired coordinates

RMSD stands for root mean square deviation. Its name gives the calculation order: square the distance between each pair of corresponding atoms, take the mean over atoms, and then take the square root. Squaring prevents opposite directions from canceling. Averaging establishes a consistent normalization for the selected atom count. Taking the square root returns the result from squared length to length. Correspondence is essential: the fifteenth selected Cα in one array must be compared with the same residue in the reference. Two arrays with equal lengths but different atom orders can still produce a meaningless structural comparison.

$$
\operatorname{RMSD}(t)=\sqrt{\frac{1}{N}\sum_{i=1}^{N}\left\|\widetilde{\mathbf r}_i(t)-\mathbf r_i^{\mathrm{ref}}\right\|^2}
$$

| Symbol | Meaning and units |
| --- | --- |
| ![Formula](https://ml-biomat.com/static/agent-math/c28bb395211208bbd75d07f3.svg) | Root mean square structural deviation at time t, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/707bb132def3690d81bf1f0c.svg) | Time of the selected frame, ps |
| ![Formula](https://ml-biomat.com/static/agent-math/256531b7f0ddb14dd11a59a3.svg) | Number of compared atoms, 76 here, dimensionless integer |
| ![Formula](https://ml-biomat.com/static/agent-math/33f73a318016d781b6ae1aa9.svg) | Index of a corresponding atom in the fixed order, dimensionless |
| ![Formula](https://ml-biomat.com/static/agent-math/53ed5a9277e7e49f9cb02e14.svg) | Three-dimensional coordinate vector of Cα atom i after the chosen treatment, nm: unfitted, centered, or rigid-body fitted |
| ![Formula](https://ml-biomat.com/static/agent-math/7d91d2ea07ecd57330855b66.svg) | Corresponding Cα reference coordinates in the first trajectory frame, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/2ee49bcacdf21c726bb6de10.svg) | Sum of squared components of vector v, in nm² here |
| ![Formula](https://ml-biomat.com/static/agent-math/c1a69b9e26498e8da33b4b57.svg) | Sum squared distances over atom indices 1 through N |

For a two-pair worked example, let the treated points lie 0.1 and 0.3 nm from their respective references. The mean squared distance is (0.01+0.09)/2=0.05 nm², and its square root is 0.223607 nm. Weights are equal. The actual 76-Cα trajectory gives 0.107340 nm after rigid-body fitting at 1000 ps. Substituting each coordinate treatment produces its own RMSD curve.

The coordinates in the formula can be the original positions, translation-removed positions, or rigid-body-fitted positions, provided that the chosen treatment is specified. The three curves share a vertical scale so that their definitions can be compared directly. Across all 201 frames, the mean unfitted RMSD is 0.506850 nm, while the mean fitted RMSD is 0.147892 nm. A mean compresses a curve into one value that describes an overall scale for this interval. The time series retains the order of events. For example, the fitted RMSD around 650–700 ps exceeds that in several earlier intervals, prompting a return to the corresponding structures to identify which regions have changed.

RMSD is a geometrical difference from a selected reference, rather than a universal quality score. Another reference, atom set, or weighting convention changes the question. Large motion of a terminal region can raise the whole-protein RMSD, while a smaller local change can matter for a binding pocket. Interpret the trace alongside residue locations and specific distances. To assess sampling of a state, compare time windows, independent trajectories, and observables connected directly to the scientific question. A flat portion of an RMSD curve says that this geometrical indicator varies little over that interval.

The example also calculates the best rotation independently using NumPy singular value decomposition and compares its RMSD with MDAnalysis QCP results. These approaches organize the rotation calculation differently while using the same paired coordinates and equal weights. Over all frames, their largest RMSD difference is approximately 6.7×10⁻¹⁵ nm. Recalculating the formula from the fitted coordinates actually stored in single precision gives a maximum difference of about 4.0×10⁻⁸ nm. That coordinate-representation effect is much smaller than the structural variations of roughly 0.1 nm visible in the figure. Comparing implementations of the same definition helps identify unit, weighting, and atom-order errors.

## Radius of gyration: where the mass lies

The radius of gyration, Rg, describes how widely molecular mass is distributed around its center. Imagine assigning every atom its mass and its distance from the center: more mass farther away contributes more strongly. The calculation uses all protein atoms and first finds their center of mass. An oxygen atom and a hydrogen atom at the same distance contribute different amounts, unlike the equal Cα weights used for fitting. Mass is therefore a required physical input for this observable, rather than an optional label added to a plot.

$$
M=\sum_{i=1}^{N_p}m_i,\qquad \mathbf r_{\mathrm{cm}}=\frac{\sum_{i=1}^{N_p}m_i\mathbf r_i}{M},\qquad R_g=\sqrt{\frac{\sum_{i=1}^{N_p}m_i\|\mathbf r_i-\mathbf r_{\mathrm{cm}}\|^2}{M}}
$$

| Symbol | Meaning and units |
| --- | --- |
| ![Formula](https://ml-biomat.com/static/agent-math/34058a2a5d1de088feed7d98.svg) | Total mass of selected protein atoms, u |
| ![Formula](https://ml-biomat.com/static/agent-math/5a9c1aa4dbcfe2c2217b3e46.svg) | Number of all protein atoms, 1231 here, dimensionless integer |
| ![Formula](https://ml-biomat.com/static/agent-math/33f73a318016d781b6ae1aa9.svg) | Protein atom index, dimensionless |
| ![Formula](https://ml-biomat.com/static/agent-math/929c2a5e3b92ad47814e45bb.svg) | Mass of atom i, u, read from TPR here |
| ![Formula](https://ml-biomat.com/static/agent-math/1dd29f54f8cb4b9a864140cf.svg) | Coordinate vector of atom i in the current frame, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/fe1efa6a514c38eeec0bd835.svg) | Protein center-of-mass coordinates in the current frame, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/742acc50d5d386b6c8461bed.svg) | Mass-weighted radius of gyration, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/de714f948b8aa66300ec4bd3.svg) | Sum of squared Cartesian vector components, nm² |
| ![Formula](https://ml-biomat.com/static/agent-math/9b9441d841a7d77652c30687.svg) | Sum over all selected protein atoms |

Consider a one-dimensional example with masses 1 u and 3 u at 0 nm and 2 nm. Total mass is 4 u, and the mass center is (1×0+3×2)/4=1.5 nm. The weighted squared distance is [1×(0−1.5)²+3×(2−1.5)²]/4=0.75 nm², giving Rg=0.866025 nm. A common translation or rotation preserves this value. Applying the same operation in three dimensions to 1231 protein atoms gives 1.180766 nm in the first frame.

The mean Rg of the 201 frames is 1.190952 nm, and the first-frame value is 1.180766 nm. The graph expands the approximate 1.18–1.21 nm range to reveal changes in size. Read its numerical ticks: the height of a fluctuation within that panel does not mean that the protein has expanded by a comparable visual factor. Rg is the root mean square distance of mass from the mass center. It is neither the maximum atomic distance nor the radius of a sphere enclosing the protein. An elongated arrangement and a more compact-looking cluster can have similar Rg values, so a shape description also benefits from structure views or directional measures.

Translation and rotation leave Rg unchanged. Translating every atom shifts the center of mass by the same amount, preserving relative positions; rotation preserves distances from that center. We therefore calculate Rg directly for the whole protein in each frame without first applying the Cα alignment. This gives a useful numerical check: applying an arbitrary rigid transformation to the same molecular coordinates should preserve Rg to numerical precision. Periodic imaging is a separate matter. If a molecular image is split across a boundary, ordinary Cartesian distances can change, and whole-molecule reconstruction is needed first.

`protein.radius_of_gyration()` uses masses supplied by the TPR topology. The program then repeats the calculation independently: retrieve all protein coordinates, find their mass-weighted center, average squared distances with the same weights, and take the square root. The two routes agree at every frame, with a maximum difference below 10⁻¹⁵ nm. The protein mass in this topology is approximately 8564.922 u, where u is the atomic mass unit. Mass units cancel between the numerator and denominator of the Rg expression, leaving nm. When using a format such as PDB that may not explicitly provide all masses, check element assignments and mass values before using the observable.

## Locate motion along the residue sequence

An RMSD time trace combines differences across many atoms into one value for each frame. RMSF reverses the question: keep one atom fixed by identity, and measure how its position fluctuates about its own mean over time. F stands for fluctuation. Once each residue has a value, residue number becomes the horizontal axis, making local backbone mobility comparable across the protein. Aligning frames before calculating mean positions reduces the contribution of global rotation. We use fitted RMSF to compare local mobility: every frame follows the same first-frame fitting rule, then a new mean position is calculated for each Cα within the selected window. The figures and interactive views also retain unfitted and translation-removed results to show how global motion contributes to positional fluctuations. Each treatment uses the mean of its own coordinates within the current window.

$$
\overline{\mathbf r}_i=\frac{1}{K}\sum_{k=1}^{K}\widetilde{\mathbf r}_i(t_k),\qquad \operatorname{RMSF}_i=\sqrt{\frac{1}{K}\sum_{k=1}^{K}\|\widetilde{\mathbf r}_i(t_k)-\overline{\mathbf r}_i\|^2}
$$

| Symbol | Meaning and units |
| --- | --- |
| ![Formula](https://ml-biomat.com/static/agent-math/33f73a318016d781b6ae1aa9.svg) | Index of the selected Cα atom, dimensionless |
| ![Formula](https://ml-biomat.com/static/agent-math/24733a44cf365eb5e1b92574.svg) | Number of saved frames within the averaging window, dimensionless integer |
| ![Formula](https://ml-biomat.com/static/agent-math/8dc6f7e80ecaac9fa07890ce.svg) | Index of a saved frame within the window, dimensionless |
| ![Formula](https://ml-biomat.com/static/agent-math/1c9b48d61e70baede492433d.svg) | Time of saved frame k, ps |
| ![Formula](https://ml-biomat.com/static/agent-math/2af86cc6a230c44cc20e877d.svg) | Cα position after the specified coordinate treatment, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/d0d1de2e76d7a6a0433c4e77.svg) | Mean coordinates of that atom over the selected time window, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/b8ef4d276aebf957b6e970a4.svg) | Root mean square fluctuation about the atom’s own window mean, nm |
| ![Formula](https://ml-biomat.com/static/agent-math/de714f948b8aa66300ec4bd3.svg) | Sum of squared components of a three-dimensional coordinate difference, nm² |
| ![Formula](https://ml-biomat.com/static/agent-math/0dfcceb73a3665cd8b838c11.svg) | Sum over all frames in the selected window |

Suppose a point occupies one-dimensional positions 0, 0.2, and 0.4 nm at three saved times, with its other coordinates zero. Its mean is 0.2 nm, and squared deviations are 0.04, 0, and 0.04 nm². RMSF is therefore √(0.08/3)=0.163299 nm. Three-dimensional data sum squared deviations across coordinates before averaging frames. Actual fitted Gly76 gives 0.487722 nm over all 201 frames, and 0.313331 nm in the 41-frame 0–200 ps window using that window’s own mean.

The expression averages squared distances. RMSF therefore differs from the simple mean distance to a mean position, and from averaging a whole-protein RMSD curve. The former still concerns one atom over time, while the latter has already combined many atoms into each value. Dividing by the window's frame count describes the spread of the recorded positions around their mean; it is not the standard error of that mean. Neighboring trajectory frames are usually correlated. Estimating statistical uncertainty in a long-time average requires accounting for that correlation, rather than treating 201 consecutive snapshots as 201 independent experiments.

![With a fixed alignment rule, three windows produce their own means and RMSF values; parentheses give frame counts. Lower left compares unfitted and fitted full-window fluctuations. The mean trace at right is colored by full-window fitted RMSF on a 0–0.55 nm scale.](https://ml-biomat.com/static/tutorials/python-scientific/figures/38877e1e30acdd3a87239e82.svg?v=38877e1e30ac)

Figure 3With a fixed alignment rule, three windows produce their own means and RMSF values; parentheses give frame counts. Lower left compares unfitted and fitted full-window fluctuations. The mean trace at right is colored by full-window fitted RMSF on a 0–0.55 nm scale.

Terminal Gly76 has a fitted full-window RMSF of 0.487722 nm, above most internal residues in this trajectory. Selecting 0–200 ps gives 0.313331 nm; selecting 800–1000 ps gives 0.396427 nm. Both short windows include their endpoints and contain 41 frames. A changed window changes both the coordinates included and their mean. A full-window calculation can additionally include shifts between the average positions of different periods. Simply averaging the two short-window RMSF values therefore does not recover the full-window result. A statement about “the fluctuation of residue 76” needs its alignment convention, sampling interval, and averaging window.

The structure panel colors residues by full-window RMSF and draws the backbone using full-window mean coordinates. It shows whether a peak belongs to a terminal or internal region. Mean coordinates are a statistical representation; no individual frame need have exactly that shape. The interactive view below returns to actual frames so that summary values can be connected to specific conformations. Crystallographic B factors also retain their experimental interpretation: positional distributions, disorder, and model-related factors contribute to the refined quantity. The RMSF here instead summarizes a specified molecular model over a finite trajectory interval. Comparing the two requires an appropriate model relating their meanings.

## A complete program from trajectory to tables and figures

The download contains the program, topology, and 201-frame trajectory subset. Install MDAnalysis, NumPy, and Matplotlib, then run the commands below from the extracted directory. `--output` selects the results directory, and `--language` selects figure labels. Input locations are resolved relative to the script, so the entire directory can be moved to another computer. Outputs include a time-ordered `timeseries.csv`, a window-and-residue table `rmsf.csv`, a numerical summary, and three scientific figures. CSV column names retain nm and ps so that subsequent pandas operations or comparisons with other trajectories keep their units visible.

### Install and run

Run in the extracted example directory. Chinese figures require an installed Noto Sans CJK SC, Noto Sans SC, Microsoft YaHei, or SimHei font.

```
python -m pip install MDAnalysis numpy matplotlib
python main.py --output results --language en
python main.py --output results-zh --language zh
```

`analyze` performs the calculations, and `plot_figures` draws the same results. Analysis first collects Cα coordinates and all-protein Rg frame by frame, constructs three coordinate versions, and then invokes `RMSF` for three time windows. `rms.RMSF` does not align a trajectory itself. Fitted arrays therefore enter a new in-memory trajectory before fluctuations are calculated. Each intermediate output has a clear downstream purpose: coordinates support fitting and structural displays, times define windows, and RMSF arrays supply both residue curves and structural colors. Changing visual style then leaves the scientific definition intact.

### Complete trajectory analysis and plotting program

Read actual TPR/XTC inputs, run alignment, radius of gyration, and RMSF for three windows, and save tables, a numerical summary, and three figures.

```
"""Read a real ubiquitin trajectory; separate rigid-body motion and fluctuations."""
from pathlib import Path
import argparse
import csv
import hashlib
import json
import shutil
import numpy as np
import MDAnalysis as mda
from MDAnalysis.analysis import align, rms
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.collections import LineCollection

BLUE, ORANGE, GREEN = '#176480', '#bd5b28', '#2e8071'
MODES = ('raw', 'centered', 'fitted')
WINDOWS = {'all': (0, 1000), 'early': (0, 200), 'late': (800, 1000)}


def available_plot_fonts():
    choices = ['Noto Sans CJK SC', 'Noto Sans SC', 'Microsoft YaHei',
               'SimHei', 'DejaVu Sans']
    installed = {f.name for f in font_manager.fontManager.ttflist}
    return [x for x in choices if x in installed]


def rigid_fit_svd(mobile, reference):
    """Independent equal-weight proper rotation, using row-vector coordinates."""
    x = mobile - mobile.mean(axis=0)
    y = reference - reference.mean(axis=0)
    left, _, right = np.linalg.svd(x.T @ y)
    correction = np.eye(3)
    correction[-1, -1] = np.linalg.det(left @ right)
    fitted = x @ (left @ correction @ right) + reference.mean(axis=0)
    return fitted


def analyze(output):
    source = Path(__file__).resolve().parent / 'data'
    # XTC readers save an offset index next to the trajectory. Keep it in output.
    cache = output / 'trajectory-cache'
    cache.mkdir(exist_ok=True)
    trajectory = cache / 'ubiquitin-5ps.xtc'
    shutil.copyfile(source / trajectory.name, trajectory)
    u = mda.Universe(str(source / 'reference.tpr'), str(trajectory))
    protein = u.select_atoms('protein')
    ca = u.select_atoms('protein and name CA')
    assert len(u.atoms) == 18869 and len(protein) == 1231 and len(ca) == 76
    assert np.array_equal(ca.resids, np.arange(1, 77))
    times, coordinates, rg, rg_direct = [], [], [], []
    masses = protein.masses.astype(float)
    for ts in u.trajectory:
        times.append(float(ts.time))
        coordinates.append(ca.positions.astype(float).copy() / 10)
        rg.append(float(protein.radius_of_gyration()) / 10)
        xyz = protein.positions.astype(float) / 10
        com = np.average(xyz, axis=0, weights=masses)
        rg_direct.append(float(np.sqrt(np.average(
            np.sum((xyz - com) ** 2, axis=1), weights=masses))))
    times = np.asarray(times)
    raw = np.asarray(coordinates)
    assert np.allclose(times, np.arange(201) * 5, atol=1e-6)
    reference = raw[0]
    centered = raw - raw.mean(axis=1, keepdims=True) + reference.mean(axis=0)
    # A small in-memory Universe has the same 76 atom identities and 201 frames.
    mobile = mda.Merge(ca)
    mobile.load_new((raw * 10).astype(np.float32), order='fac', dt=5)
    ref = mda.Merge(ca)
    ref.atoms.positions = reference * 10
    align.AlignTraj(mobile, ref, select='all', weights=None,
                    in_memory=True).run()
    fitted = np.array([mobile.atoms.positions.copy().astype(float) / 10
                       for _ in mobile.trajectory])
    xyz_by_mode = {'raw': raw, 'centered': centered, 'fitted': fitted}
    rmsd = {key: np.sqrt(np.mean(np.sum((a-reference)**2, axis=2), axis=1))
            for key, a in xyz_by_mode.items()}
    qcp = np.array([rms.rmsd(x, reference, center=True, superposition=True)
                    for x in raw])
    independent = np.array([rigid_fit_svd(x, reference) for x in raw])
    svd_rmsd = np.sqrt(np.mean(np.sum((independent-reference)**2, axis=2), axis=1))
    # The exact identity frame can give a tiny QCP roundoff, so compare at 1e-6 nm.
    assert np.max(np.abs(qcp-svd_rmsd)) < 1e-6
    assert np.max(np.abs(rmsd['fitted']-svd_rmsd)) < 1e-6
    assert np.max(np.abs(np.array(rg)-rg_direct)) < 1e-12
    windows, rmsf_error = {}, []
    for key, (start, end) in WINDOWS.items():
        indices = np.flatnonzero((times >= start) & (times <= end))
        record = {'start_ps': start, 'end_ps': end, 'frames': len(indices),
                  'rmsf_nm': {}, 'mean_nm': {}, 'rg_mean_nm': float(np.mean(np.array(rg)[indices]))}
        for mode, xyz in xyz_by_mode.items():
            mem = mda.Merge(ca)
            mem.load_new((xyz*10).astype(np.float32), order='fac', dt=5)
            result = rms.RMSF(mem.atoms).run(start=int(indices[0]), stop=int(indices[-1])+1)
            fluct = result.results.rmsf / 10
            direct = np.sqrt(np.mean(np.sum((xyz[indices]-xyz[indices].mean(axis=0))**2,
                                           axis=2), axis=0))
            rmsf_error.append(float(np.max(np.abs(fluct-direct))))
            record['rmsf_nm'][mode] = fluct.tolist()
            record['mean_nm'][mode] = xyz[indices].mean(axis=0).tolist()
        windows[key] = record
    assert max(rmsf_error) < 1e-6
    summary = {
        'frames': len(times), 'atoms': len(u.atoms), 'protein_atoms': len(protein),
        'CA_atoms': len(ca), 'sampling_ps': 5, 'duration_ps': float(times[-1]-times[0]),
        'protein_mass_u': float(masses.sum()),
        'rg_mean_nm': float(np.mean(rg)), 'rg_first_nm': rg[0],
        'rmsd_last_nm': {key: float(v[-1]) for key,v in rmsd.items()},
        'rmsd_mean_nm': {key: float(np.mean(v)) for key,v in rmsd.items()},
        'rmsf_76_nm': {key: value['rmsf_nm']['fitted'][75] for key,value in windows.items()},
        'rmsf_peak_residue': int(np.argmax(windows['all']['rmsf_nm']['fitted'])+1),
        'checks': {'QCP_SVD_max_nm': float(np.max(np.abs(qcp-svd_rmsd))),
                   'AlignTraj_SVD_max_nm': float(np.max(np.abs(rmsd['fitted']-svd_rmsd))),
                   'Rg_max_nm': float(np.max(np.abs(np.array(rg)-rg_direct))),
                   'RMSF_max_nm': max(rmsf_error)},
        'versions': {'MDAnalysis': mda.__version__, 'numpy': np.__version__,
                     'matplotlib': matplotlib.__version__},
        'input_sha256': {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
                         for p in (source/'reference.tpr', source/'ubiquitin-5ps.xtc')}
    }
    lab = {'times_ps': times.tolist(), 'resids': ca.resids.tolist(),
           'resnames': ca.resnames.tolist(), 'xyz_nm': {k:v.tolist() for k,v in xyz_by_mode.items()},
           'rmsd_nm': {k:v.tolist() for k,v in rmsd.items()}, 'rg_nm': rg,
           'windows': windows, 'reference_nm': reference.tolist()}
    for name, obj in [('summary',summary),('lab-data',lab)]:
        (output/f'{name}.json').write_text(json.dumps(obj,ensure_ascii=False,indent=2),encoding='utf-8')
    with (output/'timeseries.csv').open('w',newline='',encoding='utf-8') as f:
        w=csv.writer(f); w.writerow(['time_ps','RMSD_raw_nm','RMSD_centered_nm','RMSD_fitted_nm','Rg_nm'])
        w.writerows(zip(times,*[rmsd[k] for k in MODES],rg))
    with (output/'rmsf.csv').open('w',newline='',encoding='utf-8') as f:
        w=csv.writer(f); w.writerow(['window','mode','resid','resname','RMSF_nm'])
        for window, record in windows.items():
            for mode in MODES:
                w.writerows((window,mode,int(i),str(n),float(v)) for i,n,v in
                            zip(ca.resids,ca.resnames,record['rmsf_nm'][mode]))
    return lab, summary


def plot_figures(d, summary, output, language):
    zh = language == 'zh'
    def t(a,b): return a if zh else b
    plt.rcParams.update({'font.family':available_plot_fonts() if zh else ['DejaVu Sans'],
        'font.size':13,'axes.titlesize':16,'axes.labelsize':13,'xtick.labelsize':12,
        'ytick.labelsize':12,'axes.spines.top':False,'axes.spines.right':False,
        'svg.fonttype':'none','figure.facecolor':'#fffefb','axes.facecolor':'#fffefb'})
    time=np.array(d['times_ps']); ref=np.array(d['reference_nm']); ref-=ref.mean(axis=0)
    raw=np.array(d['xyz_nm']['raw']); fit=np.array(d['xyz_nm']['fitted'])
    labels=[t('未配准','Unfitted'),t('去平移','Translation removed'),t('去平移与旋转','Rigid-body fitted')]
    colors=[ORANGE,'#887494',BLUE]
    def save(fig,name):
        fig.savefig(output/f'{name}-{language}.svg',bbox_inches='tight')
        fig.savefig(output/f'{name}-{language}.png',dpi=150,bbox_inches='tight'); plt.close(fig)
    def clean(ax): ax.grid(alpha=.16); ax.set_axisbelow(True)
    fig=plt.figure(figsize=(14,8.5),layout='constrained')
    grid=fig.add_gridspec(2,2,height_ratios=[1.3,1])
    a=fig.add_subplot(grid[0,:]); b=fig.add_subplot(grid[1,0]); c=fig.add_subplot(grid[1,1])
    for mode,label,color in zip(MODES,labels,colors): a.plot(time,d['rmsd_nm'][mode],color=color,lw=1.8,label=label)
    a.set(xlabel=t('时间 / ps','Time / ps'),ylabel=t('Cα RMSD / nm','Cα RMSD / nm'),
          title=t('A  同一个第一帧参考，三种坐标处理','A  One first-frame reference, three coordinate treatments'))
    a.legend(loc='upper left',ncol=3,fontsize=12); a.set_ylim(bottom=0); clean(a)
    b.plot(time,d['rg_nm'],color=GREEN,lw=1.5); b.set(xlabel=t('时间 / ps','Time / ps'),ylabel='Rg / nm',
          title=t('B  1231个蛋白质原子的质量分布','B  Mass distribution of 1231 protein atoms')); clean(b)
    c.plot(ref[:,0],ref[:,2],color='#a6acaf',lw=2,label=t('第一帧','First frame'))
    for arr,color,label in [(raw[-1]-np.array(d['reference_nm']).mean(axis=0),ORANGE,t('1000 ps：未配准','1000 ps: unfitted')),
                             (fit[-1]-np.array(d['reference_nm']).mean(axis=0),BLUE,t('1000 ps：配准后','1000 ps: fitted'))]:
        c.plot(arr[:,0],arr[:,2],color=color,lw=1.5,alpha=.85,label=label)
    c.set(xlabel='x / nm',ylabel='z / nm',title=t('C  固定视角的Cα链迹','C  Cα traces in one fixed projection'))
    c.set_aspect('equal'); clean(c)
    save(fig,'global-motion')
    fig=plt.figure(figsize=(14,9),layout='constrained'); g=fig.add_gridspec(2,2,width_ratios=[1.25,1])
    a=fig.add_subplot(g[0,0]); b=fig.add_subplot(g[1,0]); c=fig.add_subplot(g[:,1]); res=np.arange(1,77)
    for key,col in [('all',BLUE),('early',GREEN),('late',ORANGE)]:
        r=d['windows'][key]; a.plot(res,r['rmsf_nm']['fitted'],lw=2,color=col,label=f"{r['start_ps']}–{r['end_ps']} ps ({r['frames']})")
    a.set(title=t('A  固定配准后，时间窗决定平均位置','A  A fixed alignment, different averaging windows'),xlabel=t('残基编号','Residue number'),ylabel='Cα RMSF / nm'); a.legend(fontsize=11);clean(a)
    for mode,col,label in [('raw',ORANGE,labels[0]),('fitted',BLUE,labels[2])]:
        b.plot(res,d['windows']['all']['rmsf_nm'][mode],color=col,lw=2,label=label)
    b.set(title=t('B  0–1000 ps：整体转动也会增大坐标波动','B  Global rotation also enlarges positional fluctuations'),xlabel=t('残基编号','Residue number'),ylabel='Cα RMSF / nm');b.legend(fontsize=11);clean(b)
    mean=np.array(d['windows']['all']['mean_nm']['fitted']); mean-=mean.mean(axis=0)
    fluct=np.array(d['windows']['all']['rmsf_nm']['fitted']); pts=mean[:,[0,2]]
    lc=LineCollection(np.stack([pts[:-1],pts[1:]],axis=1),cmap='viridis',norm=plt.Normalize(0,.55),linewidth=4)
    lc.set_array((fluct[:-1]+fluct[1:])/2); c.add_collection(lc);c.scatter(pts[:,0],pts[:,1],c=fluct,cmap='viridis',vmin=0,vmax=.55,s=24,zorder=3)
    for i,offset in [(0,(-20,-24)),(75,(8,8))]: c.annotate(f'{i+1} {d["resnames"][i]}',pts[i],xytext=offset,textcoords='offset points',fontsize=12)
    c.annotate('9 THR',pts[8],xytext=(1.05,1.15),textcoords='data',fontsize=12,
               arrowprops={'arrowstyle':'-','color':'#666'},bbox={'facecolor':'#fffefb','edgecolor':'none','pad':2})
    c.autoscale(); c.margins(.2);c.set_aspect('equal');c.set(xlabel='x / nm',ylabel='z / nm',title=t('C  全窗口平均构象及局部波动','C  Full-window mean and local fluctuations'))
    fig.colorbar(lc,ax=c,orientation='horizontal',pad=.09,label='Cα RMSF / nm',ticks=[0,.1,.2,.3,.4,.5]);clean(c)
    save(fig,'local-fluctuations')
    fig=plt.figure(figsize=(14,8.5),layout='constrained');g=fig.add_gridspec(2,3,height_ratios=[1.4,1])
    for j,frame in enumerate([0,100,200]):
        ax=fig.add_subplot(g[0,j]);p=fit[frame]-np.array(d['reference_nm']).mean(axis=0)
        ax.plot(ref[:,0],ref[:,2],color='#b5b8b9',lw=2,label=t('0 ps','0 ps'))
        ax.plot(p[:,0],p[:,2],color=BLUE,lw=2);ax.scatter(*p[75,[0,2]],color=ORANGE,s=65,zorder=4)
        ax.annotate('Gly76',p[75,[0,2]],xytext=(8,6),textcoords='offset points',fontsize=12)
        ax.set(xlabel='x / nm',ylabel='z / nm',title=f'{time[frame]:.0f} ps',xlim=(-2.2,2.2),ylim=(-2,2.8));ax.set_aspect('equal');clean(ax)
    a=fig.add_subplot(g[1,:2]); mean=np.array(d['windows']['all']['mean_nm']['fitted'])
    for idx,col in [(22,BLUE),(75,ORANGE)]:
        a.plot(time,np.linalg.norm(fit[:,idx]-mean[idx],axis=1),color=col,lw=1.7,label=f'{d["resnames"][idx]}{idx+1}')
    a.set(xlabel=t('时间 / ps','Time / ps'),ylabel=t('距自身平均位置 / nm','Distance from own mean / nm'),title=t('局部波动：相同时间里，两个位置怎样移动','Local fluctuations at two positions over the same time'));a.legend(ncol=2,fontsize=12);clean(a)
    b=fig.add_subplot(g[1,2]); b.axis('off')
    b.text(0,1,t('从折叠结构到原子运动','From folded structure\nto atomic motion'),va='top',fontsize=17,color=BLUE)
    b.text(0,.70,t('1977 · McCammon、Gelin、Karplus\nBPTI的经验势能与运动方程\n追踪平均结构周围的波动。\n\n上方：本例泛素的201帧子集\n灰色参考保持不动，\n橙色端点显示Gly76的位置。',
        '1977 · McCammon, Gelin, Karplus\nAn empirical potential and equations\nof motion for BPTI revealed\nfluctuations about an average.\n\nAbove: the present ubiquitin subset\nThe gray reference stays fixed;\norange tracks the position of Gly76.'),va='top',fontsize=13,linespacing=1.6)
    save(fig,'fluctuation-history')


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output',type=Path,default=Path('results'))
    parser.add_argument('--language',choices=['zh','en'],default='en')
    args=parser.parse_args(); args.output.mkdir(parents=True,exist_ok=True)
    data,summary=analyze(args.output)
    plot_figures(data,summary,args.output,args.language)
    print(json.dumps(summary,ensure_ascii=False,indent=2))


if __name__ == '__main__':
    main()
```

The program copies XTC into a cache directory inside the output before reading it because the trajectory reader stores a frame-offset index beside the trajectory for faster seeking. Results and that index remain within the output directory, allowing input data to remain unchanged. The printed summary can be compared with particular values in the figures, including 201 frames, 76 Cα atoms, and the final fitted RMSD. Independent checks use SVD fitting, direct mass-weighted distances, and a two-pass RMSF calculation that obtains means before deviations. These checks address mathematical definitions and help expose array-order and unit-conversion mistakes.

For a larger system, begin by streaming quantities that need only one frame at a time, such as Rg or a selected distance, and write their table rows as they are calculated. Load full coordinate collections into memory when repeated operations on those collections justify it. The small Cα array here makes all 201 frames convenient for teaching and interaction; water and ions do not need to be duplicated into several in-memory arrays. With another protein, update molecular identity, selections, and numbering checks first, then choose the fitting region and time windows. The calculation functions can continue to serve the same defined operations.

## Follow the same frame through structures and curves

The experiment below controls time frame, coordinate treatment, and RMSF window separately. Moving the time slider updates the structure, the cursors on RMSD and Rg, and the selected residue's position. Changing coordinate treatment reveals how global orientation affects the same frame and its RMSD. Changing the window updates the residue curve, structural colors, and local distance trace together. The gray reference remains the first frame. Rotating the viewing direction changes its projection while every numerical measurement continues to use three-dimensional coordinates.

### Trajectory, alignment, and averaging window

Compare three coordinate treatments of the same frame, then locate one residue’s fluctuation in the structure. Playback advances from the current frame and can be paused at any time; the page starts stationary.

[Figure: Current structure and selected residue trail](https://ml-biomat.com/tutorials/python-scientific/s06/en/#S06-structure)

Gray is the first frame; chain color gives RMSF for the selected window. Orange marks the selected residue and its trail within the window. u and v are orthographic projection coordinates in nm.

[Figure: Three RMSD traces and Rg over time](https://ml-biomat.com/tutorials/python-scientific/s06/en/#S06-times)

The selected coordinate treatment is emphasized, with cursors at the same frame. Pale green marks the RMSF window. Rg uses all protein-atom masses and remains unchanged.

[Figure: Residue RMSF and selected position](https://ml-biomat.com/tutorials/python-scientific/s06/en/#S06-fluctuation)

The orange marker corresponds to the same Cα in the structure. Changing the window updates the curve, structural colors, and window mean positions.

[Figure: Selected residue distance from its window mean](https://ml-biomat.com/tutorials/python-scientific/s06/en/#S06-local)

The curve retains all times; only frames in the green interval enter the current RMSF. Distances use three-dimensional coordinates.

Start at 1000 ps and compare unfitted coordinates, translation removal, and rigid-body fitting. Rg stays fixed while the terminal position and RMSD change. Keep rigid-body fitting, choose residue 76, and compare the three windows. Structural colors connect that residue to the fluctuation curve, while the local trace gives its three-dimensional distance from the selected window's mean position. Then choose residue 23 to compare an internal position with the terminus. Every view uses coordinates and statistics actually calculated by Python; the page switches among those results locally. The supplied trajectory and complete program regenerate them. Specific atoms, times, references, and units turn visible molecular motion into a question that a subsequent analysis can pursue.

[Download complete code and data](https://ml-biomat.com/static/tutorials/python-scientific/downloads/S06.zip)

Extract and follow the README; the code matches this chapter.

## References and further reading

1. [MDAnalysis: trajectories](https://userguide.mdanalysis.org/stable/trajectories/trajectories.html)

   Universe, dynamic coordinates, frame iteration, and coordinate copies.

   MDAnalysis User Guide repository: LGPL-2.1; methodological reference.
2. [MDAnalysis: RMSF tutorial](https://userguide.mdanalysis.org/stable/examples/analysis/alignment_and_rms/rmsf.html)

   Official example of alignment before RMSF.

   MDAnalysis User Guide repository: LGPL-2.1; methodological reference.
3. [MDAnalysis 2.11: RMS quantities](https://docs.mdanalysis.org/stable/documentation_pages/analysis/rms.html)

   RMSD, RMSF, weighting, and result attributes.

   MDAnalysis package LGPL-3.0-or-later; component terms retained.
4. [MDAnalysis 2.11: alignment](https://docs.mdanalysis.org/stable/documentation_pages/analysis/align.html)

   AlignTraj and in-memory coordinate handling.

   MDAnalysis package LGPL-3.0-or-later; API reference.
5. [MDAnalysis 2.11: atom groups](https://docs.mdanalysis.org/stable/documentation_pages/core/groups.html)

   Atom selections, center of mass, and radius of gyration.

   MDAnalysis package LGPL-3.0-or-later; API reference.
6. [McCammon, Gelin & Karplus (1977), Dynamics of folded proteins](https://doi.org/10.1038/267585a0)

   Historical study of atomic motion around an average BPTI structure.

   Primary scientific reference; publisher copyright.
7. [PDB 1UBQ: ubiquitin](https://www.rcsb.org/structure/1UBQ)

   Public structural identity of the starting protein.

   PDB archive data: CC0 1.0; https://www.rcsb.org/pages/policies
8. [Vijay-Kumar, Bugg & Cook (1987), Structure of ubiquitin refined at 1.8 Å resolution](https://doi.org/10.1016/0022-2836%2887%2990679-6)

   Primary structural study for 1UBQ.

   Primary scientific reference; publisher copyright.
9. [GROMACS introductory tutorial](https://tutorials.gromacs.org/docs/md-intro-tutorial.html)

   Open workflow context for preparation, dynamics, and postprocessing.

   Public tutorial; consult its stated terms for reuse.
10. [MDAnalysis licensing](https://github.com/MDAnalysis/mdanalysis/blob/develop/LICENSE)

    Package and component licensing.

    LGPL-3.0-or-later package; component licenses as listed.
