CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rdkit

Platform wheels for RDKit - a comprehensive cheminformatics and machine-learning library with Python bindings

89

1.01x
Overview
Eval results
Files

visualization.mddocs/

Molecular Visualization

2D molecular structure rendering and image generation with customizable display options for creating publication-quality molecular graphics. RDKit's drawing system provides comprehensive visualization capabilities for molecules, reactions, and chemical data with support for various output formats and styling options.

Capabilities

Basic Molecular Drawing

Generate 2D molecular structure images with standard or custom display options.

def MolToImage(mol: Mol, size: tuple = (300, 300), kekulize: bool = True,
               wedgeBonds: bool = True, fitImage: bool = False, atomLabels: dict = None,
               bondLabels: dict = None, highlightAtoms: list = None, 
               highlightBonds: list = None, highlightAtomColors: dict = None,
               highlightBondColors: dict = None, highlightRadius: dict = None) -> PIL.Image:
    """
    Generate a PIL Image of a molecule.
    
    Parameters:
    - mol: Input molecule
    - size: Image dimensions as (width, height) tuple (default (300, 300))
    - kekulize: Convert aromatic bonds to alternating single/double (default True)
    - wedgeBonds: Draw wedge/dash bonds for stereochemistry (default True)
    - fitImage: Fit molecule to image bounds (default False)
    - atomLabels: Dictionary mapping atom indices to label strings
    - bondLabels: Dictionary mapping bond indices to label strings
    - highlightAtoms: List of atom indices to highlight
    - highlightBonds: List of bond indices to highlight
    - highlightAtomColors: Dictionary mapping atom indices to highlight colors
    - highlightBondColors: Dictionary mapping bond indices to highlight colors
    - highlightRadius: Dictionary mapping atom indices to highlight radii
    
    Returns:
    PIL Image object
    """

def MolToFile(mol: Mol, filename: str, size: tuple = (300, 300), 
              imageType: str = None, **kwargs) -> None:
    """
    Save molecule image directly to file.
    
    Parameters:
    - mol: Input molecule
    - filename: Output file path (extension determines format)
    - size: Image dimensions as (width, height) tuple (default (300, 300))
    - imageType: Force specific image type ('png', 'svg', etc.)
    - **kwargs: Additional arguments passed to drawing functions
    
    Returns:
    None
    """

Reaction Drawing

Visualize chemical reactions with reactants, products, and reaction arrows.

def ReactionToImage(rxn, subImgSize: tuple = (200, 200), **kwargs) -> PIL.Image:
    """
    Generate a PIL Image of a chemical reaction.
    
    Parameters:
    - rxn: ChemicalReaction object
    - subImgSize: Size for individual molecule images (default (200, 200))
    - **kwargs: Additional drawing options
    
    Returns:
    PIL Image object showing the complete reaction
    """

def DrawReaction(rxn, **kwargs):
    """
    Draw a chemical reaction using matplotlib backend.
    
    Parameters:
    - rxn: ChemicalReaction object
    - **kwargs: Drawing options
    
    Returns:
    Matplotlib figure object
    """

Multi-Molecule Grid Display

Display multiple molecules in organized grid layouts for comparison and analysis.

def MolsToGridImage(mols: list, molsPerRow: int = 4, subImgSize: tuple = (200, 200),
                    legends: list = None, highlightAtomLists: list = None,
                    highlightBondLists: list = None, useSVG: bool = False,
                    returnPNG: bool = True, **kwargs) -> PIL.Image:
    """
    Generate a grid image of multiple molecules.
    
    Parameters:
    - mols: List of molecule objects
    - molsPerRow: Number of molecules per row (default 4)
    - subImgSize: Size of each molecule image (default (200, 200))
    - legends: List of legend strings for each molecule
    - highlightAtomLists: List of atom index lists to highlight for each molecule
    - highlightBondLists: List of bond index lists to highlight for each molecule
    - useSVG: Use SVG rendering (default False)
    - returnPNG: Return PNG format (default True)
    - **kwargs: Additional drawing options
    
    Returns:
    PIL Image object containing the molecule grid
    """

def MolsToImage(mols: list, **kwargs) -> PIL.Image:
    """
    Generate a single image containing multiple molecules.
    
    Parameters:
    - mols: List of molecule objects
    - **kwargs: Drawing options (same as MolsToGridImage)
    
    Returns:
    PIL Image object
    """

SVG Generation

Generate scalable vector graphics for high-quality molecular illustrations.

def MolToSVG(mol: Mol, size: tuple = (300, 300), kekulize: bool = True,
             drawer: object = None, **kwargs) -> str:
    """
    Generate SVG representation of a molecule.
    
    Parameters:
    - mol: Input molecule
    - size: Image dimensions as (width, height) tuple (default (300, 300))
    - kekulize: Convert aromatic bonds to alternating single/double (default True)
    - drawer: Custom drawer object (default None for auto-selection)
    - **kwargs: Additional drawing options
    
    Returns:
    SVG string representation
    """

def ReactionToSVG(rxn, **kwargs) -> str:
    """
    Generate SVG representation of a chemical reaction.
    
    Parameters:
    - rxn: ChemicalReaction object
    - **kwargs: Drawing options
    
    Returns:
    SVG string representation
    """

Drawing Options and Styling

Customize molecular drawing appearance with detailed styling controls.

