mlchem.chem.visualise package

Submodules

mlchem.chem.visualise.drawing module

class MolDrawer[source]

Bases: object

Render molecules and image grids with configurable RDKit drawing options.

MolDrawer centralises drawing configuration (drawing_options) and provides helpers for:

  • single-molecule rendering (draw_mol),

  • palette preview (show_palette),

  • loading molecules/images (load_mols, load_images),

  • and gallery output (show_images_grid).

The class can operate with:

  • mlchem defaults (MLCHEM_DEFAULTS),

  • RDKit defaults (get_rdkit_defaults),

  • and per-instance option overrides (update_drawing_options).

Typical usage:

>>> from rdkit import Chem
>>> drawer = MolDrawer(size=[400, 300], legend="Example")
>>> drawer.update_drawing_options(atomPalette='cdk', highlightColour='tomato')
>>> mol = Chem.MolFromSmiles("CCO")
>>> image = drawer.draw_mol(mol, highlightAtoms=[1])

Batch usage:

>>> drawer = MolDrawer(size=[300, 300])
>>> drawer.load_mols([Chem.MolFromSmiles("CCO"), Chem.MolFromSmiles("c1ccccc1")])
>>> drawer.show_images_grid(n_columns=2)
mol

Default molecule used by draw_mol when no molecule is passed.

Type:

rdkit.Chem.rdchem.Mol or None

highlightAtoms

Default atom indices to highlight when draw_mol receives none.

Type:

Iterable

size

Default canvas size in pixels as (width, height).

Type:

sequence of int or numpy.ndarray

legend

Default legend used by draw_mol when none is passed.

Type:

str

mol_list

Internal list of molecules accumulated via load_mols.

Type:

list

highlightAtoms_list

History of highlight index sets used in drawing calls.

Type:

list

size_list

History of canvas sizes used in drawing calls.

Type:

list

legend_list

History of legends used in drawing calls.

Type:

list

img_list

Internal image collection used by load_images, load_mols, and show_images_grid.

Type:

list[PIL.Image.Image]

colour_dictionary

Named RGB palette imported from mlchem.importables.

Type:

dict

drawing_options

Active drawing configuration (starts as a copy of MLCHEM_DEFAULTS).

Type:

dict

Methods:
  • __init__(…) – Initialise the drawer and instance-level defaults.

  • get_rdkit_defaults(…) – Return RDKit native drawing defaults as a dictionary.

  • show_palette(…) – Visualise or save a colour dictionary.

  • update_drawing_options(…) – Update instance drawing options via keyword arguments.

  • reset_drawing_options(…) – Reset options to mlchem or RDKit defaults.

  • load_images(…) – Add one or more pre-rendered PIL images to the internal image list.

  • load_mols(…) – Add molecules and immediately render/store their images.

  • show_images_grid(…) – Display and optionally save images as a tiled grid.

  • draw_mol(…) – Render a single molecule with highlights, maps, and optional ACS style.

MLCHEM_DEFAULTS = {'addAtomIndices': False, 'addBondIndices': False, 'addStereoAnnotation': False, 'additionalAtomLabelPadding': 0, 'annotationColour': 'black', 'annotationFontScale': 0.5, 'atomHighlightsAreCircles': True, 'atomLabelDeuteriumTritium': False, 'atomNoteColour': 'black', 'atomPalette': 'cdk', 'atomWeights': [], 'backgroundColour': 'white', 'baseFontSize': 0.6, 'bondLineWidth': 2, 'bondNoteColour': 'black', 'circleAtoms': True, 'clearBackground': True, 'colourMap': None, 'continuousHighlight': True, 'contourColour': 'black', 'contourWidth': 1, 'dashNegative': True, 'drawMolsSameScale': False, 'dummiesAreAttachments': False, 'explicitMethyl': False, 'fillHighlights': True, 'fixedBondLength': -1, 'fixedFontSize': -1, 'fontFile': '', 'highlightAlpha': 1, 'highlightBondWidthMultiplier': 10, 'highlightColour': 'tomato', 'highlightRadius': 0.3, 'includeRadicals': True, 'legendColour': 'black', 'legendFontSize': 25, 'mapRes': 0.05, 'mapStyle': 'GC', 'maxFontSize': 40, 'maxRadius': 30, 'minFontSize': 6, 'minRadius': 2, 'multipleBondOffset': 0.15, 'negativeColour': 'mediumvioletred', 'noAtomLabels': False, 'numContours': 10, 'padding': 0.05, 'positiveColour': 'green', 'prepareMolsBeforeDrawing': True, 'queryColour': 'red', 'rotate': 0, 'scaleBondWidth': False, 'scaleHighlightBondWidth': True, 'scalingFactor': 2, 'singleColourWedgeBonds': False, 'symbolColour': 'black', 'unspecifiedStereoIsUnknown': False, 'useComplexQueryAtomSymbols': True, 'variableAttachmentColour': 'black', 'weightAlpha': 0.2}
__init__(mol: Mol | None = None, highlightAtoms: Iterable | None = None, size: Sequence[int] | ndarray | None = None, legend: str = '') → None[source]

Initialise a MolDrawer instance and its default drawing state.

The constructor stores defaults that are reused by draw_mol unless per-call arguments are provided.

Parameters:
  • mol (rdkit.Chem.rdchem.Mol or None, optional) – Molecule to keep as instance default. If provided, draw_mol() can be called without passing mol.

  • highlightAtoms (Iterable or None, optional) – Default atom indices for highlighting in draw_mol. If None, no atoms are highlighted by default.

  • size (sequence of int, numpy.ndarray or None, optional) – Default canvas size as (width, height) in pixels. If None, uses (300, 300).

  • legend (str, optional) – Default legend text shown under molecules.

Return type:

None

Examples

>>> from rdkit import Chem
>>> drawer = MolDrawer(
...     mol=Chem.MolFromSmiles("CCO"),
...     highlightAtoms=[1],
...     size=[400, 250],
...     legend="Ethanol",
... )
draw_mol(mol: Mol = None, legend: str = '', highlightAtoms: Iterable | None = None, size: Sequence[int] | ndarray | None = None, ACS1996_mode: bool = False) → Image[source]

Render and return a single molecule image.

The method applies the active drawing_options, supports atom highlighting, optional contour visualization of atomic weights (mapStyle=’GC’ or ‘C’ when atomWeights are provided), optional custom shape overlays, and ACS 1996 styling.

Contour Visualization (Atomic Weights)

When atomWeights is provided in drawing_options, mlchem can visualize these values using two different contour styles:

  • mapStyle=’GC’ (Gaussian Contours): Renders smooth gaussian overlays using RDKit’s ContourAndDrawGaussians. Best for continuous properties like electrostatic potential or similarity gradients. Contours blend smoothly across the molecular surface.

  • mapStyle=’C’ (Circle Contours): Custom mlchem implementation using gradient circles around atoms. Best for discrete atom-by-atom properties like per-atom charges or SHAP contributions. Provides clear visual separation between atoms.

This extends RDKit’s native gaussian contour support with: - A second visualization style (circle contours) - Seamless integration with all other drawing options - Proper legend handling (solves RDKit’s alignment issues) - Fine-grained color control via atomNoteColour, legendColour, etc. - Automatic 2D coordinate handling

Parameters:
  • mol (rdkit.Chem.rdchem.Mol, optional) – Molecule to draw. If None, self.mol is used.

  • legend (str, optional) – Legend text. If empty, self.legend is used.

  • highlightAtoms (iterable of int, optional) – Atom indices to highlight. If None or empty, self.highlightAtoms is used.

  • size (sequence of int or numpy.ndarray, optional) – Canvas size (width, height). If None, self.size is used.

  • ACS1996_mode (bool, default=False) – If True, draw using Draw.DrawMoleculeACS1996.

Returns:

Rendered molecule image.

Return type:

PIL.Image.Image

Raises:
  • AssertionError – If no molecule is available (mol is None and self.mol is None).

  • ValueError – If a named colour is unknown.

  • TypeError – If provided colour tuples/palettes are not valid.

Examples

>>> mol = Chem.MolFromSmiles("CCO")
>>> drawer = MolDrawer()
>>> img = drawer.draw_mol(mol, legend="Ethanol", highlightAtoms=[1])

Draw with gaussian contour similarity map (smooth overlay):

>>> from mlchem.chem.manipulation import PropManager as PM
>>> weights = PM.Mol.get_gasteiger_charges(mol)
>>> drawer.update_drawing_options(atomWeights=weights, mapStyle='GC')
>>> img = drawer.draw_mol(mol, legend="Gaussian contours")

Draw with circle-style weight map (atom-by-atom visualization):

>>> drawer.update_drawing_options(atomWeights=weights, mapStyle='C')
>>> img = drawer.draw_mol(mol, legend="Circle contours")
static get_rdkit_defaults() → dict[str, object][source]

Retrieve the default RDKit drawing options.

This method creates a temporary RDKit drawing context and reads the values from its drawOptions object. The returned dictionary can be used to compare or restore RDKit default drawing settings.

Returns:

Dictionary of RDKit drawing option names and default values.

Return type:

dict[str, object]

Examples

>>> from mlchem.chem.visualise.drawing import MolDrawer
>>> defaults = MolDrawer.get_rdkit_defaults()
>>> isinstance(defaults, dict)
True
load_images(img_list: Iterable[Image] | Image) → None[source]

Load one or more images into self.img_list.

The method appends to existing images and flattens nested iterables.

Parameters:

img_list (PIL.Image.Image or Iterable[PIL.Image.Image]) – Single image or iterable of images to append.

Return type:

None

Examples

>>> from PIL import Image
>>> img = Image.open("example.png")
>>> drawer = MolDrawer()
>>> drawer.load_images(img)
>>> drawer.load_images([img1, img2, img3])
load_mols(mols: Mol | Iterable[Mol]) → None[source]

Load molecules and render/store their images.

Molecules are appended to self.mol_list, then each molecule in the full stored list is rendered via a temporary MolDrawer and collected in self.img_list.

Parameters:

mols (rdkit.Chem.rdchem.Mol or Iterable[rdkit.Chem.rdchem.Mol]) – Single molecule or iterable of molecules.

Return type:

None

Examples

>>> from rdkit import Chem
>>> mol1 = Chem.MolFromSmiles("CCO")
>>> mol2 = Chem.MolFromSmiles("c1ccccc1")
>>> drawer = MolDrawer()
>>> drawer.load_mols([mol1, mol2])
reset_drawing_options(source: Literal['mlchem', 'rdkit'] = 'mlchem') → None[source]

Reset drawing options from a predefined source.

Parameters:

source ({'mlchem', 'rdkit'}, default='mlchem') –

Reset source:

  • ’mlchem’: copy MolDrawer.MLCHEM_DEFAULTS.

  • ’rdkit’: use values returned by get_rdkit_defaults().

Return type:

None

Examples

>>> drawer = MolDrawer()
>>> drawer.update_drawing_options(atomPalette='avalon', rotate=90)
>>> drawer.reset_drawing_options(source='mlchem')  # Reverts to default mlchem settings
>>> drawer.reset_drawing_options(source='rdkit')  # Reverts to native RDKit defaults
show_images_grid(images: Sequence[Image] | ndarray | None = None, n_columns: int = 4, size: Sequence[int] | ndarray | None = None, buffer: int = 5, empty_tile_colour: str = 'white', save: bool = False, filename: str = '') → None[source]

Display a set of images as a tiled grid.

If images is None, the method uses self.img_list. The output is shown with IPython.display.display and can optionally be saved.

Parameters:
  • images (sequence of PIL.Image.Image or numpy.ndarray, optional) – Images to arrange. If None, uses self.img_list.

  • n_columns (int, default=4) – Number of columns in the grid layout.

  • size (sequence of int or numpy.ndarray, optional) – Size of each image in pixels as (width, height). If None, uses the default size from self.size.

  • buffer (int, default=5) – Space in pixels between images in the grid.

  • empty_tile_colour (str, default='white') – Background colour for empty grid tiles. Must be a key in self.colour_dictionary.

  • save (bool, default=False) – If True, saves the grid image to a file.

  • filename (str, default='') – Filename to save the image if save is True.

Return type:

None

Raises:

AssertionError – If empty_tile_colour is not in the colour dictionary or if size is not a 2-element sequence.

Examples

>>> drawer = MolDrawer()
>>> drawer.load_images([img1, img2, img3])
>>> drawer.show_images_grid(n_columns=2, buffer=10)
>>> drawer.show_images_grid(save=True, filename="grid_output.png")
show_palette(palette: dict | None = None, save: bool = False, filename: str = '', size: Sequence[int] = (1000, 300)) → Image[source]

Display a colour palette as an image.

If palette is not provided, self.colour_dictionary is used.

Parameters:
  • palette (dict or None, optional) – Colour mapping {name: (r, g, b)}. When None, uses self.colour_dictionary.

  • save (bool, optional) – If True, write the generated image to filename.

  • filename (str, optional) – Output path used when save=True.

  • size (sequence of int, optional) – Output size in pixels as (width, height).

Returns:

Palette image.

Return type:

PIL.Image.Image

Examples

>>> drawer = MolDrawer()
>>> drawer.show_palette()
>>> drawer.show_palette(save=True, filename="palette.png")
update_drawing_options(**args) → None[source]

Update instance drawing options used by draw_mol.

The provided keyword arguments are merged into self.drawing_options. Unknown keys are kept in the dictionary, but they only affect rendering if they are consumed in draw_mol or recognised by RDKit draw options.

Parameters:

**args (dict) –

Keyword arguments overriding one or more entries from MolDrawer.MLCHEM_DEFAULTS. Common groups include:

  • Colours: atomPalette, backgroundColour, highlightColour, highlightAlpha, queryColour, annotationColour.

  • Style/layout: bondLineWidth, baseFontSize, padding, rotate.

  • Similarity maps: atomWeights, mapStyle, colourMap, mapRes, numContours.

  • Optional shapes: shapeTypes, shapeSizes, shapeColours, shapeCoords.

Notes

  • For a complete list of default option names and values, inspect MolDrawer.MLCHEM_DEFAULTS.

  • The default mapRes in mlchem is 0.05.

Return type:

None

Examples

>>> drawer = MolDrawer()
>>> drawer.update_drawing_options(atomPalette='avalon', backgroundColour='white')
>>> options = {'highlightColour': 'orange', 'rotate': 90}
>>> drawer.update_drawing_options(**options)

mlchem.chem.visualise.simmaps module

class SimMaps[source]

Bases: object

static get_similarity_map_from_weights(mol: Mol, weights: Iterable, colorMap=None, scale: int = -1, size: tuple = (250, 250), sigma=None, coordScale: int | float = 1.5, step: float = 0.01, contour_colour: str | tuple = 'black', contourLines: int = 10, alpha: float = 0.5, contour_width: int | float = 1, resolution: float = 0.05, dash_negative: bool = True, draw2d=None, draw_molecule: bool = True, legend: str = '', **kwargs) → MolDraw2D | Figure[source]

Generate a similarity map visualisation from atomic weights.

This method overlays a similarity map on a molecule using atomic weights, with optional contour lines and colour maps.

Adapted from RDKit (https://www.rdkit.org), originally licensed under the BSD 3-Clause License.

Parameters:
  • mol (rdkit.Chem.rdchem.Mol) – The molecule to visualise.

  • weights (Iterable) – Atomic weights to visualise.

  • colorMap (str or list or matplotlib colormap, optional) – Colour map to use. If None, a custom PiWG colour map is used.

  • scale (int, default=-1) – Scaling factor. If negative, uses the maximum absolute weight.

  • size (tuple, default=(250, 250)) – Size of the output image.

  • sigma (float, optional) – Gaussian width. If None, estimated from bond lengths.

  • coordScale (float, default=1.5) – Scaling factor for coordinates.

  • step (float, default=0.01) – Step size for Gaussian calculation.

  • contour_colour (str or tuple, default='black') – Colour of contour lines. Can be a string or RGB tuple.

  • contourLines (int or list, default=10) – Number of contour lines or specific contour levels.

  • alpha (float, default=0.5) – Transparency of contour lines.

  • contour_width (float, default=1) – Width of contour lines.

  • resolution (float, default=0.05) – Grid resolution for contour plotting.

  • dash_negative (bool, default=True) – Whether to use dashed lines for negative weights.

  • draw2d (rdkit.Chem.Draw.rdMolDraw2D.MolDraw2D, optional) – RDKit drawing object. Required for rendering.

  • draw_molecule (bool, default=True) – If True, draws the molecule on the canvas after contours. If False, only draws contours; caller is responsible for drawing the molecule. Useful when integrating with mlchem’s draw_mol() to apply color options first.

  • legend (str, default='') – Legacy parameter, kept for backwards compatibility but not used. For gaussian contours, legends are added by the caller (mlchem’s draw_mol) after rendering to ensure proper alignment with contours.

  • **kwargs (dict) – Additional keyword arguments passed to matplotlib drawing.

Returns:

If draw2d is provided, returns the modified drawing object. Otherwise, returns a matplotlib figure.

Return type:

rdMolDraw2D.MolDraw2D or matplotlib.figure.Figure

Raises:

ValueError – If draw2d is not provided or the molecule has fewer than 2 atoms.

Examples

>>> SimMaps.get_similarity_map_from_weights(mol, weights, draw2d=drawer)
static get_weights_from_fingerprint(refmol: Mol, probemol: Mol, fp_type: Literal['m', 'ap', 'rk', 'tt'] = 'm', similarity_metric: Literal['Tanimoto', 'Dice', 'Cosine', 'Sokal', 'Russel', 'RogotGoldberg', 'AllBit', 'OnBit', 'Kulczynski', 'McConnaughey', 'Asymmetric', 'BraunBlanquet', 'Tversky'] = 'Tanimoto', normalise: bool = False, return_df: bool = False, **kwargs) → Iterable | DataFrame[source]

Get atomic importance weights based on fingerprint similarity.

This method calculates atomic contributions by masking atoms in the probe molecule and computing the change in similarity to a reference molecule.

Parameters:
  • refmol (rdkit.Chem.rdchem.Mol) – The reference molecule.

  • probemol (rdkit.Chem.rdchem.Mol) – The probe molecule whose atoms will be masked.

  • fp_type ({'m', 'ap', 'rk', 'tt'}, default='m') – Type of fingerprint to use.

  • similarity_metric (str, default='Tanimoto') – Similarity metric to use. Options include: ‘Tanimoto’, ‘Dice’, ‘Cosine’, ‘Sokal’, ‘Russel’, ‘RogotGoldberg’, ‘AllBit’, ‘OnBit’, ‘Kulczynski’, ‘McConnaughey’, ‘Asymmetric’, ‘BraunBlanquet’, ‘Tversky’.

  • normalise (bool, optional) – If True, normalises the weights to the range (-1, 1). Default is False.

  • return_df (bool, optional) – If True, returns a pandas DataFrame. Otherwise, returns a NumPy array.

  • **kwargs (dict) – Additional fingerprint-specific parameters. See below.

  • Parameters (Fingerprint)

  • ----------------------

  • ('m') (Morgan)

  • radius (-)

  • fpType (-)

  • atomId (-)

  • nBits (-)

  • useFeatures (-)

  • ('ap') (Atom Pair)

  • fpType

  • atomId

  • nBits

  • minLength (-)

  • maxLength (-)

  • nBitsPerEntry (-)

  • ('tt') (Topological Torsion)

  • fpType

  • atomId

  • nBits

  • targetSize (-)

  • nBitsPerEntry

  • ('rk') (RDKit)

  • fpType

  • atomId

  • nBits

  • minPath (-)

  • maxPath (-)

  • nBitsPerHash (-)

Returns:

Atomic contributions to similarity. Format depends on return_df.

Return type:

Iterable or pandas.DataFrame

Examples

>>> SimMaps.get_weights_from_fingerprint(refmol, probemol, fp_type='m')
static get_weights_from_model(mol_input: Mol | str, estimator, estimator_cols: Sequence[str] | ndarray | Index | Series, model_type: Literal['regression', 'classification'], actual_val: float, fp_type: Literal['m', 'ap', 'tt', 'rk'], normalise: bool = False, return_df: bool = False, **kwargs) → Iterable | DataFrame[source]

Get atomic importance weights from a predictive model using masked fingerprints.

This method calculates atomic contributions by iteratively masking each atom in the molecule and evaluating the change in model prediction.

Parameters:
  • mol_input (rdkit.Chem.rdchem.Mol or str) – The input molecule as an RDKit Mol object or a SMILES string.

  • estimator (sklearn.base.BaseEstimator) – A trained scikit-learn estimator.

  • estimator_cols (sequence, numpy.ndarray, pandas.Index or pandas.Series) – Feature names used by the estimator.

  • model_type ({'regression', 'classification'}) – Type of model. Must be either ‘regression’ or ‘classification’.

  • actual_val (float) – The actual value predicted by the model. For classification, this is the probability of class 1; for regression, the continuous target value.

  • fp_type ({'m', 'ap', 'tt', 'rk'}) – Type of fingerprint to use: - ‘m’: Morgan - ‘ap’: Atom Pair - ‘tt’: Topological Torsion - ‘rk’: RDKit

  • normalise (bool, optional) – If True, normalises the weights to the range (-1, 1). Default is False.

  • return_df (bool, optional) – If True, returns a pandas DataFrame. Otherwise, returns a NumPy array.

  • **kwargs (dict) – Additional fingerprint-specific parameters. See below.

  • Parameters (Fingerprint)

  • ----------------------

  • ('m') (Morgan)

  • radius (-) – Radius of the Morgan fingerprint.

  • fpType (-) – Type of fingerprint: bit vector (‘bv’) or count-based.

  • atomId (-) – Atom to mask. -1 means no masking.

  • nBits (-) – Size of the bit vector.

  • useFeatures (-) – If True, uses FeatureMorgan; otherwise, ConnectivityMorgan.

  • ('ap') (Atom Pair)

  • fpType

  • atomId

  • nBits

  • minLength (-)

  • maxLength (-)

  • nBitsPerEntry (-)

  • ('tt') (Topological Torsion)

  • fpType

  • atomId

  • nBits

  • targetSize (-)

  • nBitsPerEntry

  • ('rk') (RDKit)

  • fpType

  • atomId

  • nBits

  • minPath (-)

  • maxPath (-)

  • nBitsPerHash (-)

Returns:

Atomic contributions to model prediction. Format depends on return_df.

Return type:

Iterable or pandas.DataFrame

Examples

>>> SimMaps.get_weights_from_model("CCO", model, feature_names, "regression", 0.85, "m")

mlchem.chem.visualise.space module

Independent visual encodings

After ChemicalSpace.prepare(), each visual property can use any prepared dataframe column independently. Extra columns in the original input are aligned by SMILES and retained. For example, with the corresponding class, dataset, and score categories present:

space.plot(
    colour_by='CLASS',
    colour_map={'score[0]': 'navy', 'score[1]': 'orange'},
    shape_by='METADATA',
    shape_map={'train': 'circle', 'test': 'triangle'},
    opacity_by='METADATA',
    opacity_map={'train': 0.4, 'test': 0.9},
    marker_size_by='SCORE',
    marker_size_map={0.1: 7, 0.9: 14},
    save_html=True,
    filename='chemical_space',
)

For continuous numeric colour with a labelled colour bar:

space.plot(
    colour_by='SCORE',
    colour_continuous=True,
    colour_palette=['navy', 'cyan', 'gold'],
    shape_by='METADATA',
    shape_map={'train': 'circle', 'test': 'triangle'},
)

Every observed categorical value must be mapped; extra mapping keys are allowed. Unknown columns, missing values, invalid Bokeh colours/shapes, non-finite values, opacities outside [0, 1], and nonpositive sizes raise errors. Numeric colours are categorical unless colour_continuous=True. The continuous palette defaults to Viridis256.

Each *_by conflicts only with the corresponding legacy *_list. Continuous colour also conflicts with colour_map. Unspecified encodings keep their legacy defaults: colour, opacity, and size by CLASS; shapes by METADATA when both metadata flags are enabled. Scalar marker_size is overridden by a size list or map. The classic 866 by 650 pixel plot, hover details, tables, notebook display, and HTML export remain available.

Legend labels identify both the encoding and source column. Colour swatches use the mapped colour and a uniform circle, opacity, and size; shape swatches use the mapped shape and a uniform neutral colour, opacity, and size. Opacity and size keys are markerless text, such as Opacity (METADATA): test = 0.9 and Size (METADATA): test = 14 px. Continuous colour retains its colour bar without categorical colour swatches. The compact legend remains in one plot area. Its proxy appearance and column count can be changed through space.update_bokeh_options() using legend_proxy_size, legend_proxy_alpha, legend_colour_proxy_marker, legend_shape_proxy_colour, and legend_ncols. The metadata_exists and metadata_categorical constructor options are legacy controls for the special METADATA column and its default shape behavior. They are not required for other extra columns or explicit *_by encodings; shape_by works with any prepared column without those flags.

Structure paths

Safe, unambiguous CLASS labels can be used directly as folder names. Labels with spaces/punctuation, Windows-reserved names, and case-insensitive collisions are encoded with a stable digest for portability and collision safety. Display labels are unchanged. Inspect space.class_structure_folders and use the MOLFILE column generated by prepare() rather than reconstructing paths from labels.

class ChemicalSpace[source]

Bases: object

A module to compute and visualise datasets in a compressed embedded space.

This class handles descriptor processing, dimensionality reduction, and preparation of molecular data for interactive visualisation.

Parameters:
  • data (pd.DataFrame) – A DataFrame with ‘SMILES’, ‘NAME’, ‘CLASS’, and optional extra columns for independent plot encodings. prepare() aligns them by SMILES.

  • needs_cleaning (bool, optional) – Whether the data requires cleaning. Default is False.

  • df_descriptors (pd.DataFrame, optional) – A DataFrame with SMILES as index and descriptor columns.

  • metadata_exists (bool, optional) – Enable backwards-compatible handling of the special ‘METADATA’ column. This is not required for other optional columns or their plot encodings. Default is False.

  • metadata_categorical (bool, optional) – Treat ‘METADATA’ as categorical for legacy marker shapes. This only affects the legacy shape behavior when no ‘shape_by’ mapping is supplied. Default is False.

Raises:

ValueError – If the input data does not have the expected column structure.

__init__(data: DataFrame, needs_cleaning: bool = False, df_descriptors: DataFrame = None, metadata_exists: bool = False, metadata_categorical: bool = False)[source]

Initialise a ChemicalSpace object for visualising molecular datasets in a compressed embedded space.

This constructor sets up the molecular data, descriptor matrix, legacy metadata options, and validates the structure of the input data and loads default Bokeh visualisation settings.

Parameters:
  • data (pd.DataFrame) – A DataFrame with required ‘SMILES’, ‘NAME’, and ‘CLASS’ columns. Any additional columns are available for independent plot encodings after prepare(). ‘METADATA’ remains a special legacy column; other optional columns do not require metadata flags.

  • needs_cleaning (bool, optional) – Whether the data requires cleaning before processing. Default is False.

  • df_descriptors (pd.DataFrame, optional) – A DataFrame with SMILES as index and molecular descriptors as columns.

  • metadata_exists (bool, optional) – Enable backwards-compatible handling of the special ‘METADATA’ column; when True, that column is required in data. It is not needed to use other optional columns with plot() encodings. Default is False.

  • metadata_categorical (bool, optional) – Treat ‘METADATA’ as categorical for legacy marker shapes. It only affects plotting when shape_by is omitted; explicit shape_by can select any prepared column without enabling either metadata flag. Default is False.

Raises:

ValueError – If the data DataFrame does not have the expected column structure.

Notes

If df_descriptors is not provided, a warning is logged to remind the user to supply descriptors before visualisation.

The metadata flags predate independent dataframe-column plot encodings and remain for compatibility with callers that use the special METADATA column and its legacy marker-shape behavior. They do not designate which columns are available for the new *_by plot arguments.

Examples

>>> cs = ChemicalSpace(data=df, df_descriptors=desc_df, metadata_exists=True)
plot(colour_list: list = None, shape_list: list = None, filename: str = '', title: str = '', title_fontsize: int | str | None = None, height: int = 650, width: int = 866, marker_size: int = 10, save_html: bool = False, opacity_list: list[float] | None = None, marker_size_list: list[float] | None = None, *, colour_by: str | None = None, colour_map: Mapping | None = None, shape_by: str | None = None, shape_map: Mapping | None = None, opacity_by: str | None = None, opacity_map: Mapping | None = None, marker_size_by: str | None = None, marker_size_map: Mapping | None = None, colour_continuous: bool = False, colour_palette: Sequence[str] | None = None) → None[source]

Generate a 2D scatter plot of the chemical space using Bokeh.

This method visualises the compressed chemical space using a scatter plot, with independently configurable colour, shape, opacity, and marker size. Colour can be categorical or continuous, and the plot can optionally be saved as an HTML file.

Parameters:
  • colour_list (list, optional) – List of colours for the plot markers. Each class will be assigned a colour in self.classnames order (sorted by prepare()). If not provided, defaults to: [‘Blue’, ‘Orange’, ‘Red’, ‘Black’, ‘Green’, ‘Cyan’, ‘Magenta’, ‘Yellow’].

  • shape_list (list, optional) – List of marker shapes. If not provided, defaults to: [‘circle’, ‘triangle’, ‘square’, ‘star’, ‘diamond’, ‘cross’, ‘x’, ‘asterisk’]. With categorical metadata, shapes follow self.metadata_names order.

  • filename (str, optional) – Name of the file to save the plot as (without extension).

  • title (str, optional) – Title of the plot.

  • title_fontsize (int or str, optional) – Font size of the plot title in pixels. An integer is interpreted as pixels; a string is passed to Bokeh as a CSS font size. If omitted, uses self.bokeh_dictionary['title_fontsize'] (25px by default). An explicit plot(title_fontsize=...) overrides the configured value for that call.

  • height (int, optional) – Height of the plot in pixels. Default is 650.

  • width (int, optional) – Width of the plot in pixels. Default is 866 (650 / 0.75).

  • marker_size (int, optional) – Size of the plot markers when marker_size_list is omitted. Default is 10.

  • save_html (bool, optional) – Whether to save the plot as an HTML file. Default is False.

  • opacity_list (list of float, optional) – One finite opacity in [0, 1] per class, in self.classnames order, matching colour_list in both plotting branches. Explicit values replace automatic opacity, without scaling. If omitted, opacity uses compute_alpha(class_count) * size_ratio(class_count, remaining_count), with counts taken from self.df_compressed.

  • marker_size_list (list of float, optional) – One finite positive marker size per class, in the same order as opacity_list. Overrides marker_size. With categorical metadata, all metadata subgroups within a class share its opacity and size; these lists do not follow shape_list.

  • colour_by (str, optional) – Independently select any prepared dataframe column for each encoding. Categorical values require the corresponding *_map. Missing column values or unmapped categories raise errors. A *_by argument conflicts with the legacy *_list for that same encoding only. Other encodings retain their legacy defaults. marker_size_map overrides scalar marker_size, just as marker_size_list does.

  • shape_by (str, optional) – Independently select any prepared dataframe column for each encoding. Categorical values require the corresponding *_map. Missing column values or unmapped categories raise errors. A *_by argument conflicts with the legacy *_list for that same encoding only. Other encodings retain their legacy defaults. marker_size_map overrides scalar marker_size, just as marker_size_list does.

  • opacity_by (str, optional) – Independently select any prepared dataframe column for each encoding. Categorical values require the corresponding *_map. Missing column values or unmapped categories raise errors. A *_by argument conflicts with the legacy *_list for that same encoding only. Other encodings retain their legacy defaults. marker_size_map overrides scalar marker_size, just as marker_size_list does.

  • marker_size_by (str, optional) – Independently select any prepared dataframe column for each encoding. Categorical values require the corresponding *_map. Missing column values or unmapped categories raise errors. A *_by argument conflicts with the legacy *_list for that same encoding only. Other encodings retain their legacy defaults. marker_size_map overrides scalar marker_size, just as marker_size_list does.

  • colour_map (mapping, optional) – Category-to-style dictionaries. Extra keys are allowed for reuse on filtered data. Colours and Bokeh marker names must be valid; opacities must be finite in [0, 1], and sizes finite and positive.

  • shape_map (mapping, optional) – Category-to-style dictionaries. Extra keys are allowed for reuse on filtered data. Colours and Bokeh marker names must be valid; opacities must be finite in [0, 1], and sizes finite and positive.

  • opacity_map (mapping, optional) – Category-to-style dictionaries. Extra keys are allowed for reuse on filtered data. Colours and Bokeh marker names must be valid; opacities must be finite in [0, 1], and sizes finite and positive.

  • marker_size_map (mapping, optional) – Category-to-style dictionaries. Extra keys are allowed for reuse on filtered data. Colours and Bokeh marker names must be valid; opacities must be finite in [0, 1], and sizes finite and positive.

  • colour_continuous (bool, optional (default=False)) – Explicitly map finite numeric colour_by values to a continuous palette with a colour bar. Conflicts with colour_map and colour_list. Numeric columns otherwise use categorical mappings.

  • colour_palette (sequence of str, optional) – At least two valid colours for continuous colour only. Defaults to Viridis256.

Returns:

Displays the plot in a Jupyter notebook and optionally saves it as HTML.

Return type:

None

Raises:

ValueError – If columns, mappings, style values, conflicting arguments, or required legacy categorical metadata values are invalid.

Notes

Colour and shape keys use dedicated invisible proxy renderers with unrelated glyph properties held constant. Opacity and size keys are text-only Bokeh legend items and include the mapped values. All labels identify the encoding and source column. The legend is kept in one compact area; continuous colour uses the colour bar without categorical colour swatches. Proxy appearance and legend columns can be changed through update_bokeh_options(). The figure keeps its 866 by 650 pixel default. Hover details and exported HTML use MOLFILE paths supplied by prepare().

Examples

>>> chem_space.plot(
...     colour_list=['blue', 'green'],
...     shape_list=['circle', 'square'],
...     filename='my_plot',
...     title='Chemical Space',
...     opacity_list=[0.3, 0.9],
...     marker_size_list=[6, 12],
...     save_html=True
... )
prepare(df_compressed: DataFrame)[source]

Prepare the compressed dataframe for visualisation.

This method adds molecular structure files, names, metadata, and all extra source columns to the compressed coordinates, aligned by SMILES.

Parameters:

df_compressed (pd.DataFrame) – A DataFrame with two columns [‘DIM_1’, ‘DIM_2’] representing the compressed coordinates of the molecules.

Returns:

Updates the instance with prepared data for visualisation.

Return type:

None

Raises:
  • ValueError – If df_compressed does not have exactly two columns named [‘DIM_1’, ‘DIM_2’].

  • ValueError – If the index of df_compressed or df_processed is not a series of SMILES strings.

  • ValueError – If SMILES keys are duplicated, compressed rows have no processed/data match, or class labels are missing or cannot be sorted.

Examples

>>> chem_space.prepare(df_compressed)

The compressed dataframe’s SMILES index is the alignment key. Its row order and coordinates are preserved; input and processed SMILES must be unique. Class labels must be sortable. Structure images are generated in stable SMILES order within each class, saved beneath a folder derived from that class label, and mapped back by SMILES, independent of directory enumeration and file modification times. Portable ASCII labels use their names directly; other labels use deterministic encoded folder names, available in self.class_structure_folders. The dedicated .mlchem_structures root keeps generated files separate from existing working-directory folders. plot() renders existing MOLFILE paths and does not generate images. Spaces, punctuation, reserved Windows names, and case-insensitive collisions require encoding for portable, unambiguous paths. The readable slug plus stable digest prevents different labels from collapsing to the same folder; display labels are unchanged. Always use the prepared MOLFILE column rather than reconstructing paths from class labels. When legacy categorical metadata shapes are enabled, metadata_names is derived only from the rows in this compressed dataframe; missing metadata values are ignored here so explicit shape_by encodings can still be used. Sortable metadata categories retain their sorted order; incomparable categories use their first-appearance order. The legacy metadata shape path reports an error if plotted rows have missing metadata, since those rows cannot be assigned a shape.

process(diversity_filter: float | None, collinearity_filter: float | None, standardise: bool = True, skip_binary_columns: bool = True)[source]

Process the descriptor data by applying diversity and collinearity filters, and optionally standardising the data.

Parameters:
  • diversity_filter (float or None) – A float between 0 and 1. Higher values apply stricter filtering to remove less diverse descriptors.

  • collinearity_filter (float or None) – A float between 0 and 1. Higher values apply looser filtering to remove more collinear descriptors.

  • standardise (bool, optional) – Whether to standardise the filtered descriptor data. Default is True.

  • skip_binary_columns (bool, optional) – Whether binary 0/1 columns are left unchanged during standardisation. Default is True.

Returns:

Updates the instance with processed descriptor data.

Return type:

None

Raises:

ValueError – If diversity_filter or collinearity_filter are outside [0, 1).

Examples

>>> chem_space = ChemicalSpace(data, df_descriptors)
>>> chem_space.process(
...     diversity_filter=0.5,
...     collinearity_filter=0.3,
...     skip_binary_columns=False,
... )
reset_bokeh_options()[source]

Reset Bokeh plot options to their default values.

Return type:

None

Examples

>>> chem_space.reset_bokeh_options()
reset_bokeh_tooltips()[source]

Reset Bokeh tooltips to their default values.

Return type:

None

Examples

>>> chem_space.reset_bokeh_tooltips()
update_bokeh_options(**args) → None[source]

Update the Bokeh plot options.

This method allows customisation of various Bokeh plot parameters for visualisations. Users can pass keyword arguments to set options such as title properties, legend properties, and axis properties. Only documented keys are accepted; unknown keys raise ValueError instead of being stored without affecting the plot. Updated settings persist on this instance until changed again or reset with reset_bokeh_options(). They are used by plot() unless an option is explicitly supplied to that call.

Parameters:
  • title_location (str, optional) – Location of the title. Options: ‘above’, ‘below’, ‘left’, ‘right’.

  • title_fontsize (str, optional) – Font size of the title (e.g., ‘25px’).

  • title_align (str, optional) – Alignment of the title. Options: ‘left’, ‘center’, ‘right’.

  • title_background_fill_colour (str, optional) – Background colour of the title.

  • title_text_colour (str, optional) – Text colour of the title.

  • legend_location (str, optional) – Location of the legend. Options: ‘top_left’, ‘top_center’, ‘top_right’, ‘center_right’, ‘bottom_right’, ‘bottom_center’, ‘bottom_left’, ‘center_left’, ‘center’.

  • legend_title (str, optional) – Title of the legend.

  • legend_label_text_font (str, optional) – Font of the legend labels (e.g., ‘times’).

  • legend_label_text_font_style (str, optional) – Font style of the legend labels (e.g., ‘italic’).

  • legend_label_text_colour (str, optional) – Text colour of the legend labels.

  • legend_border_line_width (int, optional) – Line width of the legend border.

  • legend_border_line_colour (str, optional) – Line colour of the legend border.

  • legend_border_line_alpha (float, optional) – Transparency of the legend border (0 to 1).

  • legend_background_fill_colour (str, optional) – Background colour of the legend.

  • legend_background_fill_alpha (float, optional) – Transparency of the legend background (0 to 1).

  • legend_proxy_size (float, optional) – Uniform marker size for colour and shape legend swatches. Default is 10.

  • legend_proxy_alpha (float, optional) – Uniform visible opacity for colour and shape legend swatches. Default is 1.

  • legend_colour_proxy_marker (str, optional) – Neutral marker used by all categorical colour swatches. Default is ‘circle’.

  • legend_shape_proxy_colour (str, optional) – Neutral colour used by all categorical shape swatches. Default is ‘grey’.

  • legend_ncols (int, optional) – Number of compact columns in the encoding legend. Default is 2.

  • xaxis_label (str, optional) – Label of the x-axis.

  • xaxis_line_width (int, optional) – Line width of the x-axis.

  • xaxis_line_colour (str, optional) – Line colour of the x-axis.

  • xaxis_major_label_text_colour (str, optional) – Text colour of the x-axis major labels.

  • xaxis_major_label_orientation (str, optional) – Orientation of the x-axis major labels. Options: ‘horizontal’, ‘vertical’.

  • yaxis_label (str, optional) – Label of the y-axis.

  • yaxis_line_width (int, optional) – Line width of the y-axis.

  • yaxis_line_colour (str, optional) – Line colour of the y-axis.

  • yaxis_major_label_text_colour (str, optional) – Text colour of the y-axis major labels.

  • yaxis_major_label_orientation (str, optional) – Orientation of the y-axis major labels. Options: ‘horizontal’, ‘vertical’.

  • axis_minor_tick_in (int, optional) – Length of the minor ticks inward.

  • axis_minor_tick_out (int, optional) – Length of the minor ticks outward.

Return type:

None

Examples

>>> plot.update_bokeh_options(
...     title_location='above',
...     title_fontsize='20px',
...     legend_location='top_right',
...     xaxis_label='PC1',
...     yaxis_label='PC2'
... )