Structural Chemistry - Chemistry in 3 dimensions
Chem3D.py module
So far, it only contains the XYZData and molView classes.
Overview
Chem3D provides molView, an interactive 3D viewer and geometry-analysis
bridge between several molecular/crystal data sources and
py3Dmol. It is designed for use in
Jupyter notebooks (including Google Colab).
Supported input sources
Source |
Accepts |
|---|---|
|
Path to a local XYZ / PDB / CIF structure file |
|
Raw string (XYZ, PDB, or MDL mol/SDF block) |
|
CIF content as a string |
|
PubChem CID ( |
|
RCSB PDB ID |
|
Crystallography Open Database ID |
|
An |
|
SMILES string (PubChem lookup by default, optional local RDKit 3D generation) |
Visualization styles: 'bs' (ball-and-stick, default), 'cpk'
(space-filling spheres), and 'cartoon' (protein backbone ribbon).
Quick start
from pyphyschemtools import molView
# From a local file
molView("molecule.xyz", source="file")
# From PubChem (aspirin)
molView(2244, source="cid")
# From an ASE Atoms object
from ase.build import molecule
molView(molecule("H2O"), source="ase", style="cpk")
# Grid of several structures side by side
molView.view_grid([2244, 2519, 702], n_cols=3, source="cid")
show_n=True permanently labels atoms with their element symbol and index; highlight_atoms=[...] overlays a translucent sphere on selected atoms without altering the base style.
Headless mode
Passing viewer=False skips py3Dmol initialization and only extracts
atomic data into molView.data (an XYZData instance), useful for batch
geometric analysis without the memory cost of a 3D engine:
mv = molView("cage.xyz", viewer=False)
volume = mv.data.get_cage_volume()
Cavity and bounding-sphere analysis
XYZData exposes geometric methods (center of mass/geometry, VdW bounding
sphere) and, via CageCavityCalc,
internal cavity volume and principal dimensions (PCA-based) for molecular
cages. molView.show_bounding_sphere() and molView.show_cage_cavity()
render these directly in the viewer.
Symmetry analysis
molView.analyze_symmetry() wraps pymatgen to
return the space group (periodic structures) or point group and chirality
(isolated molecules).
API reference
- class pyphyschemtools.Chem3D.molView(mol, source=None, style='bs', displayHbonds=True, cpk_scale=0.6, w=600, h=400, supercell=(1, 1, 1), display_now=True, detect_BondOrders=True, viewer=True, zoom=None, show_n=False, highlight_atoms=None, highlight_color='yellow', highlight_scale=1.3, prefer_local_3d=False)[source]
Bases:
objectInitializes a molecular/crystal viewer and coordinate extractor.
This class acts as a bridge between various molecular data sources and the py3Dmol interactive viewer. It can operate in ‘Full’ mode (display + analysis) or ‘Headless’ mode (analysis only) by toggling the viewer parameter.
The class automatically extracts geometric data into the self.data attribute (an XYZData object), allowing for volume, dimension, and cavity calculations.
Display molecular and crystal structures in py3Dmol from various sources:
XYZ/PDB/CIF local files
XYZ-format string
PubChem CID
ASE Atoms object
COD ID
RCSB PDB ID
SMILES string (PubChem lookup by default, optional local RDKit 3D generation)
Three visualization styles are available:
‘bs’ : ball-and-stick (default)
‘cpk’ : CPK space-filling spheres (with adjustable size)
‘cartoon’: protein backbone representation
Upon creation, an interactive 3D viewer is shown directly in a Jupyter notebook cell, unless the headless viewer parameter is set to False.
- Parameters:
mol (str or ase.Atoms) –
The molecular structure to visualize.
If source=’file’, this should be a path to a structure file (XYZ, PDB, etc.)
If source=’mol’, this should be a string containing the structure (XYZ, PDB, MDL mol/SDF…)
If source=’cif’, this should be a cif file (string)
If source=’cid’, this should be a PubChem CID (string or int)
If source=’rcsb’, this should be a RCSB PDB ID (string)
If source=’cod’, this should be a COD ID (string)
If source=’ase’, this should be an ase.Atoms object
If source=’smiles’, this should be a SMILES string
source ({'file', 'mol', 'cif', 'cid', 'rcsb', 'ase', 'smiles'}, optional) – The type of the input mol (default: ‘file’).
style ({'bs', 'cpk', 'cartoon'}, optional) –
Visualization style (default: ‘bs’).
’bs’ → ball-and-stick
’cpk’ → CPK space-filling spheres
- ’cartoon’ → draws a smooth tube or ribbon through the protein backbone
(default for pdb structures)
displayHbonds (plots hydrogen bonds (default: True))
cpk_scale (float, optional) – Overall scaling factor for sphere size in CPK style (default: 0.5). Ignored when style=’bs’.
supercell (tuple of int) – Repetition of the unit cell (na, nb, nc). Default is (1, 1, 1).
w (int, optional) – Width of the viewer in pixels (default: 600).
h (int, optional) – Height of the viewer in pixels (default: 400).
detect_BondOrders (bool, optional) – If True (default) and input is XYZ, uses RDKit to perceive connectivity and bond orders (detects double/triple bonds). Requires the rdkit library. If False, fallback to standard 3Dmol distance-based single bonds.
display_now (bool, optional) – If True (default), renders the molecule immediately. Set to False to prevent immediate display when you plan to call further visualization methods provided by the molView class
viewer (bool, optional) – If True (default), initializes the py3Dmol engine and prepares the 3D model. If False, operates in ‘headless’ mode: only geometric data is processed for analysis (volume, CM, etc.), saving significant memory for high-throughput processing.
zoom (None, optional) – scaling factor
show_n (bool, optional) – If True, permanently displays each atom’s element symbol and index directly on the figure (as opposed to on-hover labels). Default: False.
highlight_atoms (list of int, optional) – Indices of atoms to highlight with an overlaid translucent sphere, without altering the base style (bs/cpk/cartoon). Default: None.
highlight_color (str, optional) – Color of the highlight overlay (default: ‘yellow’). Ignored if highlight_atoms is None.
highlight_scale (float, optional) – Scale factor of the highlight sphere relative to the atom’s own sphere (default: 1.3). Ignored if highlight_atoms is None.
prefer_local_3d (bool, optional) – Only used when source=’smiles’. If True, generates the 3D structure locally with RDKit instead of querying PubChem (default: False).
- data
Container for atomic symbols and positions, used for geometric analysis.
- Type:
XYZData or None
- v
The 3Dmol.js viewer instance (None if viewer=False).
- Type:
py3Dmol.view or None
Examples
>>> molView("molecule.xyz", source="file") >>> molView(xyz_string, source="mol") >>> molView(2244, source="cid") # PubChem aspirin >>> from ase.build import molecule >>> molView(molecule("H2O"), source="ase") >>> molView.view_grid([2244, 2519, 702], n_cols=3, source='cid', style='bs') >>> molView.view_grid(xyzFiles, n_cols=3, source='file', style='bs', titles=titles, w=500, sync=True) >>> # Headless mode for high-throughput volume calculations >>> mv = molView("cage.xyz", viewer=False) >>> vol = mv.data.get_cage_volume() >>> # Permanent atom numbering on the figure >>> molView("molecule.xyz", source="file", show_n=True) >>> # Highlight a reactive center (e.g. atoms 0 and 5) without changing the style >>> molView("molecule.xyz", source="file", highlight_atoms=[0, 5], highlight_color="magenta")
- analyze_symmetry(tolerance=0.3, angle_tolerance=5.0, eigen_tolerance=0.01, matrix_tolerance=0.1)[source]
Comprehensive symmetry analysis using Pymatgen.
- Parameters:
tolerance (float) – Distance tolerance in Å (symprec for crystals). Default 0.3.
angle_tolerance (float) – Angular tolerance in degrees (Crystals only). Default 5.0.
eigen_tolerance (float) – Inertia tensor eigenvalue tolerance (Molecules only). Default 0.01.
matrix_tolerance (float) – Symmetry operation matrix tolerance (Molecules only). Default 0.1.
- show_bounding_sphere(color='gray', opacity=0.2, scale=1.0)[source]
Calculates and displays the VdW bounding sphere in one go.
- show_cage_cavity(grid_spacing=0.5, color='cyan', opacity=0.5)[source]
Calculates cavity with CageCavityCalc and displays it as a single model.
- classmethod view_grid(mol_list, n_cols=3, titles=None, **kwargs)[source]
Displays a list of molecular structures in an interactive n_rows x n_cols grid.
This method uses ipywidgets.GridspecLayout to organize multiple 3D viewers into a clean matrix. It automatically calculates the required number of rows based on the length of the input list.
- Parameters:
mol_list (list) – A list containing the molecular data to visualize. Elements should match the expected ‘mol’ input for the class (paths, CIDs, strings, etc.).
n_cols (int, optional) – Number of columns in the grid (default: 3).
titles (list of str, optional) – Custom labels for each cell. If None, the string representation of the ‘mol’ input is used as the title.
**kwargs (dict) – Additional arguments passed to the molView constructor: - source : {‘file’, ‘mol’, ‘cif’, ‘cid’, ‘rcsb’, ‘ase’} - style : {‘bs’, ‘cpk’, ‘cartoon’} - displayHbonds : plots hydrogen bonds (default: True) - w : width of each individual viewer in pixels (default: 300) - h : height of each individual viewer in pixels (default: 300) - supercell : tuple (na, nb, nc) for crystal structures - cpk_scale : scaling factor for space-filling spheres
- Returns:
A widget object containing the grid of molecular viewers.
- Return type:
ipywidgets.GridspecLayout
Examples
>>> files = ["mol1.xyz", "mol2.xyz", "mol3.xyz", "mol4.xyz"] >>> labels = ["Reactant", "TS", "Intermediate", "Product"] >>> molView.view_grid(files, n_cols=2, titles=labels, source='file', w=400)
- class pyphyschemtools.Chem3D.XYZData(symbols, positions)[source]
Bases:
objectObject containing molecular coordinates and symbols extracted by molView. Allows for geometric calculations without reloading data.
- get_bounding_sphere(include_vdw=True, scale=1.0)[source]
Calculates the center and radius of the bounding sphere using ASE. scale: multiplication factor (e.g., 0.6 to match a reduced CPK style).
- get_cage_volume(grid_spacing=0.5, return_spheres=False)[source]
Calculates the internal cavity volume of a molecular cage using CageCavityCalc.
This method interfaces with the CageCavityCalc library by generating a temporary PDB file of the current structure. It can also retrieve the coordinates of the ‘dummy atoms’ (points) that fill the detected void.
- Parameters:
grid_spacing (float, optional) – The resolution of the grid used for volume integration in Å. Smaller values provide higher precision (default: 0.5).
return_spheres (bool, optional) – If True, returns both the volume and an ase.Atoms object containing the dummy atoms representing the cavity (default: False).
- Returns:
volume (float or None) – The calculated cavity volume in ų. Returns None if the calculation fails.
cavity_atoms (ase.Atoms, optional) – Returned only if return_spheres is True. An ASE Atoms object representing the internal void space.
- get_cavity_dimensions(cavity_atoms)[source]
Calculates the principal dimensions (Length, Width, Height) of the cavity points.
This method uses Principal Component Analysis (PCA) to find the natural axes of the cavity, making it independent of the molecule’s orientation. Percentiles are used instead of absolute Max-Min to filter out potential outliers or ‘leaking’ points at the openings.
- Parameters:
cavity_atoms (ase.Atoms) – The Atoms object containing the ‘dummy atoms’ generated by the cavity calculation.
- Returns:
The dimensions (L, W, H) sorted from largest to smallest.
- Return type:
tuple (float, float, float)
Note
source='rscb' is deprecated in favor of source='rcsb' (the correct
RCSB PDB acronym) as of the upcoming release.