ProteinMotion
Documentation · API quick reference

API quick reference

The public Python API, parameters, and command-line tools.

On this page

Browse the reference manual for individual class and function pages, parameters, methods, and rendered examples.

This quick reference covers the public Python API in version 0.15.0. Import these names from proteinmotion, except Camera and Renderer, which are in their own modules.

ProteinScene#

python
ProteinScene(width=1920, height=1080, fps=30, background="#0b1220", msaa=4, supersampling=None)

Subclass ProteinScene and implement construct(). Scene is an alias.

Method Behavior
add(*proteins) Add proteins, density objects, highlights, text or callouts at the current timeline position
play(*animations, run_time=None, easing=None) Run actions concurrently; infer grouped duration or use one second
wait(duration=1.0) Hold the current scene
focus(target, run_time=1.5, margin=1.25, follow=True) Ease the camera to a protein or region
seek(time) Evaluate a time deterministically; supports backward seeks
render(output, codec="auto", bitrate="20M") Export an MP4 and return timing/adapter metadata
render_frame(time=0, output=None, renderer=None) Render one RGBA frame; optionally save an image
preview(renderer=None, look=None) Open native or Studio preview using scene defaults

Animations in separate calls run sequentially. Concurrent writers to the same object property are rejected. Direct setters are captured at the current authoring time; play() interpolates changes. See readable authoring for grouped timing, style reuse, selection algebra, and renderer settings.

Protein#

python
Protein.from_file(path, chains="A", secondary="auto", assembly=None)
Protein.fetch("2DN1", assembly="1")
Protein.from_trajectory(trajectory)
Protein.build("AEAAAKEAAAKEAAAKA", "helix", hydrogens=False)

from_file reads PDB/mmCIF and keeps all matching models as protein.trajectory. The default selection excludes waters and hydrogens; other hetero atoms are retained. Multi-model inputs must have consistent selected atom identities/order. Files without helix or sheet records are assigned with DSSP (secondary="dssp" always, "file" never). assembly="1" builds a biological assembly; generated copies get new chain IDs. Protein.fetch downloads a PDB entry or an AF-… AlphaFold DB model once into ~/.cache/proteinmotion and passes other options to from_file. Protein.build makes an ideal peptide from one-letter codes and a conformation or phi/psi/omega angles in degrees. Torsions guide.

Method/property Behavior
cartoon(color="secondary") Helices, sheet arrows, and tubular coils
ribbon(color="rainbow", width=1.05) Continuous ribbon representation
ball_and_stick(atom_scale=0.30, bond_radius=0.14) Element-colored atoms and geometric bonds
surface(kind="ses", probe_radius=1.4, resolution=0.7, update="rebuild") Voxel molecular surface; see surface options
set_color(color) / color_residues(color, chain=None, residues=None) Atom/residue tint across every representation; None clears it
set_opacity(value) / set_residue_opacity(value, chain=None, residues=None) Global or selected opacity in [0, 1]
show_atoms() / hide_atoms() Draw every atom as ball-and-stick over the cartoon, or remove all such atoms, including the default ligands and ions
hydrogen_bonds(**options) / electrostatics(charges="formal", **options) Live interaction analyses
center() / shift(vector) / rotate(angle, axis) / scale(factor) Configure the molecular transform
positions Current interpolated coordinates in the protein's local frame
set_positions(xyz) Set coordinates with unchanged topology
copy() Make an independently animated protein
with_secondary_structure(assignments) One H/E/C character per residue, or "dssp", before add()
secondary_structure / set_secondary_structure(codes) / assign_secondary_structure() Current H/E/C string; set it at any authoring time, or assign it with DSSP
torsions(chain=None, residues=None) TorsionAngles: φ, ψ, ω, χ1–χ5 in degrees per residue
set_torsions(conformation=None, anchor="center", **angles) Change torsions immediately; see SetTorsions
animate Build fluent transform or opacity animations

Coordinates/radii are ångströms; angles are radians, except torsion angles, which are degrees. Cartoon/ribbon/surface color accepts secondary, rainbow, chain, hydropathy, or #RRGGBB. Ball-and-stick uses element colors as its base palette. Residue overrides apply to every representation.

