[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73H6XQT41R5Y6G2DG3TMPJF":3,"skill-same:01M73H6XQT41R5Y6G2DG3TMPJF":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73H6XQT41R5Y6G2DG3TMPJF","mdtraj-trajectory-analysis",null,"mdtraj molecular dynamics trajectory analysis (Python). Reads DCD\u002FXTC\u002FTRR\u002FNetCDF\u002FH5\u002FPDB topologies and trajectories; computes RMSD vs time, radius of gyration, per-residue RMSF, residue-residue contact frequency maps, phi\u002Fpsi torsions for Ramachandran plots (general + Gly\u002FPro), and 8-state DSSP secondary structure. Modules: trajectory I\u002FO, geometry (distances\u002Fangles\u002Fdihedrals), structural analysis (RMSD\u002FRg\u002FRMSF\u002FSASA), contacts, hydrogen bonds, secondary structure (DSSP), NMR observables. For broader atom-selection grammar use mdanalysis-trajectory; for running MD simulations use OpenMM\u002FGROMACS.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"LGPL-2.1","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fmdtraj-trajectory-analysis\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"mdtraj-trajectory-analysis\"\ndescription: \"mdtraj molecular dynamics trajectory analysis (Python). Reads DCD\u002FXTC\u002FTRR\u002FNetCDF\u002FH5\u002FPDB topologies and trajectories; computes RMSD vs time, radius of gyration, per-residue RMSF, residue-residue contact frequency maps, phi\u002Fpsi torsions for Ramachandran plots (general + Gly\u002FPro), and 8-state DSSP secondary structure. Modules: trajectory I\u002FO, geometry (distances\u002Fangles\u002Fdihedrals), structural analysis (RMSD\u002FRg\u002FRMSF\u002FSASA), contacts, hydrogen bonds, secondary structure (DSSP), NMR observables. For broader atom-selection grammar use mdanalysis-trajectory; for running MD simulations use OpenMM\u002FGROMACS.\"\nlicense: \"LGPL-2.1\"\n---\n\n# mdtraj Trajectory Analysis\n\n## Overview\n\nmdtraj is a dependency-light Python library for analyzing MD trajectories. Reads DCD\u002FXTC\u002FTRR\u002FNetCDF\u002FH5\u002FAMBER\u002FGROMACS\u002FCHARMM\u002FOpenMM into a `Trajectory` object backed by NumPy arrays, then exposes geometry, RMSD\u002FRg\u002FRMSF\u002FSASA, contacts, hydrogen bonds, torsions, and 8-state DSSP as pure-Python functions.\n\n> **Units**: mdtraj uses **nm** and **ps** internally. Multiply distances by 10 for Å, divide time by 1000 for ns. Torsions are in **radians** — `np.degrees()`.\n\n## When to Use\n\n- RMSD vs time, Rg, per-residue RMSF for stability across MD replicates\n- Residue-residue contact frequency maps from a trajectory ensemble\n- Backbone phi\u002Fpsi for Ramachandran (general, Gly, Pro)\n- 8-state DSSP per residue per frame for secondary-structure time series\n- Lightweight ad-hoc analyses where MDAnalysis's full framework is overkill\n- NMR observables (J-couplings, chemical shifts via SHIFTX2)\n- Use **mdanalysis-trajectory** instead when you need MDAnalysis's selection grammar, AnalysisBase parallelism, or LAMMPS\u002FNAMD-specific readers\n- Use **OpenMM\u002FGROMACS** to *run* the simulation — this skill is post-simulation only\n\n## Prerequisites\n\n- `mdtraj`, `numpy`, `pandas`, `matplotlib`\n- Topology (PDB\u002FGRO\u002FPRMTOP\u002FPSF) + trajectory (DCD\u002FXTC\u002FTRR\u002FNetCDF\u002FH5)\n- Python 3.9+, conda-forge build recommended\n\nCheck before installing — inside a pixi\u002Fconda env mdtraj is usually present:\n\n```bash\npython3 -c \"import mdtraj\" 2>\u002Fdev\u002Fnull || conda install -c conda-forge mdtraj numpy pandas matplotlib\n```\n\n## Quick Start\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"traj.xtc\", top=\"topology.pdb\")\nca = traj.topology.select(\"name CA\")\ntraj.superpose(traj, frame=0, atom_indices=ca)\n\nrmsd_ang = md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0  # nm -> Å\nprint(f\"Frames: {traj.n_frames}  RMSD: {rmsd_ang.min():.2f}–{rmsd_ang.max():.2f} Å\")\n```\n\n## Core API\n\n### Module 1: Trajectory I\u002FO\n\nLoad whole or streamed. Format auto-detected from extension.\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\n\n# Stream large trajectories — avoids OOM\nfor chunk in md.iterload(\"rep1.xtc\", top=\"protein.pdb\", chunk=500):\n    rmsd_chunk = md.rmsd(chunk, chunk, frame=0)\n\n# Save subset\nca = traj.topology.select(\"name CA\")\ntraj.atom_slice(ca).save_dcd(\"ca_only.dcd\")\n```\n\nSelecting atoms and slicing frames:\n\n```python\nbackbone = traj.topology.select(\"backbone\")\nchain_a  = traj.topology.select(\"chainid 0\")\n\nfirst_ns      = traj[:1000]\nevery_10th    = traj[::10]\nlast_half_bb  = traj[traj.n_frames \u002F\u002F 2:].atom_slice(backbone)\n```\n\n### Module 2: RMSD, Rg, RMSF\n\n`md.rmsd` superposes internally; RMSF you compute manually after explicit superpose.\n\n```python\nimport mdtraj as md, numpy as np\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\nca = traj.topology.select(\"name CA\")\n\nrmsd_ang = md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0    # Å\nrg_ang   = md.compute_rg(traj) * 10.0                              # Å\ntime_ns  = traj.time \u002F 1000.0\nprint(f\"\u003CRMSD>={rmsd_ang.mean():.2f} Å,  \u003CRg>={rg_ang.mean():.2f} Å\")\n```\n\n```python\n# Per-CA RMSF — average-structure reference\nca_traj = traj.atom_slice(ca)\nca_traj.superpose(ca_traj, frame=0)\ndiff     = ca_traj.xyz - ca_traj.xyz.mean(axis=0)\nrmsf_ang = np.sqrt((diff ** 2).sum(axis=2).mean(axis=0)) * 10.0\nres_ids  = [a.residue.resSeq for a in ca_traj.topology.atoms]\nprint(f\"Max RMSF: residue {res_ids[np.argmax(rmsf_ang)]} = {rmsf_ang.max():.2f} Å\")\n```\n\n### Module 3: Contacts and Distance Maps\n\nThreshold distances to get contact frequency.\n\n```python\nimport mdtraj as md, numpy as np\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\ndistances_nm, pairs = md.compute_contacts(traj, contacts=\"all\", scheme=\"closest-heavy\")\n# distances_nm: (n_frames, n_pairs);  pairs: (n_pairs, 2) of residue indices\n\ncontact_freq = (distances_nm \u003C 0.5).mean(axis=0)                  # 5 Å cutoff\nn_res    = traj.n_residues\nfreq_map = np.zeros((n_res, n_res))\nfor (i, j), f in zip(pairs, contact_freq):\n    freq_map[i, j] = freq_map[j, i] = f\nprint(f\"Persistent contacts (>0.8): {(contact_freq > 0.8).sum()}\")\n```\n\n### Module 4: Torsions (Ramachandran)\n\nphi\u002Fpsi returned in radians; intersect on residue since first residue has no phi and last has no psi.\n\n```python\nimport mdtraj as md, numpy as np\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\nphi_ix, phi_rad = md.compute_phi(traj)\npsi_ix, psi_rad = md.compute_psi(traj)\n\ndef res_of(indices): return np.array([traj.topology.atom(ix[1]).residue.index for ix in indices])\nphi_res, psi_res = res_of(phi_ix), res_of(psi_ix)\ncommon  = np.intersect1d(phi_res, psi_res)\nphi_deg = np.degrees(phi_rad[:, np.isin(phi_res, common)])\npsi_deg = np.degrees(psi_rad[:, np.isin(psi_res, common)])\n```\n\nFilter to Gly \u002F Pro residues:\n\n```python\nres_names = [traj.topology.residue(r).name for r in common]\ngly_cols  = [i for i, n in enumerate(res_names) if n == \"GLY\"]\npro_cols  = [i for i, n in enumerate(res_names) if n == \"PRO\"]\nphi_gly, psi_gly = phi_deg[:, gly_cols].ravel(), psi_deg[:, gly_cols].ravel()\nphi_pro, psi_pro = phi_deg[:, pro_cols].ravel(), psi_deg[:, pro_cols].ravel()\n```\n\n### Module 5: DSSP Secondary Structure (8-state)\n\n`md.compute_dssp(traj, simplified=False)` returns `(n_frames, n_residues)` of one-character codes:\n\n| Code | Meaning            |\n|------|--------------------|\n| `H`  | alpha-helix        |\n| `B`  | beta-bridge        |\n| `E`  | beta-sheet         |\n| `G`  | 3_10-helix         |\n| `I`  | pi-helix           |\n| `T`  | turn               |\n| `S`  | bend               |\n| ` ` (space) or `C` | coil |\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\ndssp = md.compute_dssp(traj, simplified=False)\ndssp[dssp == \" \"] = \"C\"\nprint(f\"DSSP grid: {dssp.shape}  unique codes: {set(dssp.flatten())}\")\n```\n\n### Module 6: Hydrogen Bonds and SASA\n\n```python\nimport mdtraj as md\nimport pandas as pd\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\n\n# Baker–Hubbard: returns (n_hbonds, 3) of [donor, H, acceptor] atom indices\nhbonds = md.baker_hubbard(traj, freq=0.5, periodic=False)\nlabel  = lambda a: f\"{traj.topology.atom(a).residue}-{traj.topology.atom(a).name}\"\nhbonds_df = pd.DataFrame({\"donor\": [label(d) for d, _, _ in hbonds],\n                         \"acceptor\": [label(a) for _, _, a in hbonds]})\n\n# SASA in nm^2 per residue per frame\nsasa_nm2 = md.shrake_rupley(traj, mode=\"residue\")\ntotal_ang2 = sasa_nm2.sum(axis=1) * 100.0                # nm^2 -> Å^2\nprint(f\"Persistent H-bonds: {len(hbonds_df)},  \u003CSASA>: {total_ang2.mean():.0f} Å²\")\n```\n\n## Key Concepts\n\n### Units (nm, ps, radians)\n\n`traj.xyz` is in nm, `traj.time` in ps, torsions in radians. Convert before plotting:\n\n```python\nimport numpy as np\nxyz_ang  = traj.xyz * 10.0\ntime_ns  = traj.time \u002F 1000.0\nphi_deg  = np.degrees(phi_rad)\n```\n\n### Pair indices vs `resSeq`\n\n`md.compute_contacts(..., contacts=\"all\")` returns **0-based residue indices** (contiguous across chains), not PDB `resSeq`. Reshape into `(n_res, n_res)` before heatmaps. Map back via `traj.topology.residue(i).resSeq` only when labeling.\n\n### 8-state vs simplified DSSP\n\n`simplified=False` → 8 states. `simplified=True` → 3 states (H\u002FE\u002FC), which loses 3_10 (G), pi-helix (I), beta-bridge (B), bend (S), turn (T).\n\n## Common Workflows\n\n### Workflow 1: Multi-Replicate Stability + Flexibility + Contacts + Ramachandran + DSSP\n\n**Goal**: structural-analysis report for three MD replicates — RMSD\u002FRg over time, per-residue RMSF, residue contact frequency map (rep1), Ramachandran general + Gly + Pro (rep1), DSSP 8-state time series (rep1). Plots use matplotlib defaults; the consumer picks palette downstream.\n\n```python\nimport mdtraj as md, numpy as np, matplotlib.pyplot as plt\nfrom pathlib import Path\n\nreplicas = {\"rep1\": \"rep1.xtc\", \"rep2\": \"rep2.xtc\", \"rep3\": \"rep3.xtc\"}\ntopology = \"protein.pdb\"\noutdir = Path(\"figures\"); outdir.mkdir(exist_ok=True)\n\ntrajs = {name: md.load(p, top=topology) for name, p in replicas.items()}\nca    = next(iter(trajs.values())).topology.select(\"name CA\")\n\n# 1. RMSD vs time + Rg (Å) for all replicates\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\nfor name, traj in trajs.items():\n    traj.superpose(traj, frame=0, atom_indices=ca)\n    ax1.plot(traj.time \u002F 1000.0, md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0, lw=1, label=name)\n    ax2.plot(traj.time \u002F 1000.0, md.compute_rg(traj) * 10.0, lw=1, label=name)\nax1.set(xlabel=\"Time (ns)\", ylabel=\"RMSD (Å)\", title=\"Backbone RMSD\")\nax2.set(xlabel=\"Time (ns)\", ylabel=\"Rg (Å)\",   title=\"Radius of gyration\")\nfor ax in (ax1, ax2): ax.legend(frameon=False)\nfig.tight_layout(); fig.savefig(outdir \u002F \"01_rmsd_rg.png\"); plt.close(fig)\n\n# 2. Per-residue RMSF (Å) across replicates\nfig, ax = plt.subplots(figsize=(10, 4))\nfor name, traj in trajs.items():\n    ct = traj.atom_slice(ca); ct.superpose(ct, frame=0)\n    rmsf = np.sqrt(((ct.xyz - ct.xyz.mean(axis=0)) ** 2).sum(axis=2).mean(axis=0)) * 10.0\n    ax.plot([a.residue.resSeq for a in ct.topology.atoms], rmsf, lw=1, label=name)\nax.set(xlabel=\"Residue\", ylabel=\"RMSF (Å)\", title=\"Per-residue flexibility\")\nax.legend(frameon=False); fig.tight_layout()\nfig.savefig(outdir \u002F \"02_rmsf.png\"); plt.close(fig)\n\n# 3. Contact frequency map (rep1, 5 Å cutoff)\nrep1 = trajs[\"rep1\"]\ndist_nm, pairs = md.compute_contacts(rep1, contacts=\"all\", scheme=\"closest-heavy\")\nfreq = (dist_nm \u003C 0.5).mean(axis=0)\nfreq_map = np.zeros((rep1.n_residues, rep1.n_residues))\nfor (i, j), f in zip(pairs, freq):\n    freq_map[i, j] = freq_map[j, i] = f\nnp.fill_diagonal(freq_map, 1.0)\nfig, ax = plt.subplots(figsize=(6, 5))\nim = ax.imshow(freq_map, vmin=0, vmax=1, origin=\"lower\")\nax.set(xlabel=\"Residue\", ylabel=\"Residue\", title=\"Contact frequency (rep1)\")\nfig.colorbar(im, ax=ax, label=\"Fraction of frames in contact\")\nfig.tight_layout(); fig.savefig(outdir \u002F \"03_contact_map.png\"); plt.close(fig)\n\n# 4. Ramachandran (rep1) — phi\u002Fpsi 2D density\nphi_ix, phi_rad = md.compute_phi(rep1)\npsi_ix, psi_rad = md.compute_psi(rep1)\ndef res_of(ix, t): return np.array([t.topology.atom(i[1]).residue.index for i in ix])\nphi_res, psi_res = res_of(phi_ix, rep1), res_of(psi_ix, rep1)\ncommon = np.intersect1d(phi_res, psi_res)\nphi_deg = np.degrees(phi_rad[:, np.isin(phi_res, common)]).ravel()\npsi_deg = np.degrees(psi_rad[:, np.isin(psi_res, common)]).ravel()\nH, _, _ = np.histogram2d(phi_deg, psi_deg, bins=72, range=[[-180, 180], [-180, 180]])\nfig, ax = plt.subplots(figsize=(5, 5))\nax.imshow(H.T, origin=\"lower\", extent=[-180, 180, -180, 180], aspect=\"equal\")\nax.set(xlabel=r\"$\\phi$ (°)\", ylabel=r\"$\\psi$ (°)\", title=\"Ramachandran (rep1)\")\nfig.tight_layout(); fig.savefig(outdir \u002F \"04_ramachandran_all.png\"); plt.close(fig)\n\n# 5. Glycine + proline Ramachandran\nres_names = [rep1.topology.residue(r).name for r in common]\nfor label, cols, fname in [(\"Glycine\", [i for i, n in enumerate(res_names) if n == \"GLY\"], \"05_rama_gly.png\"),\n                           (\"Proline\", [i for i, n in enumerate(res_names) if n == \"PRO\"], \"06_rama_pro.png\")]:\n    if not cols: continue\n    phi = np.degrees(phi_rad[:, cols]).ravel()\n    psi = np.degrees(psi_rad[:, cols]).ravel()\n    H, _, _ = np.histogram2d(phi, psi, bins=60, range=[[-180, 180], [-180, 180]])\n    fig, ax = plt.subplots(figsize=(5, 5))\n    ax.imshow(H.T, origin=\"lower\", extent=[-180, 180, -180, 180], aspect=\"equal\")\n    ax.set(xlabel=r\"$\\phi$ (°)\", ylabel=r\"$\\psi$ (°)\", title=f\"{label} Ramachandran (rep1)\")\n    fig.tight_layout(); fig.savefig(outdir \u002F fname); plt.close(fig)\n\n# 6. DSSP 8-state time series (rep1)\ndssp = md.compute_dssp(rep1, simplified=False); dssp[dssp == \" \"] = \"C\"\ncodes_order = [\"C\", \"E\", \"B\", \"S\", \"T\", \"H\", \"I\", \"G\"]\ncode_to_int = {c: i for i, c in enumerate(codes_order)}\ndssp_int = np.vectorize(lambda c: code_to_int.get(c, 0))(dssp)\nfig, ax = plt.subplots(figsize=(10, 5))\nax.imshow(dssp_int.T, aspect=\"auto\", origin=\"lower\", interpolation=\"nearest\",\n          extent=[rep1.time[0] \u002F 1000.0, rep1.time[-1] \u002F 1000.0, 0, rep1.n_residues])\nax.set(xlabel=\"Time (ns)\", ylabel=\"Residue\", title=\"DSSP 8-state (rep1)\")\nfig.tight_layout(); fig.savefig(outdir \u002F \"07_dssp_8state.png\"); plt.close(fig)\n\n# Dump DSSP code mapping so downstream code can pick its own legend\u002Fpalette\nnp.savez(outdir \u002F \"07_dssp_8state.npz\", dssp=dssp, dssp_int=dssp_int, codes_order=codes_order)\nprint(\"All figures written to figures\u002F\")\n```\n\n### Workflow 2: H-Bond Persistence + SASA Across Replicates\n\n**Goal**: persistent hydrogen bonds (≥50% of frames) and total SASA time series per replicate.\n\n```python\nimport mdtraj as md, numpy as np, pandas as pd\n\nreplicas = {\"rep1\": \"rep1.xtc\", \"rep2\": \"rep2.xtc\", \"rep3\": \"rep3.xtc\"}\ntop = \"protein.pdb\"\nrows = []\nfor name, p in replicas.items():\n    t = md.load(p, top=top)\n    hbonds = md.baker_hubbard(t, freq=0.5, periodic=False)\n    sasa_ang2 = (md.shrake_rupley(t, mode=\"residue\").sum(axis=1) * 100.0)\n    rows.append({\"replica\": name, \"n_persistent_hbonds\": len(hbonds),\n                 \"sasa_mean_ang2\": sasa_ang2.mean(), \"sasa_std_ang2\": sasa_ang2.std()})\nprint(pd.DataFrame(rows).to_string(index=False))\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `chunk` (`md.iterload`) | I\u002FO | `100` | `100`-`5000` | Frames per stream chunk; trade speed vs RAM |\n| `atom_indices` (`md.rmsd`) | Stability | `None` | array of ints | Restrict superposition + RMSD (e.g., CA only) |\n| `frame` (`md.rmsd`) | Stability | `0` | `0`-`n_frames-1` | Reference frame |\n| `contacts` (`md.compute_contacts`) | Contacts | `\"all\"` | `\"all\"`, `[(i,j),...]` | All residue pairs or custom list |\n| `scheme` (`md.compute_contacts`) | Contacts | `\"closest-heavy\"` | `\"ca\"`, `\"closest\"`, `\"closest-heavy\"`, `\"sidechain\"`, `\"sidechain-heavy\"` | Atom subset for inter-residue distance |\n| `cutoff` (contact threshold, user-set) | Contacts | `0.5` nm | `0.4`-`0.8` nm | In-contact distance (5 Å for CA, 4 Å for closest-heavy) |\n| `simplified` (`md.compute_dssp`) | DSSP | `True` | `True`\u002F`False` | `False` → 8-state codes |\n| `freq` (`md.baker_hubbard`) | H-bonds | `0.1` | `0.0`-`1.0` | Min frame fraction to report |\n| `mode` (`md.shrake_rupley`) | SASA | `\"atom\"` | `\"atom\"`, `\"residue\"` | Per-atom or summed per residue |\n| `probe_radius` (`md.shrake_rupley`) | SASA | `0.14` nm | `0.12`-`0.20` nm | Solvent probe (1.4 Å standard) |\n| `periodic` (geometry funcs) | Geometry | `True` | bool | Minimum-image convention if box info present |\n\n## Best Practices\n\n1. **Convert units before plotting** — nm → Å (×10), ps → ns (÷1000), rad → deg (`np.degrees`). #1 cause of \"my RMSD is 10× too small\".\n2. **Superpose before RMSF** — `md.rmsd` superposes internally; RMSF doesn't. Without explicit `traj.superpose(...)`, RMSF picks up rigid-body motion.\n3. **`md.iterload` for big trajectories** — 1 µs at 1 ps\u002Fframe is millions of frames. Streaming avoids OOM.\n4. **`simplified=False` for fine-grained DSSP** — 3-state collapses 3_10 \u002F pi-helix \u002F bend transitions.\n5. **Pair indices, not `resSeq`** — `md.compute_contacts` returns 0-based contiguous indices. Map to `resSeq` only for labeling.\n6. **Strip waters early** — `traj.atom_slice(traj.topology.select(\"protein\"))` cuts memory\u002Ftime 5–20× on solvated systems.\n\n## Common Recipes\n\n### Recipe: Convert Trajectory Format\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"input.nc\", top=\"topology.parm7\")\ntraj.save_xtc(\"output.xtc\")\ntraj.save_pdb(\"output.pdb\")\nprint(f\"Converted {traj.n_frames} frames -> output.xtc\")\n```\n\n### Recipe: Per-Residue Mean ± SD RMSF Across Replicates\n\nEnsemble flexibility input for flexibility-aware docking or homology refinement.\n\n```python\nimport mdtraj as md, numpy as np, pandas as pd\n\npaths = {\"rep1\": \"rep1.xtc\", \"rep2\": \"rep2.xtc\", \"rep3\": \"rep3.xtc\"}\ntop = \"protein.pdb\"\nrmsf_by_rep = {}\nfor name, p in paths.items():\n    t  = md.load(p, top=top)\n    ct = t.atom_slice(t.topology.select(\"name CA\")); ct.superpose(ct, frame=0)\n    rmsf_by_rep[name] = np.sqrt(((ct.xyz - ct.xyz.mean(axis=0)) ** 2).sum(axis=2).mean(axis=0)) * 10.0\n\ndf = pd.DataFrame(rmsf_by_rep)\ndf[\"mean\"], df[\"std\"] = df.mean(axis=1), df.std(axis=1)\ndf.to_csv(\"rmsf_replicates.csv\", index_label=\"residue_index\")\n```\n\n### Recipe: Save Frames Above RMSD Threshold\n\nCurate \"open\" conformations for clustering or downstream analysis.\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\nca   = traj.topology.select(\"name CA\")\ntraj.superpose(traj, frame=0, atom_indices=ca)\nrmsd_ang = md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0\n\nopen_state = traj[rmsd_ang > 4.0]\nopen_state.save_dcd(\"open_state.dcd\")\nprint(f\"Saved {open_state.n_frames}\u002F{traj.n_frames} frames\")\n```\n\n### Recipe: Cross-Replicate Helix Fraction\n\n```python\nimport mdtraj as md, numpy as np\n\npaths = [\"rep1.xtc\", \"rep2.xtc\", \"rep3.xtc\"]\nhelix_fracs = [(md.compute_dssp(md.load(p, top=\"protein.pdb\"), simplified=False) == \"H\").mean() for p in paths]\nprint(f\"α-helix per replicate: {[f'{h:.2f}' for h in helix_fracs]}\")\nprint(f\"Mean ± std: {np.mean(helix_fracs):.2f} ± {np.std(helix_fracs):.2f}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `RuntimeError: No topology` | XTC\u002FDCD\u002FTRR carry no topology | Pass `top=\"protein.pdb\"` (or `.prmtop`) to `md.load` |\n| RMSD 10× too small | mdtraj returns nm | Multiply by 10.0 |\n| RMSF spikes at termini | Intrinsic terminal flexibility, not a bug | Slice termini off or report explicitly |\n| DSSP returns only `H\u002FE\u002FC` | `simplified=True` default | Pass `simplified=False` |\n| Empty\u002F`' '` DSSP cells | Space = coil, not missing | `dssp[dssp == \" \"] = \"C\"` |\n| MemoryError on big trajectory | Whole trajectory in RAM | Switch to `md.iterload(..., chunk=500)` |\n| phi\u002Fpsi arrays differ in residue count | First residue has no phi; last has no psi | Intersect residue index sets before pairing |\n| Ramachandran off-center | Angles still in radians | Wrap with `np.degrees`; set `range=[[-180, 180], [-180, 180]]` |\n| `md.compute_contacts` returns NaN | Some pairs lack heavy atoms for `closest-heavy` (e.g., glycine sidechain) | Use `scheme=\"closest\"` or `\"ca\"`; drop NaN columns |\n| Contact map asymmetric | Only filled upper triangle | Mirror: `freq_map[j, i] = freq_map[i, j]` |\n| `traj.time` all zeros | Some writers leave time blank | Reconstruct: `traj.time = np.arange(traj.n_frames) * dt_ps` |\n\n## Related Skills\n\n- **mdanalysis-trajectory** — richer atom-selection grammar and AnalysisBase framework\n- **autodock-vina-docking** \u002F **smina-molecular-docking** — feed representative MD frames as docking targets\n- **chembl-database-bioactivity** — overlay ligand bioactivity on MD-derived flexibility maps\n\n## References\n\n- [mdtraj documentation](https:\u002F\u002Fmdtraj.org\u002F) — official docs, API reference, tutorials\n- [McGibbon et al. (2015)](https:\u002F\u002Fdoi.org\u002F10.1016\u002Fj.bpj.2015.08.015) — \"MDTraj: A Modern Open Library for the Analysis of Molecular Dynamics Trajectories\", *Biophys J*\n- [DSSP algorithm](https:\u002F\u002Fdoi.org\u002F10.1002\u002Fbip.360221211) — Kabsch & Sander (1983)\n- [Baker–Hubbard H-bond criterion](https:\u002F\u002Fdoi.org\u002F10.1016\u002FS0006-3495(99)77244-7) — Baker & Hubbard (1984)\n- [Shrake–Rupley SASA](https:\u002F\u002Fdoi.org\u002F10.1016\u002F0022-2836(73)90011-9) — Shrake & Rupley (1973)\n- [mdtraj GitHub](https:\u002F\u002Fgithub.com\u002Fmdtraj\u002Fmdtraj) — source, issues, examples\n","# mdtraj Trajectory Analysis\n\n## Overview\n\nmdtraj is a dependency-light Python library for analyzing MD trajectories. Reads DCD\u002FXTC\u002FTRR\u002FNetCDF\u002FH5\u002FAMBER\u002FGROMACS\u002FCHARMM\u002FOpenMM into a `Trajectory` object backed by NumPy arrays, then exposes geometry, RMSD\u002FRg\u002FRMSF\u002FSASA, contacts, hydrogen bonds, torsions, and 8-state DSSP as pure-Python functions.\n\n> **Units**: mdtraj uses **nm** and **ps** internally. Multiply distances by 10 for Å, divide time by 1000 for ns. Torsions are in **radians** — `np.degrees()`.\n\n## When to Use\n\n- RMSD vs time, Rg, per-residue RMSF for stability across MD replicates\n- Residue-residue contact frequency maps from a trajectory ensemble\n- Backbone phi\u002Fpsi for Ramachandran (general, Gly, Pro)\n- 8-state DSSP per residue per frame for secondary-structure time series\n- Lightweight ad-hoc analyses where MDAnalysis's full framework is overkill\n- NMR observables (J-couplings, chemical shifts via SHIFTX2)\n- Use **mdanalysis-trajectory** instead when you need MDAnalysis's selection grammar, AnalysisBase parallelism, or LAMMPS\u002FNAMD-specific readers\n- Use **OpenMM\u002FGROMACS** to *run* the simulation — this skill is post-simulation only\n\n## Prerequisites\n\n- `mdtraj`, `numpy`, `pandas`, `matplotlib`\n- Topology (PDB\u002FGRO\u002FPRMTOP\u002FPSF) + trajectory (DCD\u002FXTC\u002FTRR\u002FNetCDF\u002FH5)\n- Python 3.9+, conda-forge build recommended\n\nCheck before installing — inside a pixi\u002Fconda env mdtraj is usually present:\n\n```bash\npython3 -c \"import mdtraj\" 2>\u002Fdev\u002Fnull || conda install -c conda-forge mdtraj numpy pandas matplotlib\n```\n\n## Quick Start\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"traj.xtc\", top=\"topology.pdb\")\nca = traj.topology.select(\"name CA\")\ntraj.superpose(traj, frame=0, atom_indices=ca)\n\nrmsd_ang = md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0  # nm -> Å\nprint(f\"Frames: {traj.n_frames}  RMSD: {rmsd_ang.min():.2f}–{rmsd_ang.max():.2f} Å\")\n```\n\n## Core API\n\n### Module 1: Trajectory I\u002FO\n\nLoad whole or streamed. Format auto-detected from extension.\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\n\n# Stream large trajectories — avoids OOM\nfor chunk in md.iterload(\"rep1.xtc\", top=\"protein.pdb\", chunk=500):\n    rmsd_chunk = md.rmsd(chunk, chunk, frame=0)\n\n# Save subset\nca = traj.topology.select(\"name CA\")\ntraj.atom_slice(ca).save_dcd(\"ca_only.dcd\")\n```\n\nSelecting atoms and slicing frames:\n\n```python\nbackbone = traj.topology.select(\"backbone\")\nchain_a  = traj.topology.select(\"chainid 0\")\n\nfirst_ns      = traj[:1000]\nevery_10th    = traj[::10]\nlast_half_bb  = traj[traj.n_frames \u002F\u002F 2:].atom_slice(backbone)\n```\n\n### Module 2: RMSD, Rg, RMSF\n\n`md.rmsd` superposes internally; RMSF you compute manually after explicit superpose.\n\n```python\nimport mdtraj as md, numpy as np\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\nca = traj.topology.select(\"name CA\")\n\nrmsd_ang = md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0    # Å\nrg_ang   = md.compute_rg(traj) * 10.0                              # Å\ntime_ns  = traj.time \u002F 1000.0\nprint(f\"\u003CRMSD>={rmsd_ang.mean():.2f} Å,  \u003CRg>={rg_ang.mean():.2f} Å\")\n```\n\n```python\n# Per-CA RMSF — average-structure reference\nca_traj = traj.atom_slice(ca)\nca_traj.superpose(ca_traj, frame=0)\ndiff     = ca_traj.xyz - ca_traj.xyz.mean(axis=0)\nrmsf_ang = np.sqrt((diff ** 2).sum(axis=2).mean(axis=0)) * 10.0\nres_ids  = [a.residue.resSeq for a in ca_traj.topology.atoms]\nprint(f\"Max RMSF: residue {res_ids[np.argmax(rmsf_ang)]} = {rmsf_ang.max():.2f} Å\")\n```\n\n### Module 3: Contacts and Distance Maps\n\nThreshold distances to get contact frequency.\n\n```python\nimport mdtraj as md, numpy as np\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\ndistances_nm, pairs = md.compute_contacts(traj, contacts=\"all\", scheme=\"closest-heavy\")\n# distances_nm: (n_frames, n_pairs);  pairs: (n_pairs, 2) of residue indices\n\ncontact_freq = (distances_nm \u003C 0.5).mean(axis=0)                  # 5 Å cutoff\nn_res    = traj.n_residues\nfreq_map = np.zeros((n_res, n_res))\nfor (i, j), f in zip(pairs, contact_freq):\n    freq_map[i, j] = freq_map[j, i] = f\nprint(f\"Persistent contacts (>0.8): {(contact_freq > 0.8).sum()}\")\n```\n\n### Module 4: Torsions (Ramachandran)\n\nphi\u002Fpsi returned in radians; intersect on residue since first residue has no phi and last has no psi.\n\n```python\nimport mdtraj as md, numpy as np\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\nphi_ix, phi_rad = md.compute_phi(traj)\npsi_ix, psi_rad = md.compute_psi(traj)\n\ndef res_of(indices): return np.array([traj.topology.atom(ix[1]).residue.index for ix in indices])\nphi_res, psi_res = res_of(phi_ix), res_of(psi_ix)\ncommon  = np.intersect1d(phi_res, psi_res)\nphi_deg = np.degrees(phi_rad[:, np.isin(phi_res, common)])\npsi_deg = np.degrees(psi_rad[:, np.isin(psi_res, common)])\n```\n\nFilter to Gly \u002F Pro residues:\n\n```python\nres_names = [traj.topology.residue(r).name for r in common]\ngly_cols  = [i for i, n in enumerate(res_names) if n == \"GLY\"]\npro_cols  = [i for i, n in enumerate(res_names) if n == \"PRO\"]\nphi_gly, psi_gly = phi_deg[:, gly_cols].ravel(), psi_deg[:, gly_cols].ravel()\nphi_pro, psi_pro = phi_deg[:, pro_cols].ravel(), psi_deg[:, pro_cols].ravel()\n```\n\n### Module 5: DSSP Secondary Structure (8-state)\n\n`md.compute_dssp(traj, simplified=False)` returns `(n_frames, n_residues)` of one-character codes:\n\n| Code | Meaning            |\n|------|--------------------|\n| `H`  | alpha-helix        |\n| `B`  | beta-bridge        |\n| `E`  | beta-sheet         |\n| `G`  | 3_10-helix         |\n| `I`  | pi-helix           |\n| `T`  | turn               |\n| `S`  | bend               |\n| ` ` (space) or `C` | coil |\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\ndssp = md.compute_dssp(traj, simplified=False)\ndssp[dssp == \" \"] = \"C\"\nprint(f\"DSSP grid: {dssp.shape}  unique codes: {set(dssp.flatten())}\")\n```\n\n### Module 6: Hydrogen Bonds and SASA\n\n```python\nimport mdtraj as md\nimport pandas as pd\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\n\n# Baker–Hubbard: returns (n_hbonds, 3) of [donor, H, acceptor] atom indices\nhbonds = md.baker_hubbard(traj, freq=0.5, periodic=False)\nlabel  = lambda a: f\"{traj.topology.atom(a).residue}-{traj.topology.atom(a).name}\"\nhbonds_df = pd.DataFrame({\"donor\": [label(d) for d, _, _ in hbonds],\n                         \"acceptor\": [label(a) for _, _, a in hbonds]})\n\n# SASA in nm^2 per residue per frame\nsasa_nm2 = md.shrake_rupley(traj, mode=\"residue\")\ntotal_ang2 = sasa_nm2.sum(axis=1) * 100.0                # nm^2 -> Å^2\nprint(f\"Persistent H-bonds: {len(hbonds_df)},  \u003CSASA>: {total_ang2.mean():.0f} Å²\")\n```\n\n## Key Concepts\n\n### Units (nm, ps, radians)\n\n`traj.xyz` is in nm, `traj.time` in ps, torsions in radians. Convert before plotting:\n\n```python\nimport numpy as np\nxyz_ang  = traj.xyz * 10.0\ntime_ns  = traj.time \u002F 1000.0\nphi_deg  = np.degrees(phi_rad)\n```\n\n### Pair indices vs `resSeq`\n\n`md.compute_contacts(..., contacts=\"all\")` returns **0-based residue indices** (contiguous across chains), not PDB `resSeq`. Reshape into `(n_res, n_res)` before heatmaps. Map back via `traj.topology.residue(i).resSeq` only when labeling.\n\n### 8-state vs simplified DSSP\n\n`simplified=False` → 8 states. `simplified=True` → 3 states (H\u002FE\u002FC), which loses 3_10 (G), pi-helix (I), beta-bridge (B), bend (S), turn (T).\n\n## Common Workflows\n\n### Workflow 1: Multi-Replicate Stability + Flexibility + Contacts + Ramachandran + DSSP\n\n**Goal**: structural-analysis report for three MD replicates — RMSD\u002FRg over time, per-residue RMSF, residue contact frequency map (rep1), Ramachandran general + Gly + Pro (rep1), DSSP 8-state time series (rep1). Plots use matplotlib defaults; the consumer picks palette downstream.\n\n```python\nimport mdtraj as md, numpy as np, matplotlib.pyplot as plt\nfrom pathlib import Path\n\nreplicas = {\"rep1\": \"rep1.xtc\", \"rep2\": \"rep2.xtc\", \"rep3\": \"rep3.xtc\"}\ntopology = \"protein.pdb\"\noutdir = Path(\"figures\"); outdir.mkdir(exist_ok=True)\n\ntrajs = {name: md.load(p, top=topology) for name, p in replicas.items()}\nca    = next(iter(trajs.values())).topology.select(\"name CA\")\n\n# 1. RMSD vs time + Rg (Å) for all replicates\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\nfor name, traj in trajs.items():\n    traj.superpose(traj, frame=0, atom_indices=ca)\n    ax1.plot(traj.time \u002F 1000.0, md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0, lw=1, label=name)\n    ax2.plot(traj.time \u002F 1000.0, md.compute_rg(traj) * 10.0, lw=1, label=name)\nax1.set(xlabel=\"Time (ns)\", ylabel=\"RMSD (Å)\", title=\"Backbone RMSD\")\nax2.set(xlabel=\"Time (ns)\", ylabel=\"Rg (Å)\",   title=\"Radius of gyration\")\nfor ax in (ax1, ax2): ax.legend(frameon=False)\nfig.tight_layout(); fig.savefig(outdir \u002F \"01_rmsd_rg.png\"); plt.close(fig)\n\n# 2. Per-residue RMSF (Å) across replicates\nfig, ax = plt.subplots(figsize=(10, 4))\nfor name, traj in trajs.items():\n    ct = traj.atom_slice(ca); ct.superpose(ct, frame=0)\n    rmsf = np.sqrt(((ct.xyz - ct.xyz.mean(axis=0)) ** 2).sum(axis=2).mean(axis=0)) * 10.0\n    ax.plot([a.residue.resSeq for a in ct.topology.atoms], rmsf, lw=1, label=name)\nax.set(xlabel=\"Residue\", ylabel=\"RMSF (Å)\", title=\"Per-residue flexibility\")\nax.legend(frameon=False); fig.tight_layout()\nfig.savefig(outdir \u002F \"02_rmsf.png\"); plt.close(fig)\n\n# 3. Contact frequency map (rep1, 5 Å cutoff)\nrep1 = trajs[\"rep1\"]\ndist_nm, pairs = md.compute_contacts(rep1, contacts=\"all\", scheme=\"closest-heavy\")\nfreq = (dist_nm \u003C 0.5).mean(axis=0)\nfreq_map = np.zeros((rep1.n_residues, rep1.n_residues))\nfor (i, j), f in zip(pairs, freq):\n    freq_map[i, j] = freq_map[j, i] = f\nnp.fill_diagonal(freq_map, 1.0)\nfig, ax = plt.subplots(figsize=(6, 5))\nim = ax.imshow(freq_map, vmin=0, vmax=1, origin=\"lower\")\nax.set(xlabel=\"Residue\", ylabel=\"Residue\", title=\"Contact frequency (rep1)\")\nfig.colorbar(im, ax=ax, label=\"Fraction of frames in contact\")\nfig.tight_layout(); fig.savefig(outdir \u002F \"03_contact_map.png\"); plt.close(fig)\n\n# 4. Ramachandran (rep1) — phi\u002Fpsi 2D density\nphi_ix, phi_rad = md.compute_phi(rep1)\npsi_ix, psi_rad = md.compute_psi(rep1)\ndef res_of(ix, t): return np.array([t.topology.atom(i[1]).residue.index for i in ix])\nphi_res, psi_res = res_of(phi_ix, rep1), res_of(psi_ix, rep1)\ncommon = np.intersect1d(phi_res, psi_res)\nphi_deg = np.degrees(phi_rad[:, np.isin(phi_res, common)]).ravel()\npsi_deg = np.degrees(psi_rad[:, np.isin(psi_res, common)]).ravel()\nH, _, _ = np.histogram2d(phi_deg, psi_deg, bins=72, range=[[-180, 180], [-180, 180]])\nfig, ax = plt.subplots(figsize=(5, 5))\nax.imshow(H.T, origin=\"lower\", extent=[-180, 180, -180, 180], aspect=\"equal\")\nax.set(xlabel=r\"$\\phi$ (°)\", ylabel=r\"$\\psi$ (°)\", title=\"Ramachandran (rep1)\")\nfig.tight_layout(); fig.savefig(outdir \u002F \"04_ramachandran_all.png\"); plt.close(fig)\n\n# 5. Glycine + proline Ramachandran\nres_names = [rep1.topology.residue(r).name for r in common]\nfor label, cols, fname in [(\"Glycine\", [i for i, n in enumerate(res_names) if n == \"GLY\"], \"05_rama_gly.png\"),\n                           (\"Proline\", [i for i, n in enumerate(res_names) if n == \"PRO\"], \"06_rama_pro.png\")]:\n    if not cols: continue\n    phi = np.degrees(phi_rad[:, cols]).ravel()\n    psi = np.degrees(psi_rad[:, cols]).ravel()\n    H, _, _ = np.histogram2d(phi, psi, bins=60, range=[[-180, 180], [-180, 180]])\n    fig, ax = plt.subplots(figsize=(5, 5))\n    ax.imshow(H.T, origin=\"lower\", extent=[-180, 180, -180, 180], aspect=\"equal\")\n    ax.set(xlabel=r\"$\\phi$ (°)\", ylabel=r\"$\\psi$ (°)\", title=f\"{label} Ramachandran (rep1)\")\n    fig.tight_layout(); fig.savefig(outdir \u002F fname); plt.close(fig)\n\n# 6. DSSP 8-state time series (rep1)\ndssp = md.compute_dssp(rep1, simplified=False); dssp[dssp == \" \"] = \"C\"\ncodes_order = [\"C\", \"E\", \"B\", \"S\", \"T\", \"H\", \"I\", \"G\"]\ncode_to_int = {c: i for i, c in enumerate(codes_order)}\ndssp_int = np.vectorize(lambda c: code_to_int.get(c, 0))(dssp)\nfig, ax = plt.subplots(figsize=(10, 5))\nax.imshow(dssp_int.T, aspect=\"auto\", origin=\"lower\", interpolation=\"nearest\",\n          extent=[rep1.time[0] \u002F 1000.0, rep1.time[-1] \u002F 1000.0, 0, rep1.n_residues])\nax.set(xlabel=\"Time (ns)\", ylabel=\"Residue\", title=\"DSSP 8-state (rep1)\")\nfig.tight_layout(); fig.savefig(outdir \u002F \"07_dssp_8state.png\"); plt.close(fig)\n\n# Dump DSSP code mapping so downstream code can pick its own legend\u002Fpalette\nnp.savez(outdir \u002F \"07_dssp_8state.npz\", dssp=dssp, dssp_int=dssp_int, codes_order=codes_order)\nprint(\"All figures written to figures\u002F\")\n```\n\n### Workflow 2: H-Bond Persistence + SASA Across Replicates\n\n**Goal**: persistent hydrogen bonds (≥50% of frames) and total SASA time series per replicate.\n\n```python\nimport mdtraj as md, numpy as np, pandas as pd\n\nreplicas = {\"rep1\": \"rep1.xtc\", \"rep2\": \"rep2.xtc\", \"rep3\": \"rep3.xtc\"}\ntop = \"protein.pdb\"\nrows = []\nfor name, p in replicas.items():\n    t = md.load(p, top=top)\n    hbonds = md.baker_hubbard(t, freq=0.5, periodic=False)\n    sasa_ang2 = (md.shrake_rupley(t, mode=\"residue\").sum(axis=1) * 100.0)\n    rows.append({\"replica\": name, \"n_persistent_hbonds\": len(hbonds),\n                 \"sasa_mean_ang2\": sasa_ang2.mean(), \"sasa_std_ang2\": sasa_ang2.std()})\nprint(pd.DataFrame(rows).to_string(index=False))\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `chunk` (`md.iterload`) | I\u002FO | `100` | `100`-`5000` | Frames per stream chunk; trade speed vs RAM |\n| `atom_indices` (`md.rmsd`) | Stability | `None` | array of ints | Restrict superposition + RMSD (e.g., CA only) |\n| `frame` (`md.rmsd`) | Stability | `0` | `0`-`n_frames-1` | Reference frame |\n| `contacts` (`md.compute_contacts`) | Contacts | `\"all\"` | `\"all\"`, `[(i,j),...]` | All residue pairs or custom list |\n| `scheme` (`md.compute_contacts`) | Contacts | `\"closest-heavy\"` | `\"ca\"`, `\"closest\"`, `\"closest-heavy\"`, `\"sidechain\"`, `\"sidechain-heavy\"` | Atom subset for inter-residue distance |\n| `cutoff` (contact threshold, user-set) | Contacts | `0.5` nm | `0.4`-`0.8` nm | In-contact distance (5 Å for CA, 4 Å for closest-heavy) |\n| `simplified` (`md.compute_dssp`) | DSSP | `True` | `True`\u002F`False` | `False` → 8-state codes |\n| `freq` (`md.baker_hubbard`) | H-bonds | `0.1` | `0.0`-`1.0` | Min frame fraction to report |\n| `mode` (`md.shrake_rupley`) | SASA | `\"atom\"` | `\"atom\"`, `\"residue\"` | Per-atom or summed per residue |\n| `probe_radius` (`md.shrake_rupley`) | SASA | `0.14` nm | `0.12`-`0.20` nm | Solvent probe (1.4 Å standard) |\n| `periodic` (geometry funcs) | Geometry | `True` | bool | Minimum-image convention if box info present |\n\n## Best Practices\n\n1. **Convert units before plotting** — nm → Å (×10), ps → ns (÷1000), rad → deg (`np.degrees`). #1 cause of \"my RMSD is 10× too small\".\n2. **Superpose before RMSF** — `md.rmsd` superposes internally; RMSF doesn't. Without explicit `traj.superpose(...)`, RMSF picks up rigid-body motion.\n3. **`md.iterload` for big trajectories** — 1 µs at 1 ps\u002Fframe is millions of frames. Streaming avoids OOM.\n4. **`simplified=False` for fine-grained DSSP** — 3-state collapses 3_10 \u002F pi-helix \u002F bend transitions.\n5. **Pair indices, not `resSeq`** — `md.compute_contacts` returns 0-based contiguous indices. Map to `resSeq` only for labeling.\n6. **Strip waters early** — `traj.atom_slice(traj.topology.select(\"protein\"))` cuts memory\u002Ftime 5–20× on solvated systems.\n\n## Common Recipes\n\n### Recipe: Convert Trajectory Format\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"input.nc\", top=\"topology.parm7\")\ntraj.save_xtc(\"output.xtc\")\ntraj.save_pdb(\"output.pdb\")\nprint(f\"Converted {traj.n_frames} frames -> output.xtc\")\n```\n\n### Recipe: Per-Residue Mean ± SD RMSF Across Replicates\n\nEnsemble flexibility input for flexibility-aware docking or homology refinement.\n\n```python\nimport mdtraj as md, numpy as np, pandas as pd\n\npaths = {\"rep1\": \"rep1.xtc\", \"rep2\": \"rep2.xtc\", \"rep3\": \"rep3.xtc\"}\ntop = \"protein.pdb\"\nrmsf_by_rep = {}\nfor name, p in paths.items():\n    t  = md.load(p, top=top)\n    ct = t.atom_slice(t.topology.select(\"name CA\")); ct.superpose(ct, frame=0)\n    rmsf_by_rep[name] = np.sqrt(((ct.xyz - ct.xyz.mean(axis=0)) ** 2).sum(axis=2).mean(axis=0)) * 10.0\n\ndf = pd.DataFrame(rmsf_by_rep)\ndf[\"mean\"], df[\"std\"] = df.mean(axis=1), df.std(axis=1)\ndf.to_csv(\"rmsf_replicates.csv\", index_label=\"residue_index\")\n```\n\n### Recipe: Save Frames Above RMSD Threshold\n\nCurate \"open\" conformations for clustering or downstream analysis.\n\n```python\nimport mdtraj as md\n\ntraj = md.load(\"rep1.xtc\", top=\"protein.pdb\")\nca   = traj.topology.select(\"name CA\")\ntraj.superpose(traj, frame=0, atom_indices=ca)\nrmsd_ang = md.rmsd(traj, traj, frame=0, atom_indices=ca) * 10.0\n\nopen_state = traj[rmsd_ang > 4.0]\nopen_state.save_dcd(\"open_state.dcd\")\nprint(f\"Saved {open_state.n_frames}\u002F{traj.n_frames} frames\")\n```\n\n### Recipe: Cross-Replicate Helix Fraction\n\n```python\nimport mdtraj as md, numpy as np\n\npaths = [\"rep1.xtc\", \"rep2.xtc\", \"rep3.xtc\"]\nhelix_fracs = [(md.compute_dssp(md.load(p, top=\"protein.pdb\"), simplified=False) == \"H\").mean() for p in paths]\nprint(f\"α-helix per replicate: {[f'{h:.2f}' for h in helix_fracs]}\")\nprint(f\"Mean ± std: {np.mean(helix_fracs):.2f} ± {np.std(helix_fracs):.2f}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `RuntimeError: No topology` | XTC\u002FDCD\u002FTRR carry no topology | Pass `top=\"protein.pdb\"` (or `.prmtop`) to `md.load` |\n| RMSD 10× too small | mdtraj returns nm | Multiply by 10.0 |\n| RMSF spikes at termini | Intrinsic terminal flexibility, not a bug | Slice termini off or report explicitly |\n| DSSP returns only `H\u002FE\u002FC` | `simplified=True` default | Pass `simplified=False` |\n| Empty\u002F`' '` DSSP cells | Space = coil, not missing | `dssp[dssp == \" \"] = \"C\"` |\n| MemoryError on big trajectory | Whole trajectory in RAM | Switch to `md.iterload(..., chunk=500)` |\n| phi\u002Fpsi arrays differ in residue count | First residue has no phi; last has no psi | Intersect residue index sets before pairing |\n| Ramachandran off-center | Angles still in radians | Wrap with `np.degrees`; set `range=[[-180, 180], [-180, 180]]` |\n| `md.compute_contacts` returns NaN | Some pairs lack heavy atoms for `closest-heavy` (e.g., glycine sidechain) | Use `scheme=\"closest\"` or `\"ca\"`; drop NaN columns |\n| Contact map asymmetric | Only filled upper triangle | Mirror: `freq_map[j, i] = freq_map[i, j]` |\n| `traj.time` all zeros | Some writers leave time blank | Reconstruct: `traj.time = np.arange(traj.n_frames) * dt_ps` |\n\n## Related Skills\n\n- **mdanalysis-trajectory** — richer atom-selection grammar and AnalysisBase framework\n- **autodock-vina-docking** \u002F **smina-molecular-docking** — feed representative MD frames as docking targets\n- **chembl-database-bioactivity** — overlay ligand bioactivity on MD-derived flexibility maps\n\n## References\n\n- [mdtraj documentation](https:\u002F\u002Fmdtraj.org\u002F) — official docs, API reference, tutorials\n- [McGibbon et al. (2015)](https:\u002F\u002Fdoi.org\u002F10.1016\u002Fj.bpj.2015.08.015) — \"MDTraj: A Modern Open Library for the Analysis of Molecular Dynamics Trajectories\", *Biophys J*\n- [DSSP algorithm](https:\u002F\u002Fdoi.org\u002F10.1002\u002Fbip.360221211) — Kabsch & Sander (1983)\n- [Baker–Hubbard H-bond criterion](https:\u002F\u002Fdoi.org\u002F10.1016\u002FS0006-3495(99)77244-7) — Baker & Hubbard (1984)\n- [Shrake–Rupley SASA](https:\u002F\u002Fdoi.org\u002F10.1016\u002F0022-2836(73)90011-9) — Shrake & Rupley (1973)\n- [mdtraj GitHub](https:\u002F\u002Fgithub.com\u002Fmdtraj\u002Fmdtraj) — source, issues, examples\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fmdtraj-trajectory-analysis",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill mdtraj-trajectory-analysis",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill mdtraj-trajectory-analysis",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill mdtraj-trajectory-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fmdtraj-trajectory-analysis\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]