molecular-visualization-3dmol
3Dmol.js WebGL molecular visualization emitted as self-contained HTML. Render structures (PDB/SDF/XYZ/MOL2/cube) with stick, sphere, cartoon, line, and surface styles; animate trajectories with a frame-delay (interval, ms) control; and animate vibrational normal modes via vibrate() from per-atom dx/dy/dz displacements or from precomputed frames. Output standalone HTML that loads 3Dmol from a CDN, with optional play/pause and speed controls. Use for transition-state imaginary-mode animations, MD or reaction-path playback, docking poses, and orbital/density isosurfaces. For static 2D chemical structure drawings use rdkit-chemdraw-cdxml; for 2D statistical plots use matplotlib or plotly.
git clone --depth 1 https://github.com/jaechang-hits/SciAgent-Skills /tmp/molecular-visualization-3dmol && cp -r /tmp/molecular-visualization-3dmol/skills/data-visualization/molecular-visualization-3dmol ~/.claude/skills/molecular-visualization-3dmolSKILL.md
# 3Dmol.js molecular visualization
## Overview
3Dmol.js is a WebGL molecular viewer that runs entirely in the browser. This skill emits
**self-contained HTML** files that load 3Dmol from a CDN and render a structure, a trajectory,
or a vibrational mode — no server, no build step, no Python runtime to view. The bundled
`scripts/mol_viewer.py` generates that HTML from any `.xyz/.trj/.pdb/.sdf/.mol2/.cube` file;
the Core API below shows the underlying 3Dmol.js calls so you can hand-write or customize a
viewer.
## When to Use
- Animate a transition-state imaginary vibrational mode (from a mode trajectory or dx/dy/dz vectors)
- Play back a reaction path (IRC/NEB) or an MD trajectory with a speed control
- Show a protein–ligand docking pose with cartoon + ligand sticks + a binding-site surface
- Display an orbital or electron-density isosurface from a Gaussian `.cube` file
- Hand a colleague one HTML file that opens in any browser, no install
- Use **py3Dmol** instead for inline viewers inside a Jupyter notebook (same engine, Python API)
- Use **PyMOL/ChimeraX** instead for publication ray-traced stills or heavy structural editing
- Use **rdkit-chemdraw-cdxml** for 2D chemical structures, **plotly/matplotlib** for 2D plots
## Prerequisites
- **Viewing**: any modern browser with network access (the HTML pulls 3Dmol.js from a CDN)
- **Generator script**: `scripts/mol_viewer.py` — Python 3 standard library only, no install
- **Optional**: `pip install py3Dmol` for notebook use (wraps the same library)
No package is needed to produce or open the HTML. The generator lives in this skill's `scripts/`
folder (next to this SKILL.md). It can't be run in place from the skill directory, so use your
file tools to read `scripts/mol_viewer.py` and save it into your working directory before running.
## Quick Start
```bash
# animate a mode/trajectory file with play/pause + speed slider, in one call
python3 mol_viewer.py ts_imaginary_mode_000.trj --mode trajectory \
--title "TS mode" --subtitle "-621.8 cm-1" --out ts_mode.html
# static structure: python3 mol_viewer.py mol.xyz --out mol.html
```
## Core API
All snippets assume `<script src="https://3Dmol.org/build/3Dmol-min.js"></script>` is loaded
and a `<div id="v"></div>` exists.
### Create a viewer and load a structure
`createViewer` binds to a div; `addModel(data, format)` loads coordinates. Always `zoomTo()`
then `render()`. Supported `format`: `xyz`, `pdb`, `sdf`, `mol2`, `cube`, `cif`.
```javascript
const viewer = $3Dmol.createViewer("v", {backgroundColor: "white"});
viewer.addModel(xyzString, "xyz"); // coordinates as a string, not a URL
viewer.setStyle({}, {stick: {radius: 0.15}, sphere: {scale: 0.28}});
viewer.zoomTo();
viewer.render();
```
### Styles and coloring
`setStyle(selection, styleSpec)` — empty selection `{}` targets all atoms. Styles: `stick`,
`sphere`, `line`, `cross`, `cartoon`. Color by element (default), a scheme, or a fixed color.
```javascript
viewer.setStyle({}, {stick: {}, sphere: {scale: 0.25}}); // ball-and-stick
viewer.setStyle({elem: "C"}, {stick: {color: "gray"}}); // per-element override
viewer.setStyle({chain: "A"}, {cartoon: {color: "spectrum"}}); // protein ribbon
viewer.render();
```
### Animate a trajectory
Load every frame with `addModelsAsFrames`, then `animate`. **`interval` is the delay between
frames in milliseconds (larger = slower)** — do not use `step`, which skips frames and looks
jumpy. `loop: "backAndForth"` makes a one-way path oscillate; `reps: 0` loops forever.
```javascript
viewer.addModelsAsFrames(trjString, "xyz"); // multi-frame .trj or multi-model .xyz/.pdb
viewer.setStyle({}, {stick: {radius: 0.14}, sphere: {scale: 0.28}});
viewer.zoomTo();
viewer.render();
viewer.animate({loop: "backAndForth", interval: 120, reps: 0});
```
### Animate a vibrational normal mode
If a model's atoms carry displacement vectors (`dx, dy, dz` — extra columns on each XYZ line:
`elem x y z dx dy dz`), `model.vibrate(numFrames, amplitude, bothWays, arrowSpec)` builds the
oscillation frames. `bothWays: true` swings symmetrically about equilibrium; `arrowSpec` draws
motion arrows.
```javascript
const m = viewer.addModel(modeXyz, "xyz"); // each atom line: elem x y z dx dy dz
m.vibrate(10, 1.0, true, {radius: 0.08, color: "black"}); // 10 frames, full amplitude, arrows
viewer.setStyle({}, {stick: {radius: 0.14}, sphere: {scale: 0.28}});
viewer.zoomTo();
viewer.render();
viewer.animate({loop: "backAndForth", interval: 120, reps: 0});
```
If you only have a precomputed frame trajectory (e.g. pysisyphus `ts_imaginary_mode_000.trj`),
use the trajectory path above instead — no `dx/dy/dz` needed.
### Surfaces and volumetric isosurfaces
`addSurface(type, style, atomsel)` builds a molecular surface (`VDW`, `SAS`, `SES`, `MS`).
For an orbital/density isosurface, load the `.cube` and call `addVolumetricData`.
```javascript
viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity: 0.75, color: "lightblue"}, {chain: "A"});
// isosurface from a Gaussian cube (positive and negative lobes):
viewer.addVolumetricData(cubeString, "cube", {isoval: 0.02, color: "blue", opacity: 0.85});
viewer.addVolumetricData(cubeString, "cube", {isoval: -0.02, color: "red", opacity: 0.85});
viewer.render();
```
### Labels and interactive speed control
`addLabel(text, spec)` annotates. For animations, a slider bound to `interval` (restarting via
`stopAnimate()` + `animate()`) lets the viewer set the speed — the fix for "sometimes too fast".
```javascript
viewer.addLabel("TS", {position: {x: 0, y: 0, z: 0}, backgroundColor: "black", fontSize: 14});
let interval = 140;
const play = () => viewer.animate({loop: "backAndForth", interval});
document.getElementById("spd").oninput = e => { interval = +e.target.value; viewer.stopAnimate(); play(); };
play();
```
## Key Concepts
**`interval` vs `step`.** `interval` (ms) sets playback speed; every frame is shown. `step`
plays every Nth frame — it skipsAnnotated matrices for single-cell genomics. Stores X with obs/var metadata, layers, embeddings (obsm/varm), graphs (obsp/varp), uns. Use for .h5ad/.zarr I/O, concatenation, scverse integration. For analysis use scanpy; for probabilistic models use scvi-tools.
GRN inference from expression via GRNBoost2 (gradient boosting) or GENIE3 (Random Forest). Load matrix, filter by TFs, infer TF-target-importance links, save network. Dask-parallelized to single-cell scale. Core SCENIC component.
Query ARCHS4 REST API for uniformly processed RNA-seq expression, tissue patterns, co-expression across 1M+ human/mouse samples. Retrieve z-scores, co-expressed genes, samples by metadata, HDF5 matrices. For variant population genetics use gnomad-database; for pathway enrichment use gget-genomic-databases (Enrichr).
Annotate bacterial and archaeal genomes and plasmids with Bakta's Prodigal/HMM/diamond pipeline. Identifies CDS, ncRNA, tRNA, rRNA, tmRNA, sORFs, CRISPR arrays, oriC/oriV/oriT, and gaps against a curated UniRef-derived database. Produces NCBI-compatible GFF3, GenBank, EMBL, JSON, FASTA, TSV, and a circular genome plot. Use Prokka for legacy pipelines or non-bacterial kingdoms; PGAP for NCBI GenBank submission.
CLI for VCF/BCF: filter, merge, annotate, query, normalize, compute stats. Core post-variant-calling: quality filtering, multi-sample merging, rsID annotation, genotype extraction. Samtools companion in HTSlib. Use GATK for complex indel realignment during calling; use VCFtools for population genetics stats.
Genomic interval ops on BED/BAM/GFF/VCF. Find overlaps, merge intervals, compute coverage, extract FASTA, find nearest features. Core for ChIP-seq peak annotation, region filtering, genome arithmetic. Use tabix for indexed single-region queries; use deeptools for normalized bigWig coverage.
Molecular biology toolkit: sequence manipulation, FASTA/GenBank/PDB I/O, NCBI Entrez, BLAST automation, pairwise/MSA alignment, Bio.PDB, phylogenetic trees. Use for batch processing, custom pipelines, format conversion, PubMed/GenBank queries. For quick gene lookups use gget; for multi-service REST APIs use bioservices.
Biopython sequence analysis: parse FASTA/FASTQ/GenBank/GFF (SeqIO), NCBI Entrez (esearch/efetch/elink), remote/local BLAST, pairwise/MSA alignment (PairwiseAligner, MUSCLE/ClustalW), phylogenetic trees (Phylo). Use for gene family studies, phylogenomics, comparative genomics, NCBI pipelines. For PCR/restriction/cloning use biopython-molecular-biology; for SAM/BAM use pysam.