Cartoons and ribbons draw ligands, ions, and loaded waters (atoms outside the traced chains) as ball-and-stick. Ligands, ions, and side chains.

NucleicAcid and BaseStyle#

NucleicAcid.from_file(path).cartoon(bases="slabs", color="base") loads DNA or RNA. Use Protein.from_file() for mixed protein–nucleic acid complexes. Both classes support nucleotide backbones, surfaces, residue styling, labels, and trajectories.

cartoon(bases=...) accepts slabs, rings, sticks, ladder, or none. Set initial dimensions with set_bases(style, backbone_radius=0.38, base_thickness=0.36, base_radius=0.16). Animate the style with BaseStyle(molecule, "rings"), or combine it with Representation(molecule, "cartoon", bases="rings"). Guide and rendered examples.

Region and RegionHighlight#

python
region = protein.select(chain="A", residues=(23, 34), atoms="CA")
ligand = protein.select(resname="HEM")
metals = protein.select(ions=True)
pocket = protein.select(within=4.0, of=ligand)
region = Region(protein, atom_indices)
combined = region_a | region_b
marker = region.highlight(style="box", color="#f2ba67", padding=1.5)

Selections use PDB author residue numbers. Tuples are inclusive ranges; lists select explicit numbers. The chain, atom-name, and resname filters also accept lists. ligands=True, ions=True, and water=True select residues outside the traced chains and combine with each other. within=r, of=region selects whole residues with an atom within r Å of region, excluding that region's own residues. Other filters must all match. Empty selections raise an error. Explicit atom indices are zero-based.

region.atom_indices, region.residue_indices, region.positions, and region.world_positions expose the selected atoms/residues and current coordinates. Indices are read-only. Unions require the same parent protein.

region.torsions(), region.set_torsions(**angles), and region.torsion_marker("phi", **options) measure, change, and mark torsions of the selection.

region.set_color(color), region.set_opacity(value) and their .animate equivalents style the selection. region.show_atoms() and region.hide_atoms() draw or remove the selection as ball-and-stick over a cartoon. region.side_chains() returns the side chains of its amino acids, including Cα. region.distance_to(other, **options) creates a distance ruler. Styling and surface guide.

Highlight styles are sphere, box, and atoms. All accept color, opacity, and padding; boxes also use line_width. Highlights follow their parent coordinates and transforms. Animate opacity on the highlight and transforms on its parent. More examples.

Text and annotations#

Import Text, Callout, ResidueLabel, ResidueLabels, Write, and Unwrite from proteinmotion.

python
Text(text, font_size=36, font="regular", color="#edf3fc",
     position=(0.06, 0.08), align="left", line_spacing=1.3,
     ligatures=True, opacity=1)
Callout(region, text, subtitle=None, position=(0.73, 0.25),
        font_size=32, font="semibold", color="#edf3fc",
        subtitle_color="#a3b3c7", line_color=None, line_width=1.5,
        tip="dot", clamp=True, follow_opacity=True, opacity=1)
ResidueLabel(region, text=None, offset=(24, -36),
             format="three_letter", include_chain=True, font_size=26, **callout_options)
ResidueLabels(region, offsets=None, avoid_overlap=True, **label_options)
Write(target, lag_ratio=None, stroke_width=1.5, reverse=False, rate_func=linear)
Unwrite(target, lag_ratio=None, stroke_width=1.5, reverse=False, rate_func=linear)

Constructor options after the positional arguments are keyword-only. Text fonts are bundled regular / semibold or a TTF/OTF path. Font sizes, outline widths, and label offsets use pixels at 1080p height. Positions are normalized viewport coordinates with (0, 0) at the top-left. Text.to_corner("UL", buff=0.06) supports all four corners.

Convenience methods: region.callout(text, **options), region.label(text=None, **options) for one residue, and protein.label_residues(chain=None, residues=None, **options). Automatic names use PDB author numbers and insertion codes. Group offsets accept residue-number or (chain, number, insertion_code) keys.

