Cheminformatics
cheminformatics.py module
So far, it only contains the easy_rdkit class
2D representation of organic and inorganic compounds
Principle
The easy_rdkit class acts as a high-level wrapper around the RDKit library, specifically tailored for chemical education. It allows for the immediate visualization of chemical bond properties that are usually hidden in standard molecular representations. It is built on the SMILES (Simplified Molecular Input Line Entry System) standard. By providing a simple text string as input, the class automatically generates a full molecular object, calculates electronic properties and descriptors - useful for machine learning, and handles 2D coordinate generation. This approach allows students to bridge the gap between chemical notation and computational representation instantaneously.
Molecular Descriptors Reference
Each descriptor provided by easy_rdkit captures a specific aspect of the molecule’s nature, from its physical bulk to its potential as a drug candidate.
Physico-chemical Properties (Lipinski & Veber Criteria)
MW (Molecular Weight): The sum of atomic masses in the molecule (g/mol). It is a primary indicator of molecular size and its ability to diffuse across biological membranes.
LogP (Partition Coefficient): A measure of lipophilicity (octanol/water partition). A high LogP indicates a hydrophobic molecule, while a low LogP suggests hydrophilicity.
QED (Quantitative Estimate of Drug-likeness): A score between 0 and 1 that reflects how much a molecule “looks like” a drug based on its underlying properties.
HBA (Hydrogen Bond Acceptors): The number of electronegative atoms (typically N or O) that can accept a hydrogen bond.
HBD (Hydrogen Bond Donors): The number of hydrogen atoms attached to electronegative atoms (N-H or O-H) that can be donated to form a hydrogen bond.
RotB (Rotatable Bonds): A measure of molecular flexibility. Note that terminal groups like Methyl (-CH3) are not counted as they do not change the overall conformation upon rotation.
TPSA (Topological Polar Surface Area): The surface area (Å2) contributed by polar atoms (N, O and their attached H). It is a key metric for the optimization of a drug’s ability to permeate cells.
Topological & Structural Indices
Aromatic / Non-Aromatic Rings: Distinguishes between stabilized aromatic systems (like benzene) and aliphatic or saturated rings (like cyclohexane).
Fsp3 (Fraction of \(sp^3\) Carbons): The ratio of sp3 hybridized carbons to the total carbon count. It measures the “3D-ness” or saturation of a molecule. Higher values often correlate with better solubility and success in clinical trials.
Connectivity Indices (Chi0 & Chi1):
Chi0: Focuses on individual atoms to estimate molecular volume and atomic crowding.
Chi1: Focuses on bonds and branching patterns. It is used in QSAR models to predict physical properties like boiling points and density.
Practical examples
A. Basic use
While standard chemical drawings often omit conjugation or hybridization states, easy_rdkit allows for their explicit visualization, making it an ideal tool for teaching structural organic chemistry.
import pyphyschemtools as t4pPC
from pyphyschemtools import easy_rdkit
# Initialize with a SMILES string (Paracetamol)
mol = easy_rdkit("CC(=O)NC1=CC=C(C=C1)O")
# 1. Highlight Aromaticity
t4pPC.centerTitle("Aromatic part")
mol.show_mol(plot_aromatic=True)
# 2. Highlight Conjugation and Lone Pairs
t4pPC.centerTitle("Conjugated part")
mol.show_mol(plot_conjugation=True, show_n=True)
B. Comprehensive Electronic View: Lewis structure
This example showcases how easy_rdkit simplifies the transition from a SMILES string to a detailed basic electronic analysis. By enabling the Lewis and hybridization flags, the library automatically calculates and overlays lone pairs, electron vacancies, and orbital states directly onto the molecular graph, providing a clear visual bridge between chemical structure and bonding theory.
import pyphyschemtools as t4pPC
from pyphyschemtools import easy_rdkit
t4pPC.centerTitle("Lewis & hybridization")
mol = easy_rdkit("CC(=O)NC1=CC=C(C=C1)O", lang="Fr")
mol.show_mol(show_Lewis=True, show_n=True, show_hybrid=True, size=(600,400))
C. Fetching a SMILES from its PubChem CID
PubChem is the world’s largest collection of freely accessible chemical information, maintained by the National Institutes of Health (NIH). It serves as a comprehensive authority for chemical structures, identifiers, and biological activities.
By integrating the PubChem Compound ID (CID) system, easy_rdkit allows you to bypass manual string entry. This ensures that the molecular structure is retrieved directly from a standardized, peer-reviewed source, significantly reducing errors for complex scaffolds.
import pyphyschemtools as t4pPC
from pyphyschemtools import easy_rdkit
mol = easy_rdkit.from_cid(2519) #cafeine
t4pPC.centerTitle("Caffeine from PubChem")
mol.show_mol(plot_conjugation=True)
print(f"compound {mol.cid} = {mol.iupac_name}\nRDKit-canonicalized SMILES = {mol.smiles}")
D. Mastering Complex Geometry
Macrocycles (large rings) are notoriously difficult to represent clearly in 2D. Using the macrocycle=True flag triggers an optimized coordinate generation algorithm.
import pyphyschemtools as t4pPC
from pyphyschemtools import easy_rdkit
# Cyclosporine: A challenging macrocycle for standard layout engines
smiles_cyc = "C/C=C/CC(C)C(O)C1C(=O)NC(CC)C(=O)N(C)CC(=O)N(C)C(CC(C)C)C(=O)NC(C(C)C)C(=O)N(C)C(CC(C)C)C(=O)NC(C)C(=O)NC(C)C(=O)N(C)C(CC(C)C)C(=O)N(C)C(CC(C)C)C(=O)N(C)C(C(C)C)C(=O)N1C"
mol = easy_rdkit(smiles_cyc)
t4pPC.centerTitle("Better representation of macrocycles")
t4pPC.centertxt("without the 'macrocycle' option")
mol.show_mol()
t4pPC.centertxt("with the 'macrocycle' option")
mol.show_mol(macrocycle=True)
E. Calculation of descriptors
This example highlights the seamless integration with PubChem and the automated extraction of molecular properties. By initializing a molecule via its Compound ID (CID), the library automatically retrieves the official IUPAC name and canonical SMILES, while providing a clear visualization of chemical features like π-conjugation and a comprehensive table of calculated physicochemical descriptors.
import pyphyschemtools as t4pPC
from pyphyschemtools import easy_rdkit
mol = easy_rdkit.from_cid(3672) #ibuprofen
t4pPC.centerTitle("Ibuprofen from PubChem")
mol.show_mol(plot_conjugation=True)
print(f"compound {mol.cid} = {mol.iupac_name}\nRDKit-canonicalized SMILES = {mol.smiles}\n")
mol.show_descriptors()
F. Store descriptors in a dataframe
This example demonstrates how to efficiently transform a chemical library into a structured dataset. By consolidating multiple easy_rdkit instances into a pandas DataFrame, you can automatically aggregate IUPAC names, PubChem IDs, and molecular descriptors into a single table, creating a powerful foundation for data analysis or machine learning workflows.
import pyphyschemtools as t4pPC
from pyphyschemtools import easy_rdkit
import pandas as pd
# A list of molecules (some from CID, some from SMILES)
my_mols = [easy_rdkit.from_cid(3672), easy_rdkit("CC(C1=CC(=CC=C1)C(=O)C2=CC=CC=C2)C(=O)O"), easy_rdkit.from_cid(156391), easy_rdkit.from_cid(3033)]
t4pPC.centerTitle("Store descriptors in dataframes")
df = pd.DataFrame([m.to_dict(auto_fetch=True) for m in my_mols])
display(df)
G. Display the smiles of a dataframe on a grid, with legends
This final step illustrates the automated generation of a molecular gallery, translating your DataFrame back into a clean, visual grid. By specifying multiple legend columns, the method creates high-quality SVG panels with vertically stacked properties, providing an ideal format for data comparison and high-resolution export for scientific publications or student report.
t4pPC.centerTitle("Draw molecules on a grid")
# Create a grid showing Name, Molecular Weight, and LogP
easy_rdkit.plot_grid_from_df(
df,
smiles_col='SMILES',
legend_cols=['CID', 'MW', 'LogP'],
mols_per_row=2,
size=(350, 400),
save_img="fig_examples/Molecules/gridMol.svg"
)
API reference
- class pyphyschemtools.cheminformatics.easy_rdkit(smiles, canonical=True, lang='En')[source]
Bases:
objectA helper class to analyze and visualize molecules using RDKit. Provides tools for Lewis structure analysis and advanced 2D drawing. Initialize the molecule object from a SMILES string.
- Parameters:
smiles (str) – The SMILES representation of the molecule.
canonical (bool) – If True, converts the SMILES to its canonical form to ensure consistent atom numbering and uniqueness.
lang (str) – Language for headers and messages of the Lewis analyzis(“En” (default) or “Fr”).
- analyze_lewis(heavy_only=True)[source]
Performs a simplified Lewis-structure analysis of the molecule, atom by atom, based on RDKit’s valence/bond perception (no 3D geometry involved).
- For each atom, derives:
valence electrons (from the periodic table)
bonding electrons (RDKit’s total valence)
formal charge
lone pairs (nonbonding electrons / 2)
vacancies (missing electrons to reach octet/duet, if any)
total electron count and whether the octet (or duet, for H/He) rule is satisfied, electron-deficient, or hypervalent
This is a teaching aid, not a rigorous electronic-structure calculation: it relies on RDKit’s bond-order perception from the SMILES, so it reflects whatever Lewis structure RDKit infers and will not be meaningful for molecules with unusual/ambiguous valence (e.g. hypervalent or radical species) beyond the simple flags above.
- Parameters:
heavy_only (bool) – If True (default), only heavy atoms (Z > 2) get a row in the returned table. H atoms are checked for duet compliance on an internal copy of the molecule with explicit Hs (self.mol itself is not modified), and a single summary line is printed after the table (✅ if all H satisfy the duet rule, ❌ with the offending atom indices otherwise). If False, H/He atoms are included in the table with full LP/vacancy detail, like heavy atoms.
- Returns:
One row per analyzed atom, with columns depending on self.lang (“En”: Atom Index, Symbol, Valence e-, Bonding e-, Formal Charge, Lone Pairs (LP), Vacancies ([]), Number of Bonds, Total e- (octet?), Octet Status (O/H/D); “Fr”: French equivalents). H/He atoms are excluded from the rows when heavy_only is True.
- Return type:
pd.DataFrame
- Raises:
ValueError – if self.mol is None (invalid SMILES), with a message
in English or French depending on self.lang. –
- analyze_stereochemistry()[source]
Summarizes the stereochemical features of the molecule as currently perceived by RDKit (chiral centers and stereogenic double bonds).
Unlike get_isomers, this does not enumerate alternative configurations — it only reports what is already encoded (or left unassigned, i.e. “?”) in self.mol.
- Returns:
Dictionary with keys
chiral_centers_count(int),chiral_centers(list of (atom_index, “R”/”S”/”?”)),stereo_bonds_count(int), andstereo_bonds(list of (begin_atom_idx, end_atom_idx, “STEREOE”/”STEREOZ”/…)).- Return type:
dict
- property descriptors
Computes (once, then caches) a set of standard molecular descriptors.
- Returns:
MW, LogP, QED, HBA, HBD, RotB (rotatable bonds), TPSA, aromatic/non-aromatic ring counts, Fsp3, and connectivity indices (Chi0, Chi1). Values are rounded for display.
- Return type:
dict
Note
Computed lazily on first access and cached in self._descriptors_cache; if self.mol changes afterward (e.g. via show_mol adding explicit Hs), the cache is NOT automatically invalidated — delete self._descriptors_cache if you need a refresh.
- static draw_consistent_svg(smiles_list, legends=None, size_per_mol=300, mols_per_row=3, bond_length=35.0, bond_width=1.2, font_size=12, save_img='export/molecules.svg')[source]
Generates an SVG file with a grid of molecules having consistent bond lengths. Ideal for high-quality printing and comparison.
- Parameters:
smiles_list (list) – List of SMILES strings to draw.
legends (list, optional) – List of strings to display under each molecule.
size_per_mol (int) – Size of the square panel for each molecule (Default: 300).
mols_per_row (int) – Number of molecules per row (Default: 3).
bond_length (float) – Fixed length for bonds in pixels (Default: 35.0).
bond_width (float) – Thickness of the bonds (Default: 1.2).
font_size (int) – Font size for atom labels (Default: 12).
save_img (str) – Output SVG file path (Default: “export/molecules.svg”).
- fetch_pubchem_data()[source]
Queries PubChem using the molecule’s current SMILES to retrieve its PubChem CID and IUPAC name, and stores them on the instance (self.cid, self.iupac_name).
This is the reverse of from_cid: instead of building the molecule from a known CID, it looks up an already-built molecule (e.g. created via easy_rdkit(“CCO”)) to see if it exists in PubChem.
Only the first match returned by PubChem is used. If the SMILES is ambiguous (e.g. corresponds to several close PubChem entries such as tautomers or salts), this may not be the expected compound — check self.cid against the PubChem page if in doubt.
Notes
Requires an internet connection (PubChem REST API via pubchempy).
Does not raise on failure: if no match is found, or if the request fails, a warning/error is printed and self.cid / self.iupac_name are left unchanged.
- classmethod from_cid(cid, canonical=True, lang='En')[source]
Builds an easy_rdkit instance directly from a PubChem CID.
Fetches the compound from PubChem, extracts its connectivity SMILES, and uses it to construct the molecule (equivalent to easy_rdkit(smiles) but starting from a known CID instead). self.cid and self.iupac_name are set from the PubChem record.
- Parameters:
cid (int or str) – The PubChem Compound ID.
canonical (bool) – Passed through to __init__.
lang (str) – Passed through to __init__ (“En” or “Fr”).
- Returns:
The constructed instance.
- Return type:
- Raises:
ValueError – if the CID does not correspond to a valid PubChem compound.
ConnectionError – if the PubChem request fails (network/API issue).
- classmethod from_name(name, canonical=True, lang='En')[source]
Builds an easy_rdkit instance directly from a compound name, by querying PubChem (e.g. “aspirin”, “caffeine”, “benzene”).
- Parameters:
name (str) – Compound name to search for on PubChem.
canonical (bool) – Passed through to __init__.
lang (str) – Passed through to __init__ (“En” or “Fr”).
- Returns:
The constructed instance, with self.cid and self.iupac_name set from the first PubChem match.
- Return type:
- Raises:
ValueError – if no PubChem compound matches the given name.
ConnectionError – if the PubChem request fails (network/API issue).
Note
If several compounds match the name, only the first PubChem result is used — check self.cid if the match seems ambiguous.
- get_isomers(max_isomers=12, verbose=True)[source]
Explores the stereochemical space of the molecule by enumerating all possible stereoisomers.
This method identifies all unassigned or flexible stereocenters (chiral centers and double bonds) and generates a complete set of discrete stereochemical configurations. It is particularly useful for resolving “flat” SMILES strings into their constituent enantiomers and diastereomers.
- Parameters:
max_isomers (int) – The maximum number of isomers to generate. This prevents computational explosion for molecules with many stereocenters (2^n). Defaults to 12.
verbose (bool) – If True, prints a summary of the number of isomers found using a colored terminal message. Defaults to True.
- Returns:
- A list of easy_rdkit instances, each representing a unique,
fully-defined stereoisomer of the parent molecule.
- Return type:
list
- static plot_grid_from_df(df, smiles_col='SMILES', legend_cols='IUPAC Name', mols_per_row=4, size=(250, 250), show_stereo=False, save_img=None)[source]
Generates a grid image of molecular structures from a pandas DataFrame.
This method extracts SMILES strings from the specified column, generates 2D representations, and arranges them in a grid. It supports multi-line legends by passing a list of column names, and can export the result to external files.
- Parameters:
df (pd.DataFrame) – DataFrame containing the molecular data.
smiles_col (str) – Name of the column containing SMILES strings. Defaults to ‘SMILES’.
legend_cols (str or list) – Column name(s) to display as legends below each molecule. If a list is provided, each value is displayed on a new line (e.g., [‘IUPAC Name’, ‘MW’, ‘LogP’]). Defaults to ‘IUPAC Name’.
mols_per_row (int) – Number of molecules to display in each row. Defaults to 4.
size (tuple) – Dimensions (width, height) in pixels for each individual molecule panel. Defaults to (250, 250).
save_img (str, optional) – File path to save the resulting image. Supports ‘.svg’ (vector) and ‘.png’ (raster) extensions. Defaults to None.
- Returns:
An SVG object for rich display in Jupyter/Colab environments.
- Return type:
IPython.display.SVG
Note
PNG export requires the Cairo backend to be available in the RDKit installation.
- show_descriptors()[source]
Prints the molecular descriptors (see descriptors) as a simple formatted table to stdout. Display-only; returns nothing.
- show_isomers(mols_per_row=4, size=(250, 250), save_img=None)[source]
Generates, labels, and displays a grid of all possible stereoisomers.
This method automates the transition from a single chemical identity to a visual comparative analysis of its stereoisomers. Each isomer is rendered with its specific SMILES string (including @ markers and / directionals) and an isomer index. It utilizes the class’s internal grid-plotting logic to ensure high-quality SVG output and optional file export.
- Parameters:
mols_per_row (int) – Number of isomer structures to display per row in the grid. Defaults to 4.
size (tuple) – The (width, height) in pixels for each individual molecular panel. Defaults to (250, 250).
save_img (str, optional) – File path (e.g., ‘isomers.svg’ or ‘isomers.png’) to export the grid. Directories are created automatically. Defaults to None.
- Returns:
- A grid image displayed directly in the Jupyter/Colab
environment.
- Return type:
IPython.display.SVG
- show_mol(size: tuple = (400, 400), show_Lewis: bool = False, plot_conjugation: bool = False, plot_aromatic: bool = False, show_n: bool = False, show_hybrid: bool = False, show_H: bool = False, show_stereo: bool = False, rep3D: bool = False, macrocycle: bool = False, highlightAtoms: list = [], legend: str = '', save_img: str = None)[source]
Renders the molecule as a 2D (SVG or PNG) depiction, with optional annotations, and displays it inline (Jupyter/Colab). Can also save the image to disk.
This is the main “do everything” drawing method of the class: most arguments toggle an independent overlay or computation that gets combined onto the same drawing. A few interactions to know about:
show_Lewis implies show_H (explicit Hs are added so lone pairs/ vacancies can be computed and displayed) and internally calls analyze_lewis(), which also prints/displays its DataFrame.
show_Lewis and show_hybrid share the same atom-note area (the little text under each atom); both can be shown together.
rep3D adds explicit Hs and computes a 3D-like embedding (AllChem.EmbedMolecule) before generating a (still 2D) drawing from it — mainly useful to get a more realistic bond geometry.
plot_conjugation and plot_aromatic each highlight bonds/atoms in a different color (blue / red) but use the same highlighting machinery, so combining both silently uses whichever was computed last (not an additive overlay).
show_stereo perceives and labels R/S and E/Z. If any chiral center or double bond is unassigned (“?”), it prints a warning and automatically turns on atom (and, for double bonds, bond) index display so you can identify what needs fixing in the SMILES.
Side effect: several options (show_H, show_Lewis, rep3D, macrocycle) mutate self.mol in place (adding Hs, 3D coords, atom notes), so self.mol may differ after calling show_mol even without save_img.
- Parameters:
size (tuple) – Drawing dimensions in pixels (width, height).
show_Lewis (bool) – Annotate atoms with lone pairs / vacancies (implies show_H; runs analyze_lewis() and displays its table).
plot_conjugation (bool) – Highlight conjugated bonds in blue.
plot_aromatic (bool) – Highlight aromatic atoms/bonds in red.
show_n (bool) – Display atom indices.
show_hybrid (bool) – Display atom hybridization (sp, sp2, sp3…).
show_H (bool) – Add explicit hydrogens to the drawing.
show_stereo (bool) – Compute and display R/S, E/Z labels; warns and auto-enables index display if stereochemistry is undefined in the input SMILES.
rep3D (bool) – Embed a 3D-like conformation (via AllChem) before drawing, for more realistic bond angles.
macrocycle (bool) – Use CoordGen for better layout of large rings (e.g. cyclodextrins).
highlightAtoms (list) – Atom indices to highlight (ignored if plot_conjugation or plot_aromatic is used).
legend (str) – Caption displayed under the structure.
save_img (str, optional) – Output file path; extension decides format (‘.svg’ or ‘.png’). Image is also always displayed inline regardless of this argument.
- Returns:
None. Displays the image (IPython.display.SVG) as a side effect; if save_img ends in ‘.png’, also regenerates and displays an SVG version for screen viewing (via a recursive call).
- to_dict(auto_fetch=False)[source]
Exports identity and descriptors as a flat dictionary, ready for use in a DataFrame row (e.g. with plot_grid_from_df).
- Parameters:
auto_fetch (bool) – If True and self.cid is not already set, calls fetch_pubchem_data() first to try to retrieve the CID/IUPAC name before building the dictionary.
- Returns:
{“IUPAC Name”, “CID”, “SMILES”} plus all keys from descriptors (MW, LogP, QED, …). CID/IUPAC Name are “N/A” if unavailable.
- Return type:
dict