class DrawingOptions:
    """
    Configuration object for molecular drawing options.
    """
    atomLabelFontSize: int = 12  # Font size for atom labels
    bondLineWidth: float = 2.0   # Width of bond lines
    multipleBondOffset: float = 0.15  # Offset for multiple bonds
    dummiesAreAttachments: bool = False  # Treat dummy atoms as attachment points
    circleAtoms: bool = True     # Draw circles around atoms
    highlightColour: tuple = (1, 1, 0)  # Default highlight color (RGB)
    atomColourPalette: dict = {}  # Custom atom color palette
    includeAtomTags: bool = False  # Include atom tags in drawing
    clearBackground: bool = True  # Use transparent background
    bgColor: tuple = (1, 1, 1)   # Background color (RGB)
    legendFontSize: int = 12     # Font size for legends

def SetDrawingOptions(opts: DrawingOptions) -> None:
    """
    Set global drawing options.
    
    Parameters:
    - opts: DrawingOptions object with configuration
    
    Returns:
    None
    """

Interactive Drawing

Enable interactive molecular editing and manipulation.

def MolFromPNG(pngData: bytes) -> Mol:
    """
    Extract molecule from PNG image data (if embedded).
    
    Parameters:
    - pngData: PNG image data as bytes
    
    Returns:
    Mol object or None if extraction fails
    """

def MolFromSVG(svgData: str) -> Mol:
    """
    Extract molecule from SVG string data (if embedded).
    
    Parameters:
    - svgData: SVG string data
    
    Returns:
    Mol object or None if extraction fails
    """

Types

# External types used in visualization functions
class PIL.Image:
    """Pillow Image object for raster graphics"""
    def save(self, filename: str) -> None: ...
    def show(self) -> None: ...

Usage Examples

Basic Molecular Drawing

from rdkit import Chem
from rdkit.Chem import Draw

# Create and draw a molecule
mol = Chem.MolFromSmiles('CCO')  # Ethanol
img = Draw.MolToImage(mol, size=(400, 400))
img.save('ethanol.png')

# Draw with custom options
img = Draw.MolToImage(mol, 
                      size=(500, 500),
                      highlightAtoms=[0, 1],  # Highlight first two carbons
                      highlightAtomColors={0: (1, 0, 0), 1: (0, 1, 0)})  # Red and green
img.save('ethanol_highlighted.png')

Grid Display of Multiple Molecules

from rdkit import Chem
from rdkit.Chem import Draw

# Create a list of molecules
smiles_list = ['CCO', 'CCCO', 'CCCCO', 'CCCCCO']
mols = [Chem.MolFromSmiles(smi) for smi in smiles_list]
legends = ['Ethanol', 'Propanol', 'Butanol', 'Pentanol']

# Create grid image
img = Draw.MolsToGridImage(mols,
                           molsPerRow=2,
                           subImgSize=(250, 250),
                           legends=legends)
img.save('alcohol_series.png')

SVG Generation

from rdkit import Chem
from rdkit.Chem import Draw

# Generate SVG for scalable graphics
mol = Chem.MolFromSmiles('c1ccccc1')  # Benzene
svg_string = Draw.MolToSVG(mol, size=(400, 400))

# Save SVG to file
with open('benzene.svg', 'w') as f:
    f.write(svg_string)

Reaction Visualization

from rdkit import Chem
from rdkit.Chem import AllChem, Draw

# Create a chemical reaction
rxn = AllChem.ReactionFromSmarts('[C:1](=[O:2])-[OD1].[N!H0:3]>>[C:1](=[O:2])[N:3]')

# Draw the reaction
img = Draw.ReactionToImage(rxn, subImgSize=(300, 300))
img.save('amidation_reaction.png')

Custom Drawing Options

from rdkit import Chem
from rdkit.Chem import Draw

# Create custom drawing options
opts = Draw.DrawingOptions()
opts.atomLabelFontSize = 18
opts.bondLineWidth = 3.0
opts.highlightColour = (0, 1, 0)  # Green highlights
opts.bgColor = (0.9, 0.9, 0.9)   # Light gray background

# Apply custom options
Draw.SetDrawingOptions(opts)

# Draw with custom styling
mol = Chem.MolFromSmiles('CCO')
img = Draw.MolToImage(mol, size=(400, 400))
img.save('ethanol_custom_style.png')

Highlighting Substructures

from rdkit import Chem
from rdkit.Chem import Draw

# Create molecule and define substructure
mol = Chem.MolFromSmiles('CCO')
pattern = Chem.MolFromSmarts('CO')  # Alcohol pattern

# Find matches
matches = mol.GetSubstructMatches(pattern)

if matches:
    # Highlight the first match
    highlight_atoms = list(matches[0])
    img = Draw.MolToImage(mol,
                          highlightAtoms=highlight_atoms,
                          highlightAtomColors={atom: (1, 0, 0) for atom in highlight_atoms})
    img.save('ethanol_alcohol_highlighted.png')

Molecule with Atom Labels

from rdkit import Chem
from rdkit.Chem import Draw

# Create molecule with custom atom labels
mol = Chem.MolFromSmiles('CCO')
atom_labels = {0: 'C1', 1: 'C2', 2: 'O'}

img = Draw.MolToImage(mol,
                      size=(400, 400),
                      atomLabels=atom_labels)
img.save('ethanol_labeled.png')

Install with Tessl CLI

npx tessl i tessl/pypi-rdkit

docs

core-chemistry.md

descriptors.md

features.md

index.md

structure-3d.md

visualization.md

tile.json