Annotations support set_opacity() and .animate.set_opacity(). Text/callouts support move_to(), shift() and animated equivalents. A single ResidueLabel supports set_offset() and .animate.set_offset() instead. Write and Unwrite operate on whole annotation objects; configure their child text styles before adding them to a scene. Full guide and runnable example.

Distance and interaction analyses#

python
Distance(start_region, end_region, mode="3d", anchor="ca", space="model",
         color="#f2ba67", label_color=None, font_size=27, precision=1,
         unit="Å", prefix="", show_distance=True, style="dashed",
         line_width=1.7, radius=0.09, dash_count=12, dash_ratio=0.6,
         follow_opacity=True, opacity=1)
HydrogenBonds(protein, donors=None, acceptors=None, max_distance=3.5,
              min_angle=150, hydrogens="auto", donor_h_cutoff=1.3)
Electrostatics(protein, charges="formal", dielectric=80, screening_length=8,
               cutoff=12, min_energy=0.05,
               exclude_same_residue=True, exclude_bonded=True)
Electrostatics.from_pqr(protein, path, allow_extra=False, **options)
charges_from_pqr(protein, path, allow_extra=False)
InteractionHighlight(analysis, mode="3d", color=None,
                     attractive_color="#58b8fa", repulsive_color="#ef7484",
                     show_distances=False, max_pairs=100, region=None,
                     endpoints="donor_acceptor",
                     **distance_options)

Options after required positional arguments (and charges) are keyword-only. Distance.distance evaluates the current distance between endpoints; labels convert to unit="nm" when requested. Analyses expose .pairs and .highlight(**options). Immutable Interaction records contain atom indices, distance, kind, optional angle/energy/hydrogen and an inferred_hydrogen flag; .as_dict() exports one record.

HydrogenBonds.hydrogen_position(pair) returns the current H coordinates. For hydrogen bonds, endpoints="hydrogen_acceptor" draws and optionally labels H···A instead of the default D···A. Alpha-helix diagnostic.

Electrostatics also provides .pair_energy(a, b) in kcal/mol and .potential(points, softening=1.0, chunk_size=2048) in kcal/mol/e. Charges must match selected atom order or exact PQR identities. Formal side-chain charges and virtual backbone H are illustrative approximations. See distance units, methods, import rules and limitations.

Camera#

python
self.camera.frame(protein, margin=1.25, aspect=self.width / self.height)
self.camera.focus(region, follow=True, aspect=self.width / self.height)
self.play(self.camera.animate.orbit(theta=0.5, phi=0.1), run_time=2)
self.play(self.camera.animate.zoom(1.3), run_time=1)

self.camera.animate.depth_cue(0.7) eases the distance fog and combines with orbit and zoom. camera.look_along(axis, protein=None) turns the view to look down an axis, such as a domain_motion axis. camera.clearest_view(region) returns the (theta, phi) with the fewest atoms in front of a region. camera.cutaway_geometry() reports the open cutaway's center, radii, tunnel depth, and axis.

frame and focus are immediate setup methods. Use self.focus(...), Focus(...), or camera.animate.focus(...) for timeline animation. theta, phi, and fov are radians; distance and target control camera position. depth_cue=0 disables distance fog. Region tracking follows the center with fixed zoom.

Animations#

