### Setup and import mols2grid Source: https://mols2grid.readthedocs.io/en/latest/notebooks/customization.html Install mols2grid on Google Colab and import the library. The installation line is commented out for local use. ```python # uncomment and run if you're on Google Colab # !pip install mols2grid # for development purposes only # %load_ext autoreload # %autoreload 2 # %env ANYWIDGET_HMR=1 ``` ```python import mols2grid ``` -------------------------------- ### Setup and imports for the notebook Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/filtering.ipynb Contains a commented pip install for Google Colab, development magics, and the necessary imports from ipywidgets, RDKit, and mols2grid. ```python # uncomment and run if you're on Google Colab # !pip install mols2grid # for development purposes only # %load_ext autoreload # %autoreload 2 # %env ANYWIDGET_HMR=1 ``` ```python from ipywidgets import interact, widgets from rdkit.Chem import Descriptors import mols2grid ``` -------------------------------- ### Setup for Google Colab and development Source: https://mols2grid.readthedocs.io/en/latest/notebooks/filtering.html Optional setup code for Google Colab and development purposes. Uncomment the pip install line if running on Colab. ```python # uncomment and run if you're on Google Colab # !pip install mols2grid # for development purposes only # %load_ext autoreload # %autoreload 2 # %env ANYWIDGET_HMR=1 ``` -------------------------------- ### Install mols2grid with pip Source: https://mols2grid.readthedocs.io/en/latest/contents.html Alternative installation method using pip. ```bash pip install mols2grid ``` -------------------------------- ### Install mols2grid (commented for Colab) Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/quickstart.ipynb Optional installation command for Google Colab, commented out. Also includes development-only lines for autoreload and HMR. ```python # uncomment and run if you're on Google Colab # !pip install mols2grid # for development purposes only # %load_ext autoreload # %autoreload 2 # %env ANYWIDGET_HMR=1 ``` -------------------------------- ### Install dependencies for Google Colab Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/callbacks.ipynb Uncomment and run these lines if you are on Google Colab to install mols2grid and py3Dmol. The other lines are for development purposes only. ```python # uncomment and run if you're on Google Colab # !pip install mols2grid py3Dmol # for development purposes only # %load_ext autoreload # %autoreload 2 # %env ANYWIDGET_HMR=1 ``` -------------------------------- ### Import ipywidgets, RDKit descriptors, and mols2grid Source: https://mols2grid.readthedocs.io/en/latest/notebooks/filtering.html Imports required libraries for the filtering example. ```python from ipywidgets import interact, widgets from rdkit.Chem import Descriptors import mols2grid ``` -------------------------------- ### transform parameter example Source: https://mols2grid.readthedocs.io/en/latest/api/simple.html Shows how to use the transform parameter to apply functions to specific columns in the grid cells. The functions take the item's value as input and return a formatted string. ```python transform={ "Solubility": lambda x: f"{x:.2f}", "Melting point": lambda x: f"MP: {5/9*(x-32):.1f}°C" } ``` -------------------------------- ### MolGrid Class Initialization Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html The constructor for the MolGrid class, which handles the setup of the molecular grid, including rendering options, dataframe preparation, and widget registration. ```python def __init__( # noqa: PLR0912 self, df, smiles_col="SMILES", mol_col=None, size=(130, 90), useSVG=True, prerender=False, cache_selection=False, removeHs=False, use_coords=False, coordGen=True, MolDrawOptions=None, name="default", rename=None, **kwargs, ): if not (smiles_col or mol_col): raise ValueError("One of `smiles_col` or `mol_col` must be set") if not isinstance(name, str): raise TypeError( f"`name` must be a string. Currently of type {type(name).__name__}" ) if not prerender: if not useSVG: raise ValueError("On-the-fly rendering of PNG images not supported") if use_coords and mol_col: raise ValueError("Cannot use coordinates with on-the-fly rendering") self.prefer_coordGen = coordGen self.removeHs = removeHs self.useSVG = useSVG self.use_coords = use_coords self.img_size = size self.prerender = prerender self.smiles_col = smiles_col self.mol_col = mol_col dataframe = df.copy() if isinstance(df, pd.DataFrame) else pd.DataFrame(df) if rename: dataframe = dataframe.rename(columns=rename) self._extra_columns = ["img", "mols2grid-id"] # Add index. dataframe["mols2grid-id"] = list(range(len(dataframe))) # Generate drawing options. if prerender: Draw.rdDepictor.SetPreferCoordGen(coordGen) opts = MolDrawOptions or Draw.MolDrawOptions() for key, value in kwargs.items(): setattr(opts, key, value) self.MolDrawOptions = opts self._MolDraw2D = Draw.MolDraw2DSVG if useSVG else Draw.MolDraw2DCairo else: opts = {} if MolDrawOptions: for key in dir(MolDrawOptions): value = getattr(MolDrawOptions, key) if not ( key.startswith("_") or callable(value) or value.__class__.__module__ != "builtins" ): opts[key] = value opts.update(kwargs) opts.update({"width": self.img_size[0], "height": self.img_size[1]}) self.json_draw_opts = json.dumps(opts) # Prepare smiles and images. self.dataframe = self._prepare_dataframe(dataframe) # Register instance. self._grid_id = name if cache_selection: try: self._cached_selection = register.get_selection(name) except KeyError: self._cached_selection = {} register._init_grid(name) else: register._update_current_grid(name) else: self._cached_selection = {} register._init_grid(name) # Create widget. widget = MolGridWidget(grid_id=name, selection=str(self._cached_selection)) selection_handler = partial(register.selection_updated, name) widget.observe(selection_handler, names=["selection"]) # Register widget JS-side. if not is_running_within_marimo(): display(widget) self.widget = widget ``` -------------------------------- ### MolGrid.get_marimo_selection() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Gets the selection for marimo. ```APIDOC ## MolGrid.get_marimo_selection() ### Description Gets the selection for marimo. ``` -------------------------------- ### MolGrid.get_selection() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Gets the current selection. ```APIDOC ## MolGrid.get_selection() ### Description Gets the current selection. ``` -------------------------------- ### mols2grid.utils source code Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/utils.html The complete source code for the mols2grid.utils module, including imports, environment setup, and utility functions for molecule processing and environment detection. ```python import gzip import re from ast import literal_eval from functools import partial, wraps from importlib.util import find_spec from pathlib import Path import pandas as pd from jinja2 import Environment, FileSystemLoader from rdkit import Chem env = Environment( loader=FileSystemLoader(Path(__file__).parent / "templates"), autoescape=False ) def requires(module): def inner(func): @wraps(func) def wrapper(*args, **kwargs): if find_spec(module): return func(*args, **kwargs) raise ModuleNotFoundError( f"The module {module!r} is required to use {func.__name__!r} " "but it is not installed!" ) return wrapper return inner def tooltip_formatter(s, subset, fmt, style, transform): """Function to generate tooltips from a pandas Series Parameters ---------- s : pandas.Series Row in the internal pandas DataFrame subset : list Subset of columns that are used for the tooltip fmt : str Format string for each key-value pair of the tooltip style : dict CSS styling applied to each item independently transform : dict Functions applied to each value before rendering """ items = [] for k, v in s[subset].to_dict().items(): displayed = transform[k](v) if transform.get(k) else v value = ( f'{displayed}' if style.get(k) else f'{displayed}' ) items.append(fmt.format(key=k, value=value)) return "
".join(items) def mol_to_smiles(mol): """Returns a SMILES from an RDKit molecule, or None if not an RDKit mol""" return Chem.MolToSmiles(mol) if mol else None def mol_to_record(mol, mol_col="mol"): """Function to create a dict of data from an RDKit molecule""" return {**mol.GetPropsAsDict(includePrivate=True), mol_col: mol} if mol else {} [docs]def sdf_to_dataframe(sdf_path, mol_col="mol"): """Creates a dataframe of molecules from an SDFile. All property fields in the SDFile are made available in the resulting dataframe Parameters ---------- sdf_path : str, Path Path to the SDFile, ending with either ``.sdf`` or ``.sdf.gz`` mol_col : str Name of the column containing the RDKit molecules in the dataframe Returns ------- df : pandas.DataFrame """ read_file = gzip.open if str(sdf_path).endswith(".gz") else partial(open, mode="rb") with read_file(sdf_path) as f: return pd.DataFrame( [mol_to_record(mol, mol_col) for mol in Chem.ForwardSDMolSupplier(f)] ) def remove_coordinates(mol): """Removes the existing coordinates from the molecule. The molecule is modified inplace""" mol.RemoveAllConformers() return mol def slugify(string): """Replaces whitespaces with hyphens""" return re.sub(r"\s+", "-", string) def callback_handler(callback, event): """Handler for applying the callback function on change""" data = literal_eval(event.new) callback(data) def _get_streamlit_script_run_ctx(): from streamlit.runtime.scriptrunner import get_script_run_ctx return get_script_run_ctx() def is_running_within_streamlit(): """ Function to check whether python code is run within streamlit Returns ------- use_streamlit : boolean True if code is run within streamlit, else False """ try: ctx = _get_streamlit_script_run_ctx() except ImportError: return False else: return ctx is not None def is_running_within_marimo(): """ Function to check whether python code is run within marimo Returns ------- use_marimo : boolean True if code is run within marimo, else False """ import sys return "marimo" in sys.modules ``` -------------------------------- ### Initialize MolGrid from an SDF File Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Creates a MolGrid instance directly from an SDFile. Supports both .sdf and .sdf.gz formats. ```python @classmethod def from_sdf(cls, sdf_file, **kwargs): """Set up the dataframe used by mols2grid directly from an SDFile. Parameters ---------- sdf_file : str, pathlib.Path Path to the SDF file (.sdf or .sdf.gz) kwargs : object Other arguments passed on initialization .. versionchanged:: 0.2.0 Added support for `.sdf.gz` files """ mol_col = kwargs.pop("mol_col", "mol") df = sdf_to_dataframe(sdf_file, mol_col=mol_col) return cls(df, mol_col=mol_col, **kwargs) ``` -------------------------------- ### Install mols2grid with conda Source: https://mols2grid.readthedocs.io/en/latest/contents.html Install mols2grid from conda-forge. Requires Python 3.10+ and dependencies rdkit, pandas, and jinja2. ```bash conda install -c conda-forge mols2grid ``` -------------------------------- ### Get DataFrame subset from selection Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/quickstart.ipynb Uses the keys of the selection dictionary to index the original DataFrame and get the selected rows. ```python df.iloc[list(mols2grid.get_selection().keys())] ``` -------------------------------- ### Import libraries and load sample data Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/callbacks.ipynb Imports required libraries and reads an SDF file, sampling 50 molecules to keep the notebook light. Uses mols2grid's built-in solubility dataset. ```python import urllib.parse import urllib.request from urllib.error import HTTPError import py3Dmol from IPython.display import display from ipywidgets import widgets import mols2grid # Optional: read SDF file and sample 50 mols from it (to keep this notebook light) df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF).sample( 50, random_state=0xAC1D1C ) ``` -------------------------------- ### MolGrid.from_sdf(sdf_file, **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Sets up the dataframe used by mols2grid from an SDF file, supporting .sdf or .sdf.gz files. ```APIDOC ## MolGrid.from_sdf(sdf_file, **kwargs) ### Description Sets up the dataframe used by the grid from an SDF file. ### Parameters #### Required Parameters - **sdf_file** (str or pathlib.Path) - Path to the SDF file (.sdf or .sdf.gz). #### Optional Parameters - **kwargs** (object) - Other initialization arguments. ``` -------------------------------- ### MolGrid.to_interactive(subset=None, tooltip=None, tooltip_fmt='{key}: {value}', tooltip_placement='auto', transform=None, sort_by=None, use_iframe=False, truncate=True, n_items_per_page=24, selection=True, substruct_highlight=None, single_highlight=False, border='1px solid #cccccc', gap=0, pad=10, fontsize='12px', fontfamily="'DejaVu', sans-serif", textalign='center', background_color='white', hover_color='rgba(0,0,0,0.05)', custom_css=None, style=None, custom_header=None, callback=None) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Returns the HTML document for the interactive template with options for selecting, filtering, highlighting, and arranging molecules. ```APIDOC ## MolGrid.to_interactive(subset=None, tooltip=None, tooltip_fmt='{key}: {value}', tooltip_placement='auto', transform=None, sort_by=None, use_iframe=False, truncate=True, n_items_per_page=24, selection=True, substruct_highlight=None, single_highlight=False, border='1px solid #cccccc', gap=0, pad=10, fontsize='12px', fontfamily="'DejaVu', sans-serif", textalign='center', background_color='white', hover_color='rgba(0,0,0,0.05)', custom_css=None, style=None, custom_header=None, callback=None) ### Description Returns the HTML document for the "interactive" template. ### Parameters #### Optional Parameters - **subset** - Additional subset of data to display. - **tooltip** - Configuration for tooltip display. - **tooltip_fmt** (str) - Tooltip text format. - **tooltip_placement** (str) - Placement of the tooltip. - **transform** - Transformation applied to data. - **sort_by** - Sorting criteria. - **use_iframe** (bool) - Whether to render in an iframe. - **truncate** (bool) - Whether to truncate content. - **n_items_per_page** (int) - Number of items per page, default is 24. - **selection** (bool) - Enable row selection. - **substruct_highlight** - Substructure highlight patterns. - **single_highlight** (bool) - Highlight only a single structure. - **border** (str) - Border style. - **gap** (int) - Gap between cells. - **pad** (int) - Padding inside cells. - **fontsize** (str) - Text for font size. - **fontfamily** (str) - Font family. - **textalign** (str) - Text alignment. - **background_color** (str) - Background color. - **hover_color** (str) - Hover background color. - **custom_css** (str) - Custom CSS. - **style** - Custom style. - **custom_header** (str) - Custom header. - **callback** (function) - Callback function. ``` -------------------------------- ### MolGrid.from_sdf() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Creates a MolGrid from an SDF file. ```APIDOC ## MolGrid.from_sdf() ### Description Creates a MolGrid from an SDF file. ``` -------------------------------- ### Get selection from widget Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/quickstart.ipynb Retrieves the current selection from the mols2grid widget as a dictionary. ```python mols2grid.get_selection() ``` -------------------------------- ### MolGrid.render(template='interactive', **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Returns the HTML document for the specified template, either 'interactive' or 'static', with configurable options via kwargs. ```APIDOC ## MolGrid.render(template='interactive', **kwargs) ### Description Returns the HTML document corresponding to the 'interactive' or 'static' template. ### Parameters #### Optional Parameters - **template** (str) - The kind of grid to draw: 'interactive' for a multi-page interactive grid with selection and filters, or 'static' for a simple table similar to MolsToGridImage() for printing. - **kwargs** (object) - Other arguments to pass to to_interactive() or to_static(). ``` -------------------------------- ### Use external_link callback in Mols2Grid Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/callbacks.ipynb Example of passing the external_link callback to the Mols2Grid view function to enable external link behavior. ```python view = Mols2Grid(...) view.display( callback=mols2grid.callbacks.external_link(), ) ``` -------------------------------- ### Get Marimo Selection State Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Returns a marimo state object for tracking selected indices. This method requires the environment to be running within marimo. ```python [docs] def get_marimo_selection(self): """Returns a marimo state object containing the list of selected indices. Only available when running in marimo. Returns ------- getter A getter function for the selection state. Calling it with no arguments returns the current list of selected IDs. """ if not is_running_within_marimo(): raise RuntimeError("This method is only available in a marimo notebook.") import marimo as mo get_state, set_state = mo.state([]) def _on_change(change): try: sel = ast.literal_eval(change["new"]) set_state(list(sel.keys())) except (ValueError, SyntaxError): pass if not getattr(self.widget, "_marimo_hooked", False): self.widget.observe(_on_change, names=["selection"]) self.widget._marimo_hooked = True return get_state ``` -------------------------------- ### Initialize MolGrid from RDKit Molecules Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Creates a MolGrid instance directly from a list of RDKit molecule objects. ```python @classmethod def from_mols(cls, mols, **kwargs): """Set up the dataframe used by mols2grid directly from a list of RDKit molecules. Parameters ---------- mols : list List of RDKit molecules kwargs : object Other arguments passed on initialization """ mol_col = kwargs.pop("mol_col", "mol") df = pd.DataFrame([mol_to_record(mol, mol_col=mol_col) for mol in mols]) return cls(df, mol_col=mol_col, **kwargs) ``` -------------------------------- ### to_static(subset=None, tooltip=None, ...) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Generates an HTML document for the static template of the chemical grid. ```APIDOC ## to_static ### Description Returns the HTML document for the static template of the grid. ### Parameters - **subset** (list or None) - Optional - Columns to be displayed in each cell of the grid. - **tooltip** (list, None or False) - Optional - Columns to be displayed inside the tooltip. - **tooltip_fmt** (str) - Optional - Format string of each key/value pair in the tooltip. - **tooltip_trigger** (str) - Optional - Sequence of triggers for the tooltip: click, hover or focus. - **tooltip_placement** (str) - Optional - Position of the tooltip: auto, top, bottom, left or right. - **transform** (dict or None) - Optional - Functions applied to specific items in all cells. - **sort_by** (str or None) - Optional - Sort the grid according to the following field. - **use_iframe** (bool) - Optional - Whether to use an iframe to display the grid. - **truncate** (bool) - Optional - Whether to truncate the text in each cell if it is too long. - **n_cols** (int) - Optional - Number of columns in the table. - **border** (str) - Optional - CSS border property for cells. - **gap** (int) - Optional - Gap between cells. - **pad** (int) - Optional - Padding within cells. - **fontsize** (str) - Optional - Font size for text. - **fontfamily** (str) - Optional - Font family for text. - **textalign** (str) - Optional - Text alignment. - **custom_css** (str or None) - Optional - Custom CSS styles. - **style** (dict or None) - Optional - Style definitions for cells. - **custom_header** (str or None) - Optional - Custom libraries to be loaded in the header. - **callback** (str, callable or None) - Optional - JavaScript or Python callback to be executed when clicking on an image. ### Returns - **html_document** (str) - The generated HTML string. ``` -------------------------------- ### Style a column with conditional CSS Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/dispatch.html Use the style parameter to apply CSS styling to a specific column. The function receives the item's value and returns a CSS string. In this example, text is colored red when the Solubility value is less than -5. ```python style={"Solubility": lambda x: "color: red" if x < -5 else ""} ``` -------------------------------- ### To interactive template Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Returns the HTML document for the interactive template. ```python [docs] def to_interactive( # noqa: PLR0912 self, # Display subset=None, tooltip=None, tooltip_fmt="{key}: {value}", tooltip_placement="auto", transform=None, sort_by=None, use_iframe=False, truncate=True, n_items_per_page=24, selection=True, # Mols substruct_highlight=None, single_highlight=False, # CSS border="1px solid #cccccc", gap=0, pad=10, fontsize="12px", fontfamily="'DejaVu', sans-serif", textalign="center", background_color="white", hover_color="rgba(0,0,0,0.05)", custom_css=None, style=None, # Customization custom_header=None, callback=None, ): """Returns the HTML document for the "interactive" template.""" ``` -------------------------------- ### to_static() Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Returns the HTML document for the static template. Provides extensive customization options for display, CSS styling, and tooltips. ```APIDOC ## to_static() ### Description Returns the HTML document for the "static" template. Allows customization of displayed columns, tooltips, transformations, sorting, iframe usage, truncation, number of columns, CSS styling, and custom headers. ### Parameters #### Display - **subset** (list or None, default=None) - Optional - Columns to be displayed in each cell. The "img" and "mols2grid-id" columns are displayed by default. - **tooltip** (list, None or False, default=None) - Optional - Columns to be displayed inside the tooltip. When no subset is set, all columns are listed by default. Use False to hide the tooltip. - **tooltip_fmt** (str, default="{key}: {value}") - Optional - Format string of each key/value pair in the tooltip. - **tooltip_trigger** (str, default="focus") - Optional - Sequence of triggers for the tooltip: click, hover, or focus. - **tooltip_placement** (str, default="auto") - Optional - Position of the tooltip: auto, top, bottom, left, or right. - **transform** (dict or None, default=None) - Optional - Functions applied to specific items in all cells. The dict must follow a key: function structure where the key corresponds to a column in subset or tooltip. - **sort_by** (str or None, default=None) - Optional - Sort the grid according to the given field (must be present in subset or tooltip). - **use_iframe** (bool, default=False) - Optional - Whether to use an iframe to display the grid. Defaults to True in Jupyter Notebook or JupyterLab. - **truncate** (bool, default=False) - Optional - Whether to truncate text in each cell if too long. - **n_cols** (int, default=5) - Optional - Number of columns in the table. #### CSS Styling - **border** (str, default="1px solid #cccccc") - Optional - CSS border style. - **gap** (int, default=0) - Optional - Gap between cells. - **pad** (int, default=10) - Optional - Padding inside cells. - **fontsize** (str, default="12px") - Optional - Font size. - **fontfamily** (str, default="'DejaVu', sans-serif") - Optional - Font family. - **textalign** (str, default="center") - Optional - Text alignment. - **custom_css** (str or None, default=None) - Optional - Custom CSS. - **style** (dict or None, default=None) - Optional - Additional styling. #### Customization - **custom_header** (str or None, default=None) - Optional - Custom header HTML. ### Returns - HTML document (string) for the static template. ``` -------------------------------- ### Display grid from SDFile Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/quickstart.ipynb Displays a molecular grid from an SDFile using mols2grid.display. Supports .sdf and .sdf.gz files. ```python mols2grid.display(mols2grid.datafiles.SOLUBILITY_SDF) ``` -------------------------------- ### Import mols2grid Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/quickstart.ipynb Imports the mols2grid library. ```python import mols2grid ``` -------------------------------- ### MolGrid.render() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Renders the HTML document. ```APIDOC ## MolGrid.render() ### Description Renders the HTML document. ``` -------------------------------- ### display(arg, **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/dispatch.html Generate an interactive grid of molecules and display it. This is a singledispatch function that accepts a pandas DataFrame, SDF file path, or list of molecules, and returns an IPython HTML view. ```APIDOC ## display(arg, **kwargs) ### Description Generate an interactive grid of molecules and display it. This is a singledispatch function that accepts a pandas DataFrame, SDF file path, or list of molecules, and returns an IPython HTML view. ### Parameters #### arg (pandas.DataFrame, SDF file, or list of molecules) - Required - The input containing your molecules. #### Customization Parameters - **name** (str, default="default") - Optional - Name of the grid. Used when retrieving selections from multiple grids at the same time. - **rename** (dict or None, default=None) - Optional - Rename the properties in the final document. - **custom_header** (str or None, default=None) - Optional - Custom libraries to be loaded in the header of the document. - **callback** (str, callable or None, default=None) - Optional - Only available for the "interactive" template. JavaScript or Python callback to be executed when clicking on an image. A dictionary containing the data for the full cell is directly available as `data` in JS. For Python, the callback function must have `data` as the first argument. All values in the `data` dict are parsed as strings, except "mols2grid-id" which is always an integer. Fields containing spaces in their name will be replaced by hyphens, e.g., "mol weight" becomes available as `data["mol-weight"]`. ### Returns - **view** (IPython.core.display.HTML) - The HTML representation of the interactive grid. ### Notes - You can also directly use RDKit's MolDrawOptions parameters as arguments. Additionally, `atomColourPalette` is available to customize the atom palette if you're not prerendering images (`prerender=False`). - Version history: Added `sort_by`, `custom_css`, `custom_header`, and `callback` arguments in 0.1.0. Added `substruct_highlight` in 0.2.0. Changed behavior in 0.2.2 and 1.0.0. ``` -------------------------------- ### Customize grid content and style with mols2grid.display Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/customization.ipynb Displays a grid from the solubility SDF file with renamed fields, a subset of columns, tooltip fields, conditional styling, value transformations, sorting, and molecule drawing options. The style uses lambda functions to apply CSS based on values. ```python mols2grid.display( mols2grid.datafiles.SOLUBILITY_SDF, # rename fields for the output document rename={"SOL": "Solubility", "SOL_classification": "Class", "NAME": "Name"}, # set what's displayed on the grid subset=["ID", "img", "Solubility"], # set what's displayed on the hover tooltip tooltip=["Name", "SMILES", "Class", "Solubility"], # style for the grid labels and tooltips style={ "Solubility": lambda x: "color: red; font-weight: bold;" if x < -3 else "", "__all__": lambda x: "background-color: azure;" if x["Solubility"] > -1 else "", }, # change the precision and format (or other transformations) transform={"Solubility": lambda x: round(x, 2)}, # sort the grid in a different order by default sort_by="Name", # molecule drawing parameters fixedBondLength=25, clearBackground=False, ) ``` -------------------------------- ### MolGrid.from_mols(mols, **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Class method to set up the dataframe used by mols2grid from a list of RDKit molecules. ```APIDOC ## MolGrid.from_mols(mols, **kwargs) ### Description Sets up the dataframe used by the grid from a list of RDKit molecules. ### Parameters #### Required Parameters - **mols** (list) - List of RDKit molecules. #### Optional Parameters - **kwargs** (object) - Other arguments passed on initialization. ``` -------------------------------- ### Render grid Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Returns the HTML document for the specified template type. ```python [docs] def render(self, template="interactive", **kwargs): """Returns the HTML document corresponding to the "interactive" or "static" template. See :meth:`to_interactive` and :meth:`to_static` for the full list of arguments. Parameters ---------- template : str What kind of grid to draw: * interactive An interactive grid that layouts the original set of molecules on several pages, allowing for selecting molecules and filtering them using text or substructure queries. * static A simple table with all molecules displayed at once, similarly to RDKit's :func:`~rdkit.Chem.Draw.rdMolDraw2D.MolsToGridImage`. This template is mainly used for printing on paper or in a PDF file. Most of the interactive actions aren't available. """ self.template = template return getattr(self, f"to_{self.template}")(**kwargs) ``` -------------------------------- ### MolGrid display(_use_iframe=False, iframe_width='100%', iframe_height=None, iframe_allow='clipboard-write', iframe_sandbox='allow-scripts allow-same-origin allow-downloads allow-popups allow-modals', **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Renders and displays the molecular grid in a Jupyter notebook. Returns an IPython.core.display.HTML object for inline viewing. ```APIDOC ## MolGrid.display(_use_iframe=False, iframe_width='100%', iframe_height=None, iframe_allow='clipboard-write', iframe_sandbox='allow-scripts allow-same-origin allow-downloads allow-popups allow-modals', **kwargs) ### Description Renders and displays the grid in a Jupyter notebook. ### Method display ### Parameters #### Optional Parameters - **use_iframe** (bool) - Optional - Whether to use an iframe for embedding. - **iframe_width** (string) - Optional - Width of the iframe, defaults to '100%'. - **iframe_height** (string) - Optional - Height of the iframe, defaults to None. - **iframe_allow** (string) - Optional - Permission policy for the iframe, defaults to 'clipboard-write'. - **iframe_sandbox** (string) - Optional - Sandbox restrictions for the iframe. ### Returns - **view** (IPython.core.display.HTML) ``` -------------------------------- ### render(template='interactive', **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Returns the HTML document corresponding to the 'interactive' or 'static' template. Dispatches to to_interactive or to_static based on the template parameter. ```APIDOC ## render(template='interactive', **kwargs) ### Description Returns the HTML document corresponding to the 'interactive' or 'static' template. Dispatches to to_interactive or to_static based on the template parameter. ### Method Function ### Signature `render(self, template='interactive', **kwargs)` ### Parameters - **template** (str) - Optional - What kind of grid to draw: 'interactive' (default) or 'static'. - **kwargs** - Optional - Additional arguments passed to the selected template method (see to_interactive and to_static). ### Returns - **str** - The HTML document for the selected template. ``` -------------------------------- ### MolGrid.to_static() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Converts the grid to a static HTML. ```APIDOC ## MolGrid.to_static() ### Description Converts the grid to a static HTML. ``` -------------------------------- ### MolGrid.save(output, **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Renders and saves the grid to an HTML document. ```APIDOC ## MolGrid.save(output, **kwargs) ### Description Renders and saves the grid in an HTML document. ### Parameters #### Required Parameters - **output** (str) - The path to save the HTML file. #### Optional Parameters - **kwargs** (object) - Additional arguments for rendering. ``` -------------------------------- ### display registration for str and Path Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/dispatch.html Registers the display function for string and Path inputs, treating them as SDF file paths. ```python @display.register(str) @display.register(Path) def _(sdf, **kwargs): template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "display") return MolGrid.from_sdf(sdf, **kwargs).display(template=template, **render_kwargs) ``` -------------------------------- ### Display grid from DataFrame with mol_col Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/quickstart.ipynb Converts an SDFile to a DataFrame, samples 50 rows, and displays the grid using the 'mol' column for RDKit molecules. ```python df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF) subset_df = df.sample(50, random_state=0xAC1D1C) mols2grid.display(subset_df, mol_col="mol") ``` -------------------------------- ### MolGrid.from_mols() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Creates a MolGrid from a list of molecules. ```APIDOC ## MolGrid.from_mols() ### Description Creates a MolGrid from a list of molecules. ``` -------------------------------- ### Built-in info callback Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/callbacks.ipynb Uses the built-in mols2grid.callbacks.info() function to display a popup with molecule information. ```python mols2grid.display( df, callback=mols2grid.callbacks.info(), ) ``` -------------------------------- ### MolGrid Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Constructor for the MolGrid class, which handles drawing molecules, rendering the HTML document, and saving or displaying it in a Jupyter Notebook. ```APIDOC ## MolGrid ### Description Creates a grid of molecules for display in Jupyter Notebooks. Allows advanced usage like filtering with external controls. ### Constructor `_class_ mols2grid.MolGrid(_df_, _smiles_col ='SMILES'_, _mol_col =None_, _size =(130, 90)_, _useSVG =True_, _prerender =False_, _cache_selection =False_, _removeHs =False_, _use_coords =False_, _coordGen =True_, _MolDrawOptions =None_, _name ='default'_, _rename =None_, _** kwargs_)` ### Parameters - **df** (pandas.DataFrame, dict or list) - Required - Dataframe containing a SMILES or mol column, or dictionary containing a list of SMILES, or list of dictionaries containing a SMILES field. - **smiles_col** (str or None) - Optional, default="SMILES" - Name of the SMILES column in the dataframe, if available. - **mol_col** (str or None) - Optional, default=None - Name of an RDKit molecule column. If available, coordinates and atom/bonds annotations from this will be used for depiction. ``` -------------------------------- ### show_3d() Source: https://mols2grid.readthedocs.io/en/latest/api/callbacks.html Queries the API(s) listed in `query` using the SMILES of the structure, to fetch the 3D structure and display it with `3Dmol.js`. ```APIDOC ## show_3d() ### Description Queries the API(s) listed in `query` using the SMILES of the structure, to fetch the 3D structure and display it with `3Dmol.js`. ### Function Signature `mols2grid.callbacks.show_3d(title='SMILES', subtitle=None, query=None, height='100%', style='width:100%;height:100%') -> JSCallback` ### Parameters - **title** (str) - Optional - Title of the popup. Use `title='${data["Name"]}'` to use the value of the column “Name” as a title. - **subtitle** (str) - Optional - Secondary title which works the same as title. - **query** (list or dict) - Optional - List of APIs used to fetch the 3D structure from (by order of priority). To use a custom API, use a dict with the following format: ``` { "url": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{}/SDF?record_type=3d", "format": "sdf", "field": "SMILES", "encode": True, } ``` In this example, the value in the `SMILES` field will be URI-encoded and replace the curly-braces in the `url` strings to create the URL to fetch the 3D structure from in the SDF format. - **height** (str) - Optional - Height of the 3Dmol.js viewer in the modal. - **style** (str) - Optional - CSS style applied to the modal window. ### Returns - **JSCallback** - JavaScript callback that displays the 3D structure. ``` -------------------------------- ### Configure list.js mapping and CSS styles Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Sets up the mapping for list.js and applies custom CSS styles to the dataframe columns. ```python # Set mapping for list.js. if "__all__" in style: whole_cell_style = True x = "[{data: ['mols2grid-id', 'cellstyle']}, " else: whole_cell_style = False x = "[{data: ['mols2grid-id']}, " value_names = [slugify(c) for c in value_names] value_names = x + str(value_names)[1:] # Apply CSS styles. for col, func in style.items(): if col == "__all__": name = "cellstyle" df[name] = df.apply(func, axis=1) else: name = f"style-{slugify(col)}" df[name] = df[col].apply(func) final_columns.append(name) value_names = value_names[:-1] + f", {{ attr: 'style', name: {name!r} }}"] ``` -------------------------------- ### Save grid to HTML file Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Renders the grid and saves it to a specified file path. ```python def save(self, output, **kwargs): """Render and save the grid in an HTML document.""" with open(output, "w", encoding="utf-8") as f: f.write(self.render(**kwargs)) ``` -------------------------------- ### Apache License 2.0 notice Source: https://mols2grid.readthedocs.io/en/latest/contents.html Apache License 2.0 notice for mols2grid, covering all files in the directory and subdirectories unless otherwise noted. ```text Copyright 2021-2025 Cédric BOUYSSET Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Grid template rendering Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Renders the static HTML template with the provided configuration parameters. ```python template = env.get_template("static.html") template_kwargs = { "tooltip": tooltip, "tooltip_trigger": repr(tooltip_trigger), "tooltip_placement": repr(tooltip_placement), "use_iframe": use_iframe, "truncate": truncate, "border": border, "gap": gap, "pad": pad, "textalign": textalign, "fontsize": fontsize, "fontfamily": fontfamily, "iframe_padding": 18, "cell_width": self.img_size[0], "custom_css": custom_css or "", "custom_header": custom_header or "", "data": "\n".join(data), } return template.render(**template_kwargs) ``` -------------------------------- ### Handle tooltips and custom transformations Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Formats tooltips and applies user-defined transformation functions to the dataframe. ```python # Create tooltip. if tooltip: df["m2g-tooltip"] = df.apply( tooltip_formatter, axis=1, args=(tooltip, tooltip_fmt, style, transform) ) final_columns += ["m2g-tooltip"] value_names = ( value_names[:-1] + ", {attr: 'data-content', name: 'm2g-tooltip'}]" ) info_btn_html = '
i
' else: info_btn_html = "" # Apply custom user function. for col, func in transform.items(): df[col] = df[col].apply(func) ``` -------------------------------- ### MolGrid.display() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Displays the grid in a Jupyter Notebook. ```APIDOC ## MolGrid.display() ### Description Displays the grid in a Jupyter Notebook. ``` -------------------------------- ### Add selection checkboxes and callbacks Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/molgrid.html Configures checkbox inputs for selection and callback buttons for grid interactivity. ```python # Add checkboxes. if selection: if self._cached_selection: df["cached_checkbox"] = False df.loc[ df["mols2grid-id"].isin(self._cached_selection.keys()), "cached_checkbox", ] = True final_columns += ["cached_checkbox"] value_names = ( value_names[:-1] + ", {attr: 'checked', name: 'cached_checkbox'}]" ) checkbox_html = ( '' ) else: checkbox_html = "" # Add callback button. callback_btn_html = '
' if callback else "" ``` -------------------------------- ### Convert SDF to DataFrame and display a sample Source: https://mols2grid.readthedocs.io/en/latest/notebooks/quickstart.html Converts the same SDF file to a pandas DataFrame using sdf_to_dataframe, samples 50 rows, and then displays the subset with mols2grid.display specifying mol_col="mol". Requires the DataFrame to contain an RDKit molecule column. ```python df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF) subset_df = df.sample(50, random_state=0xAC1D1C) mols2grid.display(subset_df, mol_col="mol") ``` -------------------------------- ### Basic print callback with Output widget Source: https://mols2grid.readthedocs.io/en/latest/_sources/notebooks/callbacks.ipynb Defines a Python callback that prints all data fields except 'img'. Uses an ipywidgets Output widget to capture and display the output, which is mandatory for print/display in callbacks. ```python output = widgets.Output() # the Output widget let's us capture the output generated by the callback function # its presence is mandatory if you want to print/display some info with your callback @output.capture(clear_output=True, wait=True) def show_data(data): data.pop("img") for key, value in data.items(): print(key, value) view = mols2grid.display( df, callback=show_data, ) display(view) output ``` -------------------------------- ### save(arg, **kwargs) Source: https://mols2grid.readthedocs.io/en/latest/_modules/mols2grid/dispatch.html Generate an interactive grid of molecules and save it to a file. This is a singledispatch function that accepts a pandas DataFrame, SDF file path, or list of molecules, and requires an output path. ```APIDOC ## save(arg, **kwargs) ### Description Generate an interactive grid of molecules and save it to a file. This is a singledispatch function that accepts a pandas DataFrame, SDF file path, or list of molecules, and requires an output path. ### Parameters #### arg (pandas.DataFrame, SDF file, or list of molecules) - Required - The input containing your molecules. #### output (str) - Required - Name and path of the output document. ### Notes - See `display` for the full list of arguments. ``` -------------------------------- ### MolGrid.template Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Template attribute. ```APIDOC ## MolGrid.template ### Description Template attribute. ``` -------------------------------- ### MolGrid.save() Source: https://mols2grid.readthedocs.io/en/latest/api/molgrid.html Saves the grid to a file. ```APIDOC ## MolGrid.save() ### Description Saves the grid to a file. ```