chem and ml subpackages¶
mlchem.helper module¶
- class LogCapture[source]¶
Bases:
objectConfigure mlchem pipeline logging with optional file persistence.
By default, mlchem functions emit INFO-level logs to console. Use LogCapture to add file logging, change the log level, or silence console output.
- Parameters:
log_level (int or str, default='INFO') – Logging level threshold (e.g., ‘INFO’, ‘DEBUG’, ‘WARNING’).
to_console (bool, default=True) – Whether to print logs to console. Set False to log only to file.
to_file (str or None, default=None) – Optional file path to write logs to. If provided, logs are appended to the file as well as console (if to_console=True).
- stream¶
In-memory buffer containing captured logs.
- Type:
StringIO
Examples
>>> # Default: logs appear on console automatically >>> sfs = SequentialForwardSelection(...) >>> sfs.fit(X_train, y_train, X_test, y_test) >>> # Output appears on console immediately
>>> # Optionally: capture to file + memory for inspection >>> logs = LogCapture(to_file='pipeline.log') >>> sfs.fit(X_train, y_train, X_test, y_test) >>> print(logs.get_logs()) # View memory capture >>> # Also check pipeline.log file
>>> # Silent mode: only to file >>> logs = LogCapture(to_console=False, to_file='pipeline.log') >>> sfs.fit(X_train, y_train, X_test, y_test)
- __init__(log_level: int | str | Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] = 20, to_console: bool = True, to_file: str | None = None) None[source]¶
- clear() None[source]¶
Clear captured logs from memory buffer.
Examples
>>> import logging >>> with LogCapture(to_console=False) as capture: ... logging.warning('old message') ... capture.clear() ... capture.get_logs() ''
- get_logs() str[source]¶
Retrieve all captured logs from memory as a string.
- Returns:
Complete captured log output from in-memory buffer.
- Return type:
str
Examples
>>> import logging >>> with LogCapture(to_console=False) as capture: ... logging.warning('sample message') ... captured = 'sample message' in capture.get_logs() >>> captured True
- add_encoding_legend(plot: figure, colour_entries: Sequence[tuple[str, str]], shape_entries: Sequence[tuple[str, str]], text_entries: Sequence[str], proxy_x: float, proxy_y: float, proxy_size: int | float = 10, proxy_alpha: float = 1.0, colour_proxy_marker: str = 'circle', shape_proxy_colour: str = 'grey', ncols: int = 2)[source]¶
Add an encoding legend with isolated proxy glyphs and text-only entries.
Colour and shape proxies are invisible plot renderers located at a real data coordinate; they draw only in the legend. Text entries use
LegendItem(renderers=[])and therefore have no glyph swatch.
- add_inchi_to_dataframe(df: DataFrame, loc: int, smiles_column_name: str) DataFrame[source]¶
Add an InChI column to a DataFrame by converting SMILES strings.
- Parameters:
df (pandas.DataFrame) – Input DataFrame.
loc (int) – Column index to insert the InChI column.
smiles_column_name (str) – Name of the column containing SMILES strings.
- Returns:
DataFrame with the added InChI column.
- Return type:
pandas.DataFrame
Examples
>>> import pandas as pd >>> df = add_inchi_to_dataframe(pd.DataFrame({'SMILES': ['CCO']}), 1, 'SMILES') >>> df.columns.tolist() ['SMILES', 'INCHI']
- assign_sign(x: float | int) str[source]¶
Return the sign of a number as ‘+’ or ‘-‘.
- Parameters:
x (float or int) – Input value.
- Returns:
‘+’ if x is non-negative, ‘-’ otherwise.
- Return type:
str
Examples
>>> assign_sign(-3) '-'
- bokeh_plot(p: figure, classnames: list[str], dict_datatables: dict[str, DataTable]) None[source]¶
Display a Bokeh plot with associated DataTables.
- Parameters:
p (bokeh.plotting.Figure) – Bokeh plot to display.
classnames (list of str) – List of class names.
dict_datatables (dict of str to DataTable) – Mapping of class names to DataTables.
- Return type:
None
Examples
>>> from bokeh.models import DataTable >>> from bokeh.plotting import figure >>> plot = figure() >>> _ = plot.line([0, 1], [0, 1]) >>> bokeh_plot(plot, ['sample'], {'sample': DataTable()})
- coerce_log_level(level: int | str) int[source]¶
Resolve a logging level name or integer into a numeric logging level.
- Parameters:
level (int or str) – Logging level as integer (e.g. 20) or level name (e.g. ‘INFO’).
- Returns:
Numeric logging level.
- Return type:
int
- Raises:
ValueError – If level is not a valid logging level name or integer.
Examples
>>> coerce_log_level('INFO') 20
- compute_alpha(size: int) float[source]¶
Compute transparency value based on sample size.
- Parameters:
size (int) – Sample size.
- Returns:
Computed alpha value.
- Return type:
float
- Raises:
ValueError – If size is negative.
Examples
>>> compute_alpha(800) 0.5
- convert_rgb(rgb_tuple: tuple[int, int, int], mode: Literal['normalise', 'denormalise']) tuple[float, float, float] | tuple[int, int, int][source]¶
Convert RGB values between 0-255 and 0-1 ranges.
- Parameters:
rgb_tuple (tuple of int) – RGB values in the form (R, G, B).
mode ({'normalise', 'denormalise'}) – Conversion mode. ‘normalise’ converts from 0-255 to 0-1, ‘denormalise’ converts from 0-1 to 0-255.
- Returns:
Converted RGB values.
- Return type:
tuple of float or tuple of int
Examples
>>> convert_rgb((255, 128, 64), 'normalise') (1.0, 0.5019607843137255, 0.25098039215686274) >>> convert_rgb((1.0, 0.5, 0.25), 'denormalise') (255, 127, 63)
- convert_size(size: tuple[float, float] | None = None, pixel_size: tuple[int, int] | None = None, dpi: int = 100) tuple[int, int] | tuple[float, float][source]¶
Convert between size in inches and size in pixels.
- Parameters:
size (tuple of float, optional) – Size in inches as (width, height).
pixel_size (tuple of int, optional) – Size in pixels as (width, height).
dpi (int, default=100) – Dots per inch used for conversion.
- Returns:
Converted size in pixels if size is provided, or in inches if pixel_size is provided.
- Return type:
tuple of int or tuple of float
Examples
>>> convert_size(size=(2, 3), dpi=100) (200, 300) >>> convert_size(pixel_size=(200, 300), dpi=100) (2.0, 3.0)
- count_features(list_features: Iterable[str]) int[source]¶
Count the total number of features, including interaction terms.
- Parameters:
list_features (iterable of str) – List of feature names, possibly including interaction terms.
- Returns:
Total number of features.
- Return type:
int
Examples
>>> count_features(['a', 'b', 'a b']) 4 >>> count_features(['a', 'a b', 'c^2']) 5 >>> count_features(['a', 'b', 'c', 'c a', 'c b^2', 'a^3']) 11
- create_mask(array: ndarray, lower: float | int, upper: float | int) ndarray[source]¶
Create a boolean mask for values within a specified range.
- Parameters:
array (numpy.ndarray) – Input array.
lower (float or int) – Lower bound.
upper (float or int) – Upper bound.
- Returns:
Boolean mask array.
- Return type:
numpy.ndarray
Examples
>>> create_mask(np.array([1, 2, 3, 4, 5]), 1.9, 4.1) array([False, True, True, True, False])
- create_progressive_column_names(serial_name: str, n: int) list[str][source]¶
Generate a list of sequential column names.
- Parameters:
serial_name (str) – Base name for the columns.
n (int) – Number of columns to generate.
- Returns:
List of column names.
- Return type:
list of str
Examples
>>> create_progressive_column_names('col', 3) ['col1', 'col2', 'col3']
- create_smooth_gradient_circle(radius: int, color: tuple[int, int, int], alpha: float) Image[source]¶
Create a smooth gradient circle with transparency.
- Parameters:
radius (int) – Radius of the circle.
color (tuple of int) – Base RGB color in the range [0, 255].
alpha (float) – Transparency level in the range [0, 1].
- Returns:
PIL Image object containing the gradient circle.
- Return type:
Image.Image
Examples
>>> create_smooth_gradient_circle(10, (255, 0, 0), 0.5).size (20, 20)
- create_structure_files(df: DataFrame, structure_column_name: str, folder_name: str) None[source]¶
Create PNG structure files for molecules in a DataFrame.
- Parameters:
df (pandas.DataFrame) – Input DataFrame.
structure_column_name (str) – Column containing molecular structures.
folder_name (str) – Folder to save the PNG images.
Notes
The folder is created if needed but is not cleared. Existing files not replaced by the generated numbered PNGs are preserved.
- Return type:
None
Examples
>>> import pandas as pd >>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as temp_dir: ... output_dir = Path(temp_dir) / 'structures' ... create_structure_files( ... pd.DataFrame({'SMILES': ['CCO']}), 'SMILES', str(output_dir) ... ) ... len(list(output_dir.iterdir())) 1
- dfs_to_excel(file_name: str, dfs: Iterable[DataFrame], sheet_names: Iterable[str]) None[source]¶
Write multiple DataFrames to an Excel file, each on a separate sheet.
- Parameters:
file_name (str) – Name of the Excel file.
dfs (iterable of pandas.DataFrame) – DataFrames to write.
sheet_names (iterable of str) – Names of the sheets.
- Return type:
None
Examples
>>> import pandas as pd >>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as temp_dir: ... output = Path(temp_dir) / 'data.xlsx' ... dfs_to_excel(str(output), [pd.DataFrame({'value': [1]})], ['data']) ... output.exists() True
- disable_estimator_parallelization(estimator)[source]¶
Disable internal parallelization in sklearn estimators to avoid nested parallelization.
When wrapper-level parallelization (ThreadPoolExecutor) is used, individual estimators should disable internal job parallelism to prevent nested parallelism warnings and avoid thread conflicts.
- Parameters:
estimator (object) – A scikit-learn estimator object.
- Returns:
The estimator with internal parallelization disabled if applicable, otherwise unchanged.
- Return type:
object
Examples
>>> from sklearn.ensemble import RandomForestClassifier >>> estimator = disable_estimator_parallelization( ... RandomForestClassifier(n_jobs=4) ... ) >>> estimator.n_jobs is None True
- find_all_occurrences(text: str, substring: str) list[int][source]¶
Find all starting indices of a substring in a text.
- Parameters:
text (str) – Text to search.
substring (str) – Substring to find.
- Returns:
List of starting indices where the substring occurs.
- Return type:
list of int
Examples
>>> find_all_occurrences('test test test', 'test') [0, 5, 10]
- flatten(args: Any) tuple[Any, ...][source]¶
Flatten a nested structure into a single tuple.
- Parameters:
args (Any) – The nested structure to flatten.
- Returns:
A flattened tuple containing all elements.
- Return type:
tuple
Examples
>>> flatten([1, [2, 3], [[4, 5], 6]]) (1, 2, 3, 4, 5, 6)
- generate_cartesian_product(*lists: Sequence) list[list][source]¶
Generate the Cartesian product of multiple lists.
Produces all combinations where each combination contains exactly one element from each input list. For example, given lists A, B, and C, returns all tuples (a, b, c) where a ∈ A, b ∈ B, c ∈ C.
- Parameters:
*lists (sequence) – Two or more non-string sequences to combine.
- Returns:
List of combinations, where each combination is a list containing one element from each input list.
- Return type:
list of list
- Raises:
ValueError – If fewer than two lists are provided, or if any list is empty.
TypeError – If any argument is not a non-string sequence.
Examples
>>> generate_cartesian_product([1, 2], ['a', 'b']) [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
>>> generate_cartesian_product([True, False], ['x', 'y'], [1]) [[True, 'x', 1], [True, 'y', 1], [False, 'x', 1], [False, 'y', 1]]
- generate_combination_cascade(elements: Collection, n: int) list[list][source]¶
Generate all combinations of elements from size 1 to n.
- Parameters:
elements (collection) – Re-iterable collection of elements to combine.
n (int) – Maximum size of combinations.
- Returns:
List of combinations of elements.
- Return type:
list of list
Examples
>>> generate_combination_cascade(['a', 'b', 'c'], 2) [['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c']]
- generate_random_rgb() tuple[float, float, float][source]¶
Generate a random RGB color.
- Returns:
A tuple of three floats representing an RGB color, with each component in the range [0, 1].
- Return type:
tuple of float
Examples
>>> rgb = generate_random_rgb() >>> len(rgb), all(0 <= value <= 1 for value in rgb) (3, True)
- identify_df_duplicates(df: DataFrame, column_name: str, keep: Literal['first', 'last'] = 'last') tuple[DataFrame, DataFrame][source]¶
Identify and separate duplicate rows in a DataFrame based on a column.
- Parameters:
df (pandas.DataFrame) – Input DataFrame.
column_name (str) – Column to check for duplicates.
keep ({'first', 'last'}, default='last') – Which duplicate to keep.
- Returns:
Cleaned DataFrame and DataFrame of removed duplicates.
- Return type:
tuple of pandas.DataFrame
- Raises:
KeyError – If column_name does not exist in df.
ValueError – If keep is not ‘first’ or ‘last’.
Examples
>>> import pandas as pd >>> df = pd.DataFrame({'A': [1, 2, 2, 3]}) >>> cleaned, duplicates = identify_df_duplicates(df, 'A') >>> len(cleaned), len(duplicates) (3, 1)
- insert_string_piece(text: str, substring: str, index: int) str[source]¶
Insert a substring into a string at a specified index.
- Parameters:
text (str) – Original string.
substring (str) – Substring to insert.
index (int) – Index at which to insert the substring.
- Returns:
Modified string.
- Return type:
str
- Raises:
ValueError – If index is less than 0.
Examples
>>> insert_string_piece('Hello World', 'Beautiful ', 5) 'Hello Beautiful World'
- loadingbar(count: int, total: int, size: int) None[source]¶
Display a loading bar to indicate progress.
- Parameters:
count (int) – Current iteration.
total (int) – Total number of iterations.
size (int) – Length of the loading bar.
- Return type:
None
Examples
>>> from contextlib import redirect_stdout >>> from io import StringIO >>> output = StringIO() >>> with redirect_stdout(output): ... loadingbar(1, 3, 10) >>> '001/003' in output.getvalue() True
- make_rgb_transparent(fg_rgb: tuple[float, float, float], bg_rgb: tuple[float, float, float] = (1.0, 1.0, 1.0), alpha: float = 0.5) tuple[float, float, float][source]¶
Apply transparency to a foreground RGB color over a background color.
- Parameters:
fg_rgb (tuple of float) – Foreground RGB color in the range [0, 1].
bg_rgb (tuple of float, optional) – Background RGB color in the range [0, 1]. Default is white (1.0, 1.0, 1.0).
alpha (float, default=0.5) – Transparency level, where 0 is fully transparent and 1 is fully opaque.
- Returns:
RGB color after applying transparency.
- Return type:
tuple of float
Examples
>>> make_rgb_transparent((1.0, 0.0, 0.0), (1.0, 1.0, 1.0), 0.5) (1.0, 0.5, 0.5)
- merge_dicts_with_duplicates(dict1: dict[str, Any], dict2: dict[str, Any]) dict[str, Any][source]¶
Merge two dictionaries, renaming duplicate keys from the second dictionary.
- Parameters:
dict1 (dict of str to Any) – First dictionary.
dict2 (dict of str to Any) – Second dictionary.
- Returns:
Merged dictionary with unique keys.
- Return type:
dict of str to Any
Examples
>>> merge_dicts_with_duplicates({'a': 1, 'b': 2}, {'b': 3, 'c': 4}) {'a': 1, 'b': 2, 'b_duplicate': 3, 'c': 4}
- normalise_iterable(values: Iterable[float | int]) list[float][source]¶
Normalise values in an iterable so that the maximum absolute value is 1.
- Parameters:
values (iterable of float or int) – Iterable of numerical values.
- Returns:
Normalised values.
- Return type:
list of float
Examples
>>> normalise_iterable([2, 4]) [0.5, 1.0]
- prepare_dataframe(df: DataFrame, dir_name: str) DataFrame[source]¶
Add a ‘MOLFILE’ column to a DataFrame with sorted file paths.
- Parameters:
df (pandas.DataFrame) – Input DataFrame.
dir_name (str) – Directory containing the files.
- Returns:
DataFrame with the added ‘MOLFILE’ column.
- Return type:
pandas.DataFrame
Examples
>>> import pandas as pd >>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as temp_dir: ... (Path(temp_dir) / 'molecule.sdf').touch() ... df = prepare_dataframe(pd.DataFrame({'A': [1], 'B': [2]}), temp_dir) ... Path(df.loc[0, 'MOLFILE']).name 'molecule.sdf'
- prepare_datatable(df: DataFrame, height: int = 500, width: int = 866) DataTable[source]¶
Create a Bokeh DataTable from a DataFrame.
- Parameters:
df (pandas.DataFrame) – Input DataFrame.
height (int, default=500) – Height of the DataTable.
width (int, default=int(650 / 0.75)) – Width of the DataTable.
- Returns:
Bokeh DataTable object.
- Return type:
bokeh.models.DataTable
- Raises:
KeyError – If required core columns are missing from the DataFrame.
Examples
>>> import pandas as pd >>> df = pd.DataFrame({ ... 'DIM_1': [1], 'DIM_2': [2], 'SMILES': ['CCO'], 'MOLFILE': ['mol.png'], ... 'NAME': ['ethanol'], 'NAME_SHORT': ['eth'] ... }) >>> table = prepare_datatable(df) >>> len(table.columns) 6
- process_custom_string(s: str, target_substring: str, replacement_list: list[str], separator: str = ';') str[source]¶
Process a string by replacing a target substring with elements from a list and formatting the result.
- Parameters:
s (str) – The original string.
target_substring (str) – The substring to replace.
replacement_list (list of str) – List of strings to replace the target substring.
separator (str, default=';') – Separator used in formatting the result.
- Returns:
The processed and formatted string.
- Return type:
str
Examples
>>> process_custom_string('Nc1ccccc1N', 'c1ccccc1', ['CYC']) ';CYC;'
- reset_string(input_string: str) str[source]¶
Remove punctuation and convert a string to lowercase.
- Parameters:
input_string (str) – Input string.
- Returns:
Processed string.
- Return type:
str
Examples
>>> reset_string('Hello, World!') 'helloworld'
- resolve_n_jobs(n_jobs: int) int[source]¶
Normalize n_jobs values used by parallel wrappers.
- Parameters:
n_jobs (int) – Requested number of workers. -1 means all CPUs.
- Returns:
Resolved positive worker count.
- Return type:
int
- Raises:
ValueError – If n_jobs is not -1 or a positive integer.
Examples
>>> resolve_n_jobs(2) 2
- show_png(data: bytes) Image[source]¶
Display a PNG image from binary data.
- Parameters:
data (bytes) – Binary data of the PNG image.
- Returns:
PIL Image object.
- Return type:
Image.Image
Examples
>>> from io import BytesIO >>> from PIL import Image >>> image_data = BytesIO() >>> Image.new('RGB', (1, 1), color='red').save(image_data, format='PNG') >>> show_png(image_data.getvalue()).size (1, 1)
- size_ratio(size1: int, size2: int) float[source]¶
Compute a ratio based on the relative sizes of two values.
- Parameters:
size1 (int) – First size.
size2 (int) – Second size.
- Returns:
Computed ratio.
- Return type:
float
- Raises:
ValueError – If either size is negative or both sizes are zero.
Examples
>>> size_ratio(1, 3) 0.875
- sort_list_by_other_list(list_1: list, list_2: list[int | float]) tuple[list[str], list[int | float]][source]¶
Sort one list based on the absolute values of another list.
- Parameters:
list_1 (list) – List of elements to sort.
list_2 (list of int or float) – List of values used to determine sort order.
- Returns:
Sorted list of elements and corresponding sorted values.
- Return type:
tuple of list
Examples
>>> sort_list_by_other_list(['apple', 'banana', 'cherry'], [3, -7, 2]) (['banana', 'apple', 'cherry'], [-7, 3, 2])
- standardise_path(path: str) str[source]¶
Convert a Windows-style path to a standardised format.
- Parameters:
path (str) – Path string with backslashes.
- Returns:
Path string with forward slashes.
- Return type:
str
Examples
>>> standardise_path('C:\\Users\\User\\Documents') 'C:/Users/User/Documents'
- start_logging(log_level: int | str | Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] = 20, to_console: bool = True, to_file: str | None = None) LogCapture[source]¶
Configure mlchem pipeline logging with optional file persistence.
Convenience function to set up logging. Logs are emitted to console by default; optionally also to a file for later inspection.
- Parameters:
log_level (int or str, default='INFO') – Logging level threshold (e.g., ‘INFO’, ‘DEBUG’, ‘WARNING’).
to_console (bool, default=True) – Whether to print logs to console.
to_file (str or None, default=None) – Optional file path to write logs to.
- Returns:
Log manager object with .get_logs() for memory inspection.
- Return type:
Examples
>>> # Log to console + file >>> logs = start_logging(to_file='pipeline.log') >>> sfs.fit(X_train, y_train, X_test, y_test) >>> print(logs.get_logs()) # Inspect memory
>>> # Log only to file (silent) >>> logs = start_logging(to_console=False, to_file='pipeline.log') >>> sfs.fit(X_train, y_train, X_test, y_test)
- suppress_warnings() None[source]¶
Suppress all warnings in the current Python session.
- Return type:
None
Examples
>>> import warnings >>> with warnings.catch_warnings(record=True) as caught: ... suppress_warnings() ... warnings.warn('suppressed', UserWarning) >>> len(caught) 0
- try_except(func: ~typing.Callable[[], ~typing.Any], exc: ~typing.Any = None, exceptions: type[BaseException] | tuple[type[BaseException], ...] = <class 'Exception'>) Any[source]¶
Execute a function and return its result or a fallback value on exception.
- Parameters:
func (callable) – Function to execute.
exc (any, optional) – Value to return if an exception occurs. Default is None.
exceptions (exception type or tuple of exception types, optional) – Exception types to catch. Default catches Exception.
- Returns:
Result of the function or fallback value.
- Return type:
any
- Raises:
TypeError – If exceptions is not an exception class or tuple of exception classes.
Examples
>>> try_except(lambda: 1 / 0, exc='error') 'error' >>> try_except(lambda: 1 / 1) 1.0
- validate_dataframe_columns(dataframe: DataFrame, required_columns: Iterable[Any], dataframe_name: str = 'dataframe') None[source]¶
Raise a clear error when a DataFrame lacks required columns.
Examples
>>> import pandas as pd >>> validate_dataframe_columns(pd.DataFrame({'feature': [1]}), ['feature'])
- validate_task_type(task_type: str) str[source]¶
Validate task type used by ML helpers.
- Parameters:
task_type (str) – Task kind.
- Returns:
The validated task type.
- Return type:
str
- Raises:
ValueError – If task_type is not ‘classification’ or ‘regression’.
Examples
>>> validate_task_type('classification') 'classification'
- visualise_colour(rgb_tuple: tuple[float, float, float]) None[source]¶
Display a single RGB color.
- Parameters:
rgb_tuple (tuple of float) – RGB values in the range [0, 1].
- Return type:
None
Examples
>>> visualise_colour((1.0, 0.0, 0.0))
- visualise_colour_grid(colour_dictionary: dict[str, tuple[float, float, float]], save: bool = False, filename: str = '', figsize: tuple[int, int] = (20, 20)) None[source]¶
Display a grid of RGB colors.
- Parameters:
colour_dictionary (dict of str to tuple of float) – Dictionary mapping color names to RGB tuples.
save (bool, default=False) – Whether to save the figure.
filename (str, optional) – Filename to save the figure if save is True.
figsize (tuple of int, default=(20, 20)) – Size of the figure.
- Return type:
None
Examples
>>> visualise_colour_grid({'red': (1.0, 0.0, 0.0), 'blue': (0.0, 0.0, 1.0)})
mlchem.importables module¶
- Useful collections to perform various tasks:
metal_list: List with all metals in SMILES notation.
chemical_dictionary: dictionary in the form {‘fragment’: int} to create a bag of fragments useful in
mlchem.chem.manipulation.colour_dictionary: dictionary of RGB tuples for a number of predefined colours.
chemotype_dictionary: collection of many pattern recognition functions that will be used by
chem.calculator.descriptors.get_chemotypes().bokeh_dictionary: collection of predefined bokeh plotting parameters.
bokeh_tooltips: predefined HMTL bokeh tooltips to interactively visualise chemical space.
interpretable_descriptors_rdkit: list of rdkit descriptors with a simple meaning.
interpretable_descriptors_mordred: list of mordred descriptors with a simple meaning.
similarity_metric_dictionary: dictionary in the form {metric_name: func} collecting various similarity metric functions (functions can be called from mlchem.metrics module as well).
mlchem.metrics module¶
- AllBitSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the AllBit similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.AllBitSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The AllBit similarity, considering both on and off bits in the fingerprints.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> AllBitSimilarity(fp, fp) 1.0
- AsymmetricSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Asymmetric similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.AsymmetricSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Asymmetric similarity, emphasizing features present in the first fingerprint.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> AsymmetricSimilarity(fp, fp) 1.0
- BraunBlanquetSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Braun-Blanquet similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.BraunBlanquetSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Braun-Blanquet similarity, calculated as the intersection over the maximum bit count.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> BraunBlanquetSimilarity(fp, fp) 1.0
- CosineSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Cosine similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.CosineSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Cosine similarity, measuring the cosine of the angle between two bit vectors.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> CosineSimilarity(fp, fp) 1.0
- DiceSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Dice similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.DiceSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Dice similarity coefficient, ranging from 0 (no similarity) to 1 (identical).
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> DiceSimilarity(fp, fp) 1.0
- FingerprintSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect, metric: callable) float[source]¶
Compute the fingerprint similarity using a specified similarity metric.
This function is a shortcut for the RDKit method DataStructs.FingerprintSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second fingerprint.
metric (callable) – The similarity metric function to use.
- Returns:
The fingerprint similarity between the two fingerprints.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> FingerprintSimilarity(fp, fp, metric=TanimotoSimilarity) 1.0
- KulczynskiSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Kulczynski similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.KulczynskiSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Kulczynski similarity, a symmetric measure of bit overlap.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> KulczynskiSimilarity(fp, fp) 1.0
- McConnaugheySimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the McConnaughey similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.McConnaugheySimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The McConnaughey similarity, a measure of structural similarity based on bit patterns.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> McConnaugheySimilarity(fp, fp) 1.0
- OffBitProjSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the OffBitProj similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.OffBitProjSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The OffBitProj similarity, based on the projection of off bits between fingerprints.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> OffBitProjSimilarity(fp, fp)[0] 1.0
- OnBitSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the OnBit similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.OnBitSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The OnBit similarity, based on the number of bits set in both fingerprints.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> OnBitSimilarity(fp, fp) 1.0
- RogotGoldbergSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Rogot-Goldberg similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.RogotGoldbergSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Rogot-Goldberg similarity, a weighted measure of bit agreement.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> RogotGoldbergSimilarity(fp, fp) 1.0
- RusselSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Cosine similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.CosineSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Cosine similarity, measuring the cosine of the angle between two bit vectors.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> RusselSimilarity(fp, fp) 0.125
- SokalSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Sokal similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.SokalSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Sokal similarity coefficient, a normalized measure of bit overlap.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> SokalSimilarity(fp, fp) 1.0
- TanimotoSimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect) float[source]¶
Compute the Tanimoto similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.TanimotoSimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first molecular fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second molecular fingerprint.
- Returns:
The Tanimoto similarity coefficient, commonly used for chemical structure comparison.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> TanimotoSimilarity(fp, fp) 1.0
- TverskySimilarity(fp1: ExplicitBitVect, fp2: ExplicitBitVect, a: float = 0.5, b: float = 0.5) float[source]¶
Compute the Tversky similarity between two fingerprints.
This function is a shortcut for the RDKit method DataStructs.TverskySimilarity.
- Parameters:
fp1 (DataStructs.cDataStructs.ExplicitBitVect) – The first fingerprint.
fp2 (DataStructs.cDataStructs.ExplicitBitVect) – The second fingerprint.
a (float, optional) – Weight for features in fp1. Default is 0.5.
b (float, optional) – Weight for features in fp2. Default is 0.5.
- Returns:
The Tversky similarity between the two fingerprints.
- Return type:
float
Examples
>>> from rdkit import DataStructs >>> fp = DataStructs.ExplicitBitVect(8) >>> _ = fp.SetBit(0) >>> TverskySimilarity(fp, fp, a=0.5, b=0.5) 1.0
- get_geometric_S(y_true: Iterable[int | str], y_pred: Iterable[int | str]) float[source]¶
Compute the geometric mean of sensitivity and specificity. The labels argument has been removed in v1.1.3 as ininfluent.
- Parameters:
y_true (Iterable[int or str]) – True labels.
y_pred (Iterable[int or str]) – Predicted labels.
- Returns:
The geometric mean of sensitivity and specificity.
- Return type:
float
Examples
>>> float(get_geometric_S([1, 1, 0, 0], [1, 0, 0, 1])) 0.5
- get_mcc(y_true: Iterable[int | str], y_pred: Iterable[int | str]) float[source]¶
Compute the Matthews Correlation Coefficient (MCC).
- Parameters:
y_true (Iterable[int or str]) – True labels.
y_pred (Iterable[int or str]) – Predicted labels.
- Returns:
The Matthews Correlation Coefficient.
- Return type:
float
Examples
>>> get_mcc([1, 1, 0, 0], [1, 0, 0, 1]) 0.0
- get_r2(y_true: Iterable[float | int], y_pred: Iterable[float | int]) float[source]¶
Compute the R-squared value using Pearson’s correlation coefficient.
- Parameters:
y_true (Iterable[float or int]) – True values.
y_pred (Iterable[float or int]) – Predicted values.
- Returns:
The R-squared value.
- Return type:
float
Examples
>>> float(get_r2([0, 1], [0, 1])) 1.0
- get_reliability_score_components(train_score: float, cv_score: float, logic: Literal['lower', 'greater'], desired_performance_score: Literal['train', 'cv', 'train_cv_average']) dict[str, float][source]¶
Calculate performance, train/CV instability, and a maximized objective.
Let
pbe the raw train score, CV score, or their arithmetic mean, as selected bydesired_performance_score, and leti = abs(train_score - cv_score). Forlogic='greater', the existing objective is unchanged:p / (1 + i). Forlogic='lower', the objective is-(p + i): the negative of loss plus an additive train/CV gap penalty in the same metric units. This requires no fixed loss range and penalizes instability even for zero or signed losses. At fixed instability, reducing loss increases the objective; at fixed loss, increasing instability decreases it.- Parameters:
train_score (float) – Score obtained on the training set.
cv_score (float) – Score obtained on the cross-validation set.
logic ({'lower', 'greater'}) – Whether lower or greater metric values are better.
desired_performance_score ({'train','cv','train_cv_average'}) – Which score to use as the performance score. Options are: ‘train’ for the training score, ‘cv’ for the cross-validation score, ‘train_cv_average’ for the average of the training and cross-validation scores.
- Returns:
Dictionary containing
performance_score(pfor greater,-pfor lower),instability_score(i), andreliability_score(always maximized). For nonnegative losses, lower-is-better reliability is nonpositive; closer to zero is better. It is a selection objective, not raw RMSE or a probability.- Return type:
dict
Examples
>>> scores = get_reliability_score_components( ... 0.8, 0.8, logic="greater", ... desired_performance_score="train_cv_average", ... ) >>> float(scores["reliability_score"]) 0.8 >>> get_reliability_score_components( ... 8.0, 12.0, logic="lower", desired_performance_score="cv", ... )["reliability_score"] -16.0
- get_rmse(y_true: Iterable[float | int], y_pred: Iterable[float | int]) float[source]¶
Compute the root mean squared error (RMSE) of a prediction.
- Parameters:
y_true (Iterable[float or int]) – True values.
y_pred (Iterable[float or int]) – Predicted values.
- Returns:
The root mean squared error.
- Return type:
float
Examples
>>> get_rmse([0, 1], [1, 0]) 1.0
- get_sensitivity(y_true: Iterable[int | str], y_pred: Iterable[int | str]) float[source]¶
Compute the sensitivity (recall) of a prediction. The labels argument has been removed in v1.1.3 as ininfluent.
- Parameters:
y_true (Iterable[int or str]) – True labels.
y_pred (Iterable[int or str]) – Predicted labels.
- Returns:
The sensitivity (recall) of the prediction.
- Return type:
float
Examples
>>> float(get_sensitivity([1, 1, 0, 0], [1, 0, 0, 1])) 0.5
- get_specificity(y_true: Iterable[int | str], y_pred: Iterable[int | str]) float[source]¶
Compute the specificity of a prediction. The labels argument has been removed in v1.1.3 as ininfluent.
- Parameters:
y_true (Iterable[int or str]) – True labels.
y_pred (Iterable[int or str]) – Predicted labels.
- Returns:
The specificity of the prediction.
- Return type:
float
Examples
>>> float(get_specificity([1, 1, 0, 0], [1, 0, 0, 1])) 0.5
- rmse_to_std_ratio(y_true: Iterable[float | int], y_pred: Iterable[float | int]) float[source]¶
Compute the ratio of the standard deviation of true values to RMSE.
- Parameters:
y_true (Iterable[float or int]) – True values.
y_pred (Iterable[float or int]) – Predicted values.
- Returns:
The ratio of standard deviation to RMSE.
- Return type:
float
Examples
>>> float(rmse_to_std_ratio([0, 1], [1, 0])) 0.5