Constructor Purpose
Write(annotation) / Unwrite(annotation) Draw or erase text and callout lines
Rotate(protein, angle, axis=(0, 1, 0)) Rotate around the molecular centroid
FadeIn(target) / FadeOut(target) Animate opacity with smooth transparency
Representation(protein, name) Transition to cartoon, ribbon, ball_and_stick, or surface
Colorize(target, color, residue_delay=0, reverse=False, easing="smooth") Fade a protein/region to a tint, or None to restore its palette
SetOpacity(target, opacity, residue_delay=0, reverse=False, easing="smooth") Fade selected atoms/residues, with optional N-to-C staggering
ShowAtoms(target, ...) / HideAtoms(target, ...) Draw or remove atoms as ball-and-stick over a cartoon, ribbon, or surface
ShowSideChains(target, ...) / HideSideChains(target, ...) Grow or remove amino acid side chains, joined to the cartoon at Cα
Reveal(camera, region, window=1.35, shape="cone") / Conceal(camera) Open or close a cutaway onto a hidden selection; shape="tunnel" marks depth every 5 Å. Guide
Thread(protein, camera=None, easing=None, ...) / Unthread(...) Thread the actual cartoon or atoms and bonds into view with eased travel, or reverse the motion. Surface is unsupported; mode="wire" retains the original effect. Guide
Morph(protein, target, align=True) Morph matching atom topology or ordered coordinate arrays
Deform(protein, function) Transform coordinates through a callable
Focus(camera, region, margin=1.25, aspect=16/9, follow=True) Animate camera focus; evaluate after molecular motion
PlayTrajectory(protein, trajectory=None, start=0, end=None, state_easing=linear) Interpolate between trajectory models
StructureMorph(source, target, align=None, chains=None, fade_out=(0, 0.35), fade_in=(0.65, 1), style="source") Morph between two experimental structures of the same protein; residues follow screw paths and side chains turn through χ angles. Guide
BackboneMorph(source, target, match=..., residue_delay=0.025) Contact-guided morph between different proteins
SetTorsions(target, phi=None, psi=None, omega=None, chi1=None, …, conformation=None, anchor="center", path="allowed", stagger=None) Move torsions to values in degrees; atoms rotate about bonds, and the cartoon blends to the new DSSP assignment. Guide
RotateTorsions(target, chi1=120, …) Turn torsions by amounts in degrees, including full turns
SecondaryStructure(protein, assignments="dssp") Blend the cartoon to DSSP of the current coordinates, or to an H/E/C string

Default motion easing is quintic smooth. Trajectory playback uses a linear clip clock by default. state_easing changes the blend inside each adjacent model pair; rate_func changes progress through the whole clip. Built-ins include linear, smooth, ease_in_out_sine, and there_and_back.

Colorize, SetOpacity, and the atom animations accept residue_delay, reverse, and easing. They use a linear clip clock and their own easing for residue transitions. Disjoint selections may run together; run_time must exceed their total residue start delay. FadeIn/FadeOut target whole proteins or annotations; use SetOpacity for regions.

For BackboneMorph, use motion_easing for individual residue motion; its timeline must stay linear to preserve delays in seconds. See matching options and limitations.

Trajectory#

python
Trajectory(frames, topology=None, units="angstrom")
Trajectory.from_npy(path, topology=None, units="angstrom")
Trajectory.from_mdanalysis(topology_file, trajectory_file,
                          selection="protein", stride=1)
trajectory.aligned(reference=None, indices=None)
trajectory.frame(index)
len(trajectory)

Coordinates have shape (frames, atoms, 3). NumPy files are memory mapped; MDAnalysis files are read lazily. aligned() removes overall rigid motion with a proper fit on the requested atom indices. Preprocess periodic boundaries before loading. NMR and MD guide.

Contact matching#

python
match = match_backbones(source, target, max_contact_error=0.30,
                        search_seconds=15, max_candidates=6000)
match.save("correspondence.json")
match = ContactMatch.load("correspondence.json")
print(match.report)

match_structures(source, target, chains=None) pairs chains, residues, ligands, and atoms of two structures of one protein for StructureMorph. domain_motion(source, target, moving, fixed=None) returns the angle (degrees), axis, point, and translation of a domain's rigid motion between them.

ContactMatch.from_pairs(source, target, source_indices, target_indices) accepts zero-based topology residue indices in increasing order. DNA/RNA uses C1′ anchors; proteins use Cα. The search maximizes matched residue count under a contact-error limit, then minimizes error among equal-sized sets. Check the report to see whether the search completed and proved optimality.

Command line#

bash
proteinmotion --version
proteinmotion init my-movie
proteinmotion install-skill
proteinmotion doctor
proteinmotion render scene.py SceneName -o film.mp4 --fps 60
proteinmotion still scene.py SceneName -o frame.png --time 4.5
proteinmotion preview scene.py SceneName

