diff --git a/docs/assets/css/custom-molalchemy.css b/docs/assets/css/custom-molalchemy.css index f46e25d..b0f1776 100644 --- a/docs/assets/css/custom-molalchemy.css +++ b/docs/assets/css/custom-molalchemy.css @@ -1,9 +1,9 @@ /* Light mode colors */ :root { --molalchemy-primary: #138c53; - --molalchemy-secondary: #274729; + --molalchemy-secondary: #138c53; --molalchemy-light-bg: #138c53; - --molalchemy-light-accent: #274729; + --molalchemy-light-accent: #138c53; /* Primary color shades */ --md-primary-fg-color: var(--molalchemy-primary); @@ -33,9 +33,9 @@ /* Dark mode colors */ [data-md-color-scheme="slate"] { --molalchemy-primary: #138c53; - --molalchemy-secondary: #343a40; + --molalchemy-secondary: #138c53; --molalchemy-dark-bg: #138c53; - --molalchemy-dark-accent: #343a40; + --molalchemy-dark-accent: #138c53; /* Primary color shades for dark mode */ --md-primary-fg-color: var(--molalchemy-primary); diff --git a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb new file mode 100644 index 0000000..1721500 --- /dev/null +++ b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb @@ -0,0 +1,517 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Similarity Threshold Settings with MolAlchemy RDKit\n", + "\n", + "This tutorial demonstrates how to manage RDKit PostgreSQL similarity thresholds using MolAlchemy's `settings` module. You'll learn how to:\n", + "\n", + "- Understand RDKit GUC (Grand Unified Configuration) threshold variables\n", + "- Get and set Tanimoto and Dice similarity thresholds\n", + "- Use the `similarity_threshold` context manager for temporary threshold changes\n", + "- See how thresholds affect similarity search results\n", + "\n", + "## Prerequisites\n", + "\n", + "Before starting this tutorial, make sure you have:\n", + "- A PostgreSQL database with RDKit extension installed\n", + "- MolAlchemy installed\n", + "- A running PostgreSQL instance (you can use the provided Docker setup)\n", + "\n", + "## Setting Up the Database\n", + "To set up a PostgreSQL database with the RDKit extension, you can use our docker images from [Docker Hub](https://hub.docker.com/repository/docker/antonsiomchen/cheminfo-db), e.g `antonsiomchen/cheminfo-db:postgres18.1-rdkit2025.09.4`\n", + "\n", + "```sh\n", + "docker run -d \\\n", + " --name molalchemy-tutorial-rdkit-orm \\\n", + " -e POSTGRES_PASSWORD=postgres \\\n", + " -e POSTGRES_DB=postgres \\\n", + " -p 5432:5432 \\\n", + " antonsiomchen/cheminfo-db:postgres18.1-rdkit2025.09.4\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Database Setup and Connection\n", + "\n", + "First, let's establish a connection to PostgreSQL and ensure the RDKit extension is enabled." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "from sqlalchemy import (\n", + " Boolean,\n", + " Computed,\n", + " Integer,\n", + " String,\n", + " engine,\n", + " select,\n", + " text,\n", + ")\n", + "from sqlalchemy.orm import (\n", + " DeclarativeBase,\n", + " Mapped,\n", + " MappedAsDataclass,\n", + " mapped_column,\n", + " sessionmaker,\n", + ")\n", + "\n", + "from molalchemy.rdkit import functions, index, types\n", + "from molalchemy.rdkit.settings import (\n", + " get_dice_threshold,\n", + " get_tanimoto_threshold,\n", + " set_dice_threshold,\n", + " set_tanimoto_threshold,\n", + " similarity_threshold,\n", + ")\n", + "\n", + "eng = engine.create_engine(\n", + " \"postgresql+psycopg://postgres:postgres@localhost:5432/postgres\"\n", + ")\n", + "SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=eng)\n", + "with SessionLocal() as session:\n", + " session.execute(text(\"CREATE EXTENSION IF NOT EXISTS rdkit\"))\n", + " session.commit()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Model Definition and Sample Data\n", + "\n", + "We'll reuse the `MoleculeFP` model from Tutorial 01, which includes a computed Morgan fingerprint column and GiST indexes for efficient searches." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "class Base(MappedAsDataclass, DeclarativeBase):\n", + " pass\n", + "\n", + "\n", + "class MoleculeFP(Base):\n", + " __tablename__ = \"molecules_fp\"\n", + " __table_args__ = (\n", + " index.RdkitIndex(\"mol_gist_idx_2\", \"mol\"),\n", + " index.RdkitIndex(\"fp_gist_idx_2\", \"fp\"),\n", + " )\n", + " id: Mapped[int] = mapped_column(\n", + " Integer, primary_key=True, autoincrement=True, init=False\n", + " )\n", + " name: Mapped[str] = mapped_column(String(100), unique=True)\n", + " mol: Mapped[bytes] = mapped_column(types.RdkitMol)\n", + " fp: Mapped[bytes] = mapped_column(\n", + " types.RdkitSparseFingerprint,\n", + " Computed(functions.morgan_fp(mol, 2), persisted=True),\n", + " init=False,\n", + " )\n", + " is_nsaid: Mapped[bool] = mapped_column(Boolean, default=False)\n", + "\n", + "\n", + "MoleculeFP.__table__.drop(eng, checkfirst=True)\n", + "MoleculeFP.__table__.create(eng, checkfirst=True)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "data = [\n", + " {\"name\": \"Aspirin\", \"mol\": \"CC(=O)OC1=CC=CC=C1C(=O)O\", \"is_nsaid\": True},\n", + " {\n", + " \"name\": \"Loratadine\",\n", + " \"mol\": \"O=C(OCC)N4CC/C(=C2/c1ccc(Cl)cc1CCc3cccnc23)CC4\",\n", + " \"is_nsaid\": False,\n", + " },\n", + " {\n", + " \"name\": \"Rofecoxib\",\n", + " \"mol\": \"O=C2OC\\\\C(=C2\\\\c1ccccc1)c3ccc(cc3)S(C)(=O)=O\",\n", + " \"is_nsaid\": True,\n", + " },\n", + " {\"name\": \"Captopril\", \"mol\": \"C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O\", \"is_nsaid\": False},\n", + " {\n", + " \"name\": \"Talidomide\",\n", + " \"mol\": \"O=C1c2ccccc2C(=O)N1C3CCC(=O)NC3=O\",\n", + " \"is_nsaid\": False,\n", + " },\n", + "]\n", + "\n", + "session = SessionLocal()\n", + "session.add_all([MoleculeFP(**d) for d in data])\n", + "session.commit()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Getting Current Thresholds\n", + "\n", + "RDKit PostgreSQL uses GUC (Grand Unified Configuration) variables to control similarity search behavior. The two key thresholds are:\n", + "\n", + "- `rdkit.tanimoto_threshold` — used by the `%` operator (Tanimoto similarity)\n", + "- `rdkit.dice_threshold` — used by the `#` operator (Dice similarity)\n", + "\n", + "Both default to `0.5`. Molecules with a similarity score above the threshold are returned by the corresponding operator.\n", + "\n", + "Let's check the current values:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tanimoto threshold: 0.5\n", + "Dice threshold: 0.5\n" + ] + } + ], + "source": [ + "print(f\"Tanimoto threshold: {get_tanimoto_threshold(session)}\")\n", + "print(f\"Dice threshold: {get_dice_threshold(session)}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Similarity Search with Default Threshold\n", + "\n", + "Let's run a Tanimoto similarity search against Desloratadine (the active metabolite of Loratadine) using the `%` operator via `MoleculeFP.fp.tanimoto()`. With the default threshold of `0.5`, only molecules with similarity ≥ 0.5 are returned.\n", + "\n", + "We'll also show the Tanimoto similarity score alongside each result using `tanimoto_sml`." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Threshold: 0.5\n", + "Results (1 matches):\n", + " Loratadine: 0.6437\n" + ] + } + ], + "source": [ + "query_smiles = \"Clc4cc2c(C(c1ncccc1CC2)=C3CCNCC3)cc4\" # Desloratadine\n", + "query_fp = functions.morgan_fp(query_smiles, 2)\n", + "\n", + "sim_score = functions.tanimoto_sml(MoleculeFP.fp, query_fp).label(\"similarity\")\n", + "\n", + "results = session.execute(\n", + " select(MoleculeFP.name, sim_score)\n", + " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .order_by(sim_score.desc())\n", + ").all()\n", + "\n", + "print(f\"Threshold: {get_tanimoto_threshold(session)}\")\n", + "print(f\"Results ({len(results)} matches):\")\n", + "for name, sim in results:\n", + " print(f\" {name}: {sim:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Changing the Tanimoto Threshold\n", + "\n", + "### Lowering the Threshold\n", + "\n", + "By lowering the threshold, we include more molecules in the results — even those with lower similarity. Let's set it to `0.1` and re-run the same query." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Threshold: 0.1\n", + "Results (3 matches):\n", + " Loratadine: 0.6437\n", + " Talidomide: 0.1800\n", + " Rofecoxib: 0.1651\n" + ] + } + ], + "source": [ + "set_tanimoto_threshold(session, 0.1)\n", + "\n", + "results = session.execute(\n", + " select(MoleculeFP.name, sim_score)\n", + " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .order_by(sim_score.desc())\n", + ").all()\n", + "\n", + "print(f\"Threshold: {get_tanimoto_threshold(session)}\")\n", + "print(f\"Results ({len(results)} matches):\")\n", + "for name, sim in results:\n", + " print(f\" {name}: {sim:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Raising the Threshold\n", + "\n", + "Conversely, raising the threshold makes the search more selective." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Threshold: 0.5\n", + "Results (1 matches):\n", + " Loratadine: 0.6437\n" + ] + } + ], + "source": [ + "set_tanimoto_threshold(session, 0.5)\n", + "\n", + "results = session.execute(\n", + " select(MoleculeFP.name, sim_score)\n", + " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .order_by(sim_score.desc())\n", + ").all()\n", + "\n", + "print(f\"Threshold: {get_tanimoto_threshold(session)}\")\n", + "print(f\"Results ({len(results)} matches):\")\n", + "for name, sim in results:\n", + " print(f\" {name}: {sim:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using the Context Manager\n", + "\n", + "The `similarity_threshold` context manager lets you temporarily change thresholds for a block of code. The original values are automatically restored when the block exits, even if an exception occurs.\n", + "\n", + "This is useful when different parts of your application need different thresholds." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Before: 0.5\n", + "Inside: 0.1\n", + "Matches: 3\n", + "After: 0.5\n" + ] + } + ], + "source": [ + "print(f\"Before: {get_tanimoto_threshold(session)}\")\n", + "\n", + "with similarity_threshold(session, tanimoto=0.1):\n", + " print(f\"Inside: {get_tanimoto_threshold(session)}\")\n", + "\n", + " results = session.execute(\n", + " select(MoleculeFP.name, sim_score)\n", + " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .order_by(sim_score.desc())\n", + " ).all()\n", + " print(f\"Matches: {len(results)}\")\n", + "\n", + "print(f\"After: {get_tanimoto_threshold(session)}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also set both thresholds at once:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tanimoto: 0.2\n", + "Dice: 0.3\n", + "Tanimoto restored: 0.5\n", + "Dice restored: 0.5\n" + ] + } + ], + "source": [ + "with similarity_threshold(session, tanimoto=0.2, dice=0.3):\n", + " print(f\"Tanimoto: {get_tanimoto_threshold(session)}\")\n", + " print(f\"Dice: {get_dice_threshold(session)}\")\n", + "\n", + "print(f\"Tanimoto restored: {get_tanimoto_threshold(session)}\")\n", + "print(f\"Dice restored: {get_dice_threshold(session)}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dice Threshold\n", + "\n", + "The Dice similarity coefficient is another metric for comparing fingerprints. It tends to give higher values than Tanimoto for the same pair of molecules. Use `set_dice_threshold` / `get_dice_threshold` and the `#` operator via `MoleculeFP.fp.dice()`." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dice threshold: 0.2\n", + "Results (3 matches):\n", + " Loratadine: 0.7832\n", + " Talidomide: 0.3051\n", + " Rofecoxib: 0.2835\n" + ] + } + ], + "source": [ + "dice_score = functions.dice_sml(MoleculeFP.fp, query_fp).label(\"dice_similarity\")\n", + "\n", + "set_dice_threshold(session, 0.2)\n", + "\n", + "results = session.execute(\n", + " select(MoleculeFP.name, dice_score)\n", + " .where(MoleculeFP.fp.dice(query_fp))\n", + " .order_by(dice_score.desc())\n", + ").all()\n", + "\n", + "print(f\"Dice threshold: {get_dice_threshold(session)}\")\n", + "print(f\"Results ({len(results)} matches):\")\n", + "for name, sim in results:\n", + " print(f\" {name}: {sim:.4f}\")\n", + "\n", + "# Reset to default\n", + "set_dice_threshold(session, 0.5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation\n", + "\n", + "The settings functions validate threshold values before sending them to the database. Thresholds must be floats between 0.0 and 1.0." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ValueError: threshold must be between 0.0 and 1.0, got 1.5\n", + "TypeError: threshold must be a float, got str\n" + ] + } + ], + "source": [ + "try:\n", + " set_tanimoto_threshold(session, 1.5)\n", + "except ValueError as e:\n", + " print(f\"ValueError: {e}\")\n", + "\n", + "try:\n", + " set_tanimoto_threshold(session, \"high\")\n", + "except TypeError as e:\n", + " print(f\"TypeError: {e}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "This tutorial demonstrated how to manage RDKit similarity thresholds with MolAlchemy:\n", + "\n", + "1. **GUC Variables**: `rdkit.tanimoto_threshold` and `rdkit.dice_threshold` control which molecules pass similarity operators\n", + "2. **Get/Set Helpers**: `get_tanimoto_threshold`, `set_tanimoto_threshold`, `get_dice_threshold`, `set_dice_threshold`\n", + "3. **Context Manager**: `similarity_threshold` for temporary, exception-safe threshold changes\n", + "4. **Validation**: Invalid thresholds raise `ValueError` or `TypeError` before reaching the database\n", + "\n", + "### Additional Resources\n", + "\n", + "- [SQLAlchemy Documentation](https://docs.sqlalchemy.org/)\n", + "- [RDKit PostgreSQL Cartridge Documentation](https://www.rdkit.org/docs/Cartridge.html)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "molalchemy (3.10.19)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.19" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/mkdocs.yml b/mkdocs.yml index 192c09a..6531925 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -94,6 +94,8 @@ nav: - RDkit - SQLAlchemy Core: tutorials/02_Getting_Started_rdkit_Core.ipynb - Bingo - SQLAlchemy ORM: tutorials/01_Getting_Started_bingo_ORM.ipynb - Migrations with Alembic: tutorials/03_alembic_migrations.md + - RDKit - Settings: tutorials/04_Similarity_Threshold_Settings.ipynb + - RDKit - Reactions: tutorials/05_Reactions_rdkit_ORM.ipynb - Contributing: tutorials/contribute.md - API: - molalchemy.bingo: diff --git a/src/molalchemy/alembic_helpers.py b/src/molalchemy/alembic_helpers.py index 6d66d96..3e6e660 100644 --- a/src/molalchemy/alembic_helpers.py +++ b/src/molalchemy/alembic_helpers.py @@ -7,7 +7,9 @@ from alembic import op from loguru import logger +from molalchemy.bingo.index import _BingoIndexBase from molalchemy.bingo.types import BingoBaseType +from molalchemy.rdkit.index import RdkitIndex from molalchemy.rdkit.types import RdkitBaseType _TYPE_TO_MODULE = { @@ -43,5 +45,16 @@ def render_item(obj_type, obj, autogen_context): autogen_context.imports.add(f"from {module} import {import_name}") return f"{obj!r}" + if obj_type == "index": + if isinstance(obj, RdkitIndex): + autogen_context.imports.add("from molalchemy.rdkit.index import RdkitIndex") + return f"{obj!r}" + if isinstance(obj, _BingoIndexBase): + class_name = obj.__class__.__name__ + autogen_context.imports.add( + f"from molalchemy.bingo.index import {class_name}" + ) + return f"{obj!r}" + # Default rendering for other objects return False diff --git a/src/molalchemy/bingo/index.py b/src/molalchemy/bingo/index.py index bbe60f7..9e2c836 100644 --- a/src/molalchemy/bingo/index.py +++ b/src/molalchemy/bingo/index.py @@ -17,7 +17,28 @@ # compiler.preparer.format_table(expr.table), # compiler.process(expr, include_table=False) # ) -class BingoMolIndex(Index): +class _BingoIndexBase(Index): + """Base class for Bingo index types with common __repr__ logic.""" + + _bingo_op_class: str + + def __init__(self, name, mol_column): + self._bingo_name = name + self._bingo_column = mol_column + super().__init__( + name, + mol_column, + postgresql_using="bingo_idx", + postgresql_ops={mol_column: self._bingo_op_class}, + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}({self._bingo_name!r}, {self._bingo_column!r})" + ) + + +class BingoMolIndex(_BingoIndexBase): """ Bingo index for molecule columns. @@ -61,16 +82,10 @@ class BingoMolIndex(Index): ``` """ - def __init__(self, name, mol_column): - super().__init__( - name, - mol_column, - postgresql_using="bingo_idx", - postgresql_ops={mol_column: "bingo.molecule"}, - ) + _bingo_op_class = "bingo.molecule" -class BingoBinaryMolIndex(Index): +class BingoBinaryMolIndex(_BingoIndexBase): """ Bingo index for binary molecule columns. @@ -115,16 +130,10 @@ class BingoBinaryMolIndex(Index): ``` """ - def __init__(self, name, mol_column): - super().__init__( - name, - mol_column, - postgresql_using="bingo_idx", - postgresql_ops={mol_column: "bingo.bmolecule"}, - ) + _bingo_op_class = "bingo.bmolecule" -class BingoRxnIndex(Index): +class BingoRxnIndex(_BingoIndexBase): """ Bingo index for reaction columns. @@ -169,16 +178,10 @@ class BingoRxnIndex(Index): ``` """ - def __init__(self, name, mol_column): - super().__init__( - name, - mol_column, - postgresql_using="bingo_idx", - postgresql_ops={mol_column: "bingo.reaction"}, - ) + _bingo_op_class = "bingo.reaction" -class BingoBinaryRxnIndex(Index): +class BingoBinaryRxnIndex(_BingoIndexBase): """ Bingo index for binary reaction columns. @@ -223,10 +226,4 @@ class BingoBinaryRxnIndex(Index): ``` """ - def __init__(self, name, mol_column): - super().__init__( - name, - mol_column, - postgresql_using="bingo_idx", - postgresql_ops={mol_column: "bingo.breaction"}, - ) + _bingo_op_class = "bingo.breaction" diff --git a/src/molalchemy/rdkit/__init__.py b/src/molalchemy/rdkit/__init__.py index e3cc9c6..52e7946 100644 --- a/src/molalchemy/rdkit/__init__.py +++ b/src/molalchemy/rdkit/__init__.py @@ -1,5 +1,12 @@ from .comparators import RdkitFPComparator, RdkitMolComparator from .index import RdkitIndex +from .settings import ( + get_dice_threshold, + get_tanimoto_threshold, + set_dice_threshold, + set_tanimoto_threshold, + similarity_threshold, +) from .types import ( RdkitBitFingerprint, RdkitMol, @@ -19,4 +26,9 @@ "RdkitReaction", "RdkitSparseFingerprint", "RdkitXQMol", + "get_dice_threshold", + "get_tanimoto_threshold", + "set_dice_threshold", + "set_tanimoto_threshold", + "similarity_threshold", ] diff --git a/src/molalchemy/rdkit/index.py b/src/molalchemy/rdkit/index.py index c6acbe1..a8b16d2 100644 --- a/src/molalchemy/rdkit/index.py +++ b/src/molalchemy/rdkit/index.py @@ -20,4 +20,10 @@ class RdkitIndex(Index): def __init__(self, name: str, *expressions, **kw): kw["postgresql_using"] = "gist" + self._rdkit_name = name + self._rdkit_expressions = expressions super().__init__(name, *expressions, **kw) + + def __repr__(self): + expr_reprs = ", ".join(repr(e) for e in self._rdkit_expressions) + return f"RdkitIndex({self._rdkit_name!r}, {expr_reprs})" diff --git a/src/molalchemy/rdkit/settings.py b/src/molalchemy/rdkit/settings.py new file mode 100644 index 0000000..ba695b4 --- /dev/null +++ b/src/molalchemy/rdkit/settings.py @@ -0,0 +1,82 @@ +"""RDKit PostgreSQL GUC settings helpers for similarity search thresholds.""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +from sqlalchemy import text + +if TYPE_CHECKING: + from collections.abc import Generator + + from sqlalchemy.orm import Session + + +def _validate_threshold(value: float) -> None: + if not isinstance(value, (int, float)): + raise TypeError(f"threshold must be a float, got {type(value).__name__}") + if not 0.0 <= value <= 1.0: + raise ValueError(f"threshold must be between 0.0 and 1.0, got {value}") + + +def set_tanimoto_threshold(session: Session, threshold: float) -> None: + """Set the rdkit.tanimoto_threshold GUC variable.""" + _validate_threshold(threshold) + session.execute(text(f"SET rdkit.tanimoto_threshold = {float(threshold)}")) + + +def set_dice_threshold(session: Session, threshold: float) -> None: + """Set the rdkit.dice_threshold GUC variable.""" + _validate_threshold(threshold) + session.execute(text(f"SET rdkit.dice_threshold = {float(threshold)}")) + + +def get_tanimoto_threshold(session: Session) -> float: + """Get the current rdkit.tanimoto_threshold value.""" + result = session.execute(text("SHOW rdkit.tanimoto_threshold")) + return float(result.scalar_one()) + + +def get_dice_threshold(session: Session) -> float: + """Get the current rdkit.dice_threshold value.""" + result = session.execute(text("SHOW rdkit.dice_threshold")) + return float(result.scalar_one()) + + +@contextmanager +def similarity_threshold( + session: Session, + *, + tanimoto: float | None = None, + dice: float | None = None, +) -> Generator[None, None, None]: + """Context manager to temporarily set similarity thresholds. + + Restores original values on exit, even if an exception occurs. + + Parameters + ---------- + session : Session + SQLAlchemy session. + tanimoto : float, optional + Tanimoto threshold to set (0.0-1.0). + dice : float, optional + Dice threshold to set (0.0-1.0). + """ + old_tanimoto = None + old_dice = None + + try: + if tanimoto is not None: + old_tanimoto = get_tanimoto_threshold(session) + set_tanimoto_threshold(session, tanimoto) + if dice is not None: + old_dice = get_dice_threshold(session) + set_dice_threshold(session, dice) + yield + finally: + if old_tanimoto is not None: + set_tanimoto_threshold(session, old_tanimoto) + if old_dice is not None: + set_dice_threshold(session, old_dice) diff --git a/src/molalchemy/rdkit/types.py b/src/molalchemy/rdkit/types.py index b277f6d..25337c1 100644 --- a/src/molalchemy/rdkit/types.py +++ b/src/molalchemy/rdkit/types.py @@ -8,6 +8,7 @@ from typing import Any, Literal from rdkit import Chem +from rdkit.Chem import AllChem, rdChemReactions from sqlalchemy import func from sqlalchemy.types import UserDefinedType @@ -170,6 +171,33 @@ def __init__(self, return_type: Literal["smiles", "bytes", "mol"] = "smiles"): def __repr__(self): return f"RdkitReaction(return_type={self.return_type!r})" + def bind_processor(self, dialect): + del dialect + + def process(value): + if value is None: + return None + if isinstance(value, rdChemReactions.ChemicalReaction): + return rdChemReactions.ReactionToSmarts(value) + if isinstance(value, str): + try: + rxn = AllChem.ReactionFromSmarts(value) + except ValueError: + rxn = None + if rxn is None: + raise ValueError( + f"Invalid reaction SMILES/SMARTS string: {value!r}" + ) + return value + raise ValueError( + "Value must be a reaction SMILES/SMARTS string or a ChemicalReaction object" + ) + + return process + + def bind_expression(self, bindvalue): + return func.reaction_from_smarts(bindvalue) + def column_expression(self, colexpr): from . import functions as rdkit_func @@ -182,14 +210,13 @@ def result_processor(self, dialect, coltype): del dialect, coltype def process(value, return_type): - from rdkit.Chem import AllChem - if value is None: return None if return_type == "mol": - # If we have bytes from rxn_send, create reaction from binary if isinstance(value, bytes | memoryview): return AllChem.ChemicalReaction(bytes(value)) + else: + return AllChem.ReactionFromSmarts(str(value)) elif return_type == "bytes": return bytes(value) if isinstance(value, memoryview) else value else: # smiles diff --git a/tests/bingo/test_index.py b/tests/bingo/test_index.py index 58abece..aa81474 100644 --- a/tests/bingo/test_index.py +++ b/tests/bingo/test_index.py @@ -187,8 +187,8 @@ def test_both_inherit_from_index(self): assert isinstance(mol_index, Index) assert isinstance(binary_index, Index) - assert type(mol_index).__bases__ == (Index,) - assert type(binary_index).__bases__ == (Index,) + assert issubclass(type(mol_index), Index) + assert issubclass(type(binary_index), Index) class TestBingoIndexCreation: diff --git a/tests/rdkit/conftest.py b/tests/rdkit/conftest.py new file mode 100644 index 0000000..53fc935 --- /dev/null +++ b/tests/rdkit/conftest.py @@ -0,0 +1,22 @@ +"""Pytest configuration for rdkit tests.""" + +import pytest +from sqlalchemy import MetaData + + +@pytest.fixture +def metadata(): + """Provide a clean MetaData instance for each test.""" + return MetaData() + + +@pytest.fixture +def sample_smiles(): + """Provide common SMILES strings for testing.""" + return { + "benzene": "c1ccccc1", + "ethanol": "CCO", + "methane": "C", + "aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O", + "caffeine": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", + } diff --git a/tests/rdkit/test_integration.py b/tests/rdkit/test_integration.py new file mode 100644 index 0000000..57e7c81 --- /dev/null +++ b/tests/rdkit/test_integration.py @@ -0,0 +1,172 @@ +"""Integration tests for rdkit query structure.""" + +from sqlalchemy import ( + Column, + Computed, + Integer, + MetaData, + String, + Table, + and_, + or_, + select, +) +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +from molalchemy.rdkit import functions as rdkit_func +from molalchemy.rdkit.index import RdkitIndex +from molalchemy.rdkit.types import RdkitMol, RdkitSparseFingerprint + + +class TestRdkitQueryIntegration: + """Integration tests for complete rdkit query structures.""" + + def setup_method(self): + """Set up test tables.""" + self.metadata = MetaData() + + self.molecules = Table( + "molecules", + self.metadata, + Column("id", Integer, primary_key=True), + Column("name", String(100)), + Column("mol", RdkitMol()), + Column( + "morgan_fp", + RdkitSparseFingerprint(), + Computed("morganbv_fp(mol)"), + ), + RdkitIndex("idx_molecules_mol", "mol"), + ) + + def test_complete_substructure_query(self): + """Test substructure query compiles with @> operator.""" + benzene = "c1ccccc1" + + stmt = select(self.molecules).where( + self.molecules.c.mol.has_substructure(benzene) + ) + + compiled = str(stmt.compile()) + assert "@>" in compiled + assert "mol_from_pkl" in compiled + + def test_exact_match_query(self): + """Test exact match query compiles with @= operator.""" + ethanol = "CCO" + + stmt = select(self.molecules).where(self.molecules.c.mol.equals(ethanol)) + + compiled = str(stmt.compile()) + assert "@=" in compiled + assert "mol_from_pkl" in compiled + + def test_tanimoto_similarity_query(self): + """Test tanimoto similarity compiles with % operator.""" + query_fp = "morganbv_fp('CCO'::mol)" + + stmt = select(self.molecules).where( + self.molecules.c.morgan_fp.tanimoto(query_fp) + ) + + compiled = str(stmt.compile()) + assert "%" in compiled + + def test_dice_similarity_query(self): + """Test dice similarity compiles with # operator.""" + query_fp = "morganbv_fp('CCO'::mol)" + + stmt = select(self.molecules).where(self.molecules.c.morgan_fp.dice(query_fp)) + + compiled = str(stmt.compile()) + assert "#" in compiled + + def test_nearest_neighbors_query(self): + """Test nearest neighbors compiles with <%> operator.""" + query_fp = "morganbv_fp('CCO'::mol)" + + stmt = select(self.molecules).where( + self.molecules.c.morgan_fp.nearest_neighbors(query_fp) + ) + + compiled = str(stmt.compile()) + assert "<%>" in compiled + + def test_complex_query_with_multiple_conditions(self): + """Test complex query with or_/and_ combinations.""" + benzene = "c1ccccc1" + ethanol = "CCO" + + stmt = select(self.molecules).where( + or_( + self.molecules.c.mol.has_substructure(benzene), + and_( + self.molecules.c.mol.equals(ethanol), + self.molecules.c.name == "Ethanol", + ), + ) + ) + + compiled = str(stmt.compile()) + assert "@>" in compiled + assert "@=" in compiled + assert "mol_from_pkl" in compiled + + +class TestRdkitORMIntegration: + """Integration tests using ORM-style definitions.""" + + def setup_method(self): + """Set up ORM models.""" + + class Base(DeclarativeBase): + pass + + class Molecule(Base): + __tablename__ = "molecules" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + mol: Mapped[str] = mapped_column(RdkitMol()) + morgan_fp: Mapped[bytes] = mapped_column( + RdkitSparseFingerprint(), + Computed("morganbv_fp(mol)"), + ) + + __table_args__ = (RdkitIndex("idx_molecules_mol", "mol"),) + + self.Base = Base + self.Molecule = Molecule + + def test_orm_substructure_query(self): + """Test substructure query with ORM.""" + benzene = "c1ccccc1" + + stmt = select(self.Molecule).where(self.Molecule.mol.has_substructure(benzene)) + + compiled = str(stmt.compile()) + assert "@>" in compiled + assert "mol_from_pkl" in compiled + + def test_orm_similarity_query(self): + """Test similarity query with ORM.""" + query_fp = "morganbv_fp('CCO'::mol)" + + stmt = select(self.Molecule).where(self.Molecule.morgan_fp.tanimoto(query_fp)) + + compiled = str(stmt.compile()) + assert "%" in compiled + + def test_orm_tanimoto_sml_function(self): + """Test tanimoto_sml function in query.""" + stmt = select( + self.Molecule, + rdkit_func.tanimoto_sml( + self.Molecule.morgan_fp, + rdkit_func.morganbv_fp("CCO"), + ).label("similarity"), + ) + + compiled = str(stmt.compile()) + assert "tanimoto_sml" in compiled + assert "morganbv_fp" in compiled diff --git a/tests/rdkit/test_settings.py b/tests/rdkit/test_settings.py new file mode 100644 index 0000000..1b02057 --- /dev/null +++ b/tests/rdkit/test_settings.py @@ -0,0 +1,120 @@ +"""Tests for RDKit similarity threshold settings helpers.""" + +from unittest.mock import Mock + +import pytest + +from molalchemy.rdkit.settings import ( + get_dice_threshold, + get_tanimoto_threshold, + set_dice_threshold, + set_tanimoto_threshold, + similarity_threshold, +) + + +@pytest.fixture +def session(): + mock = Mock() + mock.execute.return_value.scalar_one.return_value = "0.5" + return mock + + +class TestSetTanimotoThreshold: + def test_sets_threshold(self, session): + set_tanimoto_threshold(session, 0.7) + session.execute.assert_called_once() + args = session.execute.call_args + assert "rdkit.tanimoto_threshold" in str(args[0][0]) + assert "0.7" in str(args[0][0]) + + def test_rejects_negative(self, session): + with pytest.raises(ValueError, match=r"between 0\.0 and 1\.0"): + set_tanimoto_threshold(session, -0.1) + + def test_rejects_above_one(self, session): + with pytest.raises(ValueError, match=r"between 0\.0 and 1\.0"): + set_tanimoto_threshold(session, 1.1) + + def test_rejects_non_numeric(self, session): + with pytest.raises(TypeError, match="must be a float"): + set_tanimoto_threshold(session, "0.5") + + def test_accepts_zero(self, session): + set_tanimoto_threshold(session, 0.0) + session.execute.assert_called_once() + + def test_accepts_one(self, session): + set_tanimoto_threshold(session, 1.0) + session.execute.assert_called_once() + + +class TestSetDiceThreshold: + def test_sets_threshold(self, session): + set_dice_threshold(session, 0.6) + session.execute.assert_called_once() + args = session.execute.call_args + assert "rdkit.dice_threshold" in str(args[0][0]) + assert "0.6" in str(args[0][0]) + + def test_rejects_invalid(self, session): + with pytest.raises(ValueError): + set_dice_threshold(session, 2.0) + + +class TestGetTanimotoThreshold: + def test_returns_float(self, session): + result = get_tanimoto_threshold(session) + assert result == 0.5 + assert isinstance(result, float) + + +class TestGetDiceThreshold: + def test_returns_float(self, session): + result = get_dice_threshold(session) + assert result == 0.5 + assert isinstance(result, float) + + +class TestSimilarityThreshold: + def test_sets_and_restores_tanimoto(self, session): + session.execute.return_value.scalar_one.return_value = "0.5" + + with similarity_threshold(session, tanimoto=0.8): + pass + + # Should have: SHOW (get old), SET 0.8, SET 0.5 (restore) + assert session.execute.call_count == 3 + + def test_sets_and_restores_dice(self, session): + session.execute.return_value.scalar_one.return_value = "0.6" + + with similarity_threshold(session, dice=0.3): + pass + + assert session.execute.call_count == 3 + + def test_sets_and_restores_both(self, session): + session.execute.return_value.scalar_one.return_value = "0.5" + + with similarity_threshold(session, tanimoto=0.8, dice=0.3): + pass + + # SHOW tanimoto, SET tanimoto, SHOW dice, SET dice, SET tanimoto (restore), SET dice (restore) + assert session.execute.call_count == 6 + + def test_restores_on_exception(self, session): + session.execute.return_value.scalar_one.return_value = "0.5" + + with pytest.raises(RuntimeError): + with similarity_threshold(session, tanimoto=0.8): + raise RuntimeError("test error") + + # Should still restore: SHOW, SET 0.8, SET 0.5 (restore) + assert session.execute.call_count == 3 + + def test_noop_when_no_thresholds(self, session): + with similarity_threshold(session): + pass + + session.execute.assert_not_called() diff --git a/tests/rdkit/test_types.py b/tests/rdkit/test_types.py index a994d26..9f20cfe 100644 --- a/tests/rdkit/test_types.py +++ b/tests/rdkit/test_types.py @@ -252,6 +252,49 @@ def test_rdkit_reaction_in_table_definition(self): assert test_table.c.reaction.type.__class__ == RdkitReaction assert isinstance(test_table.c.reaction.type, RdkitReaction) + def test_bind_processor(self): + """Test bind_processor for different input types.""" + rdkit_rxn = RdkitReaction() + processor = rdkit_rxn.bind_processor(None) + + # Test with valid reaction SMILES/SMARTS string + rxn_smarts = "[C:1](=O)[OH].[N:2]>>[C:1](=O)[N:2]" + processed = processor(rxn_smarts) + assert isinstance(processed, str) + assert processed == rxn_smarts + + # Test with ChemicalReaction object + rxn_obj = rdChemReactions.ReactionFromSmarts(rxn_smarts) + processed = processor(rxn_obj) + assert isinstance(processed, str) + # Round-trip through ReactionToSmarts should produce valid SMARTS + rxn_roundtrip = rdChemReactions.ReactionFromSmarts(processed) + assert rxn_roundtrip is not None + + # Test with None + processed = processor(None) + assert processed is None + + # Test with invalid string + with pytest.raises(ValueError, match="Invalid reaction SMILES/SMARTS string"): + processor("not_a_reaction") + + # Test with invalid type + with pytest.raises( + ValueError, match="Value must be a reaction SMILES/SMARTS string" + ): + processor(123) + + def test_result_processor_mol_string_fallback(self): + """Test result_processor returns ChemicalReaction for string input with return_type='mol'.""" + rdkit_rxn = RdkitReaction(return_type="mol") + processor = rdkit_rxn.result_processor(None, None) + + rxn_smarts = "[C:1](=O)[OH].[N:2]>>[C:1](=O)[N:2]" + result = processor(rxn_smarts) + assert isinstance(result, AllChem.ChemicalReaction) + assert result.GetNumReactantTemplates() == 2 + class TestTypesIntegration: """Integration tests for RDKit types.""" diff --git a/tests/test_alembic_helpers.py b/tests/test_alembic_helpers.py index 068cfa1..c0add6b 100644 --- a/tests/test_alembic_helpers.py +++ b/tests/test_alembic_helpers.py @@ -9,12 +9,19 @@ drop_rdkit_extension, render_item, ) +from molalchemy.bingo.index import ( + BingoBinaryMolIndex, + BingoBinaryRxnIndex, + BingoMolIndex, + BingoRxnIndex, +) from molalchemy.bingo.types import ( BingoBinaryMol, BingoBinaryReaction, BingoMol, BingoReaction, ) +from molalchemy.rdkit.index import RdkitIndex from molalchemy.rdkit.types import ( RdkitBitFingerprint, RdkitMol, @@ -192,3 +199,86 @@ def test_drop_rdkit_extension(self, mock_op): """Test that drop_rdkit_extension executes correct SQL.""" drop_rdkit_extension() mock_op.execute.assert_called_once_with("DROP EXTENSION IF EXISTS rdkit;") + + +# All index variants with expected module, class name, and constructor repr +ALL_INDEXES = [ + ( + RdkitIndex("idx_mol", "structure"), + "molalchemy.rdkit.index", + "RdkitIndex", + "RdkitIndex('idx_mol', 'structure')", + ), + ( + BingoMolIndex("idx_mol", "structure"), + "molalchemy.bingo.index", + "BingoMolIndex", + "BingoMolIndex('idx_mol', 'structure')", + ), + ( + BingoBinaryMolIndex("idx_bmol", "structure_bin"), + "molalchemy.bingo.index", + "BingoBinaryMolIndex", + "BingoBinaryMolIndex('idx_bmol', 'structure_bin')", + ), + ( + BingoRxnIndex("idx_rxn", "reaction"), + "molalchemy.bingo.index", + "BingoRxnIndex", + "BingoRxnIndex('idx_rxn', 'reaction')", + ), + ( + BingoBinaryRxnIndex("idx_brxn", "reaction_bin"), + "molalchemy.bingo.index", + "BingoBinaryRxnIndex", + "BingoBinaryRxnIndex('idx_brxn', 'reaction_bin')", + ), +] + + +class TestRenderAllIndexes: + """Test render_item for all index variants.""" + + @pytest.mark.parametrize( + ("instance", "expected_module", "class_name", "expected_repr"), + ALL_INDEXES, + ids=[t[3] for t in ALL_INDEXES], + ) + def test_render_all_indexes( + self, instance, expected_module, class_name, expected_repr + ): + """Test that render_item produces correct import and repr for every index.""" + autogen_context = Mock() + autogen_context.imports = set() + + result = render_item("index", instance, autogen_context) + + expected_import = f"from {expected_module} import {class_name}" + assert expected_import in autogen_context.imports + assert result == expected_repr + + @pytest.mark.parametrize( + ("instance", "expected_module", "class_name", "expected_repr"), + ALL_INDEXES, + ids=[t[3] for t in ALL_INDEXES], + ) + def test_repr_roundtrip(self, instance, expected_module, class_name, expected_repr): + """Test that repr produces a valid constructor call string.""" + assert repr(instance) == expected_repr + + def test_render_unknown_index_returns_false(self): + """Test that an unknown index type returns False.""" + from sqlalchemy import Index + + autogen_context = Mock() + autogen_context.imports = set() + + result = render_item("index", Index("idx_plain", "col"), autogen_context) + + assert result is False + assert len(autogen_context.imports) == 0 + + def test_rdkit_index_multiple_expressions(self): + """Test RdkitIndex repr with multiple expressions.""" + idx = RdkitIndex("idx_multi", "col1", "col2") + assert repr(idx) == "RdkitIndex('idx_multi', 'col1', 'col2')"