Skip to content

accfg.draw

Utilities for visualising functional groups and maximum common substructures using RDKit and PIL.

Dependencies

  • rdkit (Chem, Draw, rdFMCS, rdMolDraw2D)
  • Pillow (for final image handling)
  • matplotlib (for colour maps)
  • networkx (for tree printing helpers)

Functions

draw_RascalMCES(smiles1, smiles2, legends=None, subImgSize=(500, 500))

Generate a side-by-side PNG image of two molecules with atoms/bonds belonging to their maximum common edge substructure highlighted.

  • Parameters
  • smiles1, smiles2 (str): Input SMILES to compare. Each string is converted to an RDKit molecule.
  • legends (list[str] | None): Optional captions for each panel. Defaults to blank captions.
  • subImgSize (tuple[int, int]): Width/height in pixels for each panel; forwarded to Draw.MolsToGridImage.
  • Returns: PIL.Image.Image generated by RDKit (PNG encoded bytes internally).
  • Usage
from accfg.draw import draw_RascalMCES

img = draw_RascalMCES("CCO", "CC(=O)O", legends=["ethanol", "acetic acid"])
img.show()

set_alpha(color, alpha)

Inject an alpha channel into an RGB or RGBA colour tuple. Returns a new 4-tuple (r, g, b, alpha) and is used when building highlight palettes.

show_atom_idx(smi, label='molAtomMapNumber')

Annotate each atom in a SMILES string or RDKit molecule with its index under the chosen atom property key.

  • Parameters
  • smi (str | rdkit.Chem.Mol): Source molecule.
  • label (str): Atom property name to store the index under (default molAtomMapNumber).
  • Returns: Annotated RDKit Mol.
  • Note: Mutates the atom property in-place on the returned molecule.

draw_mol_with_fgs_dict(smi, fgs_dict, with_legend=True, with_atom_idx=True, alpha=1, cmp=mpl.colormaps['Pastel1'], img_size=(500, 400))

Create a Cairo PNG drawing with atoms/bonds highlighted according to a pre-computed functional group mapping.

  • Parameters
  • smi (str): Input molecule in SMILES.
  • fgs_dict (dict[str, list[list[int]]]): Functional group name mapping to lists of atom index lists (one list per match).
  • with_legend (bool): Append a text legend summarising each functional group.
  • with_atom_idx (bool): Show atom indices by re-labelling atoms via show_atom_idx.
  • alpha (float): Alpha transparency applied to highlighted bonds.
  • cmp (matplotlib.colors.Colormap): Palette used to colour distinct functional groups.
  • img_size (tuple[int, int]): Width/height in pixels for the Cairo canvas.
  • Returns: PNG binary string from MolDraw2DCairo.GetDrawingText().
  • Usage
from accfg.draw import draw_mol_with_fgs_dict, molimg

fgs = {"alcohol": [[1]], "alkene": [[0, 2]]}
raw_png = draw_mol_with_fgs_dict("C=C(O)C", fgs)
display_image = molimg(raw_png)

draw_mol_with_fgs(smi, afg=AccFG(), canonical=True, with_legend=True, with_atom_idx=True, alpha=1, cmp=mpl.colormaps['Pastel1'], img_size=(500, 400))

End-to-end helper that runs the AccFG detector and draws the resulting highlights.

  • Parameters
  • smi (str): Input SMILES.
  • afg (accfg.main.AccFG): AccFG instance. Defaults to a new detector initialised with bundled functional groups.
  • canonical (bool): Canonicalise SMILES before processing.
  • Remaining parameters match draw_mol_with_fgs_dict.
  • Returns: PNG binary string for the highlighted molecule.

canonical_smiles(smi)

Shorthand wrapper over RDKit canonicalisation: Chem.MolToSmiles(Chem.MolFromSmiles(smi)).

draw_compare_mols(smi_1, smi_2, afg=AccFG(), similarityThreshold=0.7, canonical=True, img_size=(500, 400))

Compare two molecules, highlight unique functional groups on each, and return PIL images for the rendered molecules.

  • Parameters
  • smi_1, smi_2 (str): Target and reference SMILES.
  • afg (AccFG): Functional group detector.
  • similarityThreshold (float): Passed to compare_mols to tune MCES sensitivity.
  • canonical (bool): Canonicalise inputs before comparison.
  • img_size (tuple[int, int]): Forwarded to draw_mol_with_fgs_dict.
  • Returns: list[PIL.Image.Image] containing [target_image, reference_image].
  • Usage
from accfg.draw import draw_compare_mols

target_img, ref_img = draw_compare_mols("CCO", "CC(=O)O")
target_img.show()

molimg(x)

Convert PNG bytes produced by RDKit’s Cairo drawer into a PIL.Image. Returns None if decoding fails.

img_grid(images, titles=None, num_columns=5, font='arial.ttf', font_size=18, title_height=30, cell_width=500, cell_height=400, bg_color=(255, 255, 255))

Lay out a list of PIL images on a single canvas with optional captions per image.

  • Parameters
  • images (list[PIL.Image.Image]): Source images (resized to cell_width × cell_height).
  • titles (list[str] | None): Optional caption per image; activates the title band.
  • num_columns (int): Column count for the grid.
  • font (str): Font file loaded via ImageFont.truetype; falls back to default if missing.
  • font_size, title_height, cell_width, cell_height, bg_color: Layout controls.
  • Returns: Combined PIL.Image.Image.

Print a NetworkX directed graph as an ASCII tree rooted at provided node IDs.

  • Parameters
  • graph (networkx.DiGraph): Graph with nodes labelled by functional group names.
  • roots (list[str]): Starting nodes to print.
  • header, last (str, bool): Internal arguments controlling recursion layout.
  • show_atom_idx (bool): Append mapped atom index data stored on graph.nodes[name]['mapped_atoms'].

Convenience wrapper that prunes redundant edges (ensuring an acyclic traversal) before delegating to print_directed_graph_as_tree.

SmilesMCStoGridImage(smiles: list[str] | dict[str, str], align_substructure: bool = True, verbose: bool = False, **kwargs)

Find the maximum common substructure across multiple SMILES strings and draw the SMARTS plus aligned molecules in a grid.

  • Parameters
  • smiles (list[str] | dict[str, str]): SMILES inputs. If a dict is supplied, values become panel legends.
  • align_substructure (bool): When True, re-generate 2D coordinates to align substructures to the MCS.
  • verbose (bool): When True, return additional debugging artefacts.
  • **kwargs: Passed directly to rdFMCS.FindMCS (e.g. ringMatchesRingOnly=True).
  • Returns
  • If verbose=False: PIL.Image.Image (RDKit grid image).
  • If verbose=True: tuple (image, mcs_smarts, mcs_mol, mols).
  • Usage
from accfg.draw import SmilesMCStoGridImage

img, smarts, mcs_mol, mols = SmilesMCStoGridImage(
    ["CCO", "CC(=O)O"],
    verbose=True,
    completeRingsOnly=True
)