init creates a starter scene and a 1UBQ structure in a new folder. install-skill copies the AI agent skill; --path selects its destination folder and --force replaces modified bundled files. The default destination is the Codex skills directory. All commands are also available through python -m proteinmotion.

Shared render/still/preview options: --width, --height, --fps, --msaa 1|4, --supersampling (1–4 for the native and Studio renderers, by default 2 up to 1920 × 1080; any value of at least 1 for EEVEE, by default 1.5). Rendering also accepts --codec and --bitrate. With EEVEE, chosen by --renderer eevee or by the scene class, --blender, --samples, and --supersampling replace those fields of the scene's own eevee options; other renderers ignore --blender and --samples. Preview controls: drag to orbit, wheel to zoom, Space to pause, arrows to seek, Home to rewind, R to reset the camera, Escape to close.

Numerical properties#

ResidueValues holds one value per topology residue. Load file B factors with ResidueValues.b_factors(protein), calculate aligned fluctuations with ResidueValues.rmsf(protein), or import measurements with ResidueValues.from_mapping(protein, values).

Presets bring their own scale: ResidueValues.hydropathy(protein, scale="kyte-doolittle"), ResidueValues.conservation(protein, alignment), and ResidueValues.plddt(protein, source=None). Matching scales are ColorScale.hydropathy(), .conservation(), .plddt(), .pae(), .distance(), and .difference(). ColorScale(..., boundaries=[...]) makes a banded scale.

protein.color_by(values, scale=ColorScale(0, 40), thickness=(0.6, 1.8)) sets initial colors and optional cartoon thickness. color_by("hydropathy") and color_by("plddt") use the presets. Use ColorByProperty inside play for an eased transition, including residue delays. ColorLegend displays the same scale. Guide and rendered output.

Plots and sequence tracks#

TimeSeriesPlot(times, values, protein=protein) follows the current trajectory state. Omit protein to follow scene seconds. TimeSeriesPlot.distance(first, second) measures centroid distance between two Regions over a trajectory and places the marker at the current measurement.

ContactMap(protein, selection=region) displays live backbone contacts (Cα for proteins, C4′ or P for nucleotides). SequenceTrack(protein, selection=region) displays the current residue colors. Both use viewport position and size. Guide and rendered output.

Heatmap(matrix_or_function, protein=None, rows=None, columns=None, scale=None, highlight=None) draws a matrix with a color bar. Heatmap.pae(protein, source) reads AlphaFold DB, ColabFold, and AlphaFold 3 PAE files; Heatmap.distances(protein, region=None, reference=None) shows live residue distances or their change. Guide.

RamachandranPlot(protein, region=None, highlight=None, background="general") plots live φ/ψ over favored and allowed regions. TorsionMarker(region, "phi") draws one torsion's bond, arc, and value. Guide.

Every plot, legend, and heatmap has with_panel(color="#0b1220", opacity=1), which draws a card behind it.

Density maps#

DensityMap.from_file(path) loads MRC/CCP4 grids, including compressed files. density.isosurface(level, units="sigma") makes a contour; density.slice("z", 0.5) makes a sampled plane. Add either to a scene and animate with shell.animate.set_level(...) or section.animate.set_slice(...).

Use density.crop(region, padding=3) for local views and follow=protein when the map and protein should share scene transforms. Guide and rendered output.

Readable authoring additions#

StudioLook provides lighting, material and effects recipes. Put renderer="studio" and look=StudioLook(...) on the scene class or pass them to its constructor. Preview, stills, movies and CLI share those settings. Derive looks with look.with_presets(...).

MolecularStyle stores a representation and options; TextStyle stores typography; TextGroup stacks caption text; AnimationGroup assigns actions separate durations and offsets. animation.during(seconds, delay=...) is the timing shorthand. Complete examples and migration notes.

SetOpacity(protein, value) now changes global opacity. Use scope="residues" to preserve legacy whole-protein per-atom behavior. TimeSeriesPlot.distance now defaults to the same backbone anchors as Distance; pass anchor="centroid" to preserve legacy plots.

View this page on GitHub