Core API¶
High-level Python API for xyzrender.
Typical usage in a Jupyter notebook:
from xyzrender import load, render, render_gif
mol = load("mol.xyz")
render(mol) # displays inline in Jupyter
render(mol, hy=True) # show all hydrogens
render(mol, atom_scale=1.5, bond_width=8)
render(mol, mo=True, iso=0.05) # MO surface (mol loaded from .cube)
render(mol, nci="grad.cube") # NCI surface
# Short-form path string (loads with defaults):
render("mol.xyz")
# Reuse a style config:
cfg = build_config("flat", atom_scale=1.5)
render(mol1, config=cfg)
render(mol2, config=cfg)
For GIFs use render_gif():
render_gif("mol.xyz", gif_rot="y")
render_gif("trajectory.xyz", gif_trj=True)
render_gif("ts.xyz", gif_ts=True)
- class xyzrender.api.EnsembleFrames(positions, colors, opacities, conformer_graphs=None, reference_idx=0)[source]¶
Bases:
objectPer-conformer data for an ensemble loaded with
load(ensemble=True).Kept separate from
Molecule.graph(which holds only the reference frame) so the graph always represents a single n_atoms structure regardless of ensemble size. Consumers (render, render_gif) build the merged multi- conformer graph lazily from these arrays.- positions¶
Stacked conformer positions, shape
(n_conformers, n_atoms, 3). All frames are RMSD-aligned onto the reference frame. Contiguous memory allows vectorised rotation across all conformers simultaneously (single matmul for GIF frames).
- colors¶
Resolved hex color string per conformer (
None= use CPK).
- opacities¶
Per-conformer opacity override (
None= fully opaque).
- conformer_graphs¶
Optional per-frame graphs for
rebuild=Trueensembles (topology can differ per frame).Nonemeans all frames share the reference topology.
- reference_idx¶
Index into positions / colors / opacities that is the reference.
- colors: list[str | None]¶
- conformer_graphs: list[Graph] | None = None¶
- opacities: list[float | None]¶
- positions: ndarray¶
- reference_idx: int = 0¶
- class xyzrender.api.Molecule(graph, cube_data=None, cell_data=None, oriented=False, ensemble=None)[source]¶
Bases:
objectContainer for a loaded molecular structure.
Obtain via
load(). Pass directly torender()orrender_gif()to avoid re-parsing the file.For ensemble molecules (
load(ensemble=True)),graphholds only the reference conformer (n_atoms nodes). The full per-conformer data lives inensemble; the merged multi-conformer graph is built lazily at render time.- copy()[source]¶
Deep-copy the parts that
render()must not mutate.Graph and cell_data are deep-copied; cube_data and ensemble frames are read-only after parsing and are shared. Encapsulates the contract from MEMORY.md (render must never mutate caller’s mol).
- Return type:
- cube_data: CubeData | None = None¶
- ensemble: EnsembleFrames | None = None¶
- graph: Graph¶
- property lattice: ndarray | None¶
Crystal lattice as a 3x3 numpy array, or
Noneif non-periodic.
- orient(*, tilt_degrees=None, priority_pairs=None, force=False, return_transform=False)[source]¶
PCA-orient atoms, lattice, and
graph['lattice']atomically.Idempotent: no-op when
self.orientedis True unlessforce=True. Atoms are written back centred at the origin (mean = 0). Ghost nodes (symbol == "*", NCI dummies) are excluded from the PCA fit so they don’t bias the orientation. Lattice direction vectors and the cell origin are rotated together and synced acrosscell_dataandgraph['lattice']/graph['lattice_origin'].When return_transform is True, returns
(rot, fit_centroid)so a caller (e.g. overlay setup) can mirror the same rigid transform onto a second molecule.- Return type:
tuple[ndarray,ndarray] |None
- oriented: bool = False¶
- to_xyz(path, title='')[source]¶
Write the molecule to an XYZ file.
If the molecule carries
cell_data(e.g. loaded withcell=Trueorcrystal=...), the file is written in extXYZ format with aLattice=header so it can be reloaded withload(..., cell=True). Ghost (periodic image) atoms are excluded.- Parameters:
path (
str|PathLike) – Output path — should end with.xyz.title (
str) – Comment line written as the second line of the file.
- Return type:
None
- xyzrender.api.load(molecule, *, smiles=False, charge=0, multiplicity=None, kekule=False, rebuild=False, mol_frame=0, ts_detect=False, ts_frame=0, nci_detect=False, cell=False, quick=False, bohr=None, ensemble=False, reference_frame=0, max_frames=None, align_atoms=None, ensemble_color=None, ensemble_opacity=None, auto_align=True, reference_mol=None)[source]¶
Load a molecule from file (or SMILES string) and return a
Molecule.- Parameters:
molecule (
str|PathLike) – Path to the input file, or a SMILES string when smiles isTrue. Supported extensions:.xyz,.cube,.cub,.mol,.sdf,.mol2,.pdb,.smi,.cif, and any QM output supported by cclib.smiles (
bool) – Treat molecule as a SMILES string and generate 3-D geometry.charge (
int) – Formal molecular charge (0 = read from file when available).multiplicity (
int|None) – Spin multiplicity (None= read from file).kekule (
bool) – Convert aromatic bonds to alternating single/double (Kekulé form).rebuild (
bool) – Force xyzgraph distance-based bond detection even when the file provides explicit connectivity. When used withensemble=True, each frame’s graph is rebuilt independently (for trajectories where bonding changes between frames).mol_frame (
int) – Zero-based frame index for multi-record SDF files.ts_detect (
bool) – Run graphRC transition-state detection (requiresxyzrender[ts]).ts_frame (
int) – Reference frame index for TS detection in multi-frame files.nci_detect (
bool) – Detect non-covalent interactions with xyzgraph after loading. When used withensemble=True, NCI detection is run on each frame independently.cell (
bool) – Read the periodic cell box from an extXYZLattice=header and store it on the returnedMolecule.quick (
bool) – Skip bond-order optimisation (build_graph(quick=True)). Use when you know bond orders will be suppressed at render time (e.g.render(mol, bo=False)). CIF and PDB-with-cell always usequick=Trueautomatically regardless of this flag.ensemble (
bool) – Load as a multi-frame trajectory ensemble. All frames are RMSD-aligned onto reference_frame and merged into a single graph.reference_frame (
int) – Index of the reference frame for ensemble alignment (default: 0).max_frames (
int|None) – Maximum number of frames to include (default: all).align_atoms (
str|list[int] |None) – 1-indexed atom indices for Kabsch alignment subset (min 3). When given, the rotation is computed from this subset only but applied to all atoms.ensemble_color (
str|list[str] |None) – Conformer colour spec. May be a palette name fromxyzrender.colors.PALETTE_NAMES(sampled across frames), a single hex/named colour (broadcast to every conformer), a comma-separated list, or an explicit list of colours.ensemble_opacity (
float|None) – Opacity for non-reference conformer atoms (0-1).auto_align (
bool) –True(default) runs Kabsch alignment onto reference_frame.Falsekeeps each frame’s raw coordinates — useful when absolute geometry matters (e.g. IRC paths).reference_mol (
Molecule|None) – Optional pre-loaded (and possibly oriented)Moleculefor the reference frame. When given, its graph and positions are used directly instead of loading the reference frame from molecule. This lets interactive orientation be applied before ensemble alignment.
- Return type:
- xyzrender.api.orient(mol, viewer='vmol', also=None)[source]¶
Open molecule in an interactive viewer to set orientation interactively.
Atom positions are written back to
mol.graphin-place. Setsmol.oriented = Trueso subsequentrender()calls skip PCA auto-orientation.For cube-file molecules the cube grid alignment is handled automatically at render time via Kabsch rotation from original cube atom positions to the updated graph positions.
- Parameters:
viewer (
str) – Viewer backend:"vmol"(default, requires vmol) or"ase"(requires ase). For vmol, rotate with the mouse/arrows then presszto confirm andqto quit. For ASE GUI, rotate then close the window to confirm.also (
list[Molecule] |None) – Optional list of additional Molecules that should receive the same rigid rotation about mol’s centroid. Use this for overlay structures you want to track mol’s orientation (matters when combined withauto_align=False— otherwise Kabsch realigns anyway).
- Return type:
None
- xyzrender.api.render(molecule, *, config='default', canvas_size=None, atom_scale=None, radius_scale=None, bond_width=None, atom_stroke_width=None, bond_color=None, bond_outline_color=None, bond_outline_width=None, ts_color=None, ts_element=None, ts_dash=None, ts_width=None, nci_color=None, nci_element=None, nci_dash=None, nci_width=None, background=None, transparent=False, gradient=None, hue_shift_factor=None, light_shift_factor=None, saturation_shift_factor=None, fog=None, fog_strength=None, label_font_size=None, vdw_opacity=None, vdw_scale=None, atom_gradient_strength=None, bond_gradient_strength=None, vdw_gradient_strength=None, hide_bonds=False, unbond=None, bond=None, haptic=False, hy=None, no_hy=False, bo=None, orient=None, ref=None, only=None, exclude=None, no_cell=False, axes=None, axis=None, supercell=(1, 1, 1), ghosts=None, cell_color=None, cell_width=None, ghost_opacity=None, ts_bonds=None, nci_bonds=None, vdw=None, idx=False, cmap=None, cmap_range=None, cmap_palette=None, cmap_symm=False, cbar=False, atom_opacity=None, labels=None, label_file=None, stereo=False, stereo_style='atom', vector=None, vector_scale=None, vector_color=None, opacity=None, mo=False, dens=False, esp=None, nci=None, iso=None, mo_pos_color=None, mo_neg_color=None, mo_blur=None, mo_upsample=None, mo_outline_width=None, mo_outline_color=None, flat_mo=False, dens_color=None, nci_mode=None, nci_cutoff=None, surface_style=None, hull=None, hull_color=None, hull_opacity=None, hull_edge=None, hull_edge_width_ratio=None, hull_color_type='type', pore=False, ring_max_size=100, ring_min_size=3, face_planarity=0.25, pore_color=None, pore_opacity=None, mol_color=None, highlight=None, regions=None, bond_color_by_element=None, bond_gradient=None, dof=False, dof_strength=None, glow=None, glow_strength=None, overlay=None, overlay_color=None, overlay_config=None, align_atoms=None, auto_align=None, output=None)[source]¶
Render a molecule to SVG and return an
SVGResult.In a Jupyter cell the result displays inline automatically via
_repr_svg_(). Pass output to save to disk at the same time.- Parameters:
molecule (
str|PathLike|Molecule) – AMoleculefromload(), or a file path (loaded with defaults).config (
str|RenderConfig) – Config preset name ("default","flat", …), path to a JSON config file, or a pre-builtRenderConfigfrombuild_config(). Style kwargs below are only applied when config is a string.orient (
bool|None) –True/Falseto force / suppress PCA auto-orientation.None(default) enables auto-orientation, unless the molecule was manually oriented viaorient().ref (
str|PathLike|None) – Path to an orientation reference XYZ file. If the file exists, the molecule is Kabsch-aligned to it and PCA auto-orientation is disabled regardless of orient. If the file does not exist, current (possibly PCA-oriented) positions are saved to it. Not supported for periodic structures (raisesValueError).only (
str|list[int] |list[str|list[int]] |None) – Render-time atom filters using the same selector grammar ashighlight/radius_scale. Selectors are resolved against the original input atom numbering, then the graph is relabeled contiguously before rendering.onlykeeps matching atoms;excluderemoves matching atoms from that kept set. Auto-orientation, canvas fitting, bond rules, style regions, annotations, hulls, and overlays see the filtered graph. Cube/surface fields are not cropped.exclude (
str|list[int] |list[str|list[int]] |None) – Render-time atom filters using the same selector grammar ashighlight/radius_scale. Selectors are resolved against the original input atom numbering, then the graph is relabeled contiguously before rendering.onlykeeps matching atoms;excluderemoves matching atoms from that kept set. Auto-orientation, canvas fitting, bond rules, style regions, annotations, hulls, and overlays see the filtered graph. Cube/surface fields are not cropped.unbond (
list[str] |None) – Bond display rules. A list of spec strings that hide bonds: categories ("M","sbm","L","het"), element pairs ("M-L","Fe-het"), pi-coordination ("pi","M-pi"), element symbols ("Li"), atom indices ("2"), or index pairs ("1-3"). Specs are 1-indexed. NCI / TS overlay edges are never removed by rules.bond (
list[str] |None) – Force-show or add bonds as 1-indexed index-pair strings (["4-5"]). Overridesunbond— a bond listed here will not be removed even if it matches an unbond rule.ts_bonds (
list[tuple[int,int]] |None) – Manual TS / NCI bond overlays as 1-indexed atom pairs.nci_bonds (
list[tuple[int,int]] |None) – Manual TS / NCI bond overlays as 1-indexed atom pairs.vdw (
bool|list[int] |None) – VdW sphere display.True= all atoms; a list of 1-indexed atom indices = specific atoms;None= off (default).idx (
bool|str) – Atom index labels.Trueor"sn"(e.g.C1);"s"(element only);"n"(number only).cmap (
str|PathLike|dict[int,float] |None) – Atom property colour map: either a{1-indexed atom: value}dict, or a path to a two-column text file (index value, same format as--cmapin the CLI).atom_opacity (
dict[int,float] |list[tuple[str|list[int],float]] |None) – Per-atom fill opacity. Accepts either a{1-indexed atom: value}dict (use for per-atom levels) or a selector list[(selector, value), ...]with the same grammar asradius_scale— strings ("1-5,8","M","het") are resolved against the molecular graph; bare lists are treated as 1-indexed atom indices. Affects the atom circle only; adjacent bonds stay fully opaque. Composes with overlay / ensemble opacity viamin.cmap_palette (
str|None) – Shared scalar palette override for atom colormaps and ESP surfaces. Defaults toviridisforcmap=...andrainbowfor ESP when not specified explicitly.labels (
list[str] |None) – Inline annotation spec strings (e.g.["1 2 d", "3 a", "1 NBO"]).label_file (
str|None) – Path to an annotation file (same format as--label).stereo (
bool|list[str]) –Truefor all stereochemistry labels, or a list of classes to show ("point","ez","axis","plane","helix").stereo_style (
str) – Placement for R/S labels:"atom"(centered on atom) or"label"(offset near atom).vectors – Vector arrows to overlay. Pass a path/dict to a JSON file, or a list of
xyzrender.types.VectorArrowobjects. Each arrow is drawn as a shaft + filled arrowhead pointing fromoriginin the direction ofvector. When the 2D projected length is shorter than the arrowhead size (i.e. the arrow points nearly along the viewing axis), a compact symbol is drawn instead: a filled dot (•) when the tip is closer to the viewer, or a cross (x) when it points away. The label is suppressed in these cases and reappears automatically once the arrow is long enough to draw a proper arrowhead.mo (
bool) – Render MO lobes / density isosurface from a cube file loaded viaload().dens (
bool) – Render MO lobes / density isosurface from a cube file loaded viaload().esp (
str|PathLike|None) – Path to an ESP.cubeor.cubfile (density iso + ESP colour map).nci (
str|PathLike|None) – Path to an NCI reduced-density-gradient.cubeor.cubfile.hull (
bool|str|list[int] |list[list[int]] |None) –True= hull over all heavy atoms;"rings"= one hull per aromatic ring (auto-detected from the molecular graph); a flat list of 1-indexed atom indices (one hull, e.g.[1,2,3,4,5,6]); a list of lists (multiple hulls, e.g.[[1,2,3,4,5,6], [7,8,9]]).None(default) = off.hull_color (
str|list[str] |None) – A single color string for all hulls, or a list of colors for per-subset colouring (one per subset). Hex or named color.hull_opacity (
float|None) – Fill opacity for all hull surfaces.hull_edge (
bool|None) – Draw hull edges that are not bonds as thin lines.hull_edge_width_ratio (
float|None) – Draw hull edges that are not bonds as thin lines.overlay (
str|PathLike|Molecule|None) – Second structure to overlay (path,Molecule, orNone). The overlay is Kabsch-aligned onto the primary (MCS fallback for different atom counts). Mutually exclusive with crystal display and surfaces.overlay_color (
str|None) – Shortcut foroverlay_config.color; wins when both are set.overlay_config (
OverlayConfig|None) –OverlayConfigcarrying per-overlay style overrides (color,opacity,atom_scale,bond_width,atom_stroke_*,bond_outline_*,unbond,bond,show,config). All fields are absolute (same semantics as onRenderConfig) and individually optional — unset fields inherit the primary config.Precedence when multiple entry points are used at once: the flat
overlay_color/opacitykwargs onrender()override matching fields on overlay_config, which overrides the preset’soverlayblock, which overrides theOverlayConfigdefaults.auto_align (
bool|None) –True(default) runs Kabsch/MCS to align the overlay onto the primary.Falsekeeps each structure’s raw coordinates; the interactive viewer rotation viaorient()still propagates.opacity (
float|None) – Transparency 0 to 1. Applied to the overlay whenoverlayis given, to the ensemble when the molecule is an ensemble, else to the active surface. The three modes are mutually exclusive.
- Returns:
Wrapper around the SVG string. Displays inline in Jupyter.
- Return type:
- xyzrender.api.render_gif(molecule, *, gif_rot=None, gif_bounce=None, gif_trj=False, gif_ts=False, gif_diffuse=False, diffuse_frames=60, diffuse_noise=0.3, diffuse_bonds='fade', diffuse_rot=None, diffuse_reverse=True, anchor=None, output=None, gif_fps=10, rot_frames=120, vib_frames=None, ts_frame=0, config='default', canvas_size=None, atom_scale=None, radius_scale=None, bond_width=None, atom_stroke_width=None, bond_color=None, bond_outline_color=None, bond_outline_width=None, ts_color=None, ts_element=None, ts_dash=None, ts_width=None, nci_color=None, nci_element=None, nci_dash=None, nci_width=None, background=None, transparent=False, gradient=None, hue_shift_factor=None, light_shift_factor=None, saturation_shift_factor=None, fog=None, fog_strength=None, label_font_size=None, vdw_opacity=None, vdw_scale=None, atom_gradient_strength=None, bond_gradient_strength=None, vdw_gradient_strength=None, hide_bonds=False, unbond=None, bond=None, haptic=False, hy=None, no_hy=False, bo=None, orient=None, ref=None, only=None, exclude=None, mol_color=None, highlight=None, regions=None, bond_color_by_element=None, bond_gradient=None, dof=False, dof_strength=None, glow=None, glow_strength=None, overlay=None, overlay_color=None, overlay_config=None, auto_align=None, align_atoms=None, opacity=None, reference_graph=None, trj_bonds=False, detect_nci=False, vector=None, vector_scale=None, vector_color=None, mo=False, dens=False, iso=None, mo_pos_color=None, mo_neg_color=None, mo_blur=None, mo_upsample=None, mo_outline_width=None, mo_outline_color=None, flat_mo=False, dens_color=None, surface_style=None, hull=None, hull_color=None, hull_opacity=None, hull_edge=None, hull_edge_width_ratio=None, hull_color_type='type', pore=False, ring_max_size=100, ring_min_size=3, face_planarity=0.25, pore_color=None, pore_opacity=None, no_cell=False, axes=None, axis=None, supercell=(1, 1, 1), ghosts=None, cell_color=None, cell_width=None, ghost_opacity=None)[source]¶
Render a molecule to an animated GIF and return a
GIFResult.The result displays the GIF inline in Jupyter via
_repr_html_. Access the file path viaresult.path.At least one of gif_rot, gif_bounce, gif_trj, gif_ts, or gif_diffuse must be set.
- Parameters:
molecule (
str|PathLike|Molecule) – AMoleculefromload(), or a file path. For gif_ts and gif_trj modes, a file path is required (the trajectory or vibration data is read directly from disk).gif_rot (
str|None) – Rotation axis:"x","y","z", diagonal ("xy", …), or a 3-digit Miller index ("111").gif_trj (
bool) – Trajectory animation — molecule must be a multi-frame XYZ.gif_bounce (
float|tuple[float,str] |None) – Bounce rotation GIF. Either an amplitude in degrees (axis defaults to"y") or a(degrees, axis)tuple — e.g.50or(50, "xy"). axis uses the same vocabulary as gif_rot. Mutually exclusive with gif_rot.gif_ts (
bool) – Transition-state vibration animation (requiresxyzrender[ts]).output (
str|PathLike|None) – Output.gifpath. Defaults to<stem>.gifbeside molecule.gif_fps (
int) – Frames per second.rot_frames (
int) – Number of frames for a full rotation.ts_frame (
int) – Reference frame index for TS detection (0-indexed).config (
str|RenderConfig) – Preset name, JSON path, or pre-builtRenderConfig.
- Returns:
Wrapper with path to the written GIF file.
- Return type: