mlchem.chem.visualise package

Submodules

mlchem.chem.visualise.drawing module

class MolDrawer

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:

Iterable

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 = [], size: Iterable = [300, 300], legend: str = '') None

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, optional) – Default atom indices for highlighting in draw_mol.

  • size (Iterable, optional) – Default canvas size as (width, height) in pixels.

  • 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 = [], size: Iterable = None, ACS1996_mode: bool = False) Image

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, optional) – Atom indices to highlight. If empty, self.highlightAtoms is used.

  • size (Iterable[int, int], 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]

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]

load_images(img_list: Iterable[Image] | Image) None

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

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

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: Iterable[Image] = None, n_columns: int = 4, size: Iterable = None, buffer: int = 5, empty_tile_colour: str = 'white', save: bool = False, filename: str = '') None

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 (Iterable[PIL.Image.Image], optional) – Images to arrange. If None, uses self.img_list.

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

  • size (Iterable[int, int], 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 iterable.

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: Iterable = [1000, 300]) Image

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 (Iterable, 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

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

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

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

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: Iterable, 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

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 (Iterable) – 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

class ChemicalSpace

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 3 or 4 columns: ‘SMILES’, ‘NAME’, ‘CLASS’, and optionally ‘METADATA’.

  • 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) – True if a 4th column is present in data. Default is False.

  • metadata_categorical (bool, optional) – True if the 4th column is categorical. 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)

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

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

Parameters:
  • data (pd.DataFrame) – A DataFrame with either 3 or 4 columns: - ‘SMILES’: SMILES strings of the molecules. - ‘NAME’: Names or identifiers of the molecules. - ‘CLASS’: Class labels for grouping or colouring. - ‘METADATA’ (optional): Additional metadata for further grouping.

  • 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) – True if a fourth column (‘METADATA’) is present in data. Default is False.

  • metadata_categorical (bool, optional) – True if the metadata column is categorical. Default is False.

Raises:

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

Notes

If df_descriptors is not provided, a message will be printed to remind the user to supply descriptors before visualisation.

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 = 25, height: int = 650, width: int = 866, marker_size: int = 10, save_html: bool = False) None

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

This method visualises the compressed chemical space using a scatter plot, with options to customise colours, shapes, size, and layout. It supports categorical metadata and can optionally save the plot as an HTML file.

Parameters:
  • colour_list (list, optional) – List of colours for the plot markers. Each class will be assigned a colour. 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’].

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

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

  • title_fontsize (int, optional) – Font size of the plot title. Default is 25.

  • 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. Default is 10.

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

Returns:

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

Return type:

None

Examples

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

Prepare the compressed dataframe for visualisation.

This method adds molecular structure files, names, and metadata to the compressed coordinates.

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.

Examples

>>> chem_space.prepare(df_compressed)
process(diversity_filter: float | None, collinearity_filter: float | None, standardise: bool = True)

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.

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)
reset_bokeh_options()

Reset Bokeh plot options to their default values.

Return type:

None

Examples

>>> chem_space.reset_bokeh_options()
reset_bokeh_tooltips()

Reset Bokeh tooltips to their default values.

Return type:

None

Examples

>>> chem_space.reset_bokeh_tooltips()
update_bokeh_options(**args) None

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.

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).

  • 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'
... )