From 6b3fa5dddca9bc718859b34a01f45580878a71da Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Tue, 4 Aug 2026 21:54:56 +0200 Subject: [PATCH 01/13] update rdkit comparators --- CONTRIBUTING.md | 2 +- README.md | 23 +- docker-compose.smoke.yaml | 4 +- docker-compose.yaml | 6 +- pyproject.toml | 9 +- ruff.toml | 4 +- src/molalchemy/rdkit/__init__.py | 3 - src/molalchemy/rdkit/comparators.py | 132 ++--- src/molalchemy/rdkit/functions/_types.py | 95 +--- src/molalchemy/rdkit/functions/general.py | 75 +-- src/molalchemy/rdkit/proxy.py | 98 ---- src/molalchemy/rdkit/search.py | 44 ++ tests/rdkit/__init__.py | 30 +- tests/rdkit/test_comparators.py | 659 ++++++---------------- tests/rdkit/test_integration.py | 27 +- update_proxy_stubs.py | 268 --------- uv.lock | 75 ++- 17 files changed, 436 insertions(+), 1118 deletions(-) delete mode 100644 src/molalchemy/rdkit/proxy.py create mode 100644 src/molalchemy/rdkit/search.py delete mode 100644 update_proxy_stubs.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3bebfb7..f76ae2b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -236,7 +236,7 @@ git commit -m "test: add edge cases for similarity functions" - [ ] Tests pass: `uv run pytest` - [ ] Code is formatted: `uv run ruff format .` - [ ] Linting passes: `uv run ruff check .` -- [ ] Type checking passes: `uv run mypy src/` +- [ ] Focused type checking passes with `uv run ty check` - [ ] Documentation builds: `uv run mkdocs serve` - [ ] Changelog updated (if applicable) diff --git a/README.md b/README.md index aa09e3c..aed20db 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ molalchemy provides seamless integration between python and chemical databases, - **Input Validation**: Molecules and reactions are validated before being sent to the database - **Similarity Threshold Management**: Get/set Tanimoto and Dice thresholds with a context manager - **Alembic Integration**: Automatic handling of extensions, types, and indexes in database migrations -- **Typing Helpers**: Proxy helpers for IDE autocomplete on SQLAlchemy molecule and reaction columns +- **Typing Helpers**: Protocol helpers for precise comparator autocomplete and result types - **Easy Integration**: Drop-in replacement for standard SQLAlchemy types ## 📦 Installation @@ -93,20 +93,19 @@ molalchemy/ ├── src/molalchemy/ │ ├── types.py # Base type definitions │ ├── exceptions.py # Custom exception hierarchy -│ ├── helpers.py # Typed proxy helper functions +│ ├── helpers.py # Typed comparator helper functions +│ ├── protocols.py # Static comparator protocols │ ├── alembic_helpers.py # Alembic integration utilities │ ├── bingo/ # Bingo PostgreSQL cartridge support │ │ ├── types.py # Bingo-specific types │ │ ├── index.py # Bingo indexing │ │ ├── comparators.py # SQLAlchemy comparators -│ │ ├── proxy.py # IDE/type-checker proxy stubs │ │ ├── search.py # Shared Bingo search expression helpers │ │ └── functions/ # Bingo database functions │ └── rdkit/ # RDKit PostgreSQL cartridge support │ ├── types.py # RDKit-specific types │ ├── index.py # RDKit indexing │ ├── comparators.py # SQLAlchemy comparators -│ ├── proxy.py # IDE/type-checker proxy stubs │ ├── settings.py # Similarity threshold management │ └── functions/ # RDKit database functions ├── tests/ # Test suite @@ -127,7 +126,8 @@ To learn how to use molalchemy, check out the tutorials in the [documentation](h - [RDKit Reactions](https://molalchemy.readthedocs.io/en/latest/tutorials/05_Reactions_rdkit_ORM/) - Storing and querying RDKit reactions - [Bingo Reactions and Binary Storage](https://molalchemy.readthedocs.io/en/latest/tutorials/06_bingo_reactions_binary/) - Bingo reaction and binary column workflows - [RDKit Descriptors and Advanced Queries](https://molalchemy.readthedocs.io/en/latest/tutorials/07_rdkit_descriptors_advanced/) - Descriptor functions and richer query patterns -- [Typed Proxy Helpers](https://molalchemy.readthedocs.io/en/latest/tutorials/08_proxy_helpers/) - IDE autocomplete helpers for chemical columns +- [Typed Comparator Helpers](https://molalchemy.readthedocs.io/en/latest/tutorials/08_proxy_helpers/) - statically typed cartridge methods +- [RDKit Comparator Migration](https://molalchemy.readthedocs.io/en/latest/migrations/rdkit-comparator-api/) - migrate legacy fingerprint and comparator calls ## 🏗️ Supported Cartridges @@ -206,16 +206,16 @@ class Molecule(Base): ) ``` -### Typed Proxy Helpers +### Typed Comparator Helpers The helper functions in `molalchemy.helpers` return the original SQLAlchemy -column at runtime, but annotate it with a proxy type so IDEs and type checkers +column at runtime, but annotate it with a protocol so IDEs and type checkers can see cartridge-specific comparator methods. ```python from sqlalchemy import select -from molalchemy.helpers import bingo_col, rdkit_col +from molalchemy.helpers import bingo_col, rdkit_col, rdkit_fp_col # Bingo exact/substructure search with autocomplete-friendly column typing bingo_stmt = select(Molecule).where( @@ -228,8 +228,13 @@ rdkit_stmt = select(MoleculeWithFormats).where( ) ``` +RDKit molecule `==` and `!=` comparisons are chemically aware: PostgreSQL +dispatches them to RDKit's `mol_eq` and `mol_ne` functions. The explicit +`.equals()` and `.not_equals()` methods use the equivalent `@=` and `@<>` +operator spellings. + Use the matching helper for the cartridge and data kind: -`bingo_col`, `bingo_rxn_col`, `rdkit_col`, or `rdkit_rxn_col`. +`bingo_col`, `bingo_rxn_col`, `rdkit_col`, `rdkit_rxn_col`, or `rdkit_fp_col`. ### Configurable Return Types diff --git a/docker-compose.smoke.yaml b/docker-compose.smoke.yaml index d314a5c..c7dcdc1 100644 --- a/docker-compose.smoke.yaml +++ b/docker-compose.smoke.yaml @@ -1,6 +1,6 @@ services: bingo: - image: antonsiomchen/cheminfo-db:postgres16.13-bingo1.40.0 + image: ghcr.io/asiomchen/bingo-postgres:postgres17-bingo1.44.0 shm_size: 1024mb environment: POSTGRES_PASSWORD: postgres @@ -8,7 +8,7 @@ services: - "${BINGO_SMOKE_PORT:-55432}:5432" rdkit: - image: antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.6 + image: ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4 environment: POSTGRES_USER: postgres POSTGRES_DB: postgres diff --git a/docker-compose.yaml b/docker-compose.yaml index 83b5d3e..d74b0e0 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -2,7 +2,7 @@ services: bingo: - image: antonsiomchen/cheminfo-db:postgres16.13-bingo1.40.0 + image: ghcr.io/asiomchen/bingo-postgres:postgres17-bingo1.44.0 restart: always # set shared memory limit when using docker compose shm_size: 1024mb @@ -19,7 +19,7 @@ services: # volumes: # - db_data:/var/lib/postgresql/data rdkit: - image: antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.6 + image: ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4 restart: always ports: - 5432:5432 @@ -31,4 +31,4 @@ services: # volumes: -# db_data: \ No newline at end of file +# db_data: diff --git a/pyproject.toml b/pyproject.toml index ba68ff1..a459302 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,13 +44,12 @@ dev = [ "alembic>=1.17.0", "ipykernel>=6.30.1", "jinja2>=3.1.6", - "mypy>=1.18.2", "pandas>=2.3.3", "pytest>=8.4.2", "pytest-cov>=7.0.0", "pyyaml>=6.0.2", "ruff==0.14.5", - "sqlalchemy[mypy]>=2.0.43", + "ty>=0.0.66", ] docs = [ "griffe-typingdoc>=0.2.9", @@ -98,9 +97,3 @@ exclude = [ ".github/*", ".devcontainer/*" ] - -[tool.mypy] -plugins = "sqlalchemy.ext.mypy.plugin" - -[tool.pyrefly] - diff --git a/ruff.toml b/ruff.toml index f0dd42c..b82699c 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,4 +1,4 @@ -extend-exclude = ["update_proxy_stubs.py"] +extend-exclude = [] include = ["pyproject.toml", "src/**/*.py", "scripts/**/*.py"] # Same as Black. @@ -53,4 +53,4 @@ docstring-code-line-length = "dynamic" known-third-party = [ "alembic", "loguru", -] \ No newline at end of file +] diff --git a/src/molalchemy/rdkit/__init__.py b/src/molalchemy/rdkit/__init__.py index 3fa25e6..0110356 100644 --- a/src/molalchemy/rdkit/__init__.py +++ b/src/molalchemy/rdkit/__init__.py @@ -1,6 +1,5 @@ from .comparators import RdkitFPComparator, RdkitMolComparator, RdkitReactionComparator from .index import RdkitIndex -from .proxy import RdkitMolProxy, RdkitRxnProxy from .settings import ( get_dice_threshold, get_tanimoto_threshold, @@ -23,11 +22,9 @@ "RdkitIndex", "RdkitMol", "RdkitMolComparator", - "RdkitMolProxy", "RdkitQMol", "RdkitReaction", "RdkitReactionComparator", - "RdkitRxnProxy", "RdkitSparseFingerprint", "RdkitXQMol", "get_dice_threshold", diff --git a/src/molalchemy/rdkit/comparators.py b/src/molalchemy/rdkit/comparators.py index 98ea763..66a5e36 100644 --- a/src/molalchemy/rdkit/comparators.py +++ b/src/molalchemy/rdkit/comparators.py @@ -1,125 +1,101 @@ -from typing import Any, Literal - from sqlalchemy import ColumnElement -from sqlalchemy.sql import cast, func from sqlalchemy.types import UserDefinedType -from molalchemy.types import CString +from molalchemy.protocols import ( + RdkitFingerprintOperand, + RdkitMolOperand, + RdkitReactionOperand, + SqlOperand, +) +from molalchemy.rdkit.search import ( + _rdkit_distance, + _rdkit_mol_smarts, + _rdkit_predicate, + _rdkit_rxn_smarts, +) class RdkitMolComparator(UserDefinedType.Comparator): - def __eq__(self, other: Any) -> ColumnElement[bool]: - # Native RDKit mol "=" is already chemical equality; keep "==" mapped to - # equals() for explicit comparator parity with Bingo and reactions. - if other is None: - return super().__eq__(other) - if isinstance(other, ColumnElement) and not getattr( - other, "is_clause_element", False - ): - return super().__eq__(other) - if ( - isinstance(other, ColumnElement) - and getattr(other, "table", None) is not None - ): - return super().__eq__(other) - return self.equals(other) - - def has_substructure(self, query: Any) -> ColumnElement[bool]: + def has_substructure(self, query: RdkitMolOperand) -> ColumnElement[bool]: """Check if this molecule contains `query` as a substructure (@>).""" - return self.expr.op("@>")(query) + return _rdkit_predicate(self.expr, "@>", query) - def has_smarts(self, query: Any) -> ColumnElement[bool]: + def has_smarts(self, query: str | SqlOperand) -> ColumnElement[bool]: """Check if this molecule contains SMARTS pattern `query`.""" - return self.has_substructure(func.qmol_from_smarts(cast(query, CString))) + return _rdkit_mol_smarts(self.expr, query) - def is_substructure_of(self, query: Any) -> ColumnElement[bool]: + def is_substructure_of(self, query: RdkitMolOperand) -> ColumnElement[bool]: """Check if this molecule is a substructure of `query` (<@).""" - return self.expr.op("<@")(query) + return _rdkit_predicate(self.expr, "<@", query) - def equals(self, query: Any) -> ColumnElement[bool]: - """Check if this molecule is equal to `query` (@=).""" - return self.expr.op("@=")(query) + def equals(self, query: RdkitMolOperand) -> ColumnElement[bool]: + """Check chemical equality using `@=` (an alias of `=`, both use `mol_eq`).""" + return _rdkit_predicate(self.expr, "@=", query) - def not_equals(self, query: Any) -> ColumnElement[bool]: - """Check if this molecule is not equal to `query` (@<>).""" - return self.expr.op("@<>")(query) + def not_equals(self, query: RdkitMolOperand) -> ColumnElement[bool]: + """Check chemical inequality using `@<>` (an alias of `<>`/`mol_ne`).""" + return _rdkit_predicate(self.expr, "@<>", query) - def has_query_substructure(self, query: Any) -> ColumnElement[bool]: + def has_query_substructure(self, query: SqlOperand) -> ColumnElement[bool]: """Check if this molecule contains a query substructure `query` (@>>).""" - return self.expr.op("@>>")(query) + return _rdkit_predicate(self.expr, "@>>", query) - def is_query_substructure_of(self, query: Any) -> ColumnElement[bool]: + def is_query_substructure_of(self, query: SqlOperand) -> ColumnElement[bool]: """Check if query structure `query` contains this molecule (<<@).""" - return self.expr.op("<<@")(query) + return _rdkit_predicate(self.expr, "<<@", query) class RdkitReactionComparator(UserDefinedType.Comparator): - def __eq__(self, other: Any) -> ColumnElement[bool]: - if other is None: - return super().__eq__(other) - if isinstance(other, ColumnElement) and not getattr( - other, "is_clause_element", False - ): - return super().__eq__(other) - if ( - isinstance(other, ColumnElement) - and getattr(other, "table", None) is not None - ): - return super().__eq__(other) - return self.equals(other) - - def has_substructure(self, query: Any) -> ColumnElement[bool]: + def has_substructure(self, query: RdkitReactionOperand) -> ColumnElement[bool]: """Check if this reaction contains `query` as a substructure (@>).""" - return self.expr.op("@>")(query) + return _rdkit_predicate(self.expr, "@>", query) - def is_substructure_of(self, query: Any) -> ColumnElement[bool]: + def is_substructure_of(self, query: RdkitReactionOperand) -> ColumnElement[bool]: """Check if this reaction is a substructure of `query` (<@).""" - return self.expr.op("<@")(query) + return _rdkit_predicate(self.expr, "<@", query) - def equals(self, query: Any) -> ColumnElement[bool]: + def equals(self, query: RdkitReactionOperand) -> ColumnElement[bool]: """Check if this reaction is equal to `query` (@=).""" - return self.expr.op("@=")(query) + return _rdkit_predicate(self.expr, "@=", query) - def not_equals(self, query: Any) -> ColumnElement[bool]: + def not_equals(self, query: RdkitReactionOperand) -> ColumnElement[bool]: """Check if this reaction is not equal to `query` (@<>).""" - return self.expr.op("@<>")(query) + return _rdkit_predicate(self.expr, "@<>", query) - def has_smarts(self, query: Any) -> ColumnElement[bool]: + def has_smarts(self, query: str | SqlOperand) -> ColumnElement[bool]: """Check if this reaction contains SMARTS pattern `query`.""" - return func.substruct( - self.expr, func.reaction_from_smarts(cast(query, CString)) - ) + return _rdkit_rxn_smarts(self.expr, query) - def has_substructure_fp(self, query: Any) -> ColumnElement[bool]: + def has_substructure_fp(self, query: RdkitReactionOperand) -> ColumnElement[bool]: """Check if this reaction matches `query` via substructure fingerprints (?>).""" - return self.expr.op("?>")(query) + return _rdkit_predicate(self.expr, "?>", query) - def is_substructure_fp_of(self, query: Any) -> ColumnElement[bool]: + def is_substructure_fp_of(self, query: RdkitReactionOperand) -> ColumnElement[bool]: """Check if this reaction is fingerprint-substructure of `query` (?<).""" - return self.expr.op("?<")(query) + return _rdkit_predicate(self.expr, "?<", query) class RdkitFPComparator(UserDefinedType.Comparator): - def nearest_neighbors( - self, query: ColumnElement, type: Literal["tanimoto", "dice"] = "tanimoto" - ) -> ColumnElement[bool]: - if type == "tanimoto": - return self.expr.op("<%>")(query) - else: # dice - return self.expr.op("<#>")(query) - - def tanimoto(self, query_fp: ColumnElement) -> ColumnElement[bool]: + def tanimoto_matches(self, query: RdkitFingerprintOperand) -> ColumnElement[bool]: """Tanimoto similarity threshold operator (%). Returns whether or not the Tanimoto similarity between two fingerprints (either two sfp or two bfp values) exceeds rdkit.tanimoto_threshold. """ - return self.expr.op("%")(query_fp) + return _rdkit_predicate(self.expr, "%", query) - def dice(self, query_fp: ColumnElement) -> ColumnElement[bool]: + def dice_matches(self, query: RdkitFingerprintOperand) -> ColumnElement[bool]: """Dice similarity threshold operator (#). Returns whether or not the Dice similarity between two fingerprints (either two sfp or two bfp values) exceeds rdkit.dice_threshold. """ - return self.expr.op("#")(query_fp) + return _rdkit_predicate(self.expr, "#", query) + + def tanimoto_distance(self, query: RdkitFingerprintOperand) -> ColumnElement[float]: + """Return the Tanimoto KNN distance to `query` (`<%>`).""" + return _rdkit_distance(self.expr, "<%>", query) + + def dice_distance(self, query: RdkitFingerprintOperand) -> ColumnElement[float]: + """Return the Dice KNN distance to `query` (`<#>`).""" + return _rdkit_distance(self.expr, "<#>", query) diff --git a/src/molalchemy/rdkit/functions/_types.py b/src/molalchemy/rdkit/functions/_types.py index 148f24f..0d8c213 100644 --- a/src/molalchemy/rdkit/functions/_types.py +++ b/src/molalchemy/rdkit/functions/_types.py @@ -1,80 +1,31 @@ -from __future__ import annotations +"""Operand aliases for RDKit cartridge function wrappers.""" -from typing import TYPE_CHECKING, TypeVar +from typing import Any, TypeAlias, TypeVar -from sqlalchemy import Column, Function -from sqlalchemy.orm import InstrumentedAttribute, Mapped - -from molalchemy.rdkit.types import ( - RdkitBitFingerprint, - RdkitMol, - RdkitQMol, - RdkitReaction, - RdkitSparseFingerprint, - RdkitXQMol, -) - -""" -Type aliases for RDKit-SQLAlchemy integration. -These aliases make it easier to annotate columns, mapped attributes, -and SQL functions that return RDKit objects (Mol, QMol, ...) while still -supporting literal values (e.g. SMILES strings) and raw bytes. -""" - -# Python 3.10+ has TypeAlias built-in; otherwise fall back to typing_extensions. -if TYPE_CHECKING: - from typing import TypeAlias # pragma: no cover -else: - try: - from typing import TypeAlias # type: ignore - except ImportError: # pragma: no cover - from typing import TypeAlias # type: ignore +from rdkit import Chem +from rdkit.Chem.rdChemReactions import ChemicalReaction +from sqlalchemy.orm import InstrumentedAttribute +from sqlalchemy.sql.elements import ColumnElement T = TypeVar("T") -SQLAlchemyCoercible: TypeAlias = ( - InstrumentedAttribute[T] | Column[T] | Mapped[T] | Function[T] -) - +SQLAlchemyCoercible: TypeAlias = ColumnElement[T] | InstrumentedAttribute[T] +SqlExpression: TypeAlias = ColumnElement[Any] | InstrumentedAttribute[Any] LiteralStrBytes: TypeAlias = str | bytes - -# Text-like types for string/bytes inputs -TextLike: TypeAlias = ( - str | bytes | Column[str] | Mapped[str] | InstrumentedAttribute[str] -) - -# ---------------------------------------------------------------------- -# RDKit specific type aliases -# ---------------------------------------------------------------------- -RdkitMolCoercible: TypeAlias = RdkitMol | LiteralStrBytes -AnyRdkitMolLike: TypeAlias = SQLAlchemyCoercible[RdkitMolCoercible] | RdkitMolCoercible -RdkitQMolCoercible: TypeAlias = RdkitQMol | LiteralStrBytes -AnyRdkitQMolLike: TypeAlias = ( - SQLAlchemyCoercible[RdkitQMolCoercible] | RdkitQMolCoercible -) -RdkitXQMolCoercible: TypeAlias = RdkitXQMol | LiteralStrBytes -AnyRdkitXQMolLike: TypeAlias = ( - SQLAlchemyCoercible[RdkitXQMolCoercible] | RdkitXQMolCoercible -) -RdkitBitFingerprintCoercible: TypeAlias = RdkitBitFingerprint | LiteralStrBytes -AnyRdkitBitFingerprintLike: TypeAlias = ( - SQLAlchemyCoercible[RdkitBitFingerprintCoercible] | RdkitBitFingerprintCoercible -) -RdkitSparseFingerprintCoercible: TypeAlias = RdkitSparseFingerprint | LiteralStrBytes -AnyRdkitSparseFingerprintLike: TypeAlias = ( - SQLAlchemyCoercible[RdkitSparseFingerprintCoercible] - | RdkitSparseFingerprintCoercible -) -RdkitReactionCoercible: TypeAlias = RdkitReaction | LiteralStrBytes -AnyRdkitReactionLike: TypeAlias = ( - SQLAlchemyCoercible[RdkitReactionCoercible] | RdkitReactionCoercible -) - -# ---------------------------------------------------------------------- -# Combined fingerprint alias - convenient for functions that accept either. -# ---------------------------------------------------------------------- -AnyRdkitFingerprintLike: TypeAlias = ( - AnyRdkitBitFingerprintLike | AnyRdkitSparseFingerprintLike -) +TextLike: TypeAlias = str | bytes | SqlExpression + +RdkitMolCoercible: TypeAlias = str | Chem.Mol +AnyRdkitMolLike: TypeAlias = RdkitMolCoercible | SqlExpression +RdkitQMolCoercible: TypeAlias = str +AnyRdkitQMolLike: TypeAlias = str | SqlExpression +RdkitXQMolCoercible: TypeAlias = str +AnyRdkitXQMolLike: TypeAlias = str | SqlExpression +RdkitBitFingerprintCoercible: TypeAlias = bytes +AnyRdkitBitFingerprintLike: TypeAlias = bytes | SqlExpression +RdkitSparseFingerprintCoercible: TypeAlias = bytes +AnyRdkitSparseFingerprintLike: TypeAlias = bytes | SqlExpression +RdkitReactionCoercible: TypeAlias = str | ChemicalReaction +AnyRdkitReactionLike: TypeAlias = RdkitReactionCoercible | SqlExpression +AnyRdkitFingerprintLike: TypeAlias = bytes | SqlExpression __all__ = [ "AnyRdkitBitFingerprintLike", diff --git a/src/molalchemy/rdkit/functions/general.py b/src/molalchemy/rdkit/functions/general.py index 96d60b0..84c78d2 100644 --- a/src/molalchemy/rdkit/functions/general.py +++ b/src/molalchemy/rdkit/functions/general.py @@ -4,13 +4,17 @@ from typing import Any -from sqlalchemy import BinaryExpression, Function from sqlalchemy import types as sqltypes -from sqlalchemy.sql import cast, func +from sqlalchemy.sql import cast from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.sql.expression import Cast from sqlalchemy.sql.functions import GenericFunction +from molalchemy.rdkit.search import ( + _rdkit_mol_smarts, + _rdkit_predicate, + _rdkit_rxn_smarts, +) from molalchemy.rdkit.types import ( RdkitBitFingerprint, RdkitMol, @@ -34,7 +38,7 @@ def mol_has_substructure( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform substructure search. @@ -63,10 +67,10 @@ def mol_has_substructure( >>> # Search for molecules containing a aromatic carbon as SMARTS >>> query = select(Molecule).where(has_substructure(Molecule.structure, cast("[cH]", RdkitQMol))) """ - return mol_column.op("@>")(query) + return _rdkit_predicate(mol_column, "@>", query) -def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> Function[bool]: +def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> ColumnElement[bool]: """ Perform molecule SMARTS search. @@ -92,12 +96,12 @@ def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> Function[bool]: >>> from sqlalchemy import select >>> query = select(Molecule).where(mol_has_smarts(Molecule.structure, "[#6]")) """ - return mol_has_substructure(mol_column, qmol_from_smarts(cast(pattern, CString))) + return _rdkit_mol_smarts(mol_column, pattern) def mol_is_substructure_of( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse substructure search. @@ -118,17 +122,19 @@ def mol_is_substructure_of( BinaryExpression SQLAlchemy binary expression for the reverse substructure search. """ - return mol_column.op("<@")(query) + return _rdkit_predicate(mol_column, "<@", query) def mol_equals( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact structure matching. - Checks if the molecular structure in the column exactly matches - the query using the `@=` operator. + Checks if the molecular structure in the column chemically matches + the query using `@=`. RDKit maps both `@=` and ordinary `=` to + the `mol_eq` function, so this is an explicit spelling of the same + cartridge equality used by `column == query`. Parameters ---------- @@ -143,25 +149,26 @@ def mol_equals( BinaryExpression SQLAlchemy binary expression for the exact match search. """ - return mol_column.op("@=")(query) + return _rdkit_predicate(mol_column, "@=", query) def mol_not_equals( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform negative exact structure matching. - Checks if the molecular structure in the column differs from - the query using the `@<>` operator. + Checks if the molecular structure in the column differs chemically from + the query using `@<>`. RDKit maps both `@<>` and ordinary `<>` to + the `mol_ne` function. """ - return mol_column.op("@<>")(query) + return _rdkit_predicate(mol_column, "@<>", query) def mol_has_query_substructure( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike | AnyRdkitQMolLike | AnyRdkitXQMolLike, -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform query-substructure search. @@ -169,13 +176,13 @@ def mol_has_query_substructure( using the `@>>` operator. Use `RdkitQMol` or `RdkitXQMol` expressions for SMARTS/query semantics. """ - return mol_column.op("@>>")(query) + return _rdkit_predicate(mol_column, "@>>", query) def mol_is_query_substructure_of( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike | AnyRdkitQMolLike | AnyRdkitXQMolLike, -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse query-substructure search. @@ -183,82 +190,82 @@ def mol_is_query_substructure_of( using the `<<@` operator. Use `RdkitQMol` or `RdkitXQMol` expressions for SMARTS/query semantics. """ - return mol_column.op("<<@")(query) + return _rdkit_predicate(mol_column, "<<@", query) def rxn_has_substructure( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reaction substructure search. Checks if the reaction in the column contains the query reaction using the `@>` operator. """ - return rxn_column.op("@>")(query) + return _rdkit_predicate(rxn_column, "@>", query) def rxn_is_substructure_of( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse reaction substructure search. Checks if the reaction in the column is a substructure of the query using the `<@` operator. """ - return rxn_column.op("<@")(query) + return _rdkit_predicate(rxn_column, "<@", query) def rxn_equals( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact reaction matching. Checks if the reaction in the column exactly matches the query using the `@=` operator. """ - return rxn_column.op("@=")(query) + return _rdkit_predicate(rxn_column, "@=", query) def rxn_not_equals( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform negative exact reaction matching. Checks if the reaction in the column differs from the query using the `@<>` operator. """ - return rxn_column.op("@<>")(query) + return _rdkit_predicate(rxn_column, "@<>", query) def rxn_has_substructure_fp( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform fingerprint-backed reaction substructure search. Checks if the reaction in the column contains the query using the `?>` operator. """ - return rxn_column.op("?>")(query) + return _rdkit_predicate(rxn_column, "?>", query) def rxn_is_substructure_fp_of( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse fingerprint-backed reaction substructure search. Checks if the reaction in the column is a fingerprint substructure of the query using the `?<` operator. """ - return rxn_column.op("?<")(query) + return _rdkit_predicate(rxn_column, "?<", query) -def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> Function[bool]: +def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> ColumnElement[bool]: """ Perform reaction substructure search. @@ -286,7 +293,7 @@ def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> Function[bool]: >>> # Search for reactions containing a carbonyl formation >>> query = select(Reaction).where(has_smarts(Reaction.rxn, ">>C=O")) """ - return func.substruct(rxn_column, reaction_from_smarts(cast(pattern, CString))) + return _rdkit_rxn_smarts(rxn_column, pattern) class add(GenericFunction): diff --git a/src/molalchemy/rdkit/proxy.py b/src/molalchemy/rdkit/proxy.py deleted file mode 100644 index a23392e..0000000 --- a/src/molalchemy/rdkit/proxy.py +++ /dev/null @@ -1,98 +0,0 @@ -""" -Proxy classes for RDKit database operations. - -This module contains proxy classes that provide stub methods for type hinting -and autocomplete functionality. The actual implementation is delegated to -the corresponding function classes in the functions module. - -This file is auto-generated from the comparator classes. -Do not edit manually - use the update_proxy_stubs.py script instead. -""" - - -class RdkitMolProxy: - """ - Proxy class for molecular operations using RDKit database. - - This class provides stub methods for type hinting and autocomplete functionality. - The actual implementation is delegated to the corresponding function class. - """ - - @staticmethod - def has_substructure(query: str): - """Check if this molecule contains `query` as a substructure (@>).""" - pass - - @staticmethod - def has_smarts(query: str): - """Check if this molecule contains SMARTS pattern `query`.""" - pass - - @staticmethod - def is_substructure_of(query: str): - """Check if this molecule is a substructure of `query` (<@).""" - pass - - @staticmethod - def equals(query: str): - """Check if this molecule is equal to `query` (@=).""" - pass - - @staticmethod - def not_equals(query: str): - """Check if this molecule is not equal to `query` (@<>).""" - pass - - @staticmethod - def has_query_substructure(query: str): - """Check if this molecule contains a query substructure `query` (@>>).""" - pass - - @staticmethod - def is_query_substructure_of(query: str): - """Check if query structure `query` contains this molecule (<<@).""" - pass - - -class RdkitRxnProxy: - """ - Proxy class for chemical reaction operations using RDKit database. - - This class provides stub methods for type hinting and autocomplete functionality. - The actual implementation is delegated to the corresponding function class. - """ - - @staticmethod - def has_substructure(query: str): - """Check if this reaction contains `query` as a substructure (@>).""" - pass - - @staticmethod - def is_substructure_of(query: str): - """Check if this reaction is a substructure of `query` (<@).""" - pass - - @staticmethod - def equals(query: str): - """Check if this reaction is equal to `query` (@=).""" - pass - - @staticmethod - def not_equals(query: str): - """Check if this reaction is not equal to `query` (@<>).""" - pass - - @staticmethod - def has_smarts(query: str): - """Check if this reaction contains SMARTS pattern `query`.""" - pass - - @staticmethod - def has_substructure_fp(query: str): - """Check if this reaction matches `query` via substructure fingerprints (?>).""" - pass - - @staticmethod - def is_substructure_fp_of(query: str): - """Check if this reaction is fingerprint-substructure of `query` (?<).""" - pass diff --git a/src/molalchemy/rdkit/search.py b/src/molalchemy/rdkit/search.py new file mode 100644 index 0000000..94ddbdd --- /dev/null +++ b/src/molalchemy/rdkit/search.py @@ -0,0 +1,44 @@ +"""Private RDKit search-expression builders.""" + +from typing import Any, cast + +from sqlalchemy import Boolean, Float +from sqlalchemy.sql import cast as sql_cast +from sqlalchemy.sql import func +from sqlalchemy.sql.elements import ColumnElement + +from molalchemy.types import CString + + +def _rdkit_predicate( + column: ColumnElement[Any], operator: str, query: object +) -> ColumnElement[bool]: + """Build a Boolean RDKit cartridge operator expression.""" + return cast(ColumnElement[bool], column.bool_op(operator)(query)) + + +def _rdkit_distance( + column: ColumnElement[Any], operator: str, query: object +) -> ColumnElement[float]: + """Build a floating-point RDKit KNN distance expression.""" + return cast(ColumnElement[float], column.op(operator, return_type=Float())(query)) + + +def _rdkit_mol_smarts( + column: ColumnElement[Any], pattern: object +) -> ColumnElement[bool]: + query = func.qmol_from_smarts(sql_cast(pattern, CString)) + return _rdkit_predicate(column, "@>", query) + + +def _rdkit_rxn_smarts( + column: ColumnElement[Any], pattern: object +) -> ColumnElement[bool]: + return cast( + ColumnElement[bool], + func.substruct( + column, + func.reaction_from_smarts(sql_cast(pattern, CString)), + type_=Boolean(), + ), + ) diff --git a/tests/rdkit/__init__.py b/tests/rdkit/__init__.py index 7b8cb2d..3962d39 100644 --- a/tests/rdkit/__init__.py +++ b/tests/rdkit/__init__.py @@ -1,29 +1 @@ -"""RDKit query structure tests.""" - -from .test_comparators import ( - TestRdkitFPComparator, - TestRdkitMolComparator, - TestRdkitReactionComparator, -) -from .test_index import TestRdkitIndex -from .test_types import ( - TestRdkitBitFingerprint, - TestRdkitMol, - TestRdkitReaction, - TestRdkitSparseFingerprint, -) - -__all__ = [ - "TestCString", - "TestRdkitBitFingerprint", - "TestRdkitFPComparator", - "TestRdkitFunc", - "TestRdkitFuncIntegration", - "TestRdkitFuncWithORM", - "TestRdkitIndex", - "TestRdkitMol", - "TestRdkitMolComparator", - "TestRdkitReaction", - "TestRdkitReactionComparator", - "TestRdkitSparseFingerprint", -] +"""RDKit test package.""" diff --git a/tests/rdkit/test_comparators.py b/tests/rdkit/test_comparators.py index fd4a760..5db85fb 100644 --- a/tests/rdkit/test_comparators.py +++ b/tests/rdkit/test_comparators.py @@ -1,20 +1,24 @@ -"""Tests for RDKit comparators.""" +"""Semantic tests for RDKit comparators.""" import pytest from sqlalchemy import ( + Boolean, Column, - ColumnElement, + Float, Integer, MetaData, String, Table, + and_, bindparam, cast, + or_, + select, ) from sqlalchemy.dialects import postgresql -from sqlalchemy.sql import select +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column -from molalchemy.rdkit import RdkitMolComparator, RdkitReactionComparator +from molalchemy.rdkit import RdkitFPComparator, RdkitMolComparator from molalchemy.rdkit.types import ( RdkitBitFingerprint, RdkitMol, @@ -24,482 +28,175 @@ ) -class TestRdkitMolComparator: - """Test RdkitMolComparator methods.""" - - def setup_method(self): - """Set up test table with RdkitMol column.""" - self.metadata = MetaData() - self.test_table = Table( - "test_molecules", - self.metadata, - Column("id", Integer, primary_key=True), - Column("name", String(100)), - Column("structure", RdkitMol()), - ) - self.mol_column = self.test_table.c.structure - - @pytest.mark.parametrize( - ("method_name", "query", "operator"), - [ - ("has_substructure", "c1ccccc1", "@>"), - ("is_substructure_of", "CCOCC", "<@"), - ("equals", "CCO", "@="), - ("not_equals", "CCN", "@<>"), - ("has_query_substructure", cast("[cH]", RdkitQMol), "@>>"), - ("is_query_substructure_of", cast("[cH]", RdkitQMol), "<<@"), - ], +def sql(expression) -> str: + return str(expression.compile(dialect=postgresql.dialect(paramstyle="named"))) + + +class Base(DeclarativeBase): + pass + + +class Compound(Base): + __tablename__ = "rdkit_comparator_compounds" + + id: Mapped[int] = mapped_column(primary_key=True) + mol: Mapped[str] = mapped_column(RdkitMol()) + fp: Mapped[bytes] = mapped_column(RdkitBitFingerprint()) + + +@pytest.fixture +def columns(): + table = Table( + "rdkit_values", + MetaData(), + Column("id", Integer), + Column("mol", RdkitMol()), + Column("other_mol", RdkitMol()), + Column("rxn", RdkitReaction()), + Column("other_rxn", RdkitReaction()), + Column("bfp", RdkitBitFingerprint()), + Column("sfp", RdkitSparseFingerprint()), + Column("text", String()), ) - def test_methods_compile_to_expected_operators(self, method_name, query, operator): - """Live RDKit molecule operators are exposed directly on the comparator.""" - result = getattr(self.mol_column, method_name)(query) - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert operator in sql - if isinstance(query, str): - assert "mol_from_pkl" in sql - assert query in compiled.params.values() - else: - assert "CAST" in sql - assert "qmol" in sql - - def test_query_with_special_characters(self): - """Test query with special molecular structures.""" - query = "CC(=O)O" # acetic acid - - result = self.mol_column.equals(query) - compiled = str(result.compile()) - - assert "@=" in compiled - # The query value will be a bind parameter, not literal - assert ":structure_" in compiled - - def test_eq_operator_delegates_to_exact_match(self): - result = self.mol_column == "CCO" - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "@=" in sql - assert "mol_from_pkl" in sql - assert "CCO" in compiled.params.values() - - def test_eq_operator_with_none_uses_sql_null_check(self): - result = self.mol_column.__eq__(None) - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "IS NULL" in sql - assert "@=" not in sql - assert "mol_from_pkl" not in sql - - def test_string_queries_compile_via_molecule_coercion(self): - stmt = select(self.test_table).where( - self.mol_column.has_substructure("x' OR 1=1 --") - ) - - compiled = stmt.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "mol_from_pkl" in sql - assert "x' OR 1=1 --" not in sql - assert "x' OR 1=1 --" in compiled.params.values() - - def test_query_expressions_are_preserved(self): - stmt = select(self.test_table).where( - self.mol_column.has_query_substructure(cast("[cH]", RdkitQMol)) - ) - - compiled = stmt.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "CAST(" in sql - assert " AS qmol)" in sql - assert "mol_from_pkl" not in sql - assert "[cH]" in compiled.params.values() - - def test_has_smarts_uses_function_backed_search(self): - result = self.mol_column.has_smarts("[#6]1:[#6]:[#6]:[#6]:[#6]:[#6]:1") - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "@>" in sql - assert "substruct(" not in sql - assert "qmol_from_smarts" in sql - assert "[#6]1:[#6]:[#6]:[#6]:[#6]:[#6]:1" in compiled.params.values() - - def test_invalid_operator(self): - """Test that invalid operators raise appropriate errors.""" - query = "CCO" - - # Test with a method that doesn't exist - try: - # This should raise AttributeError since invalid_method doesn't exist - self.mol_column.invalid_method(query) - assert False, "Should have raised AttributeError" - except AttributeError: - pass - - -class TestRdkitFPComparator: - """Test RdkitFPComparator methods for fingerprint data.""" - - def setup_method(self): - """Set up test table with fingerprint columns.""" - self.metadata = MetaData() - self.test_table = Table( - "test_fingerprints", - self.metadata, - Column("id", Integer, primary_key=True), - Column("name", String(100)), - Column("fingerprint", RdkitBitFingerprint()), - Column("sparse_fp", RdkitSparseFingerprint()), - ) - self.fp_column = self.test_table.c.fingerprint - self.sparse_fp_column = self.test_table.c.sparse_fp - - def test_nearest_neighbors_tanimoto_query_generation(self): - """Test nearest_neighbors with tanimoto query generation.""" - query_fp = b"test_fingerprint" - - result = self.fp_column.nearest_neighbors(query_fp, "tanimoto") - - # Check that the result is a proper SQLAlchemy expression - assert hasattr(result, "left") - assert hasattr(result, "right") - assert hasattr(result, "operator") - - # Check that we can compile it to SQL (basic check) - compiled = str(result.compile()) - assert "<%>" in compiled - assert ":fingerprint_" in compiled - - def test_nearest_neighbors_dice_query_generation(self): - """Test nearest_neighbors with dice query generation.""" - query_fp = b"test_fingerprint" - - result = self.fp_column.nearest_neighbors(query_fp, "dice") - - # Check that the result is a proper SQLAlchemy expression - assert hasattr(result, "left") - assert hasattr(result, "right") - assert hasattr(result, "operator") - - # Check that we can compile it to SQL (basic check) - compiled = str(result.compile()) - assert "<#>" in compiled - assert ":fingerprint_" in compiled - - def test_nearest_neighbors_default_tanimoto(self): - """Test that nearest_neighbors defaults to tanimoto.""" - query_fp = b"test_fingerprint" - - result = self.fp_column.nearest_neighbors(query_fp) - compiled = str(result.compile()) - - # Should default to tanimoto - assert "<%>" in compiled - assert ":fingerprint_" in compiled - - def test_dice_similarity_query_generation(self): - """Test dice similarity query generation.""" - query_fp = b"test_fingerprint" - - result = self.fp_column.dice(query_fp) - - # Check that the result is a proper SQLAlchemy expression - assert hasattr(result, "left") - assert hasattr(result, "right") - assert hasattr(result, "operator") - - # Check that we can compile it to SQL (basic check) - compiled = str(result.compile()) - assert "#" in compiled - assert ":fingerprint_" in compiled - - def test_sparse_fingerprint_comparator_methods(self): - """Test that sparse fingerprint columns have the same comparator methods.""" - query_fp = b"test_sparse_fingerprint" - - # Test that sparse fingerprint columns also have the fingerprint comparator methods - tanimoto_result = self.sparse_fp_column.nearest_neighbors(query_fp, "tanimoto") - dice_result = self.sparse_fp_column.dice(query_fp) - - # Should compile without errors - tanimoto_compiled = str(tanimoto_result.compile()) - dice_compiled = str(dice_result.compile()) - - assert "<%>" in tanimoto_compiled - assert "#" in dice_compiled - assert ":sparse_fp_" in tanimoto_compiled - assert ":sparse_fp_" in dice_compiled - - -class TestRdkitReactionComparator: - """Test RdkitReactionComparator methods.""" - - def setup_method(self): - """Set up test table with RdkitReaction columns.""" - self.metadata = MetaData() - self.test_table = Table( - "test_reactions", - self.metadata, - Column("id", Integer, primary_key=True), - Column("rxn", RdkitReaction()), - Column("query_rxn", RdkitReaction()), - ) - self.rxn_column = self.test_table.c.rxn - - @pytest.mark.parametrize( - ("method_name", "query", "operator"), - [ - ("has_substructure", "[C:1]>>[C:1][O]", "@>"), - ("is_substructure_of", "[C:1][O]>>[C:1]", "<@"), - ("equals", "[C:1]>>[C:1]", "@="), - ("not_equals", "[C:1]>>[C:1][Cl]", "@<>"), - ("has_substructure_fp", "[C:1]>>[C:1][Br]", "?>"), - ("is_substructure_fp_of", "[C:1][Br]>>[C:1]", "?<"), - ], + return table.c + + +@pytest.mark.parametrize( + ("method", "query", "operator"), + [ + ("has_substructure", "c1ccccc1", "@>"), + ("is_substructure_of", "CCO", "<@"), + ("equals", "CCO", "@="), + ("not_equals", "CCN", "@<>"), + ("has_query_substructure", cast("[cH]", RdkitQMol), "@>>"), + ("is_query_substructure_of", cast("[cH]", RdkitQMol), "<<@"), + ], +) +def test_molecule_predicates_are_boolean(columns, method, query, operator): + expression = getattr(columns.mol, method)(query) + + assert isinstance(expression.type, Boolean) + assert operator in sql(expression) + + +def test_molecule_smarts_is_boolean(columns): + expression = columns.mol.has_smarts("[#6]") + + assert isinstance(expression.type, Boolean) + assert "qmol_from_smarts" in sql(expression) + assert "@>" in sql(expression) + + +@pytest.mark.parametrize( + ("method", "operator"), + [ + ("has_substructure", "@>"), + ("is_substructure_of", "<@"), + ("equals", "@="), + ("not_equals", "@<>"), + ("has_substructure_fp", "?>"), + ("is_substructure_fp_of", "?<"), + ], +) +def test_reaction_predicates_are_boolean(columns, method, operator): + expression = getattr(columns.rxn, method)("[C:1]>>[C:1]") + + assert isinstance(expression.type, Boolean) + assert operator in sql(expression) + + +def test_reaction_smarts_is_boolean(columns): + expression = columns.rxn.has_smarts("[C:1]>>[C:1][O]") + + assert isinstance(expression.type, Boolean) + assert "substruct" in sql(expression) + + +@pytest.mark.parametrize("fingerprint", ["bfp", "sfp"]) +@pytest.mark.parametrize( + ("method", "operator", "result_type"), + [ + ("tanimoto_matches", "%", Boolean), + ("dice_matches", "#", Boolean), + ("tanimoto_distance", "<%>", Float), + ("dice_distance", "<#>", Float), + ], +) +def test_fingerprint_operators_have_exact_types( + columns, fingerprint, method, operator, result_type +): + column = columns[fingerprint] + expression = getattr(column, method)(bindparam("query_fp", b"fingerprint")) + + assert isinstance(expression.type, result_type) + assert operator in sql(expression) + + +def test_removed_fingerprint_methods_have_no_compatibility_aliases(columns): + for name in ("tanimoto", "dice", "nearest_neighbors"): + with pytest.raises(AttributeError): + getattr(columns.bfp, name) + + +def test_predicates_compose_negate_and_label(columns): + substructure = columns.mol.has_substructure("CO") + exact = columns.mol.equals(bindparam("exact", "CCO")) + statement = select((~substructure).label("not_sub")).where( + and_(or_(substructure, exact), ~columns.mol.not_equals("CCO")) ) - def test_methods_compile_to_expected_operator(self, method_name, query, operator): - """Live RDKit reaction operators are exposed directly on the comparator.""" - result = getattr(self.rxn_column, method_name)(query) - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert operator in sql - assert "reaction_from_smarts" in sql - assert query in compiled.params.values() - - def test_string_queries_compile_via_reaction_coercion(self): - """String queries must bind as reactions, not raw text.""" - stmt = select(self.test_table).where( - self.rxn_column.has_substructure("x' OR 1=1 -- >> [C:1]") - ) - - compiled = stmt.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "reaction_from_smarts" in sql - assert "x' OR 1=1 -- >> [C:1]" not in sql - assert "x' OR 1=1 -- >> [C:1]" in compiled.params.values() - - def test_bindparam_queries_compile_via_reaction_coercion(self): - stmt = select(self.test_table).where( - self.rxn_column.equals(bindparam("query_rxn")) - ) - - compiled = stmt.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "@=" in sql - assert "reaction_from_smarts" in sql - assert "%(query_rxn)s" in sql - - def test_eq_operator_delegates_to_exact_match(self): - result = self.rxn_column == "[C:1]>>[C:1]" - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "@=" in sql - assert "reaction_from_smarts" in sql - assert "[C:1]>>[C:1]" in compiled.params.values() - - def test_eq_operator_with_none_uses_sql_null_check(self): - result = self.rxn_column.__eq__(None) - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "IS NULL" in sql - assert "@=" not in sql - assert "reaction_from_smarts" not in sql - - def test_query_column_expressions_are_preserved(self): - stmt = select(self.test_table).where( - self.rxn_column.has_substructure(self.test_table.c.query_rxn) - ) - - compiled = str( - stmt.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) - - assert "test_reactions.query_rxn" in compiled - assert "'test_reactions.query_rxn'" not in compiled - assert "reaction_from_smarts" not in compiled - - def test_has_smarts_uses_function_backed_search(self): - result = self.rxn_column.has_smarts("[C:1]>>[C:1][O]") - compiled = result.compile(dialect=postgresql.dialect()) - sql = str(compiled) - - assert "substruct(" in sql - assert "@>" not in sql - assert "reaction_from_smarts" in sql - assert "[C:1]>>[C:1][O]" in compiled.params.values() - - -class TestComparatorReturnTypes: - """Test that comparator methods return properly typed expressions.""" - - def setup_method(self): - self.metadata = MetaData() - self.test_table = Table( - "test_compounds", - self.metadata, - Column("id", Integer, primary_key=True), - Column("structure", RdkitMol()), - Column("fingerprint", RdkitBitFingerprint()), - Column("reaction", RdkitReaction()), - ) - - def test_has_substructure_returns_column_element(self): - result = self.test_table.c.structure.has_substructure("CCO") - assert isinstance(result, ColumnElement) - - def test_has_smarts_returns_column_element(self): - result = self.test_table.c.structure.has_smarts("[#6]") - assert isinstance(result, ColumnElement) - - def test_is_substructure_of_returns_column_element(self): - result = self.test_table.c.structure.is_substructure_of("CCO") - assert isinstance(result, ColumnElement) - - def test_equals_returns_column_element(self): - result = self.test_table.c.structure.equals("CCO") - assert isinstance(result, ColumnElement) - - def test_not_equals_returns_column_element(self): - result = self.test_table.c.structure.not_equals("CCN") - assert isinstance(result, ColumnElement) - - def test_has_query_substructure_returns_column_element(self): - result = self.test_table.c.structure.has_query_substructure( - cast("[cH]", RdkitQMol) - ) - assert isinstance(result, ColumnElement) - - def test_is_query_substructure_of_returns_column_element(self): - result = self.test_table.c.structure.is_query_substructure_of( - cast("[cH]", RdkitQMol) - ) - assert isinstance(result, ColumnElement) - - def test_tanimoto_returns_column_element(self): - result = self.test_table.c.fingerprint.tanimoto(b"fp") - assert isinstance(result, ColumnElement) - - def test_dice_returns_column_element(self): - result = self.test_table.c.fingerprint.dice(b"fp") - assert isinstance(result, ColumnElement) - - def test_nearest_neighbors_returns_column_element(self): - result = self.test_table.c.fingerprint.nearest_neighbors(b"fp") - assert isinstance(result, ColumnElement) - - def test_reaction_equals_returns_column_element(self): - result = self.test_table.c.reaction.equals("[C:1]>>[C:1]") - assert isinstance(result, ColumnElement) - - def test_reaction_not_equals_returns_column_element(self): - result = self.test_table.c.reaction.not_equals("[C:1]>>[C:1][O]") - assert isinstance(result, ColumnElement) - - def test_reaction_has_smarts_returns_column_element(self): - result = self.test_table.c.reaction.has_smarts("[C:1]>>[C:1][O]") - assert isinstance(result, ColumnElement) - - -class TestRdkitComparatorExports: - """Test comparators are exported from the rdkit subpackage.""" - - def test_import_mol_comparator_from_rdkit(self): - assert RdkitMolComparator is not None - - def test_import_reaction_comparator_from_rdkit(self): - assert RdkitReactionComparator is not None - - def test_import_proxies_from_rdkit(self): - from molalchemy.rdkit import RdkitMolProxy, RdkitRxnProxy - - assert RdkitMolProxy is not None - assert RdkitRxnProxy is not None - - -class TestRdkitComparatorInQueries: - """Test RDKit comparators in actual SQL queries.""" - - def setup_method(self): - """Set up test table for query testing.""" - self.metadata = MetaData() - self.test_table = Table( - "test_compounds", - self.metadata, - Column("id", Integer, primary_key=True), - Column("name", String(100)), - Column("structure", RdkitMol()), - Column("fingerprint", RdkitBitFingerprint()), - ) - - def test_has_substructure_in_select_query(self): - """Test has_substructure comparator in SELECT query.""" - query = "c1ccccc1" - - stmt = select(self.test_table).where( - self.test_table.c.structure.has_substructure(query) - ) - - # Should compile without errors - compiled = str(stmt.compile()) - assert "SELECT" in compiled - assert "@>" in compiled - assert ":structure_" in compiled - - def test_equals_in_select_query(self): - """Test equals comparator in SELECT query.""" - query = "CCO" - - stmt = select(self.test_table).where(self.test_table.c.structure.equals(query)) - - # Should compile without errors - compiled = str(stmt.compile()) - assert "SELECT" in compiled - assert "@=" in compiled - assert ":structure_" in compiled - - def test_fingerprint_similarity_in_select_query(self): - """Test fingerprint similarity comparator in SELECT query.""" - query_fp = b"test_fingerprint" - - stmt = select(self.test_table).where( - self.test_table.c.fingerprint.nearest_neighbors(query_fp) - ) - - # Should compile without errors - compiled = str(stmt.compile()) - assert "SELECT" in compiled - assert "<%>" in compiled - assert ":fingerprint_" in compiled - - def test_multiple_comparators_in_query(self): - """Test using multiple RDKit comparators in one query.""" - benzene = "c1ccccc1" - ethanol = "CCO" - query_fp = b"test_fingerprint" - - stmt = select(self.test_table).where( - self.test_table.c.structure.has_substructure(benzene) - | self.test_table.c.structure.equals(ethanol) - | self.test_table.c.fingerprint.dice(query_fp) - ) - - compiled = str(stmt.compile()) - assert "SELECT" in compiled - # Should contain all operators - assert "@>" in compiled # has_substructure - assert "@=" in compiled # equals - assert "#" in compiled # dice - # Should have proper bind parameters - assert ":structure_" in compiled - assert ":fingerprint_" in compiled + + compiled = statement.compile(dialect=postgresql.dialect()) + assert isinstance(substructure.type, Boolean) + assert {"CO", "CCO"}.issubset(set(compiled.params.values())) + + +def test_knn_distances_work_in_order_by(columns): + query = bindparam("query_fp", b"fingerprint") + statement = select(columns.id).order_by( + columns.bfp.tanimoto_distance(query), + columns.bfp.dice_distance(query), + ) + + compiled = sql(statement) + assert "ORDER BY" in compiled + assert "<%>" in compiled + assert "<#>" in compiled + + +def test_sql_expression_operands_are_preserved(columns): + subquery = select(columns.other_mol.label("query")).subquery() + expression = columns.mol.has_substructure(subquery.c.query) + compiled = sql(expression) + + assert "anon_1.query" in compiled + assert "mol_from_pkl" not in compiled + + +@pytest.mark.parametrize("name", ["mol", "rxn"]) +def test_native_equality_and_null_semantics(columns, name): + column = columns[name] + other = columns[f"other_{name}"] + + assert " = " in sql(column == other) + assert " != " in sql(column != other) + assert " = " in sql(column == "CCO") + assert " != " in sql(column != "CCO") + assert "@=" not in sql(column == other) + assert "IS NULL" in sql(column.__eq__(None)) + assert "IS NOT NULL" in sql(column.__ne__(None)) + assert "@=" in sql(column.equals(other)) + assert "@<>" in sql(column.not_equals(other)) + + +def test_orm_comparators_remain_available_at_runtime(): + predicate = Compound.mol.equals("CCO") + distance = Compound.fp.tanimoto_distance(b"fingerprint") + + assert isinstance(predicate.type, Boolean) + assert isinstance(distance.type, Float) + assert "ORDER BY" in sql(select(Compound).order_by(distance)) + + +def test_comparators_are_public(): + assert RdkitMolComparator.__name__ == "RdkitMolComparator" + assert RdkitFPComparator.__name__ == "RdkitFPComparator" diff --git a/tests/rdkit/test_integration.py b/tests/rdkit/test_integration.py index 57e7c81..9a22934 100644 --- a/tests/rdkit/test_integration.py +++ b/tests/rdkit/test_integration.py @@ -66,7 +66,7 @@ def test_tanimoto_similarity_query(self): query_fp = "morganbv_fp('CCO'::mol)" stmt = select(self.molecules).where( - self.molecules.c.morgan_fp.tanimoto(query_fp) + self.molecules.c.morgan_fp.tanimoto_matches(query_fp) ) compiled = str(stmt.compile()) @@ -76,22 +76,35 @@ 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)) + stmt = select(self.molecules).where( + self.molecules.c.morgan_fp.dice_matches(query_fp) + ) compiled = str(stmt.compile()) assert "#" in compiled - def test_nearest_neighbors_query(self): + def test_tanimoto_distance_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) + stmt = select(self.molecules).order_by( + self.molecules.c.morgan_fp.tanimoto_distance(query_fp) ) compiled = str(stmt.compile()) assert "<%>" in compiled + def test_dice_distance_query(self): + """Test Dice KNN distance compiles with <#> in ORDER BY.""" + query_fp = "morganbv_fp('CCO'::mol)" + stmt = select(self.molecules).order_by( + self.molecules.c.morgan_fp.dice_distance(query_fp) + ) + + compiled = str(stmt.compile()) + assert "ORDER BY" in compiled + assert "<#>" in compiled + def test_complex_query_with_multiple_conditions(self): """Test complex query with or_/and_ combinations.""" benzene = "c1ccccc1" @@ -152,7 +165,9 @@ 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)) + stmt = select(self.Molecule).where( + self.Molecule.morgan_fp.tanimoto_matches(query_fp) + ) compiled = str(stmt.compile()) assert "%" in compiled diff --git a/update_proxy_stubs.py b/update_proxy_stubs.py deleted file mode 100644 index 0762bff..0000000 --- a/update_proxy_stubs.py +++ /dev/null @@ -1,268 +0,0 @@ -#!/usr/bin/env python3 -""" -Script to create cartridge proxy stubs in a separate proxy.py file. - -This script reads the comparator classes and creates a new proxy.py file with -stub methods that match the comparator method signatures and docstrings. -The proxy classes provide type hinting and autocomplete functionality. -""" - -import ast -import textwrap -from pathlib import Path -from typing import Any - -TARGETS = { - "bingo": { - "comparators_path": Path("src/molalchemy/bingo/comparators.py"), - "proxy_path": Path("src/molalchemy/bingo/proxy.py"), - "mol_comparator": "BingoMolComparator", - "rxn_comparator": "BingoRxnComparator", - "mol_proxy": "BingoMolProxy", - "rxn_proxy": "BingoRxnProxy", - "label": "Bingo", - }, - "rdkit": { - "comparators_path": Path("src/molalchemy/rdkit/comparators.py"), - "proxy_path": Path("src/molalchemy/rdkit/proxy.py"), - "mol_comparator": "RdkitMolComparator", - "rxn_comparator": "RdkitReactionComparator", - "mol_proxy": "RdkitMolProxy", - "rxn_proxy": "RdkitRxnProxy", - "label": "RDKit", - }, -} - - -def extract_method_info(class_node: ast.ClassDef) -> list[dict[str, Any]]: - """ - Extract method information from an AST class node. - - Parameters - ---------- - class_node : ast.ClassDef - The AST node representing a class. - - Returns - ------- - List[Dict[str, Any]] - List of dictionaries containing method information. - """ - methods = [] - - for node in class_node.body: - if isinstance(node, ast.FunctionDef) and not node.name.startswith("_"): - # Extract method signature - args = [] - for arg in node.args.args[1:]: # Skip 'self' - arg_name = arg.arg - arg_type = "str" # Default type - default_value = "" - - # Check if there's a default value - defaults_offset = len(node.args.args) - len(node.args.defaults) - 1 - arg_index = node.args.args.index(arg) - 1 - if arg_index >= defaults_offset and node.args.defaults: - default_idx = arg_index - defaults_offset - if default_idx < len(node.args.defaults): - default = node.args.defaults[default_idx] - if isinstance(default, ast.Constant): - if isinstance(default.value, str): - default_value = f' = "{default.value}"' - else: - default_value = f" = {default.value}" - - args.append(f"{arg_name}: {arg_type}{default_value}") - - # Extract docstring - docstring = "" - if ( - node.body - and isinstance(node.body[0], ast.Expr) - and isinstance(node.body[0].value, ast.Constant) - and isinstance(node.body[0].value.value, str) - ): - docstring = textwrap.dedent(node.body[0].value.value) - - methods.append( - {"name": node.name, "args": args, "docstring": docstring.strip()} - ) - - return methods - - -def generate_proxy_method(method_info: dict[str, Any]) -> str: - """ - Generate a proxy stub method from method information. - - Parameters - ---------- - method_info : Dict[str, Any] - Dictionary containing method information. - - Returns - ------- - str - Generated proxy stub method as a string. - """ - method_name = method_info["name"] - args = method_info["args"] - docstring = method_info["docstring"] - - # Convert method signature - args_str = ", ".join(args) if args else "" - - # Format the docstring with proper indentation - if docstring: - # Split docstring into lines and add proper indentation - docstring_lines = docstring.split("\n") - formatted_docstring = ' """' + docstring_lines[0] - for line in docstring_lines[1:]: - formatted_docstring += "\n " + line - formatted_docstring += '\n """' - else: - formatted_docstring = ' """Stub method."""' - - # Generate the method stub - stub = f""" @staticmethod - def {method_name}({args_str}): -{formatted_docstring} - pass""" - - return stub - - -def create_proxy_file( - config: dict[str, Any], - mol_methods: list[dict[str, Any]], - rxn_methods: list[dict[str, Any]], -): - """ - Create a separate proxy.py file with proxy stubs. - - Parameters - ---------- - mol_methods : List[Dict[str, Any]] - List of molecular comparator methods. - rxn_methods : List[Dict[str, Any]] - List of reaction comparator methods. - """ - proxy_path = config["proxy_path"] - label = config["label"] - mol_proxy = config["mol_proxy"] - rxn_proxy = config["rxn_proxy"] - - # Generate file header - header = f'''""" -Proxy classes for {label} database operations. - -This module contains proxy classes that provide stub methods for type hinting -and autocomplete functionality. The actual implementation is delegated to -the corresponding function classes in the functions module. - -This file is auto-generated from the comparator classes. -Do not edit manually - use the update_proxy_stubs.py script instead. -""" - -''' - - # Generate molecule proxy class - mol_proxy_methods = [] - for method_info in mol_methods: - mol_proxy_methods.append(generate_proxy_method(method_info)) - mol_proxy_methods_code = "\n\n".join(mol_proxy_methods) - - mol_proxy_class = f"""class {mol_proxy}: - \"\"\" - Proxy class for molecular operations using {label} database. - - This class provides stub methods for type hinting and autocomplete functionality. - The actual implementation is delegated to the corresponding function class. - \"\"\" - -{mol_proxy_methods_code} - """ - - # Generate reaction proxy class - rxn_proxy_methods = [] - for method_info in rxn_methods: - rxn_proxy_methods.append(generate_proxy_method(method_info)) - rxn_proxy_methods_code = "\n\n".join(rxn_proxy_methods) - - rxn_proxy_class = f"""class {rxn_proxy}: - \"\"\" - Proxy class for chemical reaction operations using {label} database. - - This class provides stub methods for type hinting and autocomplete functionality. - The actual implementation is delegated to the corresponding function class. - \"\"\" - -{rxn_proxy_methods_code} - """ - - # Write the complete proxy file - with proxy_path.open("w") as f: - f.write(header) - f.write(mol_proxy_class) - f.write("\n\n\n") - f.write(rxn_proxy_class) - f.write("\n") - - print(f"Created {proxy_path} with proxy stubs!") - - -def generate_proxy(target: str) -> None: - """Main function to create proxy stubs from comparators.""" - config = TARGETS[target] - - # Read the comparators file - comparators_path = config["comparators_path"] - - if not comparators_path.exists(): - print(f"Error: {comparators_path} not found!") - return - - with comparators_path.open() as f: - source_code = f.read() - - # Parse the AST - tree = ast.parse(source_code) - - # Extract class information - mol_methods = [] - rxn_methods = [] - - for node in tree.body: - if isinstance(node, ast.ClassDef): - if node.name == config["mol_comparator"]: - mol_methods = extract_method_info(node) - print(f"Found {len(mol_methods)} methods in {config['mol_comparator']}") - elif node.name == config["rxn_comparator"]: - rxn_methods = extract_method_info(node) - print(f"Found {len(rxn_methods)} methods in {config['rxn_comparator']}") - - if mol_methods or rxn_methods: - create_proxy_file(config, mol_methods, rxn_methods) - else: - print("No methods found to generate stubs for!") - - -def main(): - import sys - - if len(sys.argv) > 1: - targets = sys.argv[1:] - else: - targets = ["bingo"] - - for target in targets: - if target not in TARGETS: - valid_targets = ", ".join(sorted(TARGETS)) - raise SystemExit( - f"Unknown target {target!r}. Expected one of: {valid_targets}" - ) - generate_proxy(target) - - -if __name__ == "__main__": - main() diff --git a/uv.lock b/uv.lock index 45a8093..0be6281 100644 --- a/uv.lock +++ b/uv.lock @@ -484,7 +484,7 @@ name = "exceptiongroup" version = "1.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749, upload-time = "2025-05-10T17:42:51.123Z" } wheels = [ @@ -653,17 +653,17 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "colorama", marker = "python_full_version < '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version < '3.11'" }, - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, - { name = "jedi", marker = "python_full_version < '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version < '3.11'" }, - { name = "pexpect", marker = "python_full_version < '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version < '3.11'" }, - { name = "pygments", marker = "python_full_version < '3.11'" }, - { name = "stack-data", marker = "python_full_version < '3.11'" }, - { name = "traitlets", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "exceptiongroup" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/85/31/10ac88f3357fc276dc8a64e8880c82e80e7459326ae1d0a211b40abf6665/ipython-8.37.0.tar.gz", hash = "sha256:ca815841e1a41a1e6b73a0b08f3038af9b2252564d01fc405356d34033012216", size = 5606088, upload-time = "2025-05-31T16:39:09.613Z" } wheels = [ @@ -679,17 +679,17 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "colorama", marker = "python_full_version >= '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version >= '3.11'" }, - { name = "ipython-pygments-lexers", marker = "python_full_version >= '3.11'" }, - { name = "jedi", marker = "python_full_version >= '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version >= '3.11'" }, - { name = "pexpect", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version >= '3.11'" }, - { name = "pygments", marker = "python_full_version >= '3.11'" }, - { name = "stack-data", marker = "python_full_version >= '3.11'" }, - { name = "traitlets", marker = "python_full_version >= '3.11'" }, - { name = "typing-extensions", marker = "python_full_version == '3.11.*'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6e/71/a86262bf5a68bf211bcc71fe302af7e05f18a2852fdc610a854d20d085e6/ipython-9.5.0.tar.gz", hash = "sha256:129c44b941fe6d9b82d36fc7a7c18127ddb1d6f02f78f867f402e2e3adde3113", size = 4389137, upload-time = "2025-08-29T12:15:21.519Z" } wheels = [ @@ -701,7 +701,7 @@ name = "ipython-pygments-lexers" version = "1.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pygments", marker = "python_full_version >= '3.11'" }, + { name = "pygments" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } wheels = [ @@ -1139,6 +1139,7 @@ dev = [ { name = "pyyaml" }, { name = "ruff" }, { name = "sqlalchemy", extra = ["mypy"] }, + { name = "ty" }, ] docs = [ { name = "griffe-typingdoc" }, @@ -1169,6 +1170,7 @@ dev = [ { name = "pyyaml", specifier = ">=6.0.2" }, { name = "ruff", specifier = "==0.14.5" }, { name = "sqlalchemy", extras = ["mypy"], specifier = ">=2.0.43" }, + { name = "ty", specifier = ">=0.0.66" }, ] docs = [ { name = "griffe-typingdoc", specifier = ">=0.2.9" }, @@ -2368,6 +2370,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/00/c0/8f5d070730d7836adc9c9b6408dec68c6ced86b304a9b26a14df072a6e8c/traitlets-5.14.3-py3-none-any.whl", hash = "sha256:b74e89e397b1ed28cc831db7aea759ba6640cb3de13090ca145426688ff1ac4f", size = 85359, upload-time = "2024-04-19T11:11:46.763Z" }, ] +[[package]] +name = "ty" +version = "0.0.66" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/58/4f6ab2a86589e422a3cf840bcf6114c565e4c39ddf4d0b7cd328af5b52b4/ty-0.0.66.tar.gz", hash = "sha256:24bddd4479ce445b51ac015410dd2d34af1cadd62a77f5b3cb269149ed83f9b5", size = 6520402, upload-time = "2026-08-04T01:09:47.714Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/45/4d/bbc28310d6d887ef73e5800f062c4bf54caa35a1b47d70c7b03d0515ecf1/ty-0.0.66-py3-none-linux_armv6l.whl", hash = "sha256:8b46450438b54b732338e4d7a78a7d2f5e1a012a13d77d121aacaca20fb814e2", size = 12409743, upload-time = "2026-08-04T01:09:01.229Z" }, + { url = "https://files.pythonhosted.org/packages/73/4e/c3d2eb2242fa0a2ef445ca2c7009dc9118e5b3dcb8b8a8bec70d58c8e4bc/ty-0.0.66-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:8e4adbe662bc3c62b52b83d46b07f703fdc3c123bb72601606c58be5ea017ed3", size = 12078362, upload-time = "2026-08-04T01:09:04.233Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/7a4b5e45d701a8de6b714dacf6ffca91b0411baaceaa781d494037623a18/ty-0.0.66-py3-none-macosx_11_0_arm64.whl", hash = "sha256:776814351735847eb934f9a3cbea21d2278ba14aa0fc099f683da11bc2d5c90a", size = 11583289, upload-time = "2026-08-04T01:09:06.973Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/fbb1f71ee2999f981f8c4b3b139231e4bcff4ede0c3b37e858fd1334ed26/ty-0.0.66-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cca1da877f613965b954bfd22d495386e260ec767c5536c8022cca98a260ea5d", size = 12137274, upload-time = "2026-08-04T01:09:09.592Z" }, + { url = "https://files.pythonhosted.org/packages/d5/07/9e0662f6603a5ac171ae6b314396e677ead4b45695fc948efb0a4837051f/ty-0.0.66-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:aa523e777bc36c0fbf8ded5844096f46cbfc3712fe5a003351a94259b7e86cf4", size = 12207047, upload-time = "2026-08-04T01:09:12.533Z" }, + { url = "https://files.pythonhosted.org/packages/bb/cc/12e01bc2ea47fa7bf20fc6cdd3249d6a340be9be4edc52b1d77256245dd0/ty-0.0.66-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3f7993c1f95f80a4e44056e6aaf8e46e608d778db131ae5ce59262ab59358f9a", size = 12919304, upload-time = "2026-08-04T01:09:15.175Z" }, + { url = "https://files.pythonhosted.org/packages/75/88/c6c0d3a8e71c9cdb560cc5c627a4bba6c47b5eec460b2f8c449b57c6d03a/ty-0.0.66-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f9b29354bcbac9f53b6952d8f46789bd81eeb9bdd7a68df7d26e654ca7498c3c", size = 13470963, upload-time = "2026-08-04T01:09:17.849Z" }, + { url = "https://files.pythonhosted.org/packages/27/c2/2f8c18063412ad80e1b3f87afce7bd50982b4a048166607b67f80660a9fb/ty-0.0.66-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fbf4e5325f7f584d9c346946e7c415b2e3cd3b8f1119d468082a90a6afd020ce", size = 13244773, upload-time = "2026-08-04T01:09:20.59Z" }, + { url = "https://files.pythonhosted.org/packages/ed/f6/fdae2b95831116dffc055ad53a99a8f21437263651047b3ad46def4950a3/ty-0.0.66-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bd304363764bd723c22fb20b17035c345420fdf66fee856934b158ebde08a91", size = 12751343, upload-time = "2026-08-04T01:09:23.225Z" }, + { url = "https://files.pythonhosted.org/packages/14/1e/7e75f0371d11463a256dc2bee98b0df401e0fa06021e200b8b601d21949d/ty-0.0.66-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:205d8589bd957ea9718d488b731b2fbdd0d1b1cefd37c79f52c0deb7cafddfef", size = 13068057, upload-time = "2026-08-04T01:09:26.052Z" }, + { url = "https://files.pythonhosted.org/packages/b4/84/f20f24518f6f0bea936e2e668ede250b9ce0774624559931599bd1f42772/ty-0.0.66-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7304a1df54741a2343801354f41d7ad87974acb541ee3e93c26cb6a1a0b863af", size = 12082318, upload-time = "2026-08-04T01:09:28.877Z" }, + { url = "https://files.pythonhosted.org/packages/08/20/70ca0eac2427d4a58a81a3a9426b20e46fb4a5a13aefc9edc2e5172e1243/ty-0.0.66-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:cf2c062863e5da0f588b0b120fec0da2e81c0913ee4cd07b50d77aa60ffd8deb", size = 12228978, upload-time = "2026-08-04T01:09:31.905Z" }, + { url = "https://files.pythonhosted.org/packages/7c/01/5a461ab34456d788248780830aed673c9e0e796f6e9dd92d3dbf02e04d7f/ty-0.0.66-py3-none-musllinux_1_2_i686.whl", hash = "sha256:a58d32c879d86428978332adf21e85009ec269314a23d330c3483c65b57aedc7", size = 12471917, upload-time = "2026-08-04T01:09:34.418Z" }, + { url = "https://files.pythonhosted.org/packages/46/ed/f8eb5eff7c9ee644490c6d2626425935c097acc54871adf659ea70624a2c/ty-0.0.66-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:b2f810fa3516c977630d78dbe9161592b3c27029fa9bb81074366624d9b5e4b6", size = 12858086, upload-time = "2026-08-04T01:09:37.602Z" }, + { url = "https://files.pythonhosted.org/packages/02/7f/8a78361f752274a550a7f6f07f127b246ece7d7fdde31121d22074e46eab/ty-0.0.66-py3-none-win32.whl", hash = "sha256:d28c3df565a387c1c5ea359aa452a46d19163616ef71be819058a424a62f1ae1", size = 11782494, upload-time = "2026-08-04T01:09:40.136Z" }, + { url = "https://files.pythonhosted.org/packages/7d/e2/deed22b823ce309b8410d50414fd15afe9e90aee8b8ca04789ba55c21231/ty-0.0.66-py3-none-win_amd64.whl", hash = "sha256:e3a457f3312c078f24c47d0da6e4f73de34d0a77ed2de22571c066c80b2fd5e7", size = 12893338, upload-time = "2026-08-04T01:09:42.825Z" }, + { url = "https://files.pythonhosted.org/packages/f9/ce/6c828f42ef1ed39f53f57f9c0cdcdf03e23666fa7a29d799042a2c34bcb4/ty-0.0.66-py3-none-win_arm64.whl", hash = "sha256:2f62ae247b9c75674fcc060635f9f00210357da7681de59234d97b50fb9e9e94", size = 12227381, upload-time = "2026-08-04T01:09:45.365Z" }, +] + [[package]] name = "typing-extensions" version = "4.15.0" From e9e08ebc2d2d8002fcde190ef74a12280c8afc40 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Tue, 4 Aug 2026 22:21:53 +0200 Subject: [PATCH 02/13] add bingo fix --- README.md | 11 +- data/bingo/general_extra.txt | 42 +- data/bingo/general_header.txt | 5 +- dev_scripts/validate_bingo_helpers.py | 35 +- dev_scripts/validate_rdkit_helpers.py | 86 +- docs/CONTRIBUTING.md | 2 +- docs/api/rdkit/types.md | 42 +- docs/index.md | 28 +- docs/migrations/rdkit-comparator-api.md | 156 ++++ docs/rdkit-postgres-manual.md | 7 +- .../01_Getting_Started_bingo_ORM.ipynb | 6 +- .../01_Getting_Started_rdkit_ORM.ipynb | 8 +- .../02_Getting_Started_rdkit_Core.ipynb | 6 +- .../04_Similarity_Threshold_Settings.ipynb | 18 +- docs/tutorials/05_Reactions_rdkit_ORM.ipynb | 4 +- docs/tutorials/08_proxy_helpers.md | 29 +- mkdocs.yml | 4 +- src/molalchemy/bingo/__init__.py | 3 - src/molalchemy/bingo/comparators.py | 108 ++- src/molalchemy/bingo/functions/_types.py | 78 +- src/molalchemy/bingo/functions/general.py | 47 +- src/molalchemy/bingo/proxy.py | 196 ----- src/molalchemy/bingo/search.py | 45 +- src/molalchemy/helpers.py | 68 +- src/molalchemy/protocols.py | 123 +++ tests/bingo/__init__.py | 39 +- tests/bingo/test_comparators.py | 737 ++++-------------- tests/bingo/test_functions.py | 31 + tests/bingo/test_integration.py | 2 +- tests/test_helpers.py | 79 +- uv.lock | 63 -- 31 files changed, 933 insertions(+), 1175 deletions(-) create mode 100644 docs/migrations/rdkit-comparator-api.md delete mode 100644 src/molalchemy/bingo/proxy.py create mode 100644 src/molalchemy/protocols.py diff --git a/README.md b/README.md index aed20db..666e924 100644 --- a/README.md +++ b/README.md @@ -228,10 +228,13 @@ rdkit_stmt = select(MoleculeWithFormats).where( ) ``` -RDKit molecule `==` and `!=` comparisons are chemically aware: PostgreSQL -dispatches them to RDKit's `mol_eq` and `mol_ne` functions. The explicit -`.equals()` and `.not_equals()` methods use the equivalent `@=` and `@<>` -operator spellings. +Equality differs between the cartridges. Bingo `==` and `!=` use PostgreSQL +storage equality (text or binary), so chemically equivalent representations +such as `CCO` and `OCC` compare different; use `.equals()` or `.not_equals()` +for Bingo chemical matching. RDKit molecule `==` and `!=` are chemically aware +because PostgreSQL dispatches them to `mol_eq` and `mol_ne`; RDKit's explicit +methods use the equivalent `@=` and `@<>` spellings. For RDKit reactions, use +the explicit methods because native `=` is not implemented by the cartridge. Use the matching helper for the cartridge and data kind: `bingo_col`, `bingo_rxn_col`, `rdkit_col`, `rdkit_rxn_col`, or `rdkit_fp_col`. diff --git a/data/bingo/general_extra.txt b/data/bingo/general_extra.txt index 03ad6a7..202ebad 100644 --- a/data/bingo/general_extra.txt +++ b/data/bingo/general_extra.txt @@ -1,6 +1,6 @@ def mol_has_substructure( mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform substructure search on a molecule column. @@ -16,16 +16,16 @@ def mol_has_substructure( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for substructure matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(query, parameters), "bingo.sub") + return _bingo_search_values(mol, (query, parameters), "bingo.sub") def mol_has_smarts( mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform SMARTS pattern matching on a molecule column. @@ -40,16 +40,16 @@ def mol_has_smarts( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for SMARTS matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(query, parameters), "bingo.smarts") + return _bingo_search_values(mol, (query, parameters), "bingo.smarts") def mol_equals( mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact structure matching on a molecule column. @@ -65,11 +65,11 @@ def mol_equals( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for exact matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(query, parameters), "bingo.exact") + return _bingo_search_values(mol, (query, parameters), "bingo.exact") def mol_similarity( @@ -78,7 +78,7 @@ def mol_similarity( bottom: float = 0.0, top: float = 1.0, metric: TextLike = "Tanimoto", -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform similarity search on a molecule column. This should be used in WHERE clauses, as it returns a boolean expression indicating whether the similarity criteria are met. @@ -99,16 +99,16 @@ def mol_similarity( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for similarity matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(bottom, top, query, metric), "bingo.sim") + return _bingo_search_values(mol, (bottom, top, query, metric), "bingo.sim") def rxn_has_substructure( rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform substructure search on a reaction column. @@ -123,16 +123,16 @@ def rxn_has_substructure( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for reaction substructure matching that can be used in WHERE clauses. """ - return _bingo_search(rxn, tuple_(query, parameters), "bingo.rsub") + return _bingo_search_values(rxn, (query, parameters), "bingo.rsub") def rxn_has_smarts( rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform SMARTS pattern matching on a reaction column. @@ -147,16 +147,16 @@ def rxn_has_smarts( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for reaction SMARTS matching that can be used in WHERE clauses. """ - return _bingo_search(rxn, tuple_(query, parameters), "bingo.rsmarts") + return _bingo_search_values(rxn, (query, parameters), "bingo.rsmarts") def rxn_equals( rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact matching on a reaction column. @@ -171,8 +171,8 @@ def rxn_equals( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for exact reaction matching that can be used in WHERE clauses. """ - return _bingo_search(rxn, tuple_(query, parameters), "bingo.rexact") + return _bingo_search_values(rxn, (query, parameters), "bingo.rexact") diff --git a/data/bingo/general_header.txt b/data/bingo/general_header.txt index d9748b6..705e8a1 100644 --- a/data/bingo/general_header.txt +++ b/data/bingo/general_header.txt @@ -4,12 +4,11 @@ This file defines public Bingo PostgreSQL function wrappers for use with SQLAlch from typing import Any, Literal -from sqlalchemy import tuple_ from sqlalchemy import types as sqltypes -from sqlalchemy.sql.elements import BinaryExpression, ColumnElement +from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.sql.functions import GenericFunction -from molalchemy.bingo.search import _bingo_search +from molalchemy.bingo.search import _bingo_search_values from ._types import ( AnyBingoBinaryMolLike, diff --git a/dev_scripts/validate_bingo_helpers.py b/dev_scripts/validate_bingo_helpers.py index 372afdd..a4a6963 100644 --- a/dev_scripts/validate_bingo_helpers.py +++ b/dev_scripts/validate_bingo_helpers.py @@ -117,12 +117,11 @@ def main() -> None: similarity_with_column_stmt = ( select(compounds.c.name) .where( - bingo_func.mol_similarity( - compounds.c.structure, + compounds.c.structure.similar_to( compounds.c.query_structure, - 0.95, - 1.0, - "Tanimoto", + minimum=0.95, + maximum=1.0, + metric="Tanimoto", ) ) .order_by(compounds.c.id) @@ -158,14 +157,11 @@ def main() -> None: reaction_exact_stmt = select(reactions.c.name).where( reactions.c.reaction_data.equals("CCO>>CC=O") ) - exact_with_column_stmt = ( + native_equality_stmt = ( select(compounds.c.name) .where(compounds.c.structure == compounds.c.query_structure) .order_by(compounds.c.id) ) - reaction_exact_with_column_stmt = select(reactions.c.name).where( - reactions.c.reaction_data == reactions.c.query_reaction - ) molecule_not_null_stmt = ( select(compounds.c.name) .where(compounds.c.structure.__ne__(None)) @@ -203,12 +199,7 @@ def main() -> None: print(function_stmt.compile(dialect=postgresql.dialect())) print(reaction_exact_stmt.compile(dialect=postgresql.dialect())) print( - exact_with_column_stmt.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) - print( - reaction_exact_with_column_stmt.compile( + native_equality_stmt.compile( dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} ) ) @@ -225,10 +216,7 @@ def main() -> None: function_row = conn.execute(function_stmt).mappings().one() invalid_check = conn.execute(invalid_check_stmt).scalar_one() reaction_exact_rows = conn.execute(reaction_exact_stmt).scalars().all() - exact_with_column_rows = conn.execute(exact_with_column_stmt).scalars().all() - reaction_exact_with_column_rows = ( - conn.execute(reaction_exact_with_column_stmt).scalars().all() - ) + native_equality_rows = conn.execute(native_equality_stmt).scalars().all() molecule_not_null_rows = conn.execute(molecule_not_null_stmt).scalars().all() reaction_not_null_rows = conn.execute(reaction_not_null_stmt).scalars().all() reaction_function_row = conn.execute(reaction_function_stmt).mappings().one() @@ -242,10 +230,7 @@ def main() -> None: print(f"function wrappers on ethanol: {dict(function_row)}") print(f"checkmolecule(not-a-mol): {invalid_check}") print(f"reaction exact(CCO>>CC=O): {reaction_exact_rows}") - print(f"exact(structure, query_structure): {exact_with_column_rows}") - print( - f"reaction exact(reaction_data, query_reaction): {reaction_exact_with_column_rows}" - ) + print(f"native equality(structure, query_structure): {native_equality_rows}") print(f"structure IS NOT NULL via != None: {molecule_not_null_rows}") print(f"reaction IS NOT NULL via != None: {reaction_not_null_rows}") print(f"reaction function wrappers: {dict(reaction_function_row)}") @@ -267,8 +252,8 @@ def main() -> None: assert function_row["fingerprint_len"] > 0 assert "invalid character" in invalid_check assert reaction_exact_rows == ["ethanol oxidation"] - assert exact_with_column_rows == ["benzene", "ethanol"] - assert reaction_exact_with_column_rows == ["ethanol oxidation"] + # Native SQL equality is textual: "CCO" and chemically equivalent "OCC" differ. + assert native_equality_rows == ["benzene"] assert molecule_not_null_rows == ["benzene", "ethanol"] assert reaction_not_null_rows == ["ethanol oxidation"] assert reaction_function_row["check_result"] is None diff --git a/dev_scripts/validate_rdkit_helpers.py b/dev_scripts/validate_rdkit_helpers.py index f9aed32..7a8e247 100644 --- a/dev_scripts/validate_rdkit_helpers.py +++ b/dev_scripts/validate_rdkit_helpers.py @@ -119,11 +119,39 @@ def main() -> None: .order_by(molecules.c.id) ) exact_stmt = select(molecules.c.name).where(molecules.c.mol.equals("CCO")) + native_equivalent_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol == "OCC") + .order_by(molecules.c.id) + ) + explicit_equivalent_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol.equals("OCC")) + .order_by(molecules.c.id) + ) + native_not_equivalent_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol != "OCC") + .order_by(molecules.c.id) + ) + explicit_not_equivalent_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol.not_equals("OCC")) + .order_by(molecules.c.id) + ) query_fp = rdkit_func.morganbv_fp(rdkit_func.mol_from_smiles("CCO")) tanimoto_stmt = select(molecules.c.name).where( - molecules.c.morgan_fp.tanimoto(query_fp) + molecules.c.morgan_fp.tanimoto_matches(query_fp) + ) + dice_stmt = select(molecules.c.name).where( + molecules.c.morgan_fp.dice_matches(query_fp) + ) + tanimoto_knn_stmt = select(molecules.c.name).order_by( + molecules.c.morgan_fp.tanimoto_distance(query_fp), molecules.c.id + ) + dice_knn_stmt = select(molecules.c.name).order_by( + molecules.c.morgan_fp.dice_distance(query_fp), molecules.c.id ) - dice_stmt = select(molecules.c.name).where(molecules.c.morgan_fp.dice(query_fp)) function_stmt = ( select( molecules.c.name, @@ -157,6 +185,12 @@ def main() -> None: reaction_null_stmt = select(nullable_reactions.c.name).where( nullable_reactions.c.rxn.__eq__(None) ) + reaction_explicit_equals_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.equals("OCC>>O=CC") + ) + reaction_explicit_not_equals_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.not_equals("CCN>>CC=N") + ) print(str(CreateTable(molecules).compile(dialect=postgresql.dialect()))) print(str(CreateTable(nullable_molecules).compile(dialect=postgresql.dialect()))) @@ -165,11 +199,19 @@ def main() -> None: print(substructure_stmt.compile(dialect=postgresql.dialect())) print(functional_substructure_stmt.compile(dialect=postgresql.dialect())) print(exact_stmt.compile(dialect=postgresql.dialect())) + print(native_equivalent_stmt.compile(dialect=postgresql.dialect())) + print(explicit_equivalent_stmt.compile(dialect=postgresql.dialect())) + print(native_not_equivalent_stmt.compile(dialect=postgresql.dialect())) + print(explicit_not_equivalent_stmt.compile(dialect=postgresql.dialect())) print(tanimoto_stmt.compile(dialect=postgresql.dialect())) print(dice_stmt.compile(dialect=postgresql.dialect())) + print(tanimoto_knn_stmt.compile(dialect=postgresql.dialect())) + print(dice_knn_stmt.compile(dialect=postgresql.dialect())) print(function_stmt.compile(dialect=postgresql.dialect())) print(molecule_null_stmt.compile(dialect=postgresql.dialect())) print(reaction_null_stmt.compile(dialect=postgresql.dialect())) + print(reaction_explicit_equals_stmt.compile(dialect=postgresql.dialect())) + print(reaction_explicit_not_equals_stmt.compile(dialect=postgresql.dialect())) with engine.connect() as conn: version = conn.exec_driver_sql("SELECT rdkit_version()").scalar_one() @@ -178,28 +220,64 @@ def main() -> None: conn.execute(functional_substructure_stmt).scalars().all() ) exact_rows = conn.execute(exact_stmt).scalars().all() + native_equivalent_rows = conn.execute(native_equivalent_stmt).scalars().all() + explicit_equivalent_rows = ( + conn.execute(explicit_equivalent_stmt).scalars().all() + ) + native_not_equivalent_rows = ( + conn.execute(native_not_equivalent_stmt).scalars().all() + ) + explicit_not_equivalent_rows = ( + conn.execute(explicit_not_equivalent_stmt).scalars().all() + ) tanimoto_rows = conn.execute(tanimoto_stmt).scalars().all() dice_rows = conn.execute(dice_stmt).scalars().all() + tanimoto_knn_rows = conn.execute(tanimoto_knn_stmt).scalars().all() + dice_knn_rows = conn.execute(dice_knn_stmt).scalars().all() function_row = conn.execute(function_stmt).mappings().one() molecule_null_rows = conn.execute(molecule_null_stmt).scalars().all() reaction_null_rows = conn.execute(reaction_null_stmt).scalars().all() + reaction_explicit_equals_rows = ( + conn.execute(reaction_explicit_equals_stmt).scalars().all() + ) + reaction_explicit_not_equals_rows = ( + conn.execute(reaction_explicit_not_equals_stmt).scalars().all() + ) print() print(f"RDKit version: {version}") print(f"substructure(c1ccccc1): {substructure_rows}") print(f"mol_has_substructure(c1ccccc1): {functional_substructure_rows}") print(f"exact(CCO): {exact_rows}") + print(f"native molecule equality(CCO, OCC): {native_equivalent_rows}") + print(f"explicit molecule equality(CCO, OCC): {explicit_equivalent_rows}") + print(f"native molecule inequality(CCO, OCC): {native_not_equivalent_rows}") + print(f"explicit molecule inequality(CCO, OCC): {explicit_not_equivalent_rows}") print(f"tanimoto fingerprint threshold(CCO): {tanimoto_rows}") print(f"dice fingerprint threshold(CCO): {dice_rows}") + print(f"tanimoto KNN(CCO): {tanimoto_knn_rows}") + print(f"dice KNN(CCO): {dice_knn_rows}") print(f"function wrappers on ethanol: {dict(function_row)}") print(f"mol IS NULL via == None: {molecule_null_rows}") print(f"reaction IS NULL via == None: {reaction_null_rows}") + print( + "explicit reaction equality(CCO>>CC=O, OCC>>O=CC): " + f"{reaction_explicit_equals_rows}" + ) + print(f"explicit reaction inequality: {reaction_explicit_not_equals_rows}") assert substructure_rows == ["benzene", "aspirin"] assert functional_substructure_rows == ["benzene", "aspirin"] assert exact_rows == ["ethanol"] + # Unlike Bingo storage equality, both RDKit molecule spellings call mol_eq. + assert native_equivalent_rows == ["ethanol"] + assert explicit_equivalent_rows == native_equivalent_rows + assert native_not_equivalent_rows == ["benzene", "aspirin"] + assert explicit_not_equivalent_rows == native_not_equivalent_rows assert tanimoto_rows == ["ethanol"] assert dice_rows == ["ethanol"] + assert tanimoto_knn_rows[0] == "ethanol" + assert dice_knn_rows[0] == "ethanol" assert function_row["smiles"] == "CCO" assert function_row["formula"] == "C2H6O" assert 46.0 < function_row["amw"] < 47.0 @@ -216,6 +294,10 @@ def main() -> None: assert function_row["pkl_len"] > 0 assert molecule_null_rows == ["unknown"] assert reaction_null_rows == ["unknown reaction"] + # RDKit reaction equality must use the explicit operators: native `=` is an + # unimplemented operator shell in the cartridge versions covered here. + assert reaction_explicit_equals_rows == ["ethanol oxidation"] + assert reaction_explicit_not_equals_rows == ["ethanol oxidation"] if __name__ == "__main__": diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 3bebfb7..f76ae2b 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -236,7 +236,7 @@ git commit -m "test: add edge cases for similarity functions" - [ ] Tests pass: `uv run pytest` - [ ] Code is formatted: `uv run ruff format .` - [ ] Linting passes: `uv run ruff check .` -- [ ] Type checking passes: `uv run mypy src/` +- [ ] Focused type checking passes with `uv run ty check` - [ ] Documentation builds: `uv run mkdocs serve` - [ ] Changelog updated (if applicable) diff --git a/docs/api/rdkit/types.md b/docs/api/rdkit/types.md index ea6db79..4e8cc6a 100644 --- a/docs/api/rdkit/types.md +++ b/docs/api/rdkit/types.md @@ -4,6 +4,46 @@ The `molalchemy.rdkit.types` module provides SQLAlchemy UserDefinedType classes These data types enable seamless integration between Python and PostgreSQL for chemical data using RDKit's powerful cheminformatics capabilities, providing efficient storage and specialized comparison operators for molecular searching. +## Molecule equality + +Equality on an RDKit `mol` column is chemical, even when expressed with normal +SQLAlchemy operators. PostgreSQL's RDKit cartridge implements `=` with +`mol_eq` and `<>` with `mol_ne`; it does not compare the original SMILES text +or serialized molecule bytes. Consequently, equivalent representations such +as `CCO` and `OCC` compare equal. + +```python +# Compiles with PostgreSQL `=` and uses RDKit's chemical `mol_eq` function. +stmt = select(Molecule).where(Molecule.structure == "OCC") + +# Explicit cartridge spelling. `@=` is also implemented by `mol_eq`. +explicit_stmt = select(Molecule).where(Molecule.structure.equals("OCC")) +``` + +The operator pairs have the same RDKit backend semantics: + +| Python API | SQL operator | RDKit function | +| --- | --- | --- | +| `column == query` | `=` | `mol_eq` | +| `column.equals(query)` | `@=` | `mol_eq` | +| `column != query` | `<>` | `mol_ne` | +| `column.not_equals(query)` | `@<>` | `mol_ne` | + +The explicit methods remain useful for readability and for the typed helper +form, but they do not provide a stricter kind of molecular equality. Equality +follows RDKit cartridge settings: for example, stereochemistry is ignored by +default and is considered when `rdkit.do_chiral_sss` is enabled. Isotopically +different molecules compare unequal. + +Comparisons with `None` retain standard SQL behavior: `column == None` and +`column != None` compile to `IS NULL` and `IS NOT NULL`, respectively. + +This differs from Bingo columns, whose native `==` and `!=` compare the stored +text or compact binary representation. Use Bingo's explicit `.equals()` and +`.not_equals()` methods for chemical equality. Also use the explicit methods +for RDKit `reaction` columns: the cartridge implements reaction `@=` and `@<>`, +but its native reaction `=` operator is only an unimplemented catalog shell. + ## Type Classes ::: molalchemy.rdkit.types @@ -12,4 +52,4 @@ These data types enable seamless integration between Python and PostgreSQL for c show_source: false show_bases: true show_root_heading: false - members_order: source \ No newline at end of file + members_order: source diff --git a/docs/index.md b/docs/index.md index aa09e3c..37947e6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,7 +33,7 @@ molalchemy provides seamless integration between python and chemical databases, - **Input Validation**: Molecules and reactions are validated before being sent to the database - **Similarity Threshold Management**: Get/set Tanimoto and Dice thresholds with a context manager - **Alembic Integration**: Automatic handling of extensions, types, and indexes in database migrations -- **Typing Helpers**: Proxy helpers for IDE autocomplete on SQLAlchemy molecule and reaction columns +- **Typing Helpers**: Protocol helpers for precise comparator autocomplete and result types - **Easy Integration**: Drop-in replacement for standard SQLAlchemy types ## 📦 Installation @@ -93,20 +93,20 @@ molalchemy/ ├── src/molalchemy/ │ ├── types.py # Base type definitions │ ├── exceptions.py # Custom exception hierarchy -│ ├── helpers.py # Typed proxy helper functions +│ ├── helpers.py # Typed comparator helper functions +│ ├── protocols.py # Static comparator protocols │ ├── alembic_helpers.py # Alembic integration utilities │ ├── bingo/ # Bingo PostgreSQL cartridge support │ │ ├── types.py # Bingo-specific types │ │ ├── index.py # Bingo indexing │ │ ├── comparators.py # SQLAlchemy comparators -│ │ ├── proxy.py # IDE/type-checker proxy stubs │ │ ├── search.py # Shared Bingo search expression helpers │ │ └── functions/ # Bingo database functions │ └── rdkit/ # RDKit PostgreSQL cartridge support │ ├── types.py # RDKit-specific types │ ├── index.py # RDKit indexing │ ├── comparators.py # SQLAlchemy comparators -│ ├── proxy.py # IDE/type-checker proxy stubs +│ ├── search.py # Shared expression builders │ ├── settings.py # Similarity threshold management │ └── functions/ # RDKit database functions ├── tests/ # Test suite @@ -127,7 +127,8 @@ To learn how to use molalchemy, check out the tutorials in the [documentation](h - [RDKit Reactions](https://molalchemy.readthedocs.io/en/latest/tutorials/05_Reactions_rdkit_ORM/) - Storing and querying RDKit reactions - [Bingo Reactions and Binary Storage](https://molalchemy.readthedocs.io/en/latest/tutorials/06_bingo_reactions_binary/) - Bingo reaction and binary column workflows - [RDKit Descriptors and Advanced Queries](https://molalchemy.readthedocs.io/en/latest/tutorials/07_rdkit_descriptors_advanced/) - Descriptor functions and richer query patterns -- [Typed Proxy Helpers](https://molalchemy.readthedocs.io/en/latest/tutorials/08_proxy_helpers/) - IDE autocomplete helpers for chemical columns +- [Typed Comparator Helpers](https://molalchemy.readthedocs.io/en/latest/tutorials/08_proxy_helpers/) - statically typed cartridge methods +- [RDKit Comparator Migration](https://molalchemy.readthedocs.io/en/latest/migrations/rdkit-comparator-api/) - migrate legacy fingerprint and comparator calls ## 🏗️ Supported Cartridges @@ -181,6 +182,7 @@ from molalchemy.rdkit.functions import ( ) from molalchemy.helpers import ( rdkit_col, # Typed molecule-column helper for IDE autocomplete + rdkit_fp_col, # Typed fingerprint-column helper rdkit_rxn_col, # Typed reaction-column helper for IDE autocomplete ) ``` @@ -206,16 +208,16 @@ class Molecule(Base): ) ``` -### Typed Proxy Helpers +### Typed Comparator Helpers The helper functions in `molalchemy.helpers` return the original SQLAlchemy -column at runtime, but annotate it with a proxy type so IDEs and type checkers +column at runtime, but annotate it with a protocol so IDEs and type checkers can see cartridge-specific comparator methods. ```python from sqlalchemy import select -from molalchemy.helpers import bingo_col, rdkit_col +from molalchemy.helpers import bingo_col, rdkit_col, rdkit_fp_col # Bingo exact/substructure search with autocomplete-friendly column typing bingo_stmt = select(Molecule).where( @@ -228,8 +230,16 @@ rdkit_stmt = select(MoleculeWithFormats).where( ) ``` +Equality differs between the cartridges. Bingo `==` and `!=` use PostgreSQL +storage equality (text or binary), so chemically equivalent representations +such as `CCO` and `OCC` compare different; use `.equals()` or `.not_equals()` +for Bingo chemical matching. RDKit molecule `==` and `!=` are chemically aware +because PostgreSQL dispatches them to `mol_eq` and `mol_ne`; RDKit's explicit +methods use the equivalent `@=` and `@<>` spellings. For RDKit reactions, use +the explicit methods because native `=` is not implemented by the cartridge. + Use the matching helper for the cartridge and data kind: -`bingo_col`, `bingo_rxn_col`, `rdkit_col`, or `rdkit_rxn_col`. +`bingo_col`, `bingo_rxn_col`, `rdkit_col`, `rdkit_rxn_col`, or `rdkit_fp_col`. ### Configurable Return Types diff --git a/docs/migrations/rdkit-comparator-api.md b/docs/migrations/rdkit-comparator-api.md new file mode 100644 index 0000000..dbfb0db --- /dev/null +++ b/docs/migrations/rdkit-comparator-api.md @@ -0,0 +1,156 @@ +# Migrating the RDKit comparator API + +This guide covers the breaking RDKit comparator changes introduced during the +v0.x API cleanup. No database schema migration is required: `RdkitMol`, +`RdkitReaction`, `RdkitBitFingerprint`, and `RdkitSparseFingerprint` retain +their existing PostgreSQL storage types and constructors. + +The changes affect how cartridge operations are written and how SQLAlchemy +types their result expressions. + +## Fingerprint methods + +The old fingerprint methods mixed threshold predicates and K-nearest-neighbor +distances under ambiguous names. Replace them as follows: + +| Previous API | New API | Result | Typical placement | +| --- | --- | --- | --- | +| `fp.tanimoto(query)` | `fp.tanimoto_matches(query)` | Boolean | `WHERE` | +| `fp.dice(query)` | `fp.dice_matches(query)` | Boolean | `WHERE` | +| `fp.nearest_neighbors(query)` | `fp.tanimoto_distance(query)` | Float | `ORDER BY` | +| `fp.nearest_neighbors(query, "dice")` | `fp.dice_distance(query)` | Float | `ORDER BY` | + +There are no compatibility aliases. Calls using `tanimoto()`, `dice()`, or +`nearest_neighbors()` must be updated. + +### Threshold searches + +The `%` and `#` operators are Boolean predicates controlled by the RDKit +similarity threshold settings. + +```python +# Before +stmt = select(Molecule).where(Molecule.fingerprint.tanimoto(query_fp)) + +# After +stmt = select(Molecule).where( + Molecule.fingerprint.tanimoto_matches(query_fp) +) +``` + +Use `dice_matches()` for the Dice `#` predicate. + +### KNN ordering + +The `<%>` and `<#>` operators return floating-point distances. They belong in +`ORDER BY`, not `WHERE`. + +```python +# Before: the name and Boolean typing obscured that this was a distance. +stmt = select(Molecule).where( + Molecule.fingerprint.nearest_neighbors(query_fp) +) + +# After: order from nearest to farthest by Tanimoto distance. +stmt = ( + select(Molecule) + .order_by(Molecule.fingerprint.tanimoto_distance(query_fp)) + .limit(20) +) + +# Dice KNN distance +dice_stmt = select(Molecule).order_by( + Molecule.fingerprint.dice_distance(query_fp) +) +``` + +Distance expressions can also be selected and labeled: + +```python +distance = Molecule.fingerprint.tanimoto_distance(query_fp).label("distance") +stmt = select(Molecule.name, distance).order_by(distance) +``` + +## Molecule equality + +Custom Python `__eq__` and `__ne__` implementations were removed so SQLAlchemy +can handle comparisons and `None` normally. This does **not** make RDKit +molecule equality textual or binary. + +For the PostgreSQL RDKit `mol` type, the operator spellings are aliases for the +same chemical comparison functions: + +| Python API | SQL operator | RDKit function | +| --- | --- | --- | +| `column == query` | `=` | `mol_eq` | +| `column.equals(query)` | `@=` | `mol_eq` | +| `column != query` | `<>` | `mol_ne` | +| `column.not_equals(query)` | `@<>` | `mol_ne` | + +Both forms are chemically aware. Equivalent SMILES representations compare as +equal, and chirality handling follows the `rdkit.do_chiral_sss` setting. The +named methods remain available when explicit chemical intent is preferable. + +Null comparisons use standard SQL: + +```python +Molecule.structure == None # IS NULL +Molecule.structure != None # IS NOT NULL +``` + +## Expression result types + +Molecule and reaction search methods now produce `ColumnElement[bool]` backed +by SQLAlchemy `Boolean`. Fingerprint KNN methods produce +`ColumnElement[float]` backed by SQLAlchemy `Float`. + +This makes Boolean composition and distance ordering accurately reflect the +database behavior: + +```python +predicate = Molecule.structure.has_substructure("c1ccccc1") +stmt = select(Molecule).where(predicate & Molecule.structure.not_equals("c1ccccc1")) + +distance = Molecule.fingerprint.dice_distance(query_fp) +stmt = select(Molecule).order_by(distance) +``` + +## Typed column helpers + +Direct comparator calls remain the runtime API. SQLAlchemy currently exposes +dynamically installed comparator methods as `Any` to static analyzers. Use the +helpers when precise editor and `ty` information is needed: + +```python +from molalchemy.helpers import rdkit_col, rdkit_fp_col, rdkit_rxn_col + +mol_predicate = rdkit_col(Molecule.structure).equals(other_molecule) +rxn_predicate = rdkit_rxn_col(Reaction.reaction).has_substructure(query_reaction) +fp_predicate = rdkit_fp_col(Molecule.fingerprint).dice_matches(other_fingerprint) +fp_distance = rdkit_fp_col(Molecule.fingerprint).tanimoto_distance(query_fp) +``` + +`rdkit_fp_col()` is new. All three helpers return the original SQLAlchemy +column at runtime after validating its MolAlchemy type. They accept Core +columns and ORM mapped attributes, including column-to-column operands. + +The old generated `RdkitMolProxy` and `RdkitRxnProxy` exports were removed. +Their replacement protocols describe real method arguments and result types; +users normally access them through the helper functions rather than importing +the protocols directly. + +## Accepted operands + +The typed comparator interface reflects the corresponding bind processors: + +- Molecules accept SMILES strings, `rdkit.Chem.Mol`, and SQL expressions. +- Reactions accept reaction strings, + `rdkit.Chem.rdChemReactions.ChemicalReaction`, and SQL expressions. +- Fingerprints accept bytes and SQL expressions. +- Core columns and ORM `InstrumentedAttribute` objects are valid SQL operands. + +## Unchanged APIs + +Constructors, conversions, descriptors, fingerprint generators, score +functions, aggregates, settings, indexes, and database/file workflows remain +standalone functions. Existing calls to those functions do not require changes. diff --git a/docs/rdkit-postgres-manual.md b/docs/rdkit-postgres-manual.md index 961cc1b..6dbd07e 100644 --- a/docs/rdkit-postgres-manual.md +++ b/docs/rdkit-postgres-manual.md @@ -148,6 +148,11 @@ Available parameters and their default values are: If all of the above are the same and the second molecule is a substructure of the first, the molecules are declared equal, Otherwise (should not happen) the first molecule is arbitrarily defined to be less than the second. +In the PostgreSQL operator catalog, `=` and `@=` both call `mol_eq`, while +`<>` and `@<>` both call `mol_ne`. The alternate spellings therefore have the +same chemical equality semantics; they are not text or binary comparisons. +Chirality handling follows the `rdkit.do_chiral_sss` setting. + There are additional operators defined in the cartridge, but these are used for internal purposes. ### Functions @@ -290,4 +295,4 @@ This document is copyright (C) 2013-2023 by Greg Landrum and other RDKit contrib This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 License. To view a copy of this license, visit [http://creativecommons.org/licenses/by-sa/4.0/](http://creativecommons.org/licenses/by-sa/4.0/) or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. -The intent of this license is similar to that of the RDKit itself. In simple words: “Do whatever you want with it, but please give us some credit.” \ No newline at end of file +The intent of this license is similar to that of the RDKit itself. In simple words: “Do whatever you want with it, but please give us some credit.” diff --git a/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb b/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb index 2eef8d6..29e43b1 100644 --- a/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb +++ b/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb @@ -33,7 +33,7 @@ "metadata": {}, "source": [ "## Setting Up the Database\n", - "To set up a PostgreSQL database with the Bingo extension, you can use our docker images from [Docker Hub](https://hub.docker.com/repository/docker/antonsiomchen/cheminfo-db), e.g `antonsiomchen/cheminfo-db:postgres17-bingo1.34.0`\n", + "To set up a PostgreSQL database with the Bingo extension, use `ghcr.io/asiomchen/bingo-postgres:postgres17-bingo1.44.0` from [GitHub Container Registry](https://github.com/asiomchen/bingo-postgres/pkgs/container/bingo-postgres).\n", "\n", "```sh\n", "docker run -d \\\n", @@ -41,7 +41,7 @@ " -e POSTGRES_PASSWORD=example \\\n", " -e POSTGRES_DB=postgres \\\n", " -p 5432:5432 \\\n", - " antonsiomchen/cheminfo-db:postgres17-bingo1.34.0\n", + " ghcr.io/asiomchen/bingo-postgres:postgres17-bingo1.44.0\n", "```" ] }, @@ -252,7 +252,7 @@ "metadata": {}, "source": [ "### 2. Exact Molecular Structure Matching\n", - "Use `molalchemy.bingo.functions.mol_equals()` to find molecules that exactly match a given SMILES string:" + "Use `molalchemy.bingo.functions.mol_equals()` to find molecules that exactly match a given structure. Bingo's native `==` and `!=` operators compare stored text or compact binary data, not chemical identity, so equivalent SMILES such as `CCO` and `OCC` compare different. Use `mol_equals()` or the explicit `.equals()` comparator for chemical equality. This differs from RDKit molecule columns, where native `==` and explicit `.equals()` are both chemically aware:" ] }, { diff --git a/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb b/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb index eb76a92..8468831 100644 --- a/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb +++ b/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb @@ -27,7 +27,7 @@ "\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-rdkit2025.09.4`\n", + "To set up a PostgreSQL database with the RDKit extension, use `ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4` from [GitHub Container Registry](https://github.com/asiomchen/rdkit-postgres/pkgs/container/rdkit-postgres).\n", "\n", "```sh\n", "docker run -d \\\n", @@ -35,7 +35,7 @@ " -e POSTGRES_PASSWORD=postgres \\\n", " -e POSTGRES_DB=postgres \\\n", " -p 5432:5432 \\\n", - " antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.4\n", + " ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4\n", "```" ] }, @@ -283,7 +283,7 @@ "metadata": {}, "source": [ "### 2. Exact Molecular Structure Matching\n", - "Use `==` to find molecules that exactly match a given SMILES string:" + "Use `==` for chemical molecule equality. Although SQLAlchemy emits the ordinary PostgreSQL `=` operator, RDKit implements it with `mol_eq`; it compares molecular structures rather than the original SMILES text or serialized bytes. The explicit `.equals()` method emits `@=`, which is another operator for the same `mol_eq` function. Likewise, `!=` and `.not_equals()` both use `mol_ne`. This differs from Bingo, where native `==` and `!=` compare stored text or binary data and explicit `.equals()` is required for chemical matching. For RDKit reaction columns, also use explicit `.equals()` because the cartridge's native reaction `=` is not implemented. Chirality handling follows the `rdkit.do_chiral_sss` setting." ] }, { @@ -696,7 +696,7 @@ } ], "source": [ - "q_1 = select(MoleculeFP).where(MoleculeFP.fp.tanimoto(target_fp))\n", + "q_1 = select(MoleculeFP).where(MoleculeFP.fp.tanimoto_matches(target_fp))\n", "q_2 = select(MoleculeFP).where(MoleculeFP.fp.op(\"%\")(target_fp))\n", "display(session.execute(q_1).all())\n", "display(session.execute(q_2).all())" diff --git a/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb b/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb index 62863ad..3baabbe 100644 --- a/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb +++ b/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb @@ -31,7 +31,7 @@ "metadata": {}, "source": [ "## 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-rdkit2025.09.4`\n", + "To set up a PostgreSQL database with the RDKit extension, use `ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4` from [GitHub Container Registry](https://github.com/asiomchen/rdkit-postgres/pkgs/container/rdkit-postgres).\n", "\n", "```sh\n", "docker run -d \\\n", @@ -39,7 +39,7 @@ " -e POSTGRES_PASSWORD=postgres \\\n", " -e POSTGRES_DB=postgres \\\n", " -p 5432:5432 \\\n", - " antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.4\n", + " ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4\n", "```" ] }, @@ -231,7 +231,7 @@ "metadata": {}, "source": [ "### 2. Exact Molecular Structure Matching\n", - "Use `molalchemy.rdkit.functions.mol.equals()` to find molecules that exactly match a given SMILES string:" + "Use `==` for chemical molecule equality. Although SQLAlchemy emits the ordinary PostgreSQL `=` operator, RDKit implements it with `mol_eq`; it compares molecular structures rather than the original SMILES text or serialized bytes. The standalone `molalchemy.rdkit.functions.mol_equals()` function emits `@=`, which uses the same `mol_eq` function. Likewise, `!=` and `mol_not_equals()` both use `mol_ne`. Chirality handling follows the `rdkit.do_chiral_sss` setting." ] }, { diff --git a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb index 9656efb..4524436 100644 --- a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb +++ b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb @@ -21,7 +21,7 @@ "- 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-rdkit2025.09.4`\n", + "To set up a PostgreSQL database with the RDKit extension, use `ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4` from [GitHub Container Registry](https://github.com/asiomchen/rdkit-postgres/pkgs/container/rdkit-postgres).\n", "\n", "```sh\n", "docker run -d \\\n", @@ -29,7 +29,7 @@ " -e POSTGRES_PASSWORD=postgres \\\n", " -e POSTGRES_DB=postgres \\\n", " -p 5432:5432 \\\n", - " antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.4\n", + " ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4\n", "```" ] }, @@ -202,7 +202,7 @@ "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", + "Let's run a Tanimoto similarity search against Desloratadine (the active metabolite of Loratadine) using the `%` operator via `MoleculeFP.fp.tanimoto_matches()`. 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`." ] @@ -230,7 +230,7 @@ "\n", "results = session.execute(\n", " select(MoleculeFP.name, sim_score)\n", - " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .where(MoleculeFP.fp.tanimoto_matches(query_fp))\n", " .order_by(sim_score.desc())\n", ").all()\n", "\n", @@ -273,7 +273,7 @@ "\n", "results = session.execute(\n", " select(MoleculeFP.name, sim_score)\n", - " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .where(MoleculeFP.fp.tanimoto_matches(query_fp))\n", " .order_by(sim_score.desc())\n", ").all()\n", "\n", @@ -312,7 +312,7 @@ "\n", "results = session.execute(\n", " select(MoleculeFP.name, sim_score)\n", - " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .where(MoleculeFP.fp.tanimoto_matches(query_fp))\n", " .order_by(sim_score.desc())\n", ").all()\n", "\n", @@ -357,7 +357,7 @@ "\n", " results = session.execute(\n", " select(MoleculeFP.name, sim_score)\n", - " .where(MoleculeFP.fp.tanimoto(query_fp))\n", + " .where(MoleculeFP.fp.tanimoto_matches(query_fp))\n", " .order_by(sim_score.desc())\n", " ).all()\n", " print(f\"Matches: {len(results)}\")\n", @@ -403,7 +403,7 @@ "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()`." + "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_matches()`." ] }, { @@ -430,7 +430,7 @@ "\n", "results = session.execute(\n", " select(MoleculeFP.name, dice_score)\n", - " .where(MoleculeFP.fp.dice(query_fp))\n", + " .where(MoleculeFP.fp.dice_matches(query_fp))\n", " .order_by(dice_score.desc())\n", ").all()\n", "\n", diff --git a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb index 029c117..a272991 100644 --- a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb +++ b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb @@ -23,7 +23,7 @@ "- 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-rdkit2025.09.4`\n", + "To set up a PostgreSQL database with the RDKit extension, use `ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4` from [GitHub Container Registry](https://github.com/asiomchen/rdkit-postgres/pkgs/container/rdkit-postgres).\n", "\n", "```sh\n", "docker run -d \\\n", @@ -31,7 +31,7 @@ " -e POSTGRES_PASSWORD=postgres \\\n", " -e POSTGRES_DB=postgres \\\n", " -p 5432:5432 \\\n", - " antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.4\n", + " ghcr.io/asiomchen/rdkit-postgres:postgres17-rdkit2026.03.4\n", "```" ] }, diff --git a/docs/tutorials/08_proxy_helpers.md b/docs/tutorials/08_proxy_helpers.md index 8a017ec..6542cfc 100644 --- a/docs/tutorials/08_proxy_helpers.md +++ b/docs/tutorials/08_proxy_helpers.md @@ -1,11 +1,11 @@ -# Typed Proxy Helpers +# Typed Comparator Helpers MolAlchemy columns already expose chemical comparator methods at runtime. For example, a `BingoMol` column can call `.has_substructure(...)` and an `RdkitMol` column can call `.equals(...)`. IDEs and type checkers cannot infer those custom SQLAlchemy comparator -methods from the mapped column type. The proxy helpers in `molalchemy.helpers` +methods from the mapped column type. The helpers in `molalchemy.helpers` are a small typing bridge for that case. ```python @@ -18,8 +18,8 @@ stmt = select(Compound).where( At runtime, `bingo_col(Compound.structure)` returns `Compound.structure` itself. It is not a wrapper and it does not change SQL generation. Its return annotation -points the editor at a proxy class with the chemical methods, so autocomplete and -static analysis can see the API of comparator. +points the editor at a typed protocol with the chemical methods, so autocomplete +and static analysis can see the comparator API and its precise result types. ## Bingo ORM @@ -73,8 +73,8 @@ directly on the mapped attributes. from sqlalchemy import Integer, String, select from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column -from molalchemy.helpers import rdkit_col, rdkit_rxn_col -from molalchemy.rdkit.types import RdkitMol, RdkitReaction +from molalchemy.helpers import rdkit_col, rdkit_fp_col, rdkit_rxn_col +from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitMol, RdkitReaction class Base(DeclarativeBase): @@ -87,6 +87,7 @@ class Compound(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True) name: Mapped[str] = mapped_column(String(100)) structure: Mapped[str] = mapped_column(RdkitMol()) + fingerprint: Mapped[bytes] = mapped_column(RdkitBitFingerprint()) class Reaction(Base): @@ -104,8 +105,18 @@ exact_match = select(Compound).where( reaction_smarts = select(Reaction).where( rdkit_rxn_col(Reaction.reaction).has_smarts("[C:1]>>[C:1][O]") ) + +nearest = select(Compound).order_by( + rdkit_fp_col(Compound.fingerprint).tanimoto_distance(b"query fingerprint") +) ``` +For RDKit molecule columns, `.equals()` is an explicit spelling of chemical +equality. RDKit maps its `@=` operator and the normal SQL `=` operator used by +`column == query` to the same `mol_eq` function. Similarly, `.not_equals()` and +`!=` both use RDKit's `mol_ne`. The helper form is useful for static typing; it +does not change the equality semantics. + ## SQLAlchemy Core The helpers also accept Core table columns. @@ -157,10 +168,14 @@ Use the matching helper for the cartridge and data kind: | `bingo_rxn_col` | `BingoReaction`, `BingoBinaryReaction` | | `rdkit_col` | `RdkitMol` | | `rdkit_rxn_col` | `RdkitReaction` | +| `rdkit_fp_col` | `RdkitBitFingerprint`, `RdkitSparseFingerprint` | ## When To Use Them -Use proxy helpers when your like ypur autocomplete or want to use static code analysis. +Direct comparator calls remain the runtime API. Use these helpers when you want +`ty` and editor autocomplete to know the cartridge-specific methods and their +`ColumnElement[bool]` or `ColumnElement[float]` results. SQLAlchemy currently +types direct dynamic comparator lookup as `Any`. For a more explicit functional style, use the cartridge function modules: diff --git a/mkdocs.yml b/mkdocs.yml index 169f6b1..2cb6443 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -99,8 +99,10 @@ nav: - RDKit - Reactions: tutorials/05_Reactions_rdkit_ORM.ipynb - Bingo - Reactions and Binary Storage: tutorials/06_bingo_reactions_binary.ipynb - RDKit - Descriptors and Advanced Queries: tutorials/07_rdkit_descriptors_advanced.ipynb - - Typed Proxy Helpers: tutorials/08_proxy_helpers.md + - Typed Comparator Helpers: tutorials/08_proxy_helpers.md - Contributing: tutorials/contribute.md + - Migration guides: + - RDKit comparator API: migrations/rdkit-comparator-api.md - API: - molalchemy.exceptions: api/exceptions.md - molalchemy.bingo: diff --git a/src/molalchemy/bingo/__init__.py b/src/molalchemy/bingo/__init__.py index 65863d6..769fbd5 100644 --- a/src/molalchemy/bingo/__init__.py +++ b/src/molalchemy/bingo/__init__.py @@ -5,7 +5,6 @@ BingoMolIndex, BingoRxnIndex, ) -from .proxy import BingoMolProxy, BingoRxnProxy from .types import BingoBinaryMol, BingoBinaryReaction, BingoMol, BingoReaction __all__ = [ @@ -16,9 +15,7 @@ "BingoMol", "BingoMolComparator", "BingoMolIndex", - "BingoMolProxy", "BingoReaction", "BingoRxnComparator", "BingoRxnIndex", - "BingoRxnProxy", ] diff --git a/src/molalchemy/bingo/comparators.py b/src/molalchemy/bingo/comparators.py index dd38dc7..338f0c2 100644 --- a/src/molalchemy/bingo/comparators.py +++ b/src/molalchemy/bingo/comparators.py @@ -1,17 +1,23 @@ """Bingo SQLAlchemy comparators for chemical structure searching.""" -from typing import Any - -from sqlalchemy import ColumnElement, tuple_ +from sqlalchemy import ColumnElement from sqlalchemy.types import UserDefinedType -from molalchemy.bingo.search import _bingo_search as _build_bingo_search +from molalchemy.bingo.search import _bingo_search_values +from molalchemy.protocols import ( + BingoOperand, + BingoParameters, + BingoSimilarityBound, +) def _bingo_search( - column: ColumnElement[Any], query: Any, parameters: Any, search_type: str + column: ColumnElement[object], + query: BingoOperand, + parameters: BingoParameters, + search_type: str, ) -> ColumnElement[bool]: - return _build_bingo_search(column, tuple_(query, parameters), search_type) + return _bingo_search_values(column, (query, parameters), search_type) class BingoMolComparator(UserDefinedType.Comparator): @@ -22,30 +28,9 @@ class BingoMolComparator(UserDefinedType.Comparator): substructure matching, SMARTS pattern matching, and exact structure matching. """ - def __eq__(self, other: Any) -> ColumnElement[bool]: - if other is None: - return super().__eq__(other) - if isinstance(other, ColumnElement) and not getattr( - other, "is_clause_element", False - ): - return super().__eq__(other) - return self.equals(other) - - def __ne__(self, other: Any) -> ColumnElement[bool]: - if other is None: - return super().__ne__(other) - if isinstance(other, ColumnElement) and not getattr( - other, "is_clause_element", False - ): - return super().__ne__(other) - if ( - isinstance(other, ColumnElement) - and getattr(other, "table", None) is not None - ): - return super().__ne__(other) - return self.not_equals(other) - - def has_substructure(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def has_substructure( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the molecular structure contains a given substructure. @@ -67,7 +52,9 @@ def has_substructure(self, query: Any, parameters: Any = "") -> ColumnElement[bo """ return _bingo_search(self.expr, query, parameters, "bingo.sub") - def has_smarts(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def has_smarts( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the molecular structure matches a SMARTS pattern. @@ -89,7 +76,9 @@ def has_smarts(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: """ return _bingo_search(self.expr, query, parameters, "bingo.smarts") - def equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the molecular structure exactly matches the given structure. @@ -111,7 +100,9 @@ def equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: """ return _bingo_search(self.expr, query, parameters, "bingo.exact") - def not_equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def not_equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the molecular structure does not exactly match the given structure. @@ -129,6 +120,18 @@ def not_equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: """ return ~self.equals(query, parameters) + def similar_to( + self, + query: BingoOperand, + minimum: BingoSimilarityBound = 0.0, + maximum: BingoSimilarityBound = 1.0, + metric: BingoParameters = "Tanimoto", + ) -> ColumnElement[bool]: + """Check whether similarity to `query` is within the requested range.""" + return _bingo_search_values( + self.expr, (minimum, maximum, query, metric), "bingo.sim" + ) + class BingoRxnComparator(UserDefinedType.Comparator): """ @@ -138,30 +141,9 @@ class BingoRxnComparator(UserDefinedType.Comparator): reaction substructure matching, SMARTS pattern matching, and exact reaction matching. """ - def __eq__(self, other: Any) -> ColumnElement[bool]: - if other is None: - return super().__eq__(other) - if isinstance(other, ColumnElement) and not getattr( - other, "is_clause_element", False - ): - return super().__eq__(other) - return self.equals(other) - - def __ne__(self, other: Any) -> ColumnElement[bool]: - if other is None: - return super().__ne__(other) - if isinstance(other, ColumnElement) and not getattr( - other, "is_clause_element", False - ): - return super().__ne__(other) - if ( - isinstance(other, ColumnElement) - and getattr(other, "table", None) is not None - ): - return super().__ne__(other) - return self.not_equals(other) - - def has_substructure(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def has_substructure( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the reaction contains a given substructure pattern. @@ -183,7 +165,9 @@ def has_substructure(self, query: Any, parameters: Any = "") -> ColumnElement[bo """ return _bingo_search(self.expr, query, parameters, "bingo.rsub") - def has_smarts(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def has_smarts( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the reaction matches a SMARTS pattern. @@ -205,7 +189,9 @@ def has_smarts(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: """ return _bingo_search(self.expr, query, parameters, "bingo.rsmarts") - def equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the reaction exactly matches the given reaction. @@ -227,7 +213,9 @@ def equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: """ return _bingo_search(self.expr, query, parameters, "bingo.rexact") - def not_equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + def not_equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: """ Check if the reaction does not exactly match the given reaction. diff --git a/src/molalchemy/bingo/functions/_types.py b/src/molalchemy/bingo/functions/_types.py index be1af44..e816658 100644 --- a/src/molalchemy/bingo/functions/_types.py +++ b/src/molalchemy/bingo/functions/_types.py @@ -1,68 +1,26 @@ -from __future__ import annotations +"""Operand aliases for Bingo cartridge function wrappers.""" -from typing import ( - TypeAlias, # pragma: no cover - TypeVar, -) - -from sqlalchemy import Column, Function -from sqlalchemy.orm import InstrumentedAttribute, Mapped - -from molalchemy.bingo.types import ( - BingoBinaryMol, - BingoBinaryReaction, - BingoMol, - BingoReaction, -) - -""" -Type aliases for Bingo-SQLAlchemy integration. -These aliases make it easier to annotate columns, mapped attributes, -and SQL functions that return Bingo objects (Mol, BinaryMol, Reaction, BinaryReaction) -while still supporting literal values (e.g. SMILES strings) and raw bytes. -""" +from typing import Any, TypeAlias, TypeVar +from sqlalchemy.orm import InstrumentedAttribute +from sqlalchemy.sql.elements import ColumnElement T = TypeVar("T") -SQLAlchemyCoercible: TypeAlias = ( - InstrumentedAttribute[T] | Column[T] | Mapped[T] | Function[T] -) - +SQLAlchemyCoercible: TypeAlias = ColumnElement[T] | InstrumentedAttribute[T] +SqlExpression: TypeAlias = ColumnElement[Any] | InstrumentedAttribute[Any] LiteralStrBytes: TypeAlias = str | bytes - -# Text-like types for string/bytes inputs -TextLike: TypeAlias = ( - str | bytes | Column[str] | Mapped[str] | InstrumentedAttribute[str] -) - -# ---------------------------------------------------------------------- -# Bingo specific type aliases -# ---------------------------------------------------------------------- -BingoMolCoercible: TypeAlias = BingoMol | str -AnyBingoMolLike: TypeAlias = SQLAlchemyCoercible[BingoMolCoercible] | BingoMolCoercible - -BingoBinaryMolCoercible: TypeAlias = BingoBinaryMol | bytes -AnyBingoBinaryMolLike: TypeAlias = ( - SQLAlchemyCoercible[BingoBinaryMolCoercible] | BingoBinaryMolCoercible -) - -BingoReactionCoercible: TypeAlias = BingoReaction | LiteralStrBytes -AnyBingoReactionLike: TypeAlias = ( - SQLAlchemyCoercible[BingoReactionCoercible] | BingoReactionCoercible -) - -BingoBinaryReactionCoercible: TypeAlias = BingoBinaryReaction | LiteralStrBytes -AnyBingoBinaryReactionLike: TypeAlias = ( - SQLAlchemyCoercible[BingoBinaryReactionCoercible] | BingoBinaryReactionCoercible -) - -# ---------------------------------------------------------------------- -# Combined aliases - convenience for functions accepting text or binary -# ---------------------------------------------------------------------- -AnyBingoMolLikeCombined: TypeAlias = AnyBingoMolLike | AnyBingoBinaryMolLike -AnyBingoReactionLikeCombined: TypeAlias = ( - AnyBingoReactionLike | AnyBingoBinaryReactionLike -) +TextLike: TypeAlias = str | bytes | SqlExpression + +BingoMolCoercible: TypeAlias = str +AnyBingoMolLike: TypeAlias = str | SqlExpression +BingoBinaryMolCoercible: TypeAlias = str | bytes +AnyBingoBinaryMolLike: TypeAlias = str | bytes | SqlExpression +BingoReactionCoercible: TypeAlias = str +AnyBingoReactionLike: TypeAlias = str | SqlExpression +BingoBinaryReactionCoercible: TypeAlias = str | bytes +AnyBingoBinaryReactionLike: TypeAlias = str | bytes | SqlExpression +AnyBingoMolLikeCombined: TypeAlias = str | bytes | SqlExpression +AnyBingoReactionLikeCombined: TypeAlias = str | bytes | SqlExpression __all__ = [ "AnyBingoBinaryMolLike", diff --git a/src/molalchemy/bingo/functions/general.py b/src/molalchemy/bingo/functions/general.py index 5e2e54d..d76f793 100644 --- a/src/molalchemy/bingo/functions/general.py +++ b/src/molalchemy/bingo/functions/general.py @@ -4,12 +4,11 @@ from typing import Any, Literal -from sqlalchemy import tuple_ from sqlalchemy import types as sqltypes -from sqlalchemy.sql.elements import BinaryExpression, ColumnElement +from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.sql.functions import GenericFunction -from molalchemy.bingo.search import _bingo_search +from molalchemy.bingo.search import _bingo_search_values from ._types import ( AnyBingoBinaryMolLike, @@ -28,7 +27,7 @@ def mol_has_substructure( mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform substructure search on a molecule column. @@ -44,16 +43,16 @@ def mol_has_substructure( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for substructure matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(query, parameters), "bingo.sub") + return _bingo_search_values(mol, (query, parameters), "bingo.sub") def mol_has_smarts( mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform SMARTS pattern matching on a molecule column. @@ -68,16 +67,16 @@ def mol_has_smarts( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for SMARTS matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(query, parameters), "bingo.smarts") + return _bingo_search_values(mol, (query, parameters), "bingo.smarts") def mol_equals( mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact structure matching on a molecule column. @@ -93,11 +92,11 @@ def mol_equals( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for exact matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(query, parameters), "bingo.exact") + return _bingo_search_values(mol, (query, parameters), "bingo.exact") def mol_similarity( @@ -106,7 +105,7 @@ def mol_similarity( bottom: float = 0.0, top: float = 1.0, metric: TextLike = "Tanimoto", -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform similarity search on a molecule column. This should be used in WHERE clauses, as it returns a boolean expression indicating whether the similarity criteria are met. @@ -127,16 +126,16 @@ def mol_similarity( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for similarity matching that can be used in WHERE clauses. """ - return _bingo_search(mol, tuple_(bottom, top, query, metric), "bingo.sim") + return _bingo_search_values(mol, (bottom, top, query, metric), "bingo.sim") def rxn_has_substructure( rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform substructure search on a reaction column. @@ -151,16 +150,16 @@ def rxn_has_substructure( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for reaction substructure matching that can be used in WHERE clauses. """ - return _bingo_search(rxn, tuple_(query, parameters), "bingo.rsub") + return _bingo_search_values(rxn, (query, parameters), "bingo.rsub") def rxn_has_smarts( rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform SMARTS pattern matching on a reaction column. @@ -175,16 +174,16 @@ def rxn_has_smarts( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for reaction SMARTS matching that can be used in WHERE clauses. """ - return _bingo_search(rxn, tuple_(query, parameters), "bingo.rsmarts") + return _bingo_search_values(rxn, (query, parameters), "bingo.rsmarts") def rxn_equals( rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact matching on a reaction column. @@ -199,11 +198,11 @@ def rxn_equals( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy expression for exact reaction matching that can be used in WHERE clauses. """ - return _bingo_search(rxn, tuple_(query, parameters), "bingo.rexact") + return _bingo_search_values(rxn, (query, parameters), "bingo.rexact") class aam(GenericFunction): diff --git a/src/molalchemy/bingo/proxy.py b/src/molalchemy/bingo/proxy.py deleted file mode 100644 index 7496c91..0000000 --- a/src/molalchemy/bingo/proxy.py +++ /dev/null @@ -1,196 +0,0 @@ -""" -Proxy classes for Bingo database operations. - -This module contains proxy classes that provide stub methods for type hinting -and autocomplete functionality. The actual implementation is delegated to -the corresponding function classes in the functions module. - -This file is auto-generated from the comparator classes. -Do not edit manually - use the update_proxy_stubs.py script instead. -""" - - -class BingoMolProxy: - """ - Proxy class for molecular operations using Bingo database. - - This class provides stub methods for type hinting and autocomplete functionality. - The actual implementation is delegated to the corresponding function class. - """ - - @staticmethod - def has_substructure(query: str, parameters: str = ""): - """Check if the molecular structure contains a given substructure. - - Parameters - ---------- - query : Any - The substructure query as a SMILES or MOL string. - parameters : Any, optional - Additional parameters for the substructure search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the substructure match operation. - - Examples - -------- - >>> mol_column.has_substructure('c1ccccc1') # benzene ring - """ - pass - - @staticmethod - def has_smarts(query: str, parameters: str = ""): - """Check if the molecular structure matches a SMARTS pattern. - - Parameters - ---------- - query : Any - The SMARTS pattern string for pattern matching. - parameters : Any, optional - Additional parameters for the SMARTS search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the SMARTS pattern match operation. - - Examples - -------- - >>> mol_column.has_smarts('[#6]1:[#6]:[#6]:[#6]:[#6]:[#6]:1') # aromatic ring - """ - pass - - @staticmethod - def equals(query: str, parameters: str = ""): - """Check if the molecular structure exactly matches the given structure. - - Parameters - ---------- - query : Any - The molecular structure query as a SMILES or MOL string. - parameters : Any, optional - Additional parameters for the exact match search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the exact structure match operation. - - Examples - -------- - >>> mol_column.equals('CCO') # ethanol exact match - """ - pass - - @staticmethod - def not_equals(query: str, parameters: str = ""): - """Check if the molecular structure does not exactly match the given structure. - - Parameters - ---------- - query : Any - The molecular structure query as a SMILES or MOL string. - parameters : Any, optional - Additional parameters for the exact match search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the negated exact structure match operation. - """ - pass - - -class BingoRxnProxy: - """ - Proxy class for chemical reaction operations using Bingo database. - - This class provides stub methods for type hinting and autocomplete functionality. - The actual implementation is delegated to the corresponding function class. - """ - - @staticmethod - def has_substructure(query: str, parameters: str = ""): - """Check if the reaction contains a given substructure pattern. - - Parameters - ---------- - query : Any - The reaction substructure query as a reaction SMILES or RXN string. - parameters : Any, optional - Additional parameters for the reaction substructure search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the reaction substructure match operation. - - Examples - -------- - >>> rxn_column.has_substructure('c1ccccc1>>c1ccc(O)cc1') # phenol formation - """ - pass - - @staticmethod - def has_smarts(query: str, parameters: str = ""): - """Check if the reaction matches a SMARTS pattern. - - Parameters - ---------- - query : Any - The reaction SMARTS pattern string for pattern matching. - parameters : Any, optional - Additional parameters for the reaction SMARTS search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the reaction SMARTS pattern match operation. - - Examples - -------- - >>> rxn_column.has_smarts('[C:1]>>[C:1][O]') # C-O bond formation - """ - pass - - @staticmethod - def equals(query: str, parameters: str = ""): - """Check if the reaction exactly matches the given reaction. - - Parameters - ---------- - query : Any - The reaction query as a reaction SMILES or RXN string. - parameters : Any, optional - Additional parameters for the exact reaction match search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the exact reaction match operation. - - Examples - -------- - >>> rxn_column.has_equals('CCO>>CC=O') # ethanol to acetaldehyde exact match - """ - pass - - @staticmethod - def not_equals(query: str, parameters: str = ""): - """Check if the reaction does not exactly match the given reaction. - - Parameters - ---------- - query : Any - The reaction query as a reaction SMILES or RXN string. - parameters : Any, optional - Additional parameters for the exact reaction match search, by default "". - - Returns - ------- - ColumnElement[bool] - A SQLAlchemy expression for the negated exact reaction match operation. - """ - pass diff --git a/src/molalchemy/bingo/search.py b/src/molalchemy/bingo/search.py index b1bfece..b08ab6f 100644 --- a/src/molalchemy/bingo/search.py +++ b/src/molalchemy/bingo/search.py @@ -2,26 +2,10 @@ from typing import Any +from sqlalchemy import tuple_ from sqlalchemy import types as sqltypes from sqlalchemy.sql import operators -from sqlalchemy.sql.elements import BinaryExpression, ColumnElement - - -class _BingoExactSearchExpression(BinaryExpression[bool]): - """Bingo exact-search expression with SQLAlchemy-style identity truth checks. - - Bingo columns overload ``==`` to mean chemical exact search, but Python - container operations such as ``column in index.expressions`` also call - ``==`` and then require a real boolean result. Returning the original - operand comparison here keeps those Python-side checks working while the - expression still compiles to the Bingo ``@`` exact-search SQL operator. - """ - - inherit_cache = True - - def __bool__(self) -> bool: - # Match SQLAlchemy's equality-expression truthiness behavior. - return self._orig[0] == self._orig[1] +from sqlalchemy.sql.elements import ColumnElement class _BingoSearchType(sqltypes.UserDefinedType): @@ -55,11 +39,20 @@ def _bingo_search( search_type: str, ) -> ColumnElement[bool]: query = query_tuple.cast(_BingoSearchType(search_type)) - if search_type in ("bingo.exact", "bingo.rexact"): - return _BingoExactSearchExpression( - column, - query, - operators.custom_op("@", is_comparison=True), - type_=sqltypes.Boolean(), - ) - return column.op("@")(query) + return column.operate( + operators.custom_op( + "@", precedence=5, is_comparison=True, return_type=sqltypes.Boolean() + ), + query, + ) + + +def _bingo_search_values( + column: ColumnElement[Any], values: tuple[object, ...], search_type: str +) -> ColumnElement[bool]: + """Build a Bingo predicate using SQLAlchemy's expression coercion. + + ``tuple_`` binds scalar values while honoring ``__clause_element__`` on ORM + attributes and other SQL expression objects. + """ + return _bingo_search(column, tuple_(*values), search_type) diff --git a/src/molalchemy/helpers.py b/src/molalchemy/helpers.py index d24decd..4202e72 100644 --- a/src/molalchemy/helpers.py +++ b/src/molalchemy/helpers.py @@ -1,4 +1,6 @@ -"""Helper functions for typed molecule and reaction column autocomplete.""" +"""Runtime-validated helpers for statically typed cartridge columns.""" + +from typing import Any, cast from sqlalchemy import Column from sqlalchemy.orm.attributes import InstrumentedAttribute @@ -9,18 +11,26 @@ BingoMol, BingoReaction, ) -from molalchemy.bingo.proxy import BingoMolProxy, BingoRxnProxy from molalchemy.rdkit import RdkitMol, RdkitReaction -from molalchemy.rdkit.proxy import RdkitMolProxy, RdkitRxnProxy +from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitSparseFingerprint + +from .protocols import ( + BingoMolColumn, + BingoReactionColumn, + RdkitFingerprintColumn, + RdkitMolColumn, + RdkitReactionColumn, +) +ChemicalColumn = Column[Any] | InstrumentedAttribute[Any] -def bingo_col(column: Column | InstrumentedAttribute) -> BingoMolProxy: + +def bingo_col(column: ChemicalColumn) -> BingoMolColumn: """ - Create a Bingo molecule proxy from a SQLAlchemy column. It is a way to trick IDE into showing - syntax highlighting and autocompletion for the molecular column operations provided by custom Comparator. + Validate a Bingo molecule column and expose its typed comparator protocol. This function validates that the input column has a compatible Bingo molecule type - and returns a proxy object that can be used for molecule-specific operations. + and returns the same object with molecule-specific static typing. Parameters ---------- @@ -30,8 +40,8 @@ def bingo_col(column: Column | InstrumentedAttribute) -> BingoMolProxy: Returns ------- - molalchemy.bingo.proxy.BingoMolProxy - A proxy object for performing Bingo molecule operations on the column. + molalchemy.protocols.BingoMolColumn + The original column typed with Bingo molecule operations. Raises ------ @@ -42,7 +52,7 @@ def bingo_col(column: Column | InstrumentedAttribute) -> BingoMolProxy: """ if isinstance(column, InstrumentedAttribute | Column): if isinstance(column.type, BingoMol) or isinstance(column.type, BingoBinaryMol): - return column # type: ignore + return cast(BingoMolColumn, column) else: raise TypeError("Column is not of type BingoMol or BingoBinaryMol") else: @@ -51,13 +61,12 @@ def bingo_col(column: Column | InstrumentedAttribute) -> BingoMolProxy: ) -def bingo_rxn_col(column: Column | InstrumentedAttribute) -> BingoRxnProxy: +def bingo_rxn_col(column: ChemicalColumn) -> BingoReactionColumn: """ - Create a Bingo reaction proxy from a SQLAlchemy column. It is a way to trick IDE into showing - syntax highlighting and autocompletion for the reaction column operations provided by custom Comparator. + Validate a Bingo reaction column and expose its typed comparator protocol. This function validates that the input column has a compatible Bingo reaction type - and returns a proxy object that can be used for reaction-specific operations. + and returns the same object with reaction-specific static typing. Parameters ---------- @@ -67,8 +76,8 @@ def bingo_rxn_col(column: Column | InstrumentedAttribute) -> BingoRxnProxy: Returns ------- - molalchemy.bingo.proxy.BingoRxnProxy - A proxy object for performing Bingo reaction operations on the column. + molalchemy.protocols.BingoReactionColumn + The original column typed with Bingo reaction operations. Raises ------ @@ -81,7 +90,7 @@ def bingo_rxn_col(column: Column | InstrumentedAttribute) -> BingoRxnProxy: if isinstance(column.type, BingoReaction) or isinstance( column.type, BingoBinaryReaction ): - return column # type: ignore + return cast(BingoReactionColumn, column) else: raise TypeError( "Column is not of type BingoReaction or BingoBinaryReaction" @@ -92,16 +101,16 @@ def bingo_rxn_col(column: Column | InstrumentedAttribute) -> BingoRxnProxy: ) -def rdkit_col(column: Column | InstrumentedAttribute) -> RdkitMolProxy: +def rdkit_col(column: ChemicalColumn) -> RdkitMolColumn: """ - Create an RDKit molecule proxy from a SQLAlchemy column. + Validate an RDKit molecule column and expose its typed comparator protocol. This validates that the input column uses `molalchemy.rdkit.types.RdkitMol` and returns the original column typed for IDE autocomplete. """ if isinstance(column, InstrumentedAttribute | Column): if isinstance(column.type, RdkitMol): - return column # type: ignore + return cast(RdkitMolColumn, column) else: raise TypeError("Column is not of type RdkitMol") else: @@ -110,19 +119,32 @@ def rdkit_col(column: Column | InstrumentedAttribute) -> RdkitMolProxy: ) -def rdkit_rxn_col(column: Column | InstrumentedAttribute) -> RdkitRxnProxy: +def rdkit_rxn_col(column: ChemicalColumn) -> RdkitReactionColumn: """ - Create an RDKit reaction proxy from a SQLAlchemy column. + Validate an RDKit reaction column and expose its typed comparator protocol. This validates that the input column uses `molalchemy.rdkit.types.RdkitReaction` and returns the original column typed for IDE autocomplete. """ if isinstance(column, InstrumentedAttribute | Column): if isinstance(column.type, RdkitReaction): - return column # type: ignore + return cast(RdkitReactionColumn, column) else: raise TypeError("Column is not of type RdkitReaction") else: raise TypeError( f"Input is not a SQLAlchemy InstrumentedAttribute or Column, got {type(column)}" ) + + +def rdkit_fp_col(column: ChemicalColumn) -> RdkitFingerprintColumn: + """Validate and statically expose an RDKit fingerprint column.""" + if isinstance(column, InstrumentedAttribute | Column): + if isinstance(column.type, RdkitBitFingerprint | RdkitSparseFingerprint): + return cast(RdkitFingerprintColumn, column) + raise TypeError( + "Column is not of type RdkitBitFingerprint or RdkitSparseFingerprint" + ) + raise TypeError( + f"Input is not a SQLAlchemy Column or InstrumentedAttribute, got {type(column)}" + ) diff --git a/src/molalchemy/protocols.py b/src/molalchemy/protocols.py new file mode 100644 index 0000000..3edcdb1 --- /dev/null +++ b/src/molalchemy/protocols.py @@ -0,0 +1,123 @@ +"""Typed interfaces for cartridge-aware SQLAlchemy columns. + +SQLAlchemy exposes custom comparator methods dynamically at runtime. These +protocols provide a precise static view for the validation helpers in +``molalchemy.helpers``. +""" + +from typing import Any, Protocol, TypeAlias + +from rdkit import Chem +from rdkit.Chem.rdChemReactions import ChemicalReaction +from sqlalchemy.orm import InstrumentedAttribute +from sqlalchemy.sql.elements import ColumnElement + +SqlOperand: TypeAlias = ColumnElement[Any] | InstrumentedAttribute[Any] +RdkitMolOperand: TypeAlias = str | Chem.Mol | SqlOperand +RdkitReactionOperand: TypeAlias = str | ChemicalReaction | SqlOperand +RdkitFingerprintOperand: TypeAlias = bytes | SqlOperand +BingoOperand: TypeAlias = str | bytes | SqlOperand +BingoParameters: TypeAlias = str | SqlOperand +BingoSimilarityBound: TypeAlias = float | SqlOperand + + +class BingoMolColumn(Protocol): + def has_substructure( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def has_smarts( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def not_equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def similar_to( + self, + query: BingoOperand, + minimum: BingoSimilarityBound = 0.0, + maximum: BingoSimilarityBound = 1.0, + metric: BingoParameters = "Tanimoto", + ) -> ColumnElement[bool]: ... + + +class BingoReactionColumn(Protocol): + def has_substructure( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def has_smarts( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + def not_equals( + self, query: BingoOperand, parameters: BingoParameters = "" + ) -> ColumnElement[bool]: ... + + +class RdkitMolColumn(Protocol): + def has_substructure(self, query: RdkitMolOperand) -> ColumnElement[bool]: ... + def has_smarts(self, query: str | SqlOperand) -> ColumnElement[bool]: ... + def is_substructure_of(self, query: RdkitMolOperand) -> ColumnElement[bool]: ... + def equals(self, query: RdkitMolOperand) -> ColumnElement[bool]: ... + def not_equals(self, query: RdkitMolOperand) -> ColumnElement[bool]: ... + def has_query_substructure(self, query: SqlOperand) -> ColumnElement[bool]: ... + def is_query_substructure_of(self, query: SqlOperand) -> ColumnElement[bool]: ... + + +class RdkitReactionColumn(Protocol): + def has_substructure(self, query: RdkitReactionOperand) -> ColumnElement[bool]: ... + + def is_substructure_of( + self, query: RdkitReactionOperand + ) -> ColumnElement[bool]: ... + + def equals(self, query: RdkitReactionOperand) -> ColumnElement[bool]: ... + def not_equals(self, query: RdkitReactionOperand) -> ColumnElement[bool]: ... + def has_smarts(self, query: str | SqlOperand) -> ColumnElement[bool]: ... + def has_substructure_fp( + self, query: RdkitReactionOperand + ) -> ColumnElement[bool]: ... + + def is_substructure_fp_of( + self, query: RdkitReactionOperand + ) -> ColumnElement[bool]: ... + + +class RdkitFingerprintColumn(Protocol): + def tanimoto_matches( + self, query: RdkitFingerprintOperand + ) -> ColumnElement[bool]: ... + + def dice_matches(self, query: RdkitFingerprintOperand) -> ColumnElement[bool]: ... + def tanimoto_distance( + self, query: RdkitFingerprintOperand + ) -> ColumnElement[float]: ... + + def dice_distance(self, query: RdkitFingerprintOperand) -> ColumnElement[float]: ... + + +__all__ = [ + "BingoMolColumn", + "BingoOperand", + "BingoParameters", + "BingoReactionColumn", + "BingoSimilarityBound", + "RdkitFingerprintColumn", + "RdkitFingerprintOperand", + "RdkitMolColumn", + "RdkitMolOperand", + "RdkitReactionColumn", + "RdkitReactionOperand", + "SqlOperand", +] diff --git a/tests/bingo/__init__.py b/tests/bingo/__init__.py index dad511b..e696ce1 100644 --- a/tests/bingo/__init__.py +++ b/tests/bingo/__init__.py @@ -1,38 +1 @@ -"""Bingo query structure tests.""" - -from .test_comparators import ( - TestBingoComparatorInQueries, - TestBingoMolComparator, - TestBingoMolComparatorWithBinaryType, -) -from .test_index import ( - TestBingoBinaryMolIndex, - TestBingoIndexCreation, - TestBingoIndexes, - TestBingoMolIndex, -) -from .test_integration import ( - TestBingoORMIntegration, - TestBingoQueryIntegration, - TestBingoQueryVariations, -) -from .test_types import TestBingoBinaryMol, TestBingoMol, TestTypesIntegration - -__all__ = [ - "TestBingoBinaryMol", - "TestBingoBinaryMolIndex", - "TestBingoComparatorInQueries", - "TestBingoFunc", - "TestBingoFuncIntegration", - "TestBingoFuncWithORM", - "TestBingoIndexCreation", - "TestBingoIndexes", - "TestBingoMol", - "TestBingoMolComparator", - "TestBingoMolComparatorWithBinaryType", - "TestBingoMolIndex", - "TestBingoORMIntegration", - "TestBingoQueryIntegration", - "TestBingoQueryVariations", - "TestTypesIntegration", -] +"""Bingo test package.""" diff --git a/tests/bingo/test_comparators.py b/tests/bingo/test_comparators.py index f5edd50..315413f 100644 --- a/tests/bingo/test_comparators.py +++ b/tests/bingo/test_comparators.py @@ -1,9 +1,21 @@ -"""Tests for bingo comparators.""" - -from sqlalchemy import Column, ColumnElement, Integer, MetaData, String, Table +"""Semantic tests for Bingo comparators.""" + +import pytest +from sqlalchemy import ( + Boolean, + Column, + Integer, + MetaData, + String, + Table, + bindparam, + select, +) from sqlalchemy.dialects import postgresql -from sqlalchemy.sql import select +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from molalchemy.bingo import BingoMolComparator, BingoRxnComparator +from molalchemy.bingo import functions as bingo_func from molalchemy.bingo.types import ( BingoBinaryMol, BingoBinaryReaction, @@ -12,607 +24,166 @@ ) -class TestBingoMolComparator: - """Test BingoMolComparator methods.""" - - def setup_method(self): - """Set up test table with BingoMol column.""" - self.metadata = MetaData() - self.test_table = Table( - "test_molecules", - self.metadata, - Column("id", Integer, primary_key=True), - Column("name", String(100)), - Column("mol", BingoMol()), - Column("query_mol", String), - ) - self.mol_column = self.test_table.c.mol - - def test_has_substructure_query_generation(self): - """Test has_substructure query generation.""" - query = "c1ccccc1" # benzene - parameters = "" - - result = self.mol_column.has_substructure(query, parameters) - - # Check that the result is a proper SQLAlchemy expression - assert hasattr(result, "left") - assert hasattr(result, "right") - assert hasattr(result, "operator") - - # Check that we can compile it to SQL (basic check) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - assert "@" in compiled - assert "bingo.sub" in compiled - assert query in compiled - - def test_has_substructure_with_parameters(self): - """Test has_substructure query with parameters.""" - query = "c1ccccc1" - parameters = "max=5" - - result = self.mol_column.has_substructure(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert query in compiled - assert parameters in compiled - assert "bingo.sub" in compiled - - def test_has_smarts_query_generation(self): - """Test SMARTS query generation.""" - query = ( - "[#6]1-[#6]-[#6]-[#6]-[#6]-[#6]-1" # benzene SMARTS (using - instead of :) - ) - parameters = "" - - result = self.mol_column.has_smarts(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.smarts" in compiled - # Check that the query appears in some form (may be escaped) - assert "[#6]1" in compiled or query in compiled - - def test_has_smarts_with_parameters(self): - """Test SMARTS query with parameters.""" - query = "[#6]1-[#6]-[#6]-[#6]-[#6]-[#6]-1" - parameters = "max=10" - - result = self.mol_column.has_smarts(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - # Check that the query appears in some form and parameters are present - assert "[#6]1" in compiled or query in compiled - assert parameters in compiled - assert "bingo.smarts" in compiled - - def test_equals_query_generation(self): - """Test exact match query generation.""" - query = "CCO" # ethanol - parameters = "" - - result = self.mol_column.equals(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.exact" in compiled - assert query in compiled - - def test_eq_operator_delegates_to_exact_match(self): - query = "CCO" - - result = self.mol_column == query - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.exact" in compiled - assert query in compiled - - def test_eq_operator_with_column_delegates_to_exact_match(self): - result = self.mol_column == self.test_table.c.query_mol - compiled = str( - result.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) - - assert "@" in compiled - assert "bingo.exact" in compiled - assert "test_molecules.query_mol" in compiled - assert "'test_molecules.query_mol'" not in compiled - - def test_eq_operator_with_none_uses_sql_null_check(self): - result = self.mol_column.__eq__(None) - compiled = str(result.compile(dialect=postgresql.dialect())) - - assert "IS NULL" in compiled - assert "bingo.exact" not in compiled - - def test_equals_with_parameters(self): - """Test exact match query with parameters.""" - query = "CCO" - parameters = "stereo=1" - - result = self.mol_column.equals(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert query in compiled - assert parameters in compiled - assert "bingo.exact" in compiled - - def test_not_equals_query_generation(self): - """Test negative exact match query generation.""" - query = "CCO" - - result = self.mol_column.not_equals(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "NOT" in compiled - assert "bingo.exact" in compiled - assert query in compiled - - def test_ne_operator_delegates_to_negative_exact_match(self): - query = "CCO" - - result = self.mol_column != query - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "NOT" in compiled - assert "bingo.exact" in compiled - assert query in compiled - - def test_ne_operator_with_none_uses_sql_not_null_check(self): - result = self.mol_column.__ne__(None) - compiled = str(result.compile(dialect=postgresql.dialect())) +def sql(expression) -> str: + return str(expression.compile(dialect=postgresql.dialect())) + + +class Base(DeclarativeBase): + pass + + +class Compound(Base): + __tablename__ = "bingo_comparator_compounds" + + id: Mapped[int] = mapped_column(primary_key=True) + mol: Mapped[str] = mapped_column(BingoMol()) + other_mol: Mapped[str] = mapped_column(BingoMol()) + query_parameters: Mapped[str] = mapped_column(String()) - assert "IS NOT NULL" in compiled - assert "bingo.exact" not in compiled - - def test_ne_operator_with_column_uses_sqlalchemy_inequality(self): - result = self.mol_column != self.test_table.c.name - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "!=" in compiled or "<>" in compiled - assert "bingo.exact" not in compiled - - def test_not_equals_with_parameters(self): - """Test negative exact match query with parameters.""" - query = "CCO" - parameters = "TAU" - - result = self.mol_column.not_equals(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "NOT" in compiled - assert "bingo.exact" in compiled - assert query in compiled - assert parameters in compiled - - def test_empty_parameters_handling(self): - """Test that empty parameters are handled correctly.""" - query = "CCO" - - # Test with empty string - result1 = self.mol_column.has_substructure(query, "") - compiled1 = str(result1.compile(compile_kwargs={"literal_binds": True})) - # Test with default (should be empty string) - result2 = self.mol_column.has_substructure(query) - compiled2 = str(result2.compile(compile_kwargs={"literal_binds": True})) +@pytest.fixture(params=[BingoMol(), BingoBinaryMol()]) +def mol_columns(request): + table = Table( + f"bingo_mols_{type(request.param).__name__.lower()}", + MetaData(), + Column("id", Integer), + Column("mol", request.param), + Column("other", request.param), + Column("query", String()), + ) + return table.c + + +@pytest.fixture(params=[BingoReaction(), BingoBinaryReaction()]) +def rxn_columns(request): + table = Table( + f"bingo_rxns_{type(request.param).__name__.lower()}", + MetaData(), + Column("id", Integer), + Column("rxn", request.param), + Column("other", request.param), + Column("query", String()), + ) + return table.c + + +@pytest.mark.parametrize( + ("method", "search_type"), + [ + ("has_substructure", "bingo.sub"), + ("has_smarts", "bingo.smarts"), + ("equals", "bingo.exact"), + ("not_equals", "bingo.exact"), + ], +) +def test_molecule_predicates_are_boolean(mol_columns, method, search_type): + expression = getattr(mol_columns.mol, method)("CCO", "TAU") + compiled = expression.compile(dialect=postgresql.dialect()) + + assert isinstance(expression.type, Boolean) + assert search_type in str(compiled) + assert "CCO" in compiled.params.values() + assert "TAU" in compiled.params.values() + + +@pytest.mark.parametrize( + ("method", "search_type"), + [ + ("has_substructure", "bingo.rsub"), + ("has_smarts", "bingo.rsmarts"), + ("equals", "bingo.rexact"), + ("not_equals", "bingo.rexact"), + ], +) +def test_reaction_predicates_are_boolean(rxn_columns, method, search_type): + expression = getattr(rxn_columns.rxn, method)("CCO>>CC=O", "STE") + compiled = expression.compile(dialect=postgresql.dialect()) + + assert isinstance(expression.type, Boolean) + assert search_type in str(compiled) + assert "CCO>>CC=O" in compiled.params.values() + assert "STE" in compiled.params.values() - # Both should be equivalent - assert compiled1 == compiled2 - - def test_query_with_special_characters(self): - """Test queries with special characters are handled properly.""" - query = ( - "CC(=O)N[C@@H](CC1=CC=CC=C1)C(=O)O" # phenylalanine with stereochemistry - ) - - result = self.mol_column.has_substructure(query) - # Should not raise any exceptions when compiling - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - assert query in compiled - - -class TestBingoMolComparatorWithBinaryType: - """Test that BingoMolComparator works with BingoBinaryMol too.""" - - def setup_method(self): - """Set up test table with BingoBinaryMol column.""" - self.metadata = MetaData() - self.test_table = Table( - "test_binary_molecules", - self.metadata, - Column("id", Integer, primary_key=True), - Column("name", String(100)), - Column("mol", BingoBinaryMol()), - Column("query_mol", String), - ) - self.mol_column = self.test_table.c.mol - - def test_binary_mol_has_substructure(self): - """Test has_substructure works with binary mol type.""" - query = "c1ccccc1" - - result = self.mol_column.has_substructure(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.sub" in compiled - assert query in compiled - - def test_binary_mol_has_smarts(self): - """Test SMARTS works with binary mol type.""" - query = "[#6]1-[#6]-[#6]-[#6]-[#6]-[#6]-1" - - result = self.mol_column.has_smarts(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.smarts" in compiled - assert "[#6]1" in compiled or query in compiled - - def test_binary_mol_equals(self): - """Test equals works with binary mol type.""" - query = "CCO" - - result = self.mol_column.equals(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.exact" in compiled - assert query in compiled - - def test_binary_mol_eq_operator_with_column_delegates_to_exact_match(self): - result = self.mol_column == self.test_table.c.query_mol - compiled = str( - result.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) - - assert "@" in compiled - assert "bingo.exact" in compiled - assert "test_binary_molecules.query_mol" in compiled - assert "'test_binary_molecules.query_mol'" not in compiled - - def test_binary_mol_ne_operator_delegates_to_negative_exact_match(self): - query = "CCO" - - result = self.mol_column != query - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "NOT" in compiled - assert "bingo.exact" in compiled - assert query in compiled - - def test_binary_mol_ne_operator_with_none_uses_sql_not_null_check(self): - result = self.mol_column.__ne__(None) - compiled = str(result.compile(dialect=postgresql.dialect())) - - assert "IS NOT NULL" in compiled - assert "bingo.exact" not in compiled - - -class TestBingoRxnComparator: - """Test BingoRxnComparator methods.""" - - def setup_method(self): - """Set up test tables with Bingo reaction columns.""" - self.metadata = MetaData() - self.test_table = Table( - "test_reactions", - self.metadata, - Column("id", Integer, primary_key=True), - Column("rxn", BingoReaction()), - Column("query_rxn", String), - ) - self.binary_table = Table( - "test_binary_reactions", - self.metadata, - Column("id", Integer, primary_key=True), - Column("rxn", BingoBinaryReaction()), - ) - self.rxn_column = self.test_table.c.rxn - - def test_reaction_has_substructure_query_generation(self): - """Test reaction substructure query generation.""" - query = "CCO>>CC=O" - - result = self.rxn_column.has_substructure(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.rsub" in compiled - assert query in compiled - - def test_reaction_has_smarts_query_generation(self): - """Test reaction SMARTS query generation.""" - query = "[C:1]>>[C:1][O]" - result = self.rxn_column.has_smarts(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) +def test_similarity_defaults_and_function_parity(mol_columns): + method = mol_columns.mol.similar_to("CCO") + function = bingo_func.mol_similarity(mol_columns.mol, "CCO") - assert "@" in compiled - assert "bingo.rsmarts" in compiled - assert query in compiled + assert isinstance(method.type, Boolean) + assert sql(method) == sql(function) + assert set(method.compile().params.values()) == {0.0, 1.0, "CCO", "Tanimoto"} - def test_reaction_equals_query_generation(self): - """Test exact reaction query generation.""" - query = "CCO>>CC=O" - - result = self.rxn_column.equals(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.rexact" in compiled - assert query in compiled - - def test_reaction_eq_operator_delegates_to_exact_match(self): - query = "CCO>>CC=O" - - result = self.rxn_column == query - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "@" in compiled - assert "bingo.rexact" in compiled - assert query in compiled - - def test_reaction_eq_operator_with_column_delegates_to_exact_match(self): - result = self.rxn_column == self.test_table.c.query_rxn - compiled = str( - result.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) - - assert "@" in compiled - assert "bingo.rexact" in compiled - assert "test_reactions.query_rxn" in compiled - assert "'test_reactions.query_rxn'" not in compiled - def test_reaction_eq_operator_with_none_uses_sql_null_check(self): - result = self.rxn_column.__eq__(None) - compiled = str(result.compile(dialect=postgresql.dialect())) +def test_similarity_custom_options_and_distinct_binds(mol_columns): + statement = select(mol_columns.id).where( + mol_columns.mol.similar_to("CCO", 0.2, 0.8, "Dice"), + mol_columns.mol.similar_to("CCN", 0.4, 0.9, "Cosine"), + ) + compiled = statement.compile(dialect=postgresql.dialect()) - assert "IS NULL" in compiled - assert "bingo.rexact" not in compiled - - def test_reaction_not_equals_query_generation(self): - """Test negative exact reaction query generation.""" - query = "CCO>>CC=O" - - result = self.rxn_column.not_equals(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "NOT" in compiled - assert "bingo.rexact" in compiled - assert query in compiled - - def test_reaction_ne_operator_delegates_to_negative_exact_match(self): - query = "CCO>>CC=O" - - result = self.rxn_column != query - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "NOT" in compiled - assert "bingo.rexact" in compiled - assert query in compiled - - def test_reaction_ne_operator_with_none_uses_sql_not_null_check(self): - result = self.rxn_column.__ne__(None) - compiled = str(result.compile(dialect=postgresql.dialect())) - - assert "IS NOT NULL" in compiled - assert "bingo.rexact" not in compiled - - def test_reaction_ne_operator_with_column_uses_sqlalchemy_inequality(self): - result = self.rxn_column != self.test_table.c.query_rxn - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) - - assert "!=" in compiled or "<>" in compiled - assert "bingo.rexact" not in compiled + assert "bingo.sim" in str(compiled) + assert {"CCO", "CCN", 0.2, 0.8, 0.4, 0.9, "Dice", "Cosine"}.issubset( + set(compiled.params.values()) + ) - def test_reaction_not_equals_with_parameters(self): - """Test negative exact reaction query with parameters.""" - query = "CCO>>CC=O" - parameters = "STE" - result = self.rxn_column.not_equals(query, parameters) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) +def test_sql_expression_tuple_members_are_preserved(mol_columns): + minimum = bindparam("minimum", 0.3) + expression = mol_columns.mol.similar_to( + mol_columns.query, minimum, 1.0, bindparam("metric", "Tanimoto") + ) + compiled = sql(expression) - assert "NOT" in compiled - assert "bingo.rexact" in compiled - assert query in compiled - assert parameters in compiled + assert "query" in compiled + assert "minimum" in compiled + assert "metric" in compiled - def test_binary_reaction_has_substructure(self): - """Test reaction comparator works with binary reaction type.""" - query = "C=C>>CC" - result = self.binary_table.c.rxn.has_substructure(query) - compiled = str(result.compile(compile_kwargs={"literal_binds": True})) +def test_predicates_compose_negate_and_label(mol_columns): + substructure = mol_columns.mol.has_substructure("CO") + exact = mol_columns.mol.equals("CCO") + statement = select((~substructure).label("not_sub")).where(substructure | exact) - assert "@" in compiled - assert "bingo.rsub" in compiled - assert query in compiled + assert isinstance(substructure.type, Boolean) + assert "NOT" in sql(statement) + assert " OR " in sql(statement) - def test_multiple_reaction_comparators_keep_distinct_bound_values(self): - """Multiple reaction predicates must not reuse the same bind names.""" - substructure = "C=C>>CC" - exact = "CCO>>CC=O" - stmt = select(self.test_table).where( - self.rxn_column.has_substructure(substructure) - | self.rxn_column.equals(exact) - ) +def test_native_molecule_equality_and_explicit_chemical_matching(mol_columns): + assert " = " in sql(mol_columns.mol == mol_columns.other) + assert " != " in sql(mol_columns.mol != mol_columns.other) + assert " = " in sql(mol_columns.mol == "CCO") + assert " != " in sql(mol_columns.mol != "CCO") + assert "bingo.exact" not in sql(mol_columns.mol == mol_columns.other) + assert "IS NULL" in sql(mol_columns.mol.__eq__(None)) + assert "IS NOT NULL" in sql(mol_columns.mol.__ne__(None)) + assert "bingo.exact" in sql(mol_columns.mol.equals(mol_columns.query)) + assert "NOT" in sql(mol_columns.mol.not_equals(mol_columns.query)) - compiled = stmt.compile(dialect=postgresql.dialect()) - assert "bingo.rsub" in str(compiled) - assert "bingo.rexact" in str(compiled) - assert substructure in compiled.params.values() - assert exact in compiled.params.values() +def test_native_reaction_equality_and_explicit_chemical_matching(rxn_columns): + assert " = " in sql(rxn_columns.rxn == rxn_columns.other) + assert " != " in sql(rxn_columns.rxn != rxn_columns.other) + assert "bingo.rexact" not in sql(rxn_columns.rxn == rxn_columns.other) + assert "IS NULL" in sql(rxn_columns.rxn.__eq__(None)) + assert "bingo.rexact" in sql(rxn_columns.rxn.equals(rxn_columns.query)) - def test_reaction_comparator_accepts_query_column_expression(self): - """Reaction comparator query inputs can be SQLAlchemy expressions.""" - stmt = select(self.test_table).where( - self.rxn_column.has_substructure(self.test_table.c.query_rxn) - ) - compiled = str( - stmt.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) +def test_orm_comparator_remains_available_at_runtime(): + expression = Compound.mol.similar_to("CCO", minimum=0.7) + assert isinstance(expression.type, Boolean) + assert "bingo.sim" in sql(select(Compound).where(expression)) - assert "test_reactions.query_rxn" in compiled - assert "'test_reactions.query_rxn'" not in compiled - assert "bingo.rsub" in compiled +def test_orm_attributes_are_preserved_as_comparator_operands(): + expression = Compound.mol.equals(Compound.other_mol, Compound.query_parameters) + compiled = sql(select(Compound).where(expression)) -class TestBingoComparatorReturnTypes: - """Test that Bingo comparator methods return properly typed expressions.""" + assert "bingo.exact" in compiled + assert "bingo_comparator_compounds.other_mol" in compiled + assert "bingo_comparator_compounds.query_parameters" in compiled - def setup_method(self): - self.metadata = MetaData() - self.test_table = Table( - "test_compounds", - self.metadata, - Column("id", Integer, primary_key=True), - Column("mol", BingoMol()), - Column("rxn", BingoReaction()), - ) - - def test_has_substructure_returns_column_element(self): - result = self.test_table.c.mol.has_substructure("CCO") - assert isinstance(result, ColumnElement) - - def test_has_smarts_returns_column_element(self): - result = self.test_table.c.mol.has_smarts("[#6]") - assert isinstance(result, ColumnElement) - def test_equals_returns_column_element(self): - result = self.test_table.c.mol.equals("CCO") - assert isinstance(result, ColumnElement) - - def test_not_equals_returns_column_element(self): - result = self.test_table.c.mol.not_equals("CCO") - assert isinstance(result, ColumnElement) - - def test_ne_operator_returns_column_element(self): - result = self.test_table.c.mol != "CCO" - assert isinstance(result, ColumnElement) - - def test_reaction_not_equals_returns_column_element(self): - result = self.test_table.c.rxn.not_equals("CCO>>CC=O") - assert isinstance(result, ColumnElement) - - def test_reaction_ne_operator_returns_column_element(self): - result = self.test_table.c.rxn != "CCO>>CC=O" - assert isinstance(result, ColumnElement) - - -class TestBingoComparatorExports: - """Test comparators are exported from bingo subpackage.""" - - def test_import_mol_comparator_from_bingo(self): - from molalchemy.bingo import BingoMolComparator - - assert BingoMolComparator is not None - - def test_import_rxn_comparator_from_bingo(self): - from molalchemy.bingo import BingoRxnComparator - - assert BingoRxnComparator is not None - - def test_bingo_proxies_include_not_equals(self): - from molalchemy.bingo import BingoMolProxy, BingoRxnProxy - - assert hasattr(BingoMolProxy, "not_equals") - assert hasattr(BingoRxnProxy, "not_equals") - - -class TestBingoComparatorInQueries: - """Test bingo comparator in actual SQL queries.""" - - def setup_method(self): - """Set up test table.""" - self.metadata = MetaData() - self.test_table = Table( - "compounds", - self.metadata, - Column("id", Integer, primary_key=True), - Column("name", String(100)), - Column("structure", BingoMol()), - Column("query_structure", String), - ) - - def test_has_substructure_in_select_query(self): - """Test has_substructure comparator in SELECT query.""" - query = "c1ccccc1" - - stmt = select(self.test_table).where( - self.test_table.c.structure.has_substructure(query) - ) - - # Should compile without errors - compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) - assert "SELECT" in compiled - assert "FROM compounds" in compiled - assert "WHERE" in compiled - assert "@" in compiled - assert "bingo.sub" in compiled - - def test_multiple_comparators_in_query(self): - """Test using multiple bingo comparators in one query.""" - benzene = "c1ccccc1" - ethanol = "CCO" - - stmt = select(self.test_table).where( - self.test_table.c.structure.has_substructure(benzene) - | self.test_table.c.structure.equals(ethanol) - ) - - compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) - assert "bingo.sub" in compiled - assert "bingo.exact" in compiled - assert benzene in compiled - assert ethanol in compiled - - def test_multiple_comparators_keep_distinct_bound_values(self): - """Multiple comparator predicates must not reuse the same bind names.""" - benzene = "c1ccccc1" - ethanol = "CCO" - - stmt = select(self.test_table).where( - self.test_table.c.structure.has_substructure(benzene) - | self.test_table.c.structure.equals(ethanol) - ) - - compiled = stmt.compile(dialect=postgresql.dialect()) - - assert "bingo.sub" in str(compiled) - assert "bingo.exact" in str(compiled) - assert benzene in compiled.params.values() - assert ethanol in compiled.params.values() - - def test_comparator_accepts_query_column_expression(self): - """Comparator query inputs can be SQLAlchemy expressions, not only strings.""" - stmt = select(self.test_table).where( - self.test_table.c.structure.has_substructure( - self.test_table.c.query_structure - ) - ) - - compiled = str( - stmt.compile( - dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} - ) - ) - - assert "test_molecules.query_structure" not in compiled - assert "compounds.query_structure" in compiled - assert "'compounds.query_structure'" not in compiled - assert "bingo.sub" in compiled +def test_comparators_are_public(): + assert BingoMolComparator.__name__ == "BingoMolComparator" + assert BingoRxnComparator.__name__ == "BingoRxnComparator" diff --git a/tests/bingo/test_functions.py b/tests/bingo/test_functions.py index a0b930a..8ef8f41 100644 --- a/tests/bingo/test_functions.py +++ b/tests/bingo/test_functions.py @@ -13,6 +13,7 @@ select, ) from sqlalchemy.dialects import postgresql +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from molalchemy.bingo import functions as bingo_func from molalchemy.bingo.types import BingoMol, BingoReaction @@ -20,6 +21,19 @@ all_funcs = bingo_func.__all__ +class Base(DeclarativeBase): + pass + + +class Compound(Base): + __tablename__ = "bingo_function_compounds" + + id: Mapped[int] = mapped_column(primary_key=True) + structure: Mapped[str] = mapped_column(BingoMol()) + query_structure: Mapped[str] = mapped_column(BingoMol()) + query_parameters: Mapped[str] = mapped_column(String()) + + @pytest.mark.parametrize("func", all_funcs) def test_any_function_returns_function_object(func): """Test that any function returns a SQLAlchemy function object.""" @@ -109,6 +123,23 @@ def test_bingo_similarity_preserves_column_expression_inputs(): assert "bingo.sim" in sql +def test_bingo_search_helpers_preserve_orm_attribute_inputs(): + """Mapped attributes should use their SQL expression, not become literals.""" + stmt = select(Compound).where( + bingo_func.mol_equals( + Compound.structure, + Compound.query_structure, + Compound.query_parameters, + ) + ) + + compiled = str(stmt.compile(dialect=postgresql.dialect())) + + assert "bingo.exact" in compiled + assert "bingo_function_compounds.query_structure" in compiled + assert "bingo_function_compounds.query_parameters" in compiled + + @pytest.mark.parametrize( ("helper_name", "column_type", "query", "search_type"), [ diff --git a/tests/bingo/test_integration.py b/tests/bingo/test_integration.py index a572c1b..01e0905 100644 --- a/tests/bingo/test_integration.py +++ b/tests/bingo/test_integration.py @@ -338,7 +338,7 @@ def test_all_function_methods(self): smarts_expr = bingo_func.mol_has_smarts( self.compounds.c.structure, benzene_smarts ) - equals_expr = self.compounds.c.structure == ethanol + equals_expr = self.compounds.c.structure.equals(ethanol) similarity_expr = bingo_func.mol_similarity( self.compounds.c.structure, ethanol, 0.7 ) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index c2becf2..34d8bda 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -9,8 +9,19 @@ BingoMol, BingoReaction, ) -from molalchemy.helpers import bingo_col, bingo_rxn_col, rdkit_col, rdkit_rxn_col -from molalchemy.rdkit.types import RdkitMol, RdkitReaction +from molalchemy.helpers import ( + bingo_col, + bingo_rxn_col, + rdkit_col, + rdkit_fp_col, + rdkit_rxn_col, +) +from molalchemy.rdkit.types import ( + RdkitBitFingerprint, + RdkitMol, + RdkitReaction, + RdkitSparseFingerprint, +) class Base(DeclarativeBase): @@ -31,7 +42,11 @@ class RdkitCompound(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True) structure: Mapped[str] = mapped_column(RdkitMol()) + other_structure: Mapped[str] = mapped_column(RdkitMol()) reaction: Mapped[str] = mapped_column(RdkitReaction()) + other_reaction: Mapped[str] = mapped_column(RdkitReaction()) + fingerprint: Mapped[bytes] = mapped_column(RdkitBitFingerprint()) + other_fingerprint: Mapped[bytes] = mapped_column(RdkitBitFingerprint()) @pytest.fixture(params=[BingoMol, BingoBinaryMol]) @@ -136,6 +151,31 @@ def test_rdkit_rxn_col_success(good_rdkit_rxn_col): assert result is good_rdkit_rxn_col +@pytest.mark.parametrize( + "fingerprint_type", [RdkitBitFingerprint, RdkitSparseFingerprint] +) +def test_rdkit_fp_col_success(fingerprint_type): + column = Column("fingerprint", fingerprint_type()) + assert rdkit_fp_col(column) is column + + +@pytest.mark.parametrize("bad_type", [String, BINARY, RdkitMol]) +def test_rdkit_fp_col_type_error(bad_type): + column = Column("fingerprint", bad_type()) + with pytest.raises( + TypeError, + match="Column is not of type RdkitBitFingerprint or RdkitSparseFingerprint", + ): + rdkit_fp_col(column) + + +def test_rdkit_fp_col_invalid_input(): + with pytest.raises( + TypeError, match="Input is not a SQLAlchemy Column or InstrumentedAttribute" + ): + rdkit_fp_col(123) + + def test_bingo_mol_proxy_helper_core_column_compiles_substructure(): table = Table( "compounds", @@ -237,6 +277,7 @@ def test_bingo_proxy_helpers_accept_orm_instrumented_attributes(): def test_rdkit_proxy_helpers_accept_orm_instrumented_attributes(): assert rdkit_col(RdkitCompound.structure) is RdkitCompound.structure assert rdkit_rxn_col(RdkitCompound.reaction) is RdkitCompound.reaction + assert rdkit_fp_col(RdkitCompound.fingerprint) is RdkitCompound.fingerprint stmt = select(RdkitCompound).where( rdkit_rxn_col(RdkitCompound.reaction).has_smarts("[C:1]>>[C:1][O]") @@ -245,3 +286,37 @@ def test_rdkit_proxy_helpers_accept_orm_instrumented_attributes(): assert "substruct" in compiled assert "reaction_from_smarts" in compiled + + +def test_rdkit_fingerprint_helper_compiles_distance_ordering(): + distance = rdkit_fp_col(RdkitCompound.fingerprint).tanimoto_distance(b"fingerprint") + compiled = str( + select(RdkitCompound) + .order_by(distance) + .compile(dialect=postgresql.dialect(paramstyle="named")) + ) + + assert "ORDER BY" in compiled + assert "<%>" in compiled + + +def test_rdkit_helpers_accept_orm_column_operands(): + molecule_match = rdkit_col(RdkitCompound.structure).equals( + RdkitCompound.other_structure + ) + reaction_match = rdkit_rxn_col(RdkitCompound.reaction).equals( + RdkitCompound.other_reaction + ) + fingerprint_match = rdkit_fp_col(RdkitCompound.fingerprint).dice_matches( + RdkitCompound.other_fingerprint + ) + + compiled = str( + select(RdkitCompound) + .where(molecule_match, reaction_match, fingerprint_match) + .compile(dialect=postgresql.dialect(paramstyle="named")) + ) + + assert "structure @= helper_rdkit_compounds.other_structure" in compiled + assert "reaction @= helper_rdkit_compounds.other_reaction" in compiled + assert "fingerprint # helper_rdkit_compounds.other_fingerprint" in compiled diff --git a/uv.lock b/uv.lock index 0be6281..9d0cbc0 100644 --- a/uv.lock +++ b/uv.lock @@ -1132,13 +1132,11 @@ dev = [ { name = "alembic" }, { name = "ipykernel" }, { name = "jinja2" }, - { name = "mypy" }, { name = "pandas" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pyyaml" }, { name = "ruff" }, - { name = "sqlalchemy", extra = ["mypy"] }, { name = "ty" }, ] docs = [ @@ -1163,13 +1161,11 @@ dev = [ { name = "alembic", specifier = ">=1.17.0" }, { name = "ipykernel", specifier = ">=6.30.1" }, { name = "jinja2", specifier = ">=3.1.6" }, - { name = "mypy", specifier = ">=1.18.2" }, { name = "pandas", specifier = ">=2.3.3" }, { name = "pytest", specifier = ">=8.4.2" }, { name = "pytest-cov", specifier = ">=7.0.0" }, { name = "pyyaml", specifier = ">=6.0.2" }, { name = "ruff", specifier = "==0.14.5" }, - { name = "sqlalchemy", extras = ["mypy"], specifier = ">=2.0.43" }, { name = "ty", specifier = ">=0.0.66" }, ] docs = [ @@ -1181,60 +1177,6 @@ docs = [ { name = "pymdown-extensions", specifier = ">=10.16.1" }, ] -[[package]] -name = "mypy" -version = "1.18.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mypy-extensions" }, - { name = "pathspec" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c0/77/8f0d0001ffad290cef2f7f216f96c814866248a0b92a722365ed54648e7e/mypy-1.18.2.tar.gz", hash = "sha256:06a398102a5f203d7477b2923dda3634c36727fa5c237d8f859ef90c42a9924b", size = 3448846, upload-time = "2025-09-19T00:11:10.519Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/03/6f/657961a0743cff32e6c0611b63ff1c1970a0b482ace35b069203bf705187/mypy-1.18.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c1eab0cf6294dafe397c261a75f96dc2c31bffe3b944faa24db5def4e2b0f77c", size = 12807973, upload-time = "2025-09-19T00:10:35.282Z" }, - { url = "https://files.pythonhosted.org/packages/10/e9/420822d4f661f13ca8900f5fa239b40ee3be8b62b32f3357df9a3045a08b/mypy-1.18.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7a780ca61fc239e4865968ebc5240bb3bf610ef59ac398de9a7421b54e4a207e", size = 11896527, upload-time = "2025-09-19T00:10:55.791Z" }, - { url = "https://files.pythonhosted.org/packages/aa/73/a05b2bbaa7005f4642fcfe40fb73f2b4fb6bb44229bd585b5878e9a87ef8/mypy-1.18.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:448acd386266989ef11662ce3c8011fd2a7b632e0ec7d61a98edd8e27472225b", size = 12507004, upload-time = "2025-09-19T00:11:05.411Z" }, - { url = "https://files.pythonhosted.org/packages/4f/01/f6e4b9f0d031c11ccbd6f17da26564f3a0f3c4155af344006434b0a05a9d/mypy-1.18.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f9e171c465ad3901dc652643ee4bffa8e9fef4d7d0eece23b428908c77a76a66", size = 13245947, upload-time = "2025-09-19T00:10:46.923Z" }, - { url = "https://files.pythonhosted.org/packages/d7/97/19727e7499bfa1ae0773d06afd30ac66a58ed7437d940c70548634b24185/mypy-1.18.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:592ec214750bc00741af1f80cbf96b5013d81486b7bb24cb052382c19e40b428", size = 13499217, upload-time = "2025-09-19T00:09:39.472Z" }, - { url = "https://files.pythonhosted.org/packages/9f/4f/90dc8c15c1441bf31cf0f9918bb077e452618708199e530f4cbd5cede6ff/mypy-1.18.2-cp310-cp310-win_amd64.whl", hash = "sha256:7fb95f97199ea11769ebe3638c29b550b5221e997c63b14ef93d2e971606ebed", size = 9766753, upload-time = "2025-09-19T00:10:49.161Z" }, - { url = "https://files.pythonhosted.org/packages/88/87/cafd3ae563f88f94eec33f35ff722d043e09832ea8530ef149ec1efbaf08/mypy-1.18.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:807d9315ab9d464125aa9fcf6d84fde6e1dc67da0b6f80e7405506b8ac72bc7f", size = 12731198, upload-time = "2025-09-19T00:09:44.857Z" }, - { url = "https://files.pythonhosted.org/packages/0f/e0/1e96c3d4266a06d4b0197ace5356d67d937d8358e2ee3ffac71faa843724/mypy-1.18.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:776bb00de1778caf4db739c6e83919c1d85a448f71979b6a0edd774ea8399341", size = 11817879, upload-time = "2025-09-19T00:09:47.131Z" }, - { url = "https://files.pythonhosted.org/packages/72/ef/0c9ba89eb03453e76bdac5a78b08260a848c7bfc5d6603634774d9cd9525/mypy-1.18.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1379451880512ffce14505493bd9fe469e0697543717298242574882cf8cdb8d", size = 12427292, upload-time = "2025-09-19T00:10:22.472Z" }, - { url = "https://files.pythonhosted.org/packages/1a/52/ec4a061dd599eb8179d5411d99775bec2a20542505988f40fc2fee781068/mypy-1.18.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1331eb7fd110d60c24999893320967594ff84c38ac6d19e0a76c5fd809a84c86", size = 13163750, upload-time = "2025-09-19T00:09:51.472Z" }, - { url = "https://files.pythonhosted.org/packages/c4/5f/2cf2ceb3b36372d51568f2208c021870fe7834cf3186b653ac6446511839/mypy-1.18.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3ca30b50a51e7ba93b00422e486cbb124f1c56a535e20eff7b2d6ab72b3b2e37", size = 13351827, upload-time = "2025-09-19T00:09:58.311Z" }, - { url = "https://files.pythonhosted.org/packages/c8/7d/2697b930179e7277529eaaec1513f8de622818696857f689e4a5432e5e27/mypy-1.18.2-cp311-cp311-win_amd64.whl", hash = "sha256:664dc726e67fa54e14536f6e1224bcfce1d9e5ac02426d2326e2bb4e081d1ce8", size = 9757983, upload-time = "2025-09-19T00:10:09.071Z" }, - { url = "https://files.pythonhosted.org/packages/07/06/dfdd2bc60c66611dd8335f463818514733bc763e4760dee289dcc33df709/mypy-1.18.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:33eca32dd124b29400c31d7cf784e795b050ace0e1f91b8dc035672725617e34", size = 12908273, upload-time = "2025-09-19T00:10:58.321Z" }, - { url = "https://files.pythonhosted.org/packages/81/14/6a9de6d13a122d5608e1a04130724caf9170333ac5a924e10f670687d3eb/mypy-1.18.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a3c47adf30d65e89b2dcd2fa32f3aeb5e94ca970d2c15fcb25e297871c8e4764", size = 11920910, upload-time = "2025-09-19T00:10:20.043Z" }, - { url = "https://files.pythonhosted.org/packages/5f/a9/b29de53e42f18e8cc547e38daa9dfa132ffdc64f7250e353f5c8cdd44bee/mypy-1.18.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5d6c838e831a062f5f29d11c9057c6009f60cb294fea33a98422688181fe2893", size = 12465585, upload-time = "2025-09-19T00:10:33.005Z" }, - { url = "https://files.pythonhosted.org/packages/77/ae/6c3d2c7c61ff21f2bee938c917616c92ebf852f015fb55917fd6e2811db2/mypy-1.18.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01199871b6110a2ce984bde85acd481232d17413868c9807e95c1b0739a58914", size = 13348562, upload-time = "2025-09-19T00:10:11.51Z" }, - { url = "https://files.pythonhosted.org/packages/4d/31/aec68ab3b4aebdf8f36d191b0685d99faa899ab990753ca0fee60fb99511/mypy-1.18.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a2afc0fa0b0e91b4599ddfe0f91e2c26c2b5a5ab263737e998d6817874c5f7c8", size = 13533296, upload-time = "2025-09-19T00:10:06.568Z" }, - { url = "https://files.pythonhosted.org/packages/9f/83/abcb3ad9478fca3ebeb6a5358bb0b22c95ea42b43b7789c7fb1297ca44f4/mypy-1.18.2-cp312-cp312-win_amd64.whl", hash = "sha256:d8068d0afe682c7c4897c0f7ce84ea77f6de953262b12d07038f4d296d547074", size = 9828828, upload-time = "2025-09-19T00:10:28.203Z" }, - { url = "https://files.pythonhosted.org/packages/5f/04/7f462e6fbba87a72bc8097b93f6842499c428a6ff0c81dd46948d175afe8/mypy-1.18.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:07b8b0f580ca6d289e69209ec9d3911b4a26e5abfde32228a288eb79df129fcc", size = 12898728, upload-time = "2025-09-19T00:10:01.33Z" }, - { url = "https://files.pythonhosted.org/packages/99/5b/61ed4efb64f1871b41fd0b82d29a64640f3516078f6c7905b68ab1ad8b13/mypy-1.18.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ed4482847168439651d3feee5833ccedbf6657e964572706a2adb1f7fa4dfe2e", size = 11910758, upload-time = "2025-09-19T00:10:42.607Z" }, - { url = "https://files.pythonhosted.org/packages/3c/46/d297d4b683cc89a6e4108c4250a6a6b717f5fa96e1a30a7944a6da44da35/mypy-1.18.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c3ad2afadd1e9fea5cf99a45a822346971ede8685cc581ed9cd4d42eaf940986", size = 12475342, upload-time = "2025-09-19T00:11:00.371Z" }, - { url = "https://files.pythonhosted.org/packages/83/45/4798f4d00df13eae3bfdf726c9244bcb495ab5bd588c0eed93a2f2dd67f3/mypy-1.18.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a431a6f1ef14cf8c144c6b14793a23ec4eae3db28277c358136e79d7d062f62d", size = 13338709, upload-time = "2025-09-19T00:11:03.358Z" }, - { url = "https://files.pythonhosted.org/packages/d7/09/479f7358d9625172521a87a9271ddd2441e1dab16a09708f056e97007207/mypy-1.18.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7ab28cc197f1dd77a67e1c6f35cd1f8e8b73ed2217e4fc005f9e6a504e46e7ba", size = 13529806, upload-time = "2025-09-19T00:10:26.073Z" }, - { url = "https://files.pythonhosted.org/packages/71/cf/ac0f2c7e9d0ea3c75cd99dff7aec1c9df4a1376537cb90e4c882267ee7e9/mypy-1.18.2-cp313-cp313-win_amd64.whl", hash = "sha256:0e2785a84b34a72ba55fb5daf079a1003a34c05b22238da94fcae2bbe46f3544", size = 9833262, upload-time = "2025-09-19T00:10:40.035Z" }, - { url = "https://files.pythonhosted.org/packages/5a/0c/7d5300883da16f0063ae53996358758b2a2df2a09c72a5061fa79a1f5006/mypy-1.18.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:62f0e1e988ad41c2a110edde6c398383a889d95b36b3e60bcf155f5164c4fdce", size = 12893775, upload-time = "2025-09-19T00:10:03.814Z" }, - { url = "https://files.pythonhosted.org/packages/50/df/2cffbf25737bdb236f60c973edf62e3e7b4ee1c25b6878629e88e2cde967/mypy-1.18.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:8795a039bab805ff0c1dfdb8cd3344642c2b99b8e439d057aba30850b8d3423d", size = 11936852, upload-time = "2025-09-19T00:10:51.631Z" }, - { url = "https://files.pythonhosted.org/packages/be/50/34059de13dd269227fb4a03be1faee6e2a4b04a2051c82ac0a0b5a773c9a/mypy-1.18.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ca1e64b24a700ab5ce10133f7ccd956a04715463d30498e64ea8715236f9c9c", size = 12480242, upload-time = "2025-09-19T00:11:07.955Z" }, - { url = "https://files.pythonhosted.org/packages/5b/11/040983fad5132d85914c874a2836252bbc57832065548885b5bb5b0d4359/mypy-1.18.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d924eef3795cc89fecf6bedc6ed32b33ac13e8321344f6ddbf8ee89f706c05cb", size = 13326683, upload-time = "2025-09-19T00:09:55.572Z" }, - { url = "https://files.pythonhosted.org/packages/e9/ba/89b2901dd77414dd7a8c8729985832a5735053be15b744c18e4586e506ef/mypy-1.18.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:20c02215a080e3a2be3aa50506c67242df1c151eaba0dcbc1e4e557922a26075", size = 13514749, upload-time = "2025-09-19T00:10:44.827Z" }, - { url = "https://files.pythonhosted.org/packages/25/bc/cc98767cffd6b2928ba680f3e5bc969c4152bf7c2d83f92f5a504b92b0eb/mypy-1.18.2-cp314-cp314-win_amd64.whl", hash = "sha256:749b5f83198f1ca64345603118a6f01a4e99ad4bf9d103ddc5a3200cc4614adf", size = 9982959, upload-time = "2025-09-19T00:10:37.344Z" }, - { url = "https://files.pythonhosted.org/packages/87/e3/be76d87158ebafa0309946c4a73831974d4d6ab4f4ef40c3b53a385a66fd/mypy-1.18.2-py3-none-any.whl", hash = "sha256:22a1748707dd62b58d2ae53562ffc4d7f8bcc727e8ac7cbc69c053ddc874d47e", size = 2352367, upload-time = "2025-09-19T00:10:15.489Z" }, -] - -[[package]] -name = "mypy-extensions" -version = "1.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, -] - [[package]] name = "nbclient" version = "0.10.2" @@ -2272,11 +2214,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b8/d9/13bdde6521f322861fab67473cec4b1cc8999f3871953531cf61945fad92/sqlalchemy-2.0.43-py3-none-any.whl", hash = "sha256:1681c21dd2ccee222c2fe0bef671d1aef7c504087c9c4e800371cfcc8ac966fc", size = 1924759, upload-time = "2025-08-11T15:39:53.024Z" }, ] -[package.optional-dependencies] -mypy = [ - { name = "mypy" }, -] - [[package]] name = "stack-data" version = "0.6.3" From 42f034f4763be7015be4d00954244d012c2dc05a Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Tue, 4 Aug 2026 22:26:21 +0200 Subject: [PATCH 03/13] update rdkit autogen --- data/rdkit/general_extra.txt | 81 ++++++++++++----------- data/rdkit/general_header.txt | 11 ++- src/molalchemy/rdkit/functions/general.py | 14 ++-- tests/rdkit/test_functions.py | 47 +++++++++++++ 4 files changed, 104 insertions(+), 49 deletions(-) diff --git a/data/rdkit/general_extra.txt b/data/rdkit/general_extra.txt index 7bfe7ba..0fa39b2 100644 --- a/data/rdkit/general_extra.txt +++ b/data/rdkit/general_extra.txt @@ -2,7 +2,7 @@ def mol_has_substructure( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform substructure search. @@ -20,7 +20,7 @@ def mol_has_substructure( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy binary expression for the substructure search. Examples @@ -31,10 +31,10 @@ def mol_has_substructure( >>> # Search for molecules containing a aromatic carbon as SMARTS >>> query = select(Molecule).where(has_substructure(Molecule.structure, cast("[cH]", RdkitQMol))) """ - return mol_column.op("@>")(query) + return _rdkit_predicate(mol_column, "@>", query) -def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> Function[bool]: +def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> ColumnElement[bool]: """ Perform molecule SMARTS search. @@ -51,8 +51,8 @@ def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> Function[bool]: Returns ------- - Function[bool] - SQLAlchemy function that returns `True` if the pattern + ColumnElement[bool] + SQLAlchemy expression that returns `True` if the pattern is found in the molecule, `False` otherwise. Examples @@ -60,12 +60,12 @@ def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> Function[bool]: >>> from sqlalchemy import select >>> query = select(Molecule).where(mol_has_smarts(Molecule.structure, "[#6]")) """ - return mol_has_substructure(mol_column, qmol_from_smarts(cast(pattern, CString))) + return _rdkit_mol_smarts(mol_column, pattern) def mol_is_substructure_of( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse substructure search. @@ -83,20 +83,22 @@ def mol_is_substructure_of( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy binary expression for the reverse substructure search. """ - return mol_column.op("<@")(query) + return _rdkit_predicate(mol_column, "<@", query) def mol_equals( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact structure matching. - Checks if the molecular structure in the column exactly matches - the query using the `@=` operator. + Checks if the molecular structure in the column chemically matches + the query using `@=`. RDKit maps both `@=` and ordinary `=` to + the `mol_eq` function, so this is an explicit spelling of the same + cartridge equality used by `column == query`. Parameters ---------- @@ -108,28 +110,29 @@ def mol_equals( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy binary expression for the exact match search. """ - return mol_column.op("@=")(query) + return _rdkit_predicate(mol_column, "@=", query) def mol_not_equals( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform negative exact structure matching. - Checks if the molecular structure in the column differs from - the query using the `@<>` operator. + Checks if the molecular structure in the column differs chemically from + the query using `@<>`. RDKit maps both `@<>` and ordinary `<>` to + the `mol_ne` function. """ - return mol_column.op("@<>")(query) + return _rdkit_predicate(mol_column, "@<>", query) def mol_has_query_substructure( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike | AnyRdkitQMolLike | AnyRdkitXQMolLike, -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform query-substructure search. @@ -137,13 +140,13 @@ def mol_has_query_substructure( using the `@>>` operator. Use `RdkitQMol` or `RdkitXQMol` expressions for SMARTS/query semantics. """ - return mol_column.op("@>>")(query) + return _rdkit_predicate(mol_column, "@>>", query) def mol_is_query_substructure_of( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike | AnyRdkitQMolLike | AnyRdkitXQMolLike, -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse query-substructure search. @@ -151,82 +154,82 @@ def mol_is_query_substructure_of( using the `<<@` operator. Use `RdkitQMol` or `RdkitXQMol` expressions for SMARTS/query semantics. """ - return mol_column.op("<<@")(query) + return _rdkit_predicate(mol_column, "<<@", query) def rxn_has_substructure( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reaction substructure search. Checks if the reaction in the column contains the query reaction using the `@>` operator. """ - return rxn_column.op("@>")(query) + return _rdkit_predicate(rxn_column, "@>", query) def rxn_is_substructure_of( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse reaction substructure search. Checks if the reaction in the column is a substructure of the query using the `<@` operator. """ - return rxn_column.op("<@")(query) + return _rdkit_predicate(rxn_column, "<@", query) def rxn_equals( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform exact reaction matching. Checks if the reaction in the column exactly matches the query using the `@=` operator. """ - return rxn_column.op("@=")(query) + return _rdkit_predicate(rxn_column, "@=", query) def rxn_not_equals( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform negative exact reaction matching. Checks if the reaction in the column differs from the query using the `@<>` operator. """ - return rxn_column.op("@<>")(query) + return _rdkit_predicate(rxn_column, "@<>", query) def rxn_has_substructure_fp( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform fingerprint-backed reaction substructure search. Checks if the reaction in the column contains the query using the `?>` operator. """ - return rxn_column.op("?>")(query) + return _rdkit_predicate(rxn_column, "?>", query) def rxn_is_substructure_fp_of( rxn_column: ColumnElement[RdkitReaction], query: AnyRdkitReactionLike -) -> BinaryExpression: +) -> ColumnElement[bool]: """ Perform reverse fingerprint-backed reaction substructure search. Checks if the reaction in the column is a fingerprint substructure of the query using the `?<` operator. """ - return rxn_column.op("?<")(query) + return _rdkit_predicate(rxn_column, "?<", query) -def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> Function[bool]: +def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> ColumnElement[bool]: """ Perform reaction substructure search. @@ -244,8 +247,8 @@ def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> Function[bool]: Returns ------- - Function[bool] - SQLAlchemy function, that returns `True` if the pattern + ColumnElement[bool] + SQLAlchemy expression that returns `True` if the pattern is found in the reaction, `False` otherwise. Examples @@ -254,4 +257,4 @@ def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> Function[bool]: >>> # Search for reactions containing a carbonyl formation >>> query = select(Reaction).where(has_smarts(Reaction.rxn, ">>C=O")) """ - return func.substruct(rxn_column, reaction_from_smarts(cast(pattern, CString))) + return _rdkit_rxn_smarts(rxn_column, pattern) diff --git a/data/rdkit/general_header.txt b/data/rdkit/general_header.txt index c37da49..0201f79 100644 --- a/data/rdkit/general_header.txt +++ b/data/rdkit/general_header.txt @@ -5,13 +5,17 @@ This file defines public RDKit PostgreSQL function wrappers for use with SQLAlch from typing import Any -from sqlalchemy import BinaryExpression, Function, String, type_coerce from sqlalchemy import types as sqltypes -from sqlalchemy.sql import cast, func +from sqlalchemy.sql import cast from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.sql.expression import Cast from sqlalchemy.sql.functions import GenericFunction +from molalchemy.rdkit.search import ( + _rdkit_mol_smarts, + _rdkit_predicate, + _rdkit_rxn_smarts, +) from molalchemy.rdkit.types import ( RdkitBitFingerprint, RdkitMol, @@ -29,4 +33,5 @@ from ._types import ( AnyRdkitQMolLike, AnyRdkitReactionLike, AnyRdkitSparseFingerprintLike, - AnyRdkitXQMolLike) \ No newline at end of file + AnyRdkitXQMolLike, +) diff --git a/src/molalchemy/rdkit/functions/general.py b/src/molalchemy/rdkit/functions/general.py index 84c78d2..1c26f97 100644 --- a/src/molalchemy/rdkit/functions/general.py +++ b/src/molalchemy/rdkit/functions/general.py @@ -56,7 +56,7 @@ def mol_has_substructure( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy binary expression for the substructure search. Examples @@ -87,8 +87,8 @@ def mol_has_smarts(mol_column: ColumnElement, pattern: str) -> ColumnElement[boo Returns ------- - Function[bool] - SQLAlchemy function that returns `True` if the pattern + ColumnElement[bool] + SQLAlchemy expression that returns `True` if the pattern is found in the molecule, `False` otherwise. Examples @@ -119,7 +119,7 @@ def mol_is_substructure_of( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy binary expression for the reverse substructure search. """ return _rdkit_predicate(mol_column, "<@", query) @@ -146,7 +146,7 @@ def mol_equals( Returns ------- - BinaryExpression + ColumnElement[bool] SQLAlchemy binary expression for the exact match search. """ return _rdkit_predicate(mol_column, "@=", query) @@ -283,8 +283,8 @@ def rxn_has_smarts(rxn_column: ColumnElement, pattern: str) -> ColumnElement[boo Returns ------- - Function[bool] - SQLAlchemy function, that returns `True` if the pattern + ColumnElement[bool] + SQLAlchemy expression that returns `True` if the pattern is found in the reaction, `False` otherwise. Examples diff --git a/tests/rdkit/test_functions.py b/tests/rdkit/test_functions.py index a0b8001..f38dfc9 100644 --- a/tests/rdkit/test_functions.py +++ b/tests/rdkit/test_functions.py @@ -13,6 +13,7 @@ select, ) from sqlalchemy.dialects import postgresql +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from molalchemy.rdkit import functions as rdkit_func from molalchemy.rdkit.types import RdkitMol, RdkitQMol, RdkitReaction @@ -20,6 +21,26 @@ all_funcs = rdkit_func.__all__ +class Base(DeclarativeBase): + pass + + +class Molecule(Base): + __tablename__ = "rdkit_function_molecules" + + id: Mapped[int] = mapped_column(primary_key=True) + structure: Mapped[str] = mapped_column(RdkitMol()) + query_structure: Mapped[str] = mapped_column(RdkitMol()) + + +class Reaction(Base): + __tablename__ = "rdkit_function_reactions" + + id: Mapped[int] = mapped_column(primary_key=True) + reaction: Mapped[str] = mapped_column(RdkitReaction()) + query_reaction: Mapped[str] = mapped_column(RdkitReaction()) + + @pytest.mark.parametrize("func", all_funcs) def test_any_function_returns_function_object(func): """Test that any function returns a SQLAlchemy function object.""" @@ -166,6 +187,19 @@ def test_molecule_query_helpers_preserve_column_expression_inputs(): assert "mol_from_pkl" not in compiled +def test_molecule_search_helpers_preserve_orm_attribute_inputs(): + """Mapped molecule attributes should remain SQL expressions.""" + stmt = select(Molecule).where( + rdkit_func.mol_equals(Molecule.structure, Molecule.query_structure) + ) + + compiled = str(stmt.compile(dialect=postgresql.dialect())) + + assert "rdkit_function_molecules.query_structure" in compiled + assert "mol_from_pkl" not in compiled + assert "@=" in compiled + + @pytest.mark.parametrize( ("helper_name", "query", "operator"), [ @@ -265,3 +299,16 @@ def test_reaction_search_helpers_preserve_column_expression_inputs(): assert "reactions.query_reaction" in compiled assert "'reactions.query_reaction'" not in compiled assert "reaction_from_smarts" not in compiled + + +def test_reaction_search_helpers_preserve_orm_attribute_inputs(): + """Mapped reaction attributes should remain SQL expressions.""" + stmt = select(Reaction).where( + rdkit_func.rxn_equals(Reaction.reaction, Reaction.query_reaction) + ) + + compiled = str(stmt.compile(dialect=postgresql.dialect())) + + assert "rdkit_function_reactions.query_reaction" in compiled + assert "reaction_from_smarts" not in compiled + assert "@=" in compiled From 23c107795f908a46f4d927f3f8100ee6e174326d Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Tue, 4 Aug 2026 22:37:04 +0200 Subject: [PATCH 04/13] update docs --- README.md | 1 + docs/index.md | 1 + docs/migrations/bingo-comparator-api.md | 189 ++++++++++++++++++++++++ mkdocs.yml | 1 + 4 files changed, 192 insertions(+) create mode 100644 docs/migrations/bingo-comparator-api.md diff --git a/README.md b/README.md index 666e924..c5589fe 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ To learn how to use molalchemy, check out the tutorials in the [documentation](h - [Bingo Reactions and Binary Storage](https://molalchemy.readthedocs.io/en/latest/tutorials/06_bingo_reactions_binary/) - Bingo reaction and binary column workflows - [RDKit Descriptors and Advanced Queries](https://molalchemy.readthedocs.io/en/latest/tutorials/07_rdkit_descriptors_advanced/) - Descriptor functions and richer query patterns - [Typed Comparator Helpers](https://molalchemy.readthedocs.io/en/latest/tutorials/08_proxy_helpers/) - statically typed cartridge methods +- [Bingo Comparator Migration](https://molalchemy.readthedocs.io/en/latest/migrations/bingo-comparator-api/) - migrate equality and typed comparator calls - [RDKit Comparator Migration](https://molalchemy.readthedocs.io/en/latest/migrations/rdkit-comparator-api/) - migrate legacy fingerprint and comparator calls ## 🏗️ Supported Cartridges diff --git a/docs/index.md b/docs/index.md index 37947e6..d5857d2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -128,6 +128,7 @@ To learn how to use molalchemy, check out the tutorials in the [documentation](h - [Bingo Reactions and Binary Storage](https://molalchemy.readthedocs.io/en/latest/tutorials/06_bingo_reactions_binary/) - Bingo reaction and binary column workflows - [RDKit Descriptors and Advanced Queries](https://molalchemy.readthedocs.io/en/latest/tutorials/07_rdkit_descriptors_advanced/) - Descriptor functions and richer query patterns - [Typed Comparator Helpers](https://molalchemy.readthedocs.io/en/latest/tutorials/08_proxy_helpers/) - statically typed cartridge methods +- [Bingo Comparator Migration](https://molalchemy.readthedocs.io/en/latest/migrations/bingo-comparator-api/) - migrate equality and typed comparator calls - [RDKit Comparator Migration](https://molalchemy.readthedocs.io/en/latest/migrations/rdkit-comparator-api/) - migrate legacy fingerprint and comparator calls ## 🏗️ Supported Cartridges diff --git a/docs/migrations/bingo-comparator-api.md b/docs/migrations/bingo-comparator-api.md new file mode 100644 index 0000000..ba4d09e --- /dev/null +++ b/docs/migrations/bingo-comparator-api.md @@ -0,0 +1,189 @@ +# Migrating the Bingo comparator API + +This guide covers the breaking Bingo comparator changes introduced during the +v0.x API cleanup. No database schema migration is required: `BingoMol`, +`BingoBinaryMol`, `BingoReaction`, and `BingoBinaryReaction` retain their +existing PostgreSQL storage types and constructors. + +The main migration is to make chemical equality explicit. Search predicates +also have more precise result and operand types, and molecule similarity is now +available directly from the comparator. + +## Chemical equality is now explicit + +The custom Bingo `__eq__` and `__ne__` implementations were removed. Normal +Python comparison operators now use PostgreSQL storage equality; named methods +perform Bingo chemical matching. + +| Intent | Previous API | New API | +| --- | --- | --- | +| Molecule exact match | `column == query` | `column.equals(query)` | +| Molecule exact mismatch | `column != query` | `column.not_equals(query)` | +| Reaction exact match | `column == query` | `column.equals(query)` | +| Reaction exact mismatch | `column != query` | `column.not_equals(query)` | +| Storage equality | Operand-dependent | `column == query` | +| Storage inequality | Operand-dependent | `column != query` | + +The old implementation could choose different behavior for literals and +table-bound expressions. The replacement rules above describe intent: migrate +every chemical comparison to a named method, regardless of operand shape. + +For example: + +```python +# Before: overloaded == requested a Bingo exact search. +stmt = select(Compound).where(Compound.structure == "OCC") + +# After: chemical intent is explicit. +stmt = select(Compound).where(Compound.structure.equals("OCC")) + +# Negated Bingo exact search. +different = select(Compound).where( + Compound.structure.not_equals("OCC") +) +``` + +The explicit methods accept the same optional Bingo search parameters: + +```python +stereo_match = Compound.structure.equals(query, "STE") +tautomer_match = Compound.structure.equals(query, "TAU") +``` + +The standalone helpers remain available: + +```python +from molalchemy.bingo import functions as bingo_func + +mol_predicate = bingo_func.mol_equals(Compound.structure, query, "STE") +rxn_predicate = bingo_func.rxn_equals(Reaction.reaction, query_reaction) +``` + +## Storage equality is not chemical equality + +The meaning of native `==` and `!=` depends on the underlying PostgreSQL +storage type: + +| MolAlchemy type | PostgreSQL storage | Native comparison | +| --- | --- | --- | +| `BingoMol` | `varchar` | Text equality | +| `BingoReaction` | `varchar` | Text equality | +| `BingoBinaryMol` | `bytea` | Binary equality | +| `BingoBinaryReaction` | `bytea` | Binary equality | + +Chemically equivalent representations are not guaranteed to have equal +storage. For example, `CCO` and `OCC` match with Bingo exact search but compare +unequal with native text equality. Compact binary representations likewise +must not be used as a substitute for chemical equality. + +This differs from RDKit molecule columns, where PostgreSQL implements native +`=` and explicit `@=` with the same chemical `mol_eq` function. + +## Null comparisons + +`None` now follows standard SQLAlchemy semantics without comparator-specific +branches: + +```python +Compound.structure == None # IS NULL +Compound.structure != None # IS NOT NULL +``` + +Use `is_(None)` and `is_not(None)` if explicit SQL-style spelling is preferred. + +## Similarity comparator + +Molecule columns now expose `similar_to()` as the comparator equivalent of +`bingo_func.mol_similarity()`: + +```python +predicate = Compound.structure.similar_to( + query, + minimum=0.7, + maximum=1.0, + metric="Tanimoto", +) +stmt = select(Compound).where(predicate) +``` + +`similar_to()` returns a Boolean range predicate. It does not return a numeric +similarity score; use `bingo_func.getsimilarity()` when the score itself is +needed. + +## Boolean expression results + +Molecule and reaction search methods now return `ColumnElement[bool]` backed by +SQLAlchemy `Boolean`. This applies to substructure, SMARTS, exact, negated +exact, and similarity predicates. + +They can be composed and labeled like ordinary SQLAlchemy predicates: + +```python +aromatic = Compound.structure.has_substructure("c1ccccc1") +not_ethanol = Compound.structure.not_equals("CCO") + +stmt = select(Compound).where(aromatic & not_ethanol) +labeled = select(aromatic.label("is_aromatic")) +``` + +## SQL expression operands + +Search inputs can be Python literals, explicit bind parameters, Core columns, +subquery columns, or ORM mapped attributes. Scalars remain bound parameters; +SQL expressions remain expressions. + +```python +# ORM column-to-column exact search +predicate = Compound.structure.equals(Compound.reference_structure) + +# A mapped attribute can also supply search parameters. +configured = Compound.structure.equals( + Compound.reference_structure, + Compound.exact_parameters, +) +``` + +This behavior is shared by comparator methods and standalone helpers. It also +applies to the query, similarity bounds, and metric operands where their typed +interfaces accept SQL expressions. + +## Typed column helpers + +Direct comparator calls remain the runtime API. Use the typed helpers when an +editor or static analyzer needs the cartridge-specific method surface: + +```python +from molalchemy.helpers import bingo_col, bingo_rxn_col + +mol_predicate = bingo_col(Compound.structure).equals(query) +similarity = bingo_col(Compound.structure).similar_to(query, minimum=0.8) +rxn_predicate = bingo_rxn_col(Reaction.reaction).has_substructure(query_reaction) +``` + +Both helpers validate the MolAlchemy column type and return the original +SQLAlchemy column at runtime. They accept Core columns and ORM mapped +attributes. + +The old generated `BingoMolProxy` and `BingoRxnProxy` exports were +removed. Their replacements are typed protocols normally accessed through +`bingo_col()` and `bingo_rxn_col()`. + +## Unchanged APIs + +The following APIs do not require migration: + +- `has_substructure()` and `has_smarts()` method names and parameters. +- The prefixed standalone helpers such as `mol_has_substructure()`, + `mol_has_smarts()`, `rxn_has_substructure()`, and `rxn_has_smarts()`. +- Bingo type constructors, indexes, conversions, descriptors, imports, + exports, and property functions. + +## Migration checklist + +1. Replace chemical `column == query` with `column.equals(query)`. +2. Replace chemical `column != query` with `column.not_equals(query)`. +3. Keep `== None`/`!= None`, or use `is_(None)`/`is_not(None)`. +4. Treat native equality as text or binary storage equality only. +5. Optionally replace `bingo_func.mol_similarity()` with `similar_to()` when a + comparator method is clearer. +6. Replace removed proxy imports with `bingo_col()` or `bingo_rxn_col()`. diff --git a/mkdocs.yml b/mkdocs.yml index 2cb6443..63f144d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -102,6 +102,7 @@ nav: - Typed Comparator Helpers: tutorials/08_proxy_helpers.md - Contributing: tutorials/contribute.md - Migration guides: + - Bingo comparator API: migrations/bingo-comparator-api.md - RDKit comparator API: migrations/rdkit-comparator-api.md - API: - molalchemy.exceptions: api/exceptions.md From 55ae8357fd456c3ad2b4c9487b84eb23c7d06d49 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Tue, 4 Aug 2026 23:05:36 +0200 Subject: [PATCH 05/13] add rdkit setting --- README.md | 20 +- dev_scripts/validate_rdkit_helpers.py | 73 +++++- docs/api/rdkit/settings.md | 34 +++ docs/index.md | 20 +- .../04_Similarity_Threshold_Settings.ipynb | 26 ++- mkdocs.yml | 1 + src/molalchemy/rdkit/__init__.py | 4 + src/molalchemy/rdkit/settings.py | 193 +++++++++++++-- tests/rdkit/test_settings.py | 219 ++++++++++++++++++ 9 files changed, 552 insertions(+), 38 deletions(-) create mode 100644 docs/api/rdkit/settings.md diff --git a/README.md b/README.md index c5589fe..1f7af56 100644 --- a/README.md +++ b/README.md @@ -257,17 +257,31 @@ class MoleculeWithFormats(Base): structure_bytes: Mapped[bytes] = mapped_column(RdkitMol(return_type="bytes")) ``` -### Similarity Threshold Management +### RDKit Cartridge Settings -RDKit PostgreSQL uses GUC variables to control similarity search behavior. MolAlchemy provides helpers to manage these thresholds: +RDKit PostgreSQL uses GUC variables to control similarity, substructure matching, and fingerprint sizes. Use an immutable settings object to establish a baseline whenever a pooled connection is checked out: ```python +from sqlalchemy import create_engine + from molalchemy.rdkit.settings import ( + RdkitSettings, + configure_engine, get_tanimoto_threshold, set_tanimoto_threshold, similarity_threshold, ) +engine = configure_engine( + create_engine("postgresql+psycopg://localhost/chemistry"), + RdkitSettings( + tanimoto_threshold=0.5, + dice_threshold=0.5, + do_chiral_sss=True, + morgan_fp_size=2048, + ), +) + # Get/set thresholds directly print(get_tanimoto_threshold(session)) # 0.5 (default) set_tanimoto_threshold(session, 0.3) @@ -279,6 +293,8 @@ with similarity_threshold(session, tanimoto=0.1, dice=0.2): # Original thresholds are restored automatically ``` +`None` fields leave the server value unchanged. Calling `configure_engine` again replaces the previous MolAlchemy baseline, and `RdkitSettings()` removes it. See the [RDKit cartridge configuration reference](https://rdkit.org/new_docs/Cartridge.html#configuration) for the underlying settings. + ### Chemical Reactions Store and query chemical reactions using `RdkitReaction`: diff --git a/dev_scripts/validate_rdkit_helpers.py b/dev_scripts/validate_rdkit_helpers.py index 7a8e247..88a588c 100644 --- a/dev_scripts/validate_rdkit_helpers.py +++ b/dev_scripts/validate_rdkit_helpers.py @@ -19,6 +19,7 @@ from sqlalchemy.exc import OperationalError from sqlalchemy.schema import CreateTable +from molalchemy.rdkit import RdkitSettings, configure_engine from molalchemy.rdkit import functions as rdkit_func from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitMol, RdkitReaction from molalchemy.types import CString @@ -43,9 +44,75 @@ def wait_for_db(engine) -> None: def main() -> None: - engine = create_engine(DATABASE_URL, echo=False) + configured_gucs = { + "rdkit.tanimoto_threshold": "0.55", + "rdkit.dice_threshold": "0.45", + "rdkit.do_chiral_sss": "on", + "rdkit.do_enhanced_stereo_sss": "off", + "rdkit.sss_fp_size": "2048", + "rdkit.morgan_fp_size": "2048", + "rdkit.featmorgan_fp_size": "2048", + "rdkit.layered_fp_size": "2048", + "rdkit.rdkit_fp_size": "2048", + "rdkit.torsion_fp_size": "2048", + "rdkit.atompair_fp_size": "2048", + "rdkit.avalon_fp_size": "2048", + } + baseline_settings = RdkitSettings( + tanimoto_threshold=0.55, + dice_threshold=0.45, + do_chiral_sss=True, + do_enhanced_stereo_sss=False, + sss_fp_size=2048, + morgan_fp_size=2048, + featmorgan_fp_size=2048, + layered_fp_size=2048, + rdkit_fp_size=2048, + torsion_fp_size=2048, + atompair_fp_size=2048, + avalon_fp_size=2048, + ) + engine = configure_engine( + create_engine(DATABASE_URL, echo=False, pool_size=1, max_overflow=0), + baseline_settings, + ) wait_for_db(engine) + with engine.connect() as conn: + actual_gucs = { + name: conn.exec_driver_sql(f"SHOW {name}").scalar_one() + for name in configured_gucs + } + assert actual_gucs == configured_gucs + + # Prove that checkout reapplies the baseline to a reused physical connection. + with engine.begin() as conn: + conn.exec_driver_sql("SET rdkit.tanimoto_threshold = 0.13") + with engine.connect() as conn: + reapplied_tanimoto = conn.exec_driver_sql( + "SHOW rdkit.tanimoto_threshold" + ).scalar_one() + assert reapplied_tanimoto == configured_gucs["rdkit.tanimoto_threshold"] + + # Engine.dispose() replaces the pool. The baseline must follow the engine + # so that connections created by the replacement pool are configured too. + engine.dispose() + with engine.connect() as conn: + reapplied_after_dispose = conn.exec_driver_sql( + "SHOW rdkit.tanimoto_threshold" + ).scalar_one() + assert reapplied_after_dispose == configured_gucs["rdkit.tanimoto_threshold"] + + # Reconfiguration must also remove the saved listener cleanly after the + # engine has replaced its pool. + configure_engine(engine, RdkitSettings(tanimoto_threshold=0.65)) + with engine.connect() as conn: + reconfigured_after_dispose = conn.exec_driver_sql( + "SHOW rdkit.tanimoto_threshold" + ).scalar_one() + assert reconfigured_after_dispose == "0.65" + configure_engine(engine, baseline_settings) + metadata = MetaData() molecules = Table( "molalchemy_rdkit_helper_validation", @@ -246,6 +313,10 @@ def main() -> None: print() print(f"RDKit version: {version}") + print(f"configured RDKit GUCs: {actual_gucs}") + print(f"reapplied tanimoto threshold: {reapplied_tanimoto}") + print(f"reapplied after engine disposal: {reapplied_after_dispose}") + print(f"reconfigured after engine disposal: {reconfigured_after_dispose}") print(f"substructure(c1ccccc1): {substructure_rows}") print(f"mol_has_substructure(c1ccccc1): {functional_substructure_rows}") print(f"exact(CCO): {exact_rows}") diff --git a/docs/api/rdkit/settings.md b/docs/api/rdkit/settings.md new file mode 100644 index 0000000..afcc260 --- /dev/null +++ b/docs/api/rdkit/settings.md @@ -0,0 +1,34 @@ +# RDKit settings + +MolAlchemy can establish a baseline for all [RDKit PostgreSQL cartridge +settings](https://rdkit.org/new_docs/Cartridge.html#configuration) each time a +connection is checked out of a synchronous SQLAlchemy pool: + +```python +from sqlalchemy import create_engine + +from molalchemy.rdkit import RdkitSettings, configure_engine + +engine = configure_engine( + create_engine("postgresql+psycopg://localhost/chemistry"), + RdkitSettings( + tanimoto_threshold=0.5, + dice_threshold=0.5, + do_chiral_sss=True, + do_enhanced_stereo_sss=True, + morgan_fp_size=2048, + ), +) +``` + +Only non-`None` fields are changed. Reconfiguring the same engine replaces its +previous MolAlchemy listener; passing an empty `RdkitSettings()` removes that +listener. Because the baseline is applied on every checkout, a request that +changes an RDKit GUC does not permanently change the next request's pooled +connection. + +The `set_*`, `get_*`, and `similarity_threshold` helpers remain useful for +intentional, session-local threshold changes. `configure_engine` is for a pool +baseline, while those helpers are for query or unit-of-work scope. + +::: molalchemy.rdkit.settings diff --git a/docs/index.md b/docs/index.md index d5857d2..2c4f924 100644 --- a/docs/index.md +++ b/docs/index.md @@ -259,17 +259,31 @@ class MoleculeWithFormats(Base): structure_bytes: Mapped[bytes] = mapped_column(RdkitMol(return_type="bytes")) ``` -### Similarity Threshold Management +### RDKit Cartridge Settings -RDKit PostgreSQL uses GUC variables to control similarity search behavior. MolAlchemy provides helpers to manage these thresholds: +RDKit PostgreSQL uses GUC variables to control similarity, substructure matching, and fingerprint sizes. Use an immutable settings object to establish a baseline whenever a pooled connection is checked out: ```python +from sqlalchemy import create_engine + from molalchemy.rdkit.settings import ( + RdkitSettings, + configure_engine, get_tanimoto_threshold, set_tanimoto_threshold, similarity_threshold, ) +engine = configure_engine( + create_engine("postgresql+psycopg://localhost/chemistry"), + RdkitSettings( + tanimoto_threshold=0.5, + dice_threshold=0.5, + do_chiral_sss=True, + morgan_fp_size=2048, + ), +) + # Get/set thresholds directly print(get_tanimoto_threshold(session)) # 0.5 (default) set_tanimoto_threshold(session, 0.3) @@ -281,6 +295,8 @@ with similarity_threshold(session, tanimoto=0.1, dice=0.2): # Original thresholds are restored automatically ``` +`None` fields leave the server value unchanged. Calling `configure_engine` again replaces the previous MolAlchemy baseline, and `RdkitSettings()` removes it. See the [RDKit cartridge configuration reference](https://rdkit.org/new_docs/Cartridge.html#configuration) for the underlying settings. + ### Chemical Reactions Store and query chemical reactions using `RdkitReaction`: diff --git a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb index 4524436..5e35b8c 100644 --- a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb +++ b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb @@ -69,6 +69,8 @@ "\n", "from molalchemy.rdkit import functions, index, types\n", "from molalchemy.rdkit.settings import (\n", + " RdkitSettings,\n", + " configure_engine,\n", " get_dice_threshold,\n", " get_tanimoto_threshold,\n", " set_dice_threshold,\n", @@ -76,11 +78,14 @@ " similarity_threshold,\n", ")\n", "\n", - "eng = engine.create_engine(\n", - " os.environ.get(\n", - " \"RDKIT_DATABASE_URL\",\n", - " \"postgresql+psycopg://postgres:postgres@127.0.0.1:55433/postgres\",\n", - " )\n", + "eng = configure_engine(\n", + " engine.create_engine(\n", + " os.environ.get(\n", + " \"RDKIT_DATABASE_URL\",\n", + " \"postgresql+psycopg://postgres:postgres@127.0.0.1:55433/postgres\",\n", + " )\n", + " ),\n", + " RdkitSettings(tanimoto_threshold=0.5, dice_threshold=0.5),\n", ")\n", "SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=eng)\n", "with SessionLocal() as session:\n", @@ -484,12 +489,13 @@ "source": [ "## Summary\n", "\n", - "This tutorial demonstrated how to manage RDKit similarity thresholds with MolAlchemy:\n", + "This tutorial demonstrated how to manage RDKit similarity thresholds with MolAlchemy. `configure_engine` reapplies a validated baseline on every pool checkout, preventing a session-level change from leaking through a reused connection:\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", + "1. **Engine baseline**: `RdkitSettings` and `configure_engine` cover every GUC in the RDKit cartridge configuration reference\n", + "2. **GUC Variables**: `rdkit.tanimoto_threshold` and `rdkit.dice_threshold` control which molecules pass similarity operators\n", + "3. **Get/Set Helpers**: `get_tanimoto_threshold`, `set_tanimoto_threshold`, `get_dice_threshold`, `set_dice_threshold`\n", + "4. **Context Manager**: `similarity_threshold` provides temporary, exception-safe threshold changes\n", + "5. **Validation**: Invalid values raise `ValueError` or `TypeError` before reaching the database\n", "\n", "### Additional Resources\n", "\n", diff --git a/mkdocs.yml b/mkdocs.yml index 63f144d..135bdb8 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -114,6 +114,7 @@ nav: - rdkit.types: api/rdkit/types.md - rdkit.functions: api/rdkit/functions.md - rdkit.index: api/rdkit/db_index.md + - rdkit.settings: api/rdkit/settings.md - Cartridge Manuals: - Bingo PostgreSQL: bingo-postgres-manual.md - RDKit PostgreSQL: rdkit-postgres-manual.md diff --git a/src/molalchemy/rdkit/__init__.py b/src/molalchemy/rdkit/__init__.py index 0110356..57a27a8 100644 --- a/src/molalchemy/rdkit/__init__.py +++ b/src/molalchemy/rdkit/__init__.py @@ -1,6 +1,8 @@ from .comparators import RdkitFPComparator, RdkitMolComparator, RdkitReactionComparator from .index import RdkitIndex from .settings import ( + RdkitSettings, + configure_engine, get_dice_threshold, get_tanimoto_threshold, set_dice_threshold, @@ -25,8 +27,10 @@ "RdkitQMol", "RdkitReaction", "RdkitReactionComparator", + "RdkitSettings", "RdkitSparseFingerprint", "RdkitXQMol", + "configure_engine", "get_dice_threshold", "get_tanimoto_threshold", "set_dice_threshold", diff --git a/src/molalchemy/rdkit/settings.py b/src/molalchemy/rdkit/settings.py index ba695b4..2d42e80 100644 --- a/src/molalchemy/rdkit/settings.py +++ b/src/molalchemy/rdkit/settings.py @@ -1,33 +1,192 @@ -"""RDKit PostgreSQL GUC settings helpers for similarity search thresholds.""" +"""RDKit PostgreSQL cartridge settings helpers.""" from __future__ import annotations from contextlib import contextmanager -from typing import TYPE_CHECKING +from dataclasses import dataclass, fields +from threading import RLock +from typing import TYPE_CHECKING, Any +from weakref import WeakKeyDictionary -from sqlalchemy import text +from sqlalchemy import event, text +from sqlalchemy.engine import Engine if TYPE_CHECKING: - from collections.abc import Generator + from collections.abc import Callable, 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__}") +_GUC_NAMES = { + "tanimoto_threshold": "rdkit.tanimoto_threshold", + "dice_threshold": "rdkit.dice_threshold", + "do_chiral_sss": "rdkit.do_chiral_sss", + "do_enhanced_stereo_sss": "rdkit.do_enhanced_stereo_sss", + "sss_fp_size": "rdkit.sss_fp_size", + "morgan_fp_size": "rdkit.morgan_fp_size", + "featmorgan_fp_size": "rdkit.featmorgan_fp_size", + "layered_fp_size": "rdkit.layered_fp_size", + "rdkit_fp_size": "rdkit.rdkit_fp_size", + "torsion_fp_size": "rdkit.torsion_fp_size", + "atompair_fp_size": "rdkit.atompair_fp_size", + "avalon_fp_size": "rdkit.avalon_fp_size", +} +_THRESHOLD_FIELDS = frozenset(("tanimoto_threshold", "dice_threshold")) +_BOOLEAN_FIELDS = frozenset(("do_chiral_sss", "do_enhanced_stereo_sss")) +_SIZE_FIELDS = frozenset(_GUC_NAMES) - _THRESHOLD_FIELDS - _BOOLEAN_FIELDS + + +def _validate_threshold(value: float, name: str = "threshold") -> None: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError(f"{name} 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}") + raise ValueError(f"{name} must be between 0.0 and 1.0, got {value}") + + +@dataclass(frozen=True, slots=True) +class RdkitSettings: + """Baseline RDKit cartridge settings for SQLAlchemy engine connections. + + Every field corresponds to a PostgreSQL GUC documented by the RDKit + cartridge. ``None`` means that the server or connection's existing value + is left unchanged. Thresholds must be between 0 and 1, fingerprint sizes + must be positive integers, and substructure-search flags must be booleans. + + Use :func:`configure_engine` to apply an instance to an engine's pooled + connections on every checkout. + """ + + tanimoto_threshold: float | None = None + dice_threshold: float | None = None + do_chiral_sss: bool | None = None + do_enhanced_stereo_sss: bool | None = None + sss_fp_size: int | None = None + morgan_fp_size: int | None = None + featmorgan_fp_size: int | None = None + layered_fp_size: int | None = None + rdkit_fp_size: int | None = None + torsion_fp_size: int | None = None + atompair_fp_size: int | None = None + avalon_fp_size: int | None = None + + def __post_init__(self) -> None: + for field in fields(self): + value = getattr(self, field.name) + if value is None: + continue + if field.name in _THRESHOLD_FIELDS: + _validate_threshold(value, field.name) + elif field.name in _BOOLEAN_FIELDS: + if type(value) is not bool: + raise TypeError( + f"{field.name} must be a bool, got {type(value).__name__}" + ) + elif field.name in _SIZE_FIELDS: + if type(value) is not int: + raise TypeError( + f"{field.name} must be an int, got {type(value).__name__}" + ) + if value <= 0: + raise ValueError( + f"{field.name} must be greater than 0, got {value}" + ) + + def _guc_values(self) -> tuple[tuple[str, str], ...]: + values: list[tuple[str, str]] = [] + for field in fields(self): + value = getattr(self, field.name) + if value is None: + continue + if field.name in _BOOLEAN_FIELDS: + serialized = "on" if value else "off" + elif field.name in _THRESHOLD_FIELDS: + serialized = str(float(value)) + else: + serialized = str(value) + values.append((_GUC_NAMES[field.name], serialized)) + return tuple(values) + + +if TYPE_CHECKING: + _CheckoutListener = Callable[[Any, Any, Any], None] +else: + _CheckoutListener = Any + +_engine_listeners: WeakKeyDictionary[Engine, _CheckoutListener] = WeakKeyDictionary() +_engine_listeners_lock = RLock() + + +def _make_checkout_listener( + values: tuple[tuple[str, str], ...], +) -> _CheckoutListener: + placeholders = ", ".join("set_config(%s, %s, false)" for _ in values) + statement = f"SELECT {placeholders}" + parameters = tuple(item for pair in values for item in pair) + + def apply_settings(dbapi_connection: Any, _record: Any, _proxy: Any) -> None: + previous_autocommit = dbapi_connection.autocommit + cursor = None + try: + dbapi_connection.autocommit = True + cursor = dbapi_connection.cursor() + cursor.execute(statement, parameters) + finally: + try: + if cursor is not None: + cursor.close() + finally: + dbapi_connection.autocommit = previous_autocommit + + return apply_settings + + +def configure_engine(engine: Engine, settings: RdkitSettings | None = None) -> Engine: + """Apply an RDKit settings baseline whenever a pooled connection is checked out. + + Calling this function again for the same engine replaces its previous + molalchemy listener. Passing an empty :class:`RdkitSettings` removes any + previous listener. The engine itself is returned for convenient assignment. + + Parameters + ---------- + engine + A synchronous SQLAlchemy PostgreSQL engine. + settings + Validated RDKit cartridge settings. Fields set to ``None`` are not sent + to PostgreSQL. + """ + if not isinstance(engine, Engine): + raise TypeError(f"engine must be an Engine, got {type(engine).__name__}") + if engine.dialect.name != "postgresql": + raise ValueError("RDKit cartridge settings require a PostgreSQL engine") + if not isinstance(settings, RdkitSettings) and settings is not None: + raise TypeError( + f"settings must be RdkitSettings, got {type(settings).__name__}" + ) + if settings is None: + return engine + values = settings._guc_values() + listener = _make_checkout_listener(values) if values else None + + with _engine_listeners_lock: + previous_listener = _engine_listeners.pop(engine, None) + if previous_listener is not None: + event.remove(engine, "checkout", previous_listener) + if listener is not None: + event.listen(engine, "checkout", listener) + _engine_listeners[engine] = listener + + return engine def set_tanimoto_threshold(session: Session, threshold: float) -> None: - """Set the rdkit.tanimoto_threshold GUC variable.""" + """Set the rdkit.tanimoto_threshold GUC variable for a session.""" _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.""" + """Set the rdkit.dice_threshold GUC variable for a session.""" _validate_threshold(threshold) session.execute(text(f"SET rdkit.dice_threshold = {float(threshold)}")) @@ -51,19 +210,7 @@ def similarity_threshold( 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). - """ + """Temporarily set and then restore session similarity thresholds.""" old_tanimoto = None old_dice = None diff --git a/tests/rdkit/test_settings.py b/tests/rdkit/test_settings.py index 1b02057..ecd674b 100644 --- a/tests/rdkit/test_settings.py +++ b/tests/rdkit/test_settings.py @@ -3,8 +3,12 @@ from unittest.mock import Mock import pytest +from sqlalchemy import create_engine +import molalchemy.rdkit.settings as settings_module from molalchemy.rdkit.settings import ( + RdkitSettings, + configure_engine, get_dice_threshold, get_tanimoto_threshold, set_dice_threshold, @@ -20,6 +24,221 @@ def session(): return mock +@pytest.fixture +def postgres_engine(monkeypatch): + engine = create_engine("sqlite://") + monkeypatch.setattr(engine.dialect, "name", "postgresql") + yield engine + settings_module._engine_listeners.pop(engine, None) + engine.dispose() + + +class TestRdkitSettings: + def test_serializes_every_documented_setting(self): + settings = RdkitSettings( + tanimoto_threshold=0.7, + dice_threshold=1, + do_chiral_sss=True, + do_enhanced_stereo_sss=False, + sss_fp_size=1024, + morgan_fp_size=2048, + featmorgan_fp_size=2049, + layered_fp_size=2050, + rdkit_fp_size=2051, + torsion_fp_size=2052, + atompair_fp_size=2053, + avalon_fp_size=2054, + ) + + assert settings._guc_values() == ( + ("rdkit.tanimoto_threshold", "0.7"), + ("rdkit.dice_threshold", "1.0"), + ("rdkit.do_chiral_sss", "on"), + ("rdkit.do_enhanced_stereo_sss", "off"), + ("rdkit.sss_fp_size", "1024"), + ("rdkit.morgan_fp_size", "2048"), + ("rdkit.featmorgan_fp_size", "2049"), + ("rdkit.layered_fp_size", "2050"), + ("rdkit.rdkit_fp_size", "2051"), + ("rdkit.torsion_fp_size", "2052"), + ("rdkit.atompair_fp_size", "2053"), + ("rdkit.avalon_fp_size", "2054"), + ) + + @pytest.mark.parametrize("field", ["tanimoto_threshold", "dice_threshold"]) + @pytest.mark.parametrize("value", [-0.1, 1.1]) + def test_rejects_out_of_range_thresholds(self, field, value): + with pytest.raises(ValueError, match=field): + RdkitSettings(**{field: value}) + + @pytest.mark.parametrize("field", ["tanimoto_threshold", "dice_threshold"]) + @pytest.mark.parametrize("value", [True, "0.5"]) + def test_rejects_non_numeric_thresholds(self, field, value): + with pytest.raises(TypeError, match=field): + RdkitSettings(**{field: value}) + + @pytest.mark.parametrize( + "field", ["do_chiral_sss", "do_enhanced_stereo_sss"] + ) + @pytest.mark.parametrize("value", [0, 1, "on"]) + def test_rejects_non_boolean_flags(self, field, value): + with pytest.raises(TypeError, match=field): + RdkitSettings(**{field: value}) + + @pytest.mark.parametrize( + "field", + [ + "sss_fp_size", + "morgan_fp_size", + "featmorgan_fp_size", + "layered_fp_size", + "rdkit_fp_size", + "torsion_fp_size", + "atompair_fp_size", + "avalon_fp_size", + ], + ) + @pytest.mark.parametrize("value", [True, 1.5, "2048"]) + def test_rejects_non_integer_fingerprint_sizes(self, field, value): + with pytest.raises(TypeError, match=field): + RdkitSettings(**{field: value}) + + @pytest.mark.parametrize("value", [0, -1]) + def test_rejects_non_positive_fingerprint_sizes(self, value): + with pytest.raises(ValueError, match="morgan_fp_size"): + RdkitSettings(morgan_fp_size=value) + + +class TestConfigureEngine: + def test_returns_engine_and_registers_parameterized_checkout_listener( + self, postgres_engine, monkeypatch + ): + registered = [] + monkeypatch.setattr( + settings_module.event, + "listen", + lambda target, name, listener: registered.append((target, name, listener)), + ) + + result = configure_engine( + postgres_engine, + RdkitSettings( + tanimoto_threshold=0.42, + do_chiral_sss=True, + morgan_fp_size=1024, + ), + ) + + assert result is postgres_engine + assert len(registered) == 1 + assert registered[0][:2] == (postgres_engine, "checkout") + + cursor = Mock() + dbapi_connection = Mock() + dbapi_connection.autocommit = False + dbapi_connection.cursor.return_value = cursor + registered[0][2](dbapi_connection, Mock(), Mock()) + + statement, parameters = cursor.execute.call_args.args + assert statement.count("set_config(%s, %s, false)") == 3 + assert parameters == ( + "rdkit.tanimoto_threshold", + "0.42", + "rdkit.do_chiral_sss", + "on", + "rdkit.morgan_fp_size", + "1024", + ) + cursor.close.assert_called_once_with() + assert dbapi_connection.autocommit is False + + def test_reconfiguration_replaces_previous_listener( + self, postgres_engine, monkeypatch + ): + registered = [] + removed = [] + monkeypatch.setattr( + settings_module.event, + "listen", + lambda target, name, listener: registered.append(listener), + ) + monkeypatch.setattr( + settings_module.event, + "remove", + lambda target, name, listener: removed.append(listener), + ) + + configure_engine(postgres_engine, RdkitSettings(tanimoto_threshold=0.4)) + configure_engine(postgres_engine, RdkitSettings(dice_threshold=0.6)) + + assert len(registered) == 2 + assert removed == [registered[0]] + + def test_empty_settings_remove_listener_without_registering_another( + self, postgres_engine, monkeypatch + ): + registered = [] + removed = [] + monkeypatch.setattr( + settings_module.event, + "listen", + lambda target, name, listener: registered.append(listener), + ) + monkeypatch.setattr( + settings_module.event, + "remove", + lambda target, name, listener: removed.append(listener), + ) + + configure_engine(postgres_engine, RdkitSettings(dice_threshold=0.6)) + configure_engine(postgres_engine, RdkitSettings()) + + assert len(registered) == 1 + assert removed == registered + + def test_reconfiguration_survives_engine_dispose(self, postgres_engine): + configure_engine( + postgres_engine, RdkitSettings(tanimoto_threshold=0.4) + ) + original_pool = postgres_engine.pool + + postgres_engine.dispose() + + assert postgres_engine.pool is not original_pool + configure_engine(postgres_engine, RdkitSettings(tanimoto_threshold=0.6)) + configure_engine(postgres_engine, RdkitSettings()) + + def test_listener_restores_connection_state_after_execute_error( + self, postgres_engine, monkeypatch + ): + registered = [] + monkeypatch.setattr( + settings_module.event, + "listen", + lambda target, name, listener: registered.append(listener), + ) + configure_engine(postgres_engine, RdkitSettings(dice_threshold=0.6)) + cursor = Mock() + cursor.execute.side_effect = RuntimeError("database error") + dbapi_connection = Mock() + dbapi_connection.autocommit = False + dbapi_connection.cursor.return_value = cursor + + with pytest.raises(RuntimeError, match="database error"): + registered[0](dbapi_connection, Mock(), Mock()) + + cursor.close.assert_called_once_with() + assert dbapi_connection.autocommit is False + + def test_rejects_non_postgresql_engine(self): + engine = create_engine("sqlite://") + try: + with pytest.raises(ValueError, match="PostgreSQL"): + configure_engine(engine, RdkitSettings(tanimoto_threshold=0.5)) + finally: + engine.dispose() + + class TestSetTanimotoThreshold: def test_sets_threshold(self, session): set_tanimoto_threshold(session, 0.7) From 15fa2931df051016e3e0c95a82c7ac2c67d9b3fa Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Tue, 4 Aug 2026 23:18:35 +0200 Subject: [PATCH 06/13] fix ty --- CONTRIBUTING.md | 2 +- docs/CONTRIBUTING.md | 2 +- docs/index.md | 2 -- pyproject.toml | 1 + src/molalchemy/bingo/search.py | 6 +++++- src/molalchemy/rdkit/types.py | 2 +- uv.lock | 11 +++++++++++ 7 files changed, 20 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f76ae2b..9acf09e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -236,7 +236,7 @@ git commit -m "test: add edge cases for similarity functions" - [ ] Tests pass: `uv run pytest` - [ ] Code is formatted: `uv run ruff format .` - [ ] Linting passes: `uv run ruff check .` -- [ ] Focused type checking passes with `uv run ty check` +- [ ] Focused type checking passes: `uv run ty check src` - [ ] Documentation builds: `uv run mkdocs serve` - [ ] Changelog updated (if applicable) diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index f76ae2b..9acf09e 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -236,7 +236,7 @@ git commit -m "test: add edge cases for similarity functions" - [ ] Tests pass: `uv run pytest` - [ ] Code is formatted: `uv run ruff format .` - [ ] Linting passes: `uv run ruff check .` -- [ ] Focused type checking passes with `uv run ty check` +- [ ] Focused type checking passes: `uv run ty check src` - [ ] Documentation builds: `uv run mkdocs serve` - [ ] Changelog updated (if applicable) diff --git a/docs/index.md b/docs/index.md index 2c4f924..1f7af56 100644 --- a/docs/index.md +++ b/docs/index.md @@ -106,7 +106,6 @@ molalchemy/ │ ├── types.py # RDKit-specific types │ ├── index.py # RDKit indexing │ ├── comparators.py # SQLAlchemy comparators -│ ├── search.py # Shared expression builders │ ├── settings.py # Similarity threshold management │ └── functions/ # RDKit database functions ├── tests/ # Test suite @@ -183,7 +182,6 @@ from molalchemy.rdkit.functions import ( ) from molalchemy.helpers import ( rdkit_col, # Typed molecule-column helper for IDE autocomplete - rdkit_fp_col, # Typed fingerprint-column helper rdkit_rxn_col, # Typed reaction-column helper for IDE autocomplete ) ``` diff --git a/pyproject.toml b/pyproject.toml index a459302..35d925a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,7 @@ dev = [ "pytest>=8.4.2", "pytest-cov>=7.0.0", "pyyaml>=6.0.2", + "rdkit-stubs>=0.8", "ruff==0.14.5", "ty>=0.0.66", ] diff --git a/src/molalchemy/bingo/search.py b/src/molalchemy/bingo/search.py index b08ab6f..a0d5076 100644 --- a/src/molalchemy/bingo/search.py +++ b/src/molalchemy/bingo/search.py @@ -55,4 +55,8 @@ def _bingo_search_values( ``tuple_`` binds scalar values while honoring ``__clause_element__`` on ORM attributes and other SQL expression objects. """ - return _bingo_search(column, tuple_(*values), search_type) + return _bingo_search( + column, + tuple_(*values), # ty: ignore[invalid-argument-type] + search_type, + ) diff --git a/src/molalchemy/rdkit/types.py b/src/molalchemy/rdkit/types.py index 804ec99..dd19a03 100644 --- a/src/molalchemy/rdkit/types.py +++ b/src/molalchemy/rdkit/types.py @@ -77,7 +77,7 @@ def process(value): raise InvalidMoleculeError( "Value must be a SMILES string or an RDKit Mol object" ) - return value.ToBinary() + return value.ToBinary() # ty: ignore[no-matching-overload] return process diff --git a/uv.lock b/uv.lock index 9d0cbc0..a3fcb40 100644 --- a/uv.lock +++ b/uv.lock @@ -1136,6 +1136,7 @@ dev = [ { name = "pytest" }, { name = "pytest-cov" }, { name = "pyyaml" }, + { name = "rdkit-stubs" }, { name = "ruff" }, { name = "ty" }, ] @@ -1165,6 +1166,7 @@ dev = [ { name = "pytest", specifier = ">=8.4.2" }, { name = "pytest-cov", specifier = ">=7.0.0" }, { name = "pyyaml", specifier = ">=6.0.2" }, + { name = "rdkit-stubs", specifier = ">=0.8" }, { name = "ruff", specifier = "==0.14.5" }, { name = "ty", specifier = ">=0.0.66" }, ] @@ -1961,6 +1963,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/37/1d/415fcfdc96c0453d02d8265684083bfac45425c52aeee64aadc330aa6f66/rdkit-2025.3.6-cp314-cp314-win_amd64.whl", hash = "sha256:600d7fc3a2665baa9de7ec6870f33a53027f532f9a47e5df765ac91539c7e746", size = 24004467, upload-time = "2025-09-05T12:47:33.743Z" }, ] +[[package]] +name = "rdkit-stubs" +version = "0.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/af/e0/67632bd3811b1d24b9eb912912321003ad7ab02b0ac93dd6c955840ec537/rdkit-stubs-0.8.tar.gz", hash = "sha256:2af5a1dcccdc85e598fda9b7f7ad3cc8bd6bc32fc55414a98d9fa69f85c12549", size = 101706, upload-time = "2024-09-19T18:43:50.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/0f/90088510d4758e0ee475ae1fc7f96e7bccd0e31f24107567075482b2fe9e/rdkit_stubs-0.8-py3-none-any.whl", hash = "sha256:1d58bcc604181b52713d62d5904386b1682c42b9694ddb20ceb81d3b896ccbd0", size = 186615, upload-time = "2024-09-19T18:43:49.101Z" }, +] + [[package]] name = "referencing" version = "0.36.2" From 4e655ff27759045ecac4e560812db094945c6c7c Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Wed, 5 Aug 2026 19:40:25 +0200 Subject: [PATCH 07/13] fix is_query_substructure_of --- dev_scripts/validate_rdkit_helpers.py | 191 +++++++++++++++++++++++--- src/molalchemy/rdkit/comparators.py | 8 +- tests/rdkit/test_comparators.py | 7 + 3 files changed, 186 insertions(+), 20 deletions(-) diff --git a/dev_scripts/validate_rdkit_helpers.py b/dev_scripts/validate_rdkit_helpers.py index 88a588c..3f768e1 100644 --- a/dev_scripts/validate_rdkit_helpers.py +++ b/dev_scripts/validate_rdkit_helpers.py @@ -19,7 +19,13 @@ from sqlalchemy.exc import OperationalError from sqlalchemy.schema import CreateTable -from molalchemy.rdkit import RdkitSettings, configure_engine +from molalchemy.rdkit import ( + RdkitFPComparator, + RdkitMolComparator, + RdkitReactionComparator, + RdkitSettings, + configure_engine, +) from molalchemy.rdkit import functions as rdkit_func from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitMol, RdkitReaction from molalchemy.types import CString @@ -30,6 +36,15 @@ ) +def declared_comparator_methods(comparator: type) -> set[str]: + """Return methods declared directly on a comparator, excluding internals.""" + return { + name + for name, value in vars(comparator).items() + if not name.startswith("_") and callable(value) + } + + def wait_for_db(engine) -> None: deadline = time.monotonic() + 60 while True: @@ -180,6 +195,16 @@ def main() -> None: .where(molecules.c.mol.has_substructure("c1ccccc1")) .order_by(molecules.c.id) ) + smarts_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol.has_smarts("[CH3][CH2][OH]")) + .order_by(molecules.c.id) + ) + reverse_substructure_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol.is_substructure_of("CCO")) + .order_by(molecules.c.id) + ) functional_substructure_stmt = ( select(molecules.c.name) .where(rdkit_func.mol_has_substructure(molecules.c.mol, "c1ccccc1")) @@ -206,6 +231,17 @@ def main() -> None: .where(molecules.c.mol.not_equals("OCC")) .order_by(molecules.c.id) ) + query_mol = rdkit_func.qmol_from_smiles(cast("CCO", CString)) + query_substructure_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol.has_query_substructure(query_mol)) + .order_by(molecules.c.id) + ) + reverse_query_substructure_stmt = ( + select(molecules.c.name) + .where(molecules.c.mol.is_query_substructure_of(query_mol)) + .order_by(molecules.c.id) + ) query_fp = rdkit_func.morganbv_fp(rdkit_func.mol_from_smiles("CCO")) tanimoto_stmt = select(molecules.c.name).where( molecules.c.morgan_fp.tanimoto_matches(query_fp) @@ -258,12 +294,80 @@ def main() -> None: reaction_explicit_not_equals_stmt = select(nullable_reactions.c.name).where( nullable_reactions.c.rxn.not_equals("CCN>>CC=N") ) + reaction_substructure_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.has_substructure("CCO>>CC=O") + ) + reaction_reverse_substructure_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.is_substructure_of("CCO>>CC=O") + ) + reaction_smarts_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.has_smarts("CCO>>CC=O") + ) + reaction_substructure_fp_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.has_substructure_fp("CCO>>CC=O") + ) + reaction_reverse_substructure_fp_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.is_substructure_fp_of("CCO>>CC=O") + ) + + comparator_statements = { + ("RdkitMolComparator", "has_substructure"): substructure_stmt, + ("RdkitMolComparator", "has_smarts"): smarts_stmt, + ("RdkitMolComparator", "is_substructure_of"): reverse_substructure_stmt, + ("RdkitMolComparator", "equals"): explicit_equivalent_stmt, + ("RdkitMolComparator", "not_equals"): explicit_not_equivalent_stmt, + ("RdkitMolComparator", "has_query_substructure"): query_substructure_stmt, + ( + "RdkitMolComparator", + "is_query_substructure_of", + ): reverse_query_substructure_stmt, + ("RdkitReactionComparator", "has_substructure"): reaction_substructure_stmt, + ( + "RdkitReactionComparator", + "is_substructure_of", + ): reaction_reverse_substructure_stmt, + ("RdkitReactionComparator", "equals"): reaction_explicit_equals_stmt, + ( + "RdkitReactionComparator", + "not_equals", + ): reaction_explicit_not_equals_stmt, + ("RdkitReactionComparator", "has_smarts"): reaction_smarts_stmt, + ( + "RdkitReactionComparator", + "has_substructure_fp", + ): reaction_substructure_fp_stmt, + ( + "RdkitReactionComparator", + "is_substructure_fp_of", + ): reaction_reverse_substructure_fp_stmt, + ("RdkitFPComparator", "tanimoto_matches"): tanimoto_stmt, + ("RdkitFPComparator", "dice_matches"): dice_stmt, + ("RdkitFPComparator", "tanimoto_distance"): tanimoto_knn_stmt, + ("RdkitFPComparator", "dice_distance"): dice_knn_stmt, + } + comparator_classes = ( + RdkitMolComparator, + RdkitReactionComparator, + RdkitFPComparator, + ) + declared_methods = { + (comparator.__name__, method) + for comparator in comparator_classes + for method in declared_comparator_methods(comparator) + } + assert comparator_statements.keys() == declared_methods, ( + "live comparator coverage mismatch: " + f"missing={sorted(declared_methods - comparator_statements.keys())}, " + f"unexpected={sorted(comparator_statements.keys() - declared_methods)}" + ) print(str(CreateTable(molecules).compile(dialect=postgresql.dialect()))) print(str(CreateTable(nullable_molecules).compile(dialect=postgresql.dialect()))) print(str(CreateTable(nullable_reactions).compile(dialect=postgresql.dialect()))) print() print(substructure_stmt.compile(dialect=postgresql.dialect())) + print(smarts_stmt.compile(dialect=postgresql.dialect())) + print(reverse_substructure_stmt.compile(dialect=postgresql.dialect())) print(functional_substructure_stmt.compile(dialect=postgresql.dialect())) print(exact_stmt.compile(dialect=postgresql.dialect())) print(native_equivalent_stmt.compile(dialect=postgresql.dialect())) @@ -279,37 +383,50 @@ def main() -> None: print(reaction_null_stmt.compile(dialect=postgresql.dialect())) print(reaction_explicit_equals_stmt.compile(dialect=postgresql.dialect())) print(reaction_explicit_not_equals_stmt.compile(dialect=postgresql.dialect())) + print(query_substructure_stmt.compile(dialect=postgresql.dialect())) + print(reverse_query_substructure_stmt.compile(dialect=postgresql.dialect())) + print(reaction_substructure_stmt.compile(dialect=postgresql.dialect())) + print(reaction_reverse_substructure_stmt.compile(dialect=postgresql.dialect())) + print(reaction_smarts_stmt.compile(dialect=postgresql.dialect())) + print(reaction_substructure_fp_stmt.compile(dialect=postgresql.dialect())) + print(reaction_reverse_substructure_fp_stmt.compile(dialect=postgresql.dialect())) with engine.connect() as conn: version = conn.exec_driver_sql("SELECT rdkit_version()").scalar_one() - substructure_rows = conn.execute(substructure_stmt).scalars().all() + comparator_results = { + name: conn.execute(statement).scalars().all() + for name, statement in comparator_statements.items() + } + substructure_rows = comparator_results[ + ("RdkitMolComparator", "has_substructure") + ] functional_substructure_rows = ( conn.execute(functional_substructure_stmt).scalars().all() ) exact_rows = conn.execute(exact_stmt).scalars().all() native_equivalent_rows = conn.execute(native_equivalent_stmt).scalars().all() - explicit_equivalent_rows = ( - conn.execute(explicit_equivalent_stmt).scalars().all() - ) + explicit_equivalent_rows = comparator_results[("RdkitMolComparator", "equals")] native_not_equivalent_rows = ( conn.execute(native_not_equivalent_stmt).scalars().all() ) - explicit_not_equivalent_rows = ( - conn.execute(explicit_not_equivalent_stmt).scalars().all() - ) - tanimoto_rows = conn.execute(tanimoto_stmt).scalars().all() - dice_rows = conn.execute(dice_stmt).scalars().all() - tanimoto_knn_rows = conn.execute(tanimoto_knn_stmt).scalars().all() - dice_knn_rows = conn.execute(dice_knn_stmt).scalars().all() + explicit_not_equivalent_rows = comparator_results[ + ("RdkitMolComparator", "not_equals") + ] + tanimoto_rows = comparator_results[("RdkitFPComparator", "tanimoto_matches")] + dice_rows = comparator_results[("RdkitFPComparator", "dice_matches")] + tanimoto_knn_rows = comparator_results[ + ("RdkitFPComparator", "tanimoto_distance") + ] + dice_knn_rows = comparator_results[("RdkitFPComparator", "dice_distance")] function_row = conn.execute(function_stmt).mappings().one() molecule_null_rows = conn.execute(molecule_null_stmt).scalars().all() reaction_null_rows = conn.execute(reaction_null_stmt).scalars().all() - reaction_explicit_equals_rows = ( - conn.execute(reaction_explicit_equals_stmt).scalars().all() - ) - reaction_explicit_not_equals_rows = ( - conn.execute(reaction_explicit_not_equals_stmt).scalars().all() - ) + reaction_explicit_equals_rows = comparator_results[ + ("RdkitReactionComparator", "equals") + ] + reaction_explicit_not_equals_rows = comparator_results[ + ("RdkitReactionComparator", "not_equals") + ] print() print(f"RDKit version: {version}") @@ -336,6 +453,8 @@ def main() -> None: f"{reaction_explicit_equals_rows}" ) print(f"explicit reaction inequality: {reaction_explicit_not_equals_rows}") + for comparator_method, rows in comparator_results.items(): + print(f"live comparator {'.'.join(comparator_method)}: {rows}") assert substructure_rows == ["benzene", "aspirin"] assert functional_substructure_rows == ["benzene", "aspirin"] @@ -369,6 +488,42 @@ def main() -> None: # unimplemented operator shell in the cartridge versions covered here. assert reaction_explicit_equals_rows == ["ethanol oxidation"] assert reaction_explicit_not_equals_rows == ["ethanol oxidation"] + expected_comparator_results = { + ("RdkitMolComparator", "has_substructure"): ["benzene", "aspirin"], + ("RdkitMolComparator", "has_smarts"): ["ethanol"], + ("RdkitMolComparator", "is_substructure_of"): ["ethanol"], + ("RdkitMolComparator", "equals"): ["ethanol"], + ("RdkitMolComparator", "not_equals"): ["benzene", "aspirin"], + ("RdkitMolComparator", "has_query_substructure"): ["ethanol", "aspirin"], + ("RdkitMolComparator", "is_query_substructure_of"): [ + "ethanol", + "aspirin", + ], + ("RdkitReactionComparator", "has_substructure"): ["ethanol oxidation"], + ("RdkitReactionComparator", "is_substructure_of"): ["ethanol oxidation"], + ("RdkitReactionComparator", "equals"): ["ethanol oxidation"], + ("RdkitReactionComparator", "not_equals"): ["ethanol oxidation"], + ("RdkitReactionComparator", "has_smarts"): ["ethanol oxidation"], + ("RdkitReactionComparator", "has_substructure_fp"): ["ethanol oxidation"], + ( + "RdkitReactionComparator", + "is_substructure_fp_of", + ): ["ethanol oxidation"], + ("RdkitFPComparator", "tanimoto_matches"): ["ethanol"], + ("RdkitFPComparator", "dice_matches"): ["ethanol"], + ("RdkitFPComparator", "tanimoto_distance"): [ + "ethanol", + "aspirin", + "benzene", + ], + ("RdkitFPComparator", "dice_distance"): [ + "ethanol", + "aspirin", + "benzene", + ], + } + assert comparator_results == expected_comparator_results + print(f"validated all {len(declared_methods)} declared RDKit comparator methods") if __name__ == "__main__": diff --git a/src/molalchemy/rdkit/comparators.py b/src/molalchemy/rdkit/comparators.py index 66a5e36..b00c8c2 100644 --- a/src/molalchemy/rdkit/comparators.py +++ b/src/molalchemy/rdkit/comparators.py @@ -1,3 +1,5 @@ +from typing import Any, cast + from sqlalchemy import ColumnElement from sqlalchemy.types import UserDefinedType @@ -41,8 +43,10 @@ def has_query_substructure(self, query: SqlOperand) -> ColumnElement[bool]: return _rdkit_predicate(self.expr, "@>>", query) def is_query_substructure_of(self, query: SqlOperand) -> ColumnElement[bool]: - """Check if query structure `query` contains this molecule (<<@).""" - return _rdkit_predicate(self.expr, "<<@", query) + """Apply the reverse query-substructure spelling (`query <<@ molecule`).""" + # RDKit declares this reverse operator as qmol/xqmol <<@ mol, unlike + # the forward mol @>> qmol spelling. + return _rdkit_predicate(cast(ColumnElement[Any], query), "<<@", self.expr) class RdkitReactionComparator(UserDefinedType.Comparator): diff --git a/tests/rdkit/test_comparators.py b/tests/rdkit/test_comparators.py index 5db85fb..3b40d3d 100644 --- a/tests/rdkit/test_comparators.py +++ b/tests/rdkit/test_comparators.py @@ -87,6 +87,13 @@ def test_molecule_smarts_is_boolean(columns): assert "@>" in sql(expression) +def test_reverse_query_substructure_puts_query_on_the_left(columns): + query = cast("[cH]", RdkitQMol) + expression = columns.mol.is_query_substructure_of(query) + + assert sql(expression).startswith("CAST(:param_1 AS qmol) <<@ rdkit_values.mol") + + @pytest.mark.parametrize( ("method", "operator"), [ From f4ded0569b7d30442918c48266a3f856ab132197 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Wed, 5 Aug 2026 19:45:32 +0200 Subject: [PATCH 08/13] extend bingo tests --- dev_scripts/validate_bingo_helpers.py | 86 ++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 3 deletions(-) diff --git a/dev_scripts/validate_bingo_helpers.py b/dev_scripts/validate_bingo_helpers.py index a4a6963..30597b5 100644 --- a/dev_scripts/validate_bingo_helpers.py +++ b/dev_scripts/validate_bingo_helpers.py @@ -17,6 +17,7 @@ from sqlalchemy.exc import OperationalError from sqlalchemy.schema import CreateTable +from molalchemy.bingo import BingoMolComparator, BingoRxnComparator from molalchemy.bingo import functions as bingo_func from molalchemy.bingo.types import BingoBinaryReaction, BingoMol @@ -26,6 +27,15 @@ ) +def declared_comparator_methods(comparator: type) -> set[str]: + """Return methods declared directly on a comparator, excluding internals.""" + return { + name + for name, value in vars(comparator).items() + if not name.startswith("_") and callable(value) + } + + def wait_for_db(engine) -> None: deadline = time.monotonic() + 60 while True: @@ -111,6 +121,17 @@ def main() -> None: substructure_stmt = select(compounds.c.name).where( compounds.c.structure.has_substructure("c1ccccc1") ) + comparator_smarts_stmt = select(compounds.c.name).where( + compounds.c.structure.has_smarts("[#6]-[#8]") + ) + comparator_equals_stmt = select(compounds.c.name).where( + compounds.c.structure.equals("OCC") + ) + comparator_not_equals_stmt = ( + select(compounds.c.name) + .where(compounds.c.structure.not_equals("CCO")) + .order_by(compounds.c.id) + ) exact_stmt = select(compounds.c.name).where( bingo_func.mol_equals(compounds.c.structure, "CCO") ) @@ -157,6 +178,15 @@ def main() -> None: reaction_exact_stmt = select(reactions.c.name).where( reactions.c.reaction_data.equals("CCO>>CC=O") ) + reaction_substructure_stmt = select(reactions.c.name).where( + reactions.c.reaction_data.has_substructure("CCO>>CC=O") + ) + reaction_smarts_stmt = select(reactions.c.name).where( + reactions.c.reaction_data.has_smarts("CCO>>CC=O") + ) + reaction_not_equals_stmt = select(reactions.c.name).where( + reactions.c.reaction_data.not_equals("CCN>>CC=N") + ) native_equality_stmt = ( select(compounds.c.name) .where(compounds.c.structure == compounds.c.query_structure) @@ -185,10 +215,36 @@ def main() -> None: .limit(1) ) + comparator_statements = { + ("BingoMolComparator", "has_substructure"): substructure_stmt, + ("BingoMolComparator", "has_smarts"): comparator_smarts_stmt, + ("BingoMolComparator", "equals"): comparator_equals_stmt, + ("BingoMolComparator", "not_equals"): comparator_not_equals_stmt, + ("BingoMolComparator", "similar_to"): similarity_with_column_stmt, + ("BingoRxnComparator", "has_substructure"): reaction_substructure_stmt, + ("BingoRxnComparator", "has_smarts"): reaction_smarts_stmt, + ("BingoRxnComparator", "equals"): reaction_exact_stmt, + ("BingoRxnComparator", "not_equals"): reaction_not_equals_stmt, + } + comparator_classes = (BingoMolComparator, BingoRxnComparator) + declared_methods = { + (comparator.__name__, method) + for comparator in comparator_classes + for method in declared_comparator_methods(comparator) + } + assert comparator_statements.keys() == declared_methods, ( + "live comparator coverage mismatch: " + f"missing={sorted(declared_methods - comparator_statements.keys())}, " + f"unexpected={sorted(comparator_statements.keys() - declared_methods)}" + ) + print(str(CreateTable(compounds).compile(dialect=postgresql.dialect()))) print(str(CreateTable(reactions).compile(dialect=postgresql.dialect()))) print() print(substructure_stmt.compile(dialect=postgresql.dialect())) + print(comparator_smarts_stmt.compile(dialect=postgresql.dialect())) + print(comparator_equals_stmt.compile(dialect=postgresql.dialect())) + print(comparator_not_equals_stmt.compile(dialect=postgresql.dialect())) print(exact_stmt.compile(dialect=postgresql.dialect())) print(smarts_stmt.compile(dialect=postgresql.dialect())) print( @@ -198,6 +254,9 @@ def main() -> None: ) print(function_stmt.compile(dialect=postgresql.dialect())) print(reaction_exact_stmt.compile(dialect=postgresql.dialect())) + print(reaction_substructure_stmt.compile(dialect=postgresql.dialect())) + print(reaction_smarts_stmt.compile(dialect=postgresql.dialect())) + print(reaction_not_equals_stmt.compile(dialect=postgresql.dialect())) print( native_equality_stmt.compile( dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} @@ -209,13 +268,19 @@ def main() -> None: with engine.connect() as conn: version = conn.exec_driver_sql("SELECT bingo.getversion()").scalar_one() - substructure_rows = conn.execute(substructure_stmt).scalars().all() + comparator_results = { + name: conn.execute(statement).scalars().all() + for name, statement in comparator_statements.items() + } + substructure_rows = comparator_results[ + ("BingoMolComparator", "has_substructure") + ] exact_rows = conn.execute(exact_stmt).scalars().all() smarts_rows = conn.execute(smarts_stmt).scalars().all() - similarity_rows = conn.execute(similarity_with_column_stmt).scalars().all() + similarity_rows = comparator_results[("BingoMolComparator", "similar_to")] function_row = conn.execute(function_stmt).mappings().one() invalid_check = conn.execute(invalid_check_stmt).scalar_one() - reaction_exact_rows = conn.execute(reaction_exact_stmt).scalars().all() + reaction_exact_rows = comparator_results[("BingoRxnComparator", "equals")] native_equality_rows = conn.execute(native_equality_stmt).scalars().all() molecule_not_null_rows = conn.execute(molecule_not_null_stmt).scalars().all() reaction_not_null_rows = conn.execute(reaction_not_null_stmt).scalars().all() @@ -234,6 +299,8 @@ def main() -> None: print(f"structure IS NOT NULL via != None: {molecule_not_null_rows}") print(f"reaction IS NOT NULL via != None: {reaction_not_null_rows}") print(f"reaction function wrappers: {dict(reaction_function_row)}") + for comparator_method, rows in comparator_results.items(): + print(f"live comparator {'.'.join(comparator_method)}: {rows}") assert substructure_rows == ["benzene"] assert exact_rows == ["ethanol"] @@ -259,6 +326,19 @@ def main() -> None: assert reaction_function_row["check_result"] is None assert reaction_function_row["reaction_smiles"] assert reaction_function_row["rxnfile_len"] > 100 + expected_comparator_results = { + ("BingoMolComparator", "has_substructure"): ["benzene"], + ("BingoMolComparator", "has_smarts"): ["ethanol"], + ("BingoMolComparator", "equals"): ["ethanol"], + ("BingoMolComparator", "not_equals"): ["benzene"], + ("BingoMolComparator", "similar_to"): ["benzene", "ethanol"], + ("BingoRxnComparator", "has_substructure"): ["ethanol oxidation"], + ("BingoRxnComparator", "has_smarts"): ["ethanol oxidation"], + ("BingoRxnComparator", "equals"): ["ethanol oxidation"], + ("BingoRxnComparator", "not_equals"): ["ethanol oxidation"], + } + assert comparator_results == expected_comparator_results + print(f"validated all {len(declared_methods)} declared Bingo comparator methods") if __name__ == "__main__": From 957313daa9fd0c7c52edcd1113a427f11fb9219f Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Wed, 5 Aug 2026 20:01:19 +0200 Subject: [PATCH 09/13] fix docs build --- Makefile | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index cf850f9..0d7e05d 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,16 @@ SMOKE_PROJECT ?= molalchemy-smoke BINGO_SMOKE_PORT ?= 55432 RDKIT_SMOKE_PORT ?= 55433 +# CairoSVG, used by MkDocs Material's social plugin, loads the native Cairo +# library through cffi. On macOS, dyld does not search Homebrew's opt prefix by +# default, so discover it rather than hard-coding an Intel or Apple Silicon path. +ifeq ($(shell uname -s),Darwin) +HOMEBREW_CAIRO_PREFIX := $(shell brew --prefix cairo 2>/dev/null) +ifneq ($(strip $(HOMEBREW_CAIRO_PREFIX)),) +DOCS_CAIRO_ENV := DYLD_FALLBACK_LIBRARY_PATH="$(HOMEBREW_CAIRO_PREFIX)/lib$${DYLD_FALLBACK_LIBRARY_PATH:+:$${DYLD_FALLBACK_LIBRARY_PATH}}" +endif +endif + test: @uv run pytest tests/ --cov=src/molalchemy --cov-report=term-missing --cov-report=xml @@ -24,7 +34,7 @@ smoke: docs-test: - @JUPYTER_PLATFORM_DIRS=1 uv run mkdocs build --strict --site-dir /tmp/molalchemy-site + @$(DOCS_CAIRO_ENV) JUPYTER_PLATFORM_DIRS=1 uv run mkdocs build --strict --site-dir /tmp/molalchemy-site sync-docs: @cp README.md docs/index.md From aa0863bb409144914dfb6044bb768a68c954b37a Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Sat, 8 Aug 2026 21:49:43 +0200 Subject: [PATCH 10/13] harmonize bingo comparator --- Makefile | 3 + data/bingo/config.json | 4 ++ data/bingo/functions.json | 2 +- data/bingo/general_extra.txt | 65 ++++++++++++++---- data/bingo/general_header.txt | 8 ++- dev_scripts/validate_bingo_helpers.py | 6 ++ docs/migrations/bingo-comparator-api.md | 25 +++++-- docs/tutorials/08_proxy_helpers.md | 14 ++++ mkdocs.yml | 2 +- src/molalchemy/bingo/comparators.py | 9 +++ src/molalchemy/bingo/functions/__init__.py | 8 +++ src/molalchemy/bingo/functions/general.py | 76 +++++++++++++++++----- src/molalchemy/bingo/search.py | 6 +- src/molalchemy/protocols.py | 8 ++- tests/bingo/README.md | 4 +- tests/bingo/test_comparators.py | 40 +++++++++++- tests/bingo/test_functions.py | 50 ++++++++++++-- tests/test_helpers.py | 6 ++ 18 files changed, 288 insertions(+), 48 deletions(-) diff --git a/Makefile b/Makefile index 0d7e05d..88a4427 100644 --- a/Makefile +++ b/Makefile @@ -36,6 +36,9 @@ smoke: docs-test: @$(DOCS_CAIRO_ENV) JUPYTER_PLATFORM_DIRS=1 uv run mkdocs build --strict --site-dir /tmp/molalchemy-site +docs-serve: + @$(DOCS_CAIRO_ENV) JUPYTER_PLATFORM_DIRS=1 uv run mkdocs serve + sync-docs: @cp README.md docs/index.md @cp CHANGELOG.md docs/ diff --git a/data/bingo/config.json b/data/bingo/config.json index 059b108..b91d171 100644 --- a/data/bingo/config.json +++ b/data/bingo/config.json @@ -4,10 +4,14 @@ "mol_has_substructure", "mol_has_smarts", "mol_equals", + "mol_not_equals", + "mol_similar_to", "mol_similarity", + "mol_similarity_score", "rxn_has_substructure", "rxn_has_smarts", "rxn_equals", + "rxn_not_equals", "AnyBingoMol", "AnyBingoReaction" ] diff --git a/data/bingo/functions.json b/data/bingo/functions.json index 577aa75..8ebc70a 100644 --- a/data/bingo/functions.json +++ b/data/bingo/functions.json @@ -743,7 +743,7 @@ "name": "getsimilarity", "return_type": { "description": "SQLAlchemy function", - "type": "float | sqltypes.Float" + "type": "sqltypes.Float" } }, "getstructurescount": { diff --git a/data/bingo/general_extra.txt b/data/bingo/general_extra.txt index 202ebad..59042fa 100644 --- a/data/bingo/general_extra.txt +++ b/data/bingo/general_extra.txt @@ -72,28 +72,34 @@ def mol_equals( return _bingo_search_values(mol, (query, parameters), "bingo.exact") -def mol_similarity( - mol: ColumnElement[AnyBingoMol], - query: TextLike, - bottom: float = 0.0, - top: float = 1.0, - metric: TextLike = "Tanimoto", +def mol_not_equals( + mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" +) -> ColumnElement[bool]: + """Perform negated exact structure matching on a molecule column.""" + return ~mol_equals(mol, query, parameters) + + +def mol_similar_to( + mol: SqlOperand, + query: BingoOperand, + minimum: BingoSimilarityBound = 0.0, + maximum: BingoSimilarityBound = 1.0, + metric: BingoParameters = "Tanimoto", ) -> ColumnElement[bool]: """ - Perform similarity search on a molecule column. This should be used in WHERE clauses, as it - returns a boolean expression indicating whether the similarity criteria are met. + Check whether molecular similarity is within the requested range. Parameters ---------- - mol : AnyBingoMolLike | AnyBingoBinaryMolLike + mol : SqlOperand SQLAlchemy column containing molecule data (SMILES, Molfile, or binary). - query : TextLike + query : BingoOperand Query molecule as SMILES or Molfile string for similarity comparison. - bottom : float, optional + minimum : BingoSimilarityBound, optional Minimum similarity threshold (default is 0.0). - top : float, optional + maximum : BingoSimilarityBound, optional Maximum similarity threshold (default is 1.0). - metric : TextLike, optional + metric : BingoParameters, optional Similarity metric to use (default is "Tanimoto"). Other options include "Dice", "Cosine", etc. @@ -103,7 +109,31 @@ def mol_similarity( SQLAlchemy expression for similarity matching that can be used in WHERE clauses. """ - return _bingo_search_values(mol, (bottom, top, query, metric), "bingo.sim") + return _bingo_search_values(mol, (minimum, maximum, query, metric), "bingo.sim") + + +def mol_similarity( + mol: SqlOperand, + query: BingoOperand, + bottom: BingoSimilarityBound = 0.0, + top: BingoSimilarityBound = 1.0, + metric: BingoParameters = "Tanimoto", +) -> ColumnElement[bool]: + """Compatibility spelling for :func:`mol_similar_to`. + + ``bottom`` and ``top`` retain the historical keyword names. New code should + use :func:`mol_similar_to` with ``minimum`` and ``maximum``. + """ + return mol_similar_to(mol, query, bottom, top, metric) + + +def mol_similarity_score( + mol: SqlOperand, + query: BingoOperand, + metric: BingoParameters = "Tanimoto", +) -> ColumnElement[float]: + """Return the numeric molecular similarity score for ``query``.""" + return cast(ColumnElement[float], getsimilarity(mol, query, metric)) def rxn_has_substructure( @@ -176,3 +206,10 @@ def rxn_equals( """ return _bingo_search_values(rxn, (query, parameters), "bingo.rexact") + + +def rxn_not_equals( + rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" +) -> ColumnElement[bool]: + """Perform negated exact matching on a reaction column.""" + return ~rxn_equals(rxn, query, parameters) diff --git a/data/bingo/general_header.txt b/data/bingo/general_header.txt index 705e8a1..a0787f4 100644 --- a/data/bingo/general_header.txt +++ b/data/bingo/general_header.txt @@ -2,13 +2,19 @@ This file defines public Bingo PostgreSQL function wrappers for use with SQLAlchemy. """ -from typing import Any, Literal +from typing import Any, Literal, cast from sqlalchemy import types as sqltypes from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.sql.functions import GenericFunction from molalchemy.bingo.search import _bingo_search_values +from molalchemy.protocols import ( + BingoOperand, + BingoParameters, + BingoSimilarityBound, + SqlOperand, +) from ._types import ( AnyBingoBinaryMolLike, diff --git a/dev_scripts/validate_bingo_helpers.py b/dev_scripts/validate_bingo_helpers.py index 30597b5..19f4555 100644 --- a/dev_scripts/validate_bingo_helpers.py +++ b/dev_scripts/validate_bingo_helpers.py @@ -147,6 +147,9 @@ def main() -> None: ) .order_by(compounds.c.id) ) + similarity_score_stmt = select( + compounds.c.structure.similarity_score(compounds.c.query_structure) + ).where(compounds.c.name == "ethanol") smarts_stmt = select(compounds.c.name).where( bingo_func.mol_has_smarts(compounds.c.structure, "[#6]-[#8]") ) @@ -221,6 +224,7 @@ def main() -> None: ("BingoMolComparator", "equals"): comparator_equals_stmt, ("BingoMolComparator", "not_equals"): comparator_not_equals_stmt, ("BingoMolComparator", "similar_to"): similarity_with_column_stmt, + ("BingoMolComparator", "similarity_score"): similarity_score_stmt, ("BingoRxnComparator", "has_substructure"): reaction_substructure_stmt, ("BingoRxnComparator", "has_smarts"): reaction_smarts_stmt, ("BingoRxnComparator", "equals"): reaction_exact_stmt, @@ -252,6 +256,7 @@ def main() -> None: dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} ) ) + print(similarity_score_stmt.compile(dialect=postgresql.dialect())) print(function_stmt.compile(dialect=postgresql.dialect())) print(reaction_exact_stmt.compile(dialect=postgresql.dialect())) print(reaction_substructure_stmt.compile(dialect=postgresql.dialect())) @@ -332,6 +337,7 @@ def main() -> None: ("BingoMolComparator", "equals"): ["ethanol"], ("BingoMolComparator", "not_equals"): ["benzene"], ("BingoMolComparator", "similar_to"): ["benzene", "ethanol"], + ("BingoMolComparator", "similarity_score"): [1.0], ("BingoRxnComparator", "has_substructure"): ["ethanol oxidation"], ("BingoRxnComparator", "has_smarts"): ["ethanol oxidation"], ("BingoRxnComparator", "equals"): ["ethanol oxidation"], diff --git a/docs/migrations/bingo-comparator-api.md b/docs/migrations/bingo-comparator-api.md index ba4d09e..e4caf89 100644 --- a/docs/migrations/bingo-comparator-api.md +++ b/docs/migrations/bingo-comparator-api.md @@ -93,8 +93,9 @@ Use `is_(None)` and `is_not(None)` if explicit SQL-style spelling is preferred. ## Similarity comparator -Molecule columns now expose `similar_to()` as the comparator equivalent of -`bingo_func.mol_similarity()`: +Molecule columns expose separate APIs for Boolean similarity searches and +numeric similarity scores. `similar_to()` is the comparator equivalent of +`bingo_func.mol_similar_to()`: ```python predicate = Compound.structure.similar_to( @@ -107,8 +108,20 @@ stmt = select(Compound).where(predicate) ``` `similar_to()` returns a Boolean range predicate. It does not return a numeric -similarity score; use `bingo_func.getsimilarity()` when the score itself is -needed. +similarity score. Use `similarity_score()` or +`bingo_func.mol_similarity_score()` when the score itself is needed: + +```python +score = Compound.structure.similarity_score(query, metric="Tanimoto") +functional_score = bingo_func.mol_similarity_score( + Compound.structure, query, metric="Tanimoto" +) +``` + +The cartridge-level `getsimilarity()` wrapper remains available. The older +`mol_similarity()` predicate also remains as a compatibility spelling and +retains its `bottom` and `top` keyword names; new code should use +`mol_similar_to()` with `minimum` and `maximum`. ## Boolean expression results @@ -184,6 +197,6 @@ The following APIs do not require migration: 2. Replace chemical `column != query` with `column.not_equals(query)`. 3. Keep `== None`/`!= None`, or use `is_(None)`/`is_not(None)`. 4. Treat native equality as text or binary storage equality only. -5. Optionally replace `bingo_func.mol_similarity()` with `similar_to()` when a - comparator method is clearer. +5. Use `similar_to()`/`mol_similar_to()` for predicates and + `similarity_score()`/`mol_similarity_score()` for numeric scores. 6. Replace removed proxy imports with `bingo_col()` or `bingo_rxn_col()`. diff --git a/docs/tutorials/08_proxy_helpers.md b/docs/tutorials/08_proxy_helpers.md index 6542cfc..e4047d3 100644 --- a/docs/tutorials/08_proxy_helpers.md +++ b/docs/tutorials/08_proxy_helpers.md @@ -59,6 +59,12 @@ ethanol_query = select(Compound).where( bingo_col(Compound.structure).equals("CCO") ) +similarity_query = select(Compound).where( + bingo_col(Compound.structure).similar_to("CCO", minimum=0.7) +) + +similarity_score = bingo_col(Compound.structure).similarity_score("CCO") + reaction_query = select(Reaction).where( bingo_rxn_col(Reaction.reaction).equals("CCO>>CC=O") ) @@ -187,4 +193,12 @@ from molalchemy.bingo import functions as bingo_func stmt = select(Compound).where( bingo_func.mol_has_substructure(Compound.structure, "c1ccccc1") ) + +similar = select(Compound).where( + bingo_func.mol_similar_to(Compound.structure, "CCO", minimum=0.7) +) + +scores = select( + bingo_func.mol_similarity_score(Compound.structure, "CCO") +) ``` diff --git a/mkdocs.yml b/mkdocs.yml index 135bdb8..dee4919 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -101,7 +101,7 @@ nav: - RDKit - Descriptors and Advanced Queries: tutorials/07_rdkit_descriptors_advanced.ipynb - Typed Comparator Helpers: tutorials/08_proxy_helpers.md - Contributing: tutorials/contribute.md - - Migration guides: + - Migration to 0.1.x: - Bingo comparator API: migrations/bingo-comparator-api.md - RDKit comparator API: migrations/rdkit-comparator-api.md - API: diff --git a/src/molalchemy/bingo/comparators.py b/src/molalchemy/bingo/comparators.py index 338f0c2..e1122e0 100644 --- a/src/molalchemy/bingo/comparators.py +++ b/src/molalchemy/bingo/comparators.py @@ -3,6 +3,7 @@ from sqlalchemy import ColumnElement from sqlalchemy.types import UserDefinedType +from molalchemy.bingo.functions.general import mol_similarity_score from molalchemy.bingo.search import _bingo_search_values from molalchemy.protocols import ( BingoOperand, @@ -132,6 +133,14 @@ def similar_to( self.expr, (minimum, maximum, query, metric), "bingo.sim" ) + def similarity_score( + self, + query: BingoOperand, + metric: BingoParameters = "Tanimoto", + ) -> ColumnElement[float]: + """Return the numeric similarity score for `query`.""" + return mol_similarity_score(self.expr, query, metric) + class BingoRxnComparator(UserDefinedType.Comparator): """ diff --git a/src/molalchemy/bingo/functions/__init__.py b/src/molalchemy/bingo/functions/__init__.py index 0b2246b..1c483d0 100644 --- a/src/molalchemy/bingo/functions/__init__.py +++ b/src/molalchemy/bingo/functions/__init__.py @@ -44,7 +44,10 @@ mol_equals, mol_has_smarts, mol_has_substructure, + mol_not_equals, + mol_similar_to, mol_similarity, + mol_similarity_score, molfile, precachedatabase, rcml, @@ -53,6 +56,7 @@ rxn_equals, rxn_has_smarts, rxn_has_substructure, + rxn_not_equals, rxnfile, smiles, standardize, @@ -138,7 +142,10 @@ "mol_equals", "mol_has_smarts", "mol_has_substructure", + "mol_not_equals", + "mol_similar_to", "mol_similarity", + "mol_similarity_score", "molfile", "precachedatabase", "rcml", @@ -147,6 +154,7 @@ "rxn_equals", "rxn_has_smarts", "rxn_has_substructure", + "rxn_not_equals", "rxnfile", "smiles", "standardize", diff --git a/src/molalchemy/bingo/functions/general.py b/src/molalchemy/bingo/functions/general.py index d76f793..4832a28 100644 --- a/src/molalchemy/bingo/functions/general.py +++ b/src/molalchemy/bingo/functions/general.py @@ -2,13 +2,19 @@ This file defines public Bingo PostgreSQL function wrappers for use with SQLAlchemy. """ -from typing import Any, Literal +from typing import Any, Literal, cast from sqlalchemy import types as sqltypes from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.sql.functions import GenericFunction from molalchemy.bingo.search import _bingo_search_values +from molalchemy.protocols import ( + BingoOperand, + BingoParameters, + BingoSimilarityBound, + SqlOperand, +) from ._types import ( AnyBingoBinaryMolLike, @@ -99,28 +105,34 @@ def mol_equals( return _bingo_search_values(mol, (query, parameters), "bingo.exact") -def mol_similarity( - mol: ColumnElement[AnyBingoMol], - query: TextLike, - bottom: float = 0.0, - top: float = 1.0, - metric: TextLike = "Tanimoto", +def mol_not_equals( + mol: ColumnElement[AnyBingoMol], query: TextLike, parameters: TextLike = "" +) -> ColumnElement[bool]: + """Perform negated exact structure matching on a molecule column.""" + return ~mol_equals(mol, query, parameters) + + +def mol_similar_to( + mol: SqlOperand, + query: BingoOperand, + minimum: BingoSimilarityBound = 0.0, + maximum: BingoSimilarityBound = 1.0, + metric: BingoParameters = "Tanimoto", ) -> ColumnElement[bool]: """ - Perform similarity search on a molecule column. This should be used in WHERE clauses, as it - returns a boolean expression indicating whether the similarity criteria are met. + Check whether molecular similarity is within the requested range. Parameters ---------- - mol : AnyBingoMolLike | AnyBingoBinaryMolLike + mol : SqlOperand SQLAlchemy column containing molecule data (SMILES, Molfile, or binary). - query : TextLike + query : BingoOperand Query molecule as SMILES or Molfile string for similarity comparison. - bottom : float, optional + minimum : BingoSimilarityBound, optional Minimum similarity threshold (default is 0.0). - top : float, optional + maximum : BingoSimilarityBound, optional Maximum similarity threshold (default is 1.0). - metric : TextLike, optional + metric : BingoParameters, optional Similarity metric to use (default is "Tanimoto"). Other options include "Dice", "Cosine", etc. @@ -130,7 +142,31 @@ def mol_similarity( SQLAlchemy expression for similarity matching that can be used in WHERE clauses. """ - return _bingo_search_values(mol, (bottom, top, query, metric), "bingo.sim") + return _bingo_search_values(mol, (minimum, maximum, query, metric), "bingo.sim") + + +def mol_similarity( + mol: SqlOperand, + query: BingoOperand, + bottom: BingoSimilarityBound = 0.0, + top: BingoSimilarityBound = 1.0, + metric: BingoParameters = "Tanimoto", +) -> ColumnElement[bool]: + """Compatibility spelling for :func:`mol_similar_to`. + + ``bottom`` and ``top`` retain the historical keyword names. New code should + use :func:`mol_similar_to` with ``minimum`` and ``maximum``. + """ + return mol_similar_to(mol, query, bottom, top, metric) + + +def mol_similarity_score( + mol: SqlOperand, + query: BingoOperand, + metric: BingoParameters = "Tanimoto", +) -> ColumnElement[float]: + """Return the numeric molecular similarity score for ``query``.""" + return cast(ColumnElement[float], getsimilarity(mol, query, metric)) def rxn_has_substructure( @@ -205,6 +241,13 @@ def rxn_equals( return _bingo_search_values(rxn, (query, parameters), "bingo.rexact") +def rxn_not_equals( + rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = "" +) -> ColumnElement[bool]: + """Perform negated exact matching on a reaction column.""" + return ~rxn_equals(rxn, query, parameters) + + class aam(GenericFunction): inherit_cache = True name = "aam" @@ -641,6 +684,7 @@ def __init__(self, arg_1: AnyBingoMolLike, **kwargs: Any) -> None: class getsimilarity(GenericFunction): + type = sqltypes.Float() inherit_cache = True name = "getsimilarity" @@ -666,7 +710,7 @@ def __init__( Returns ------- - Function[float | sqltypes.Float] + Function[sqltypes.Float] SQLAlchemy function """ super().__init__(mol, query, metric, **kwargs) diff --git a/src/molalchemy/bingo/search.py b/src/molalchemy/bingo/search.py index a0d5076..2e3c67e 100644 --- a/src/molalchemy/bingo/search.py +++ b/src/molalchemy/bingo/search.py @@ -7,6 +7,8 @@ from sqlalchemy.sql import operators from sqlalchemy.sql.elements import ColumnElement +from molalchemy.protocols import SqlOperand + class _BingoSearchType(sqltypes.UserDefinedType): """SQLAlchemy type wrapper for casting search tuples to Bingo search types.""" @@ -34,7 +36,7 @@ def get_col_spec(self, **kw: Any) -> str: def _bingo_search( - column: ColumnElement[Any], + column: SqlOperand, query_tuple: Any, search_type: str, ) -> ColumnElement[bool]: @@ -48,7 +50,7 @@ def _bingo_search( def _bingo_search_values( - column: ColumnElement[Any], values: tuple[object, ...], search_type: str + column: SqlOperand, values: tuple[object, ...], search_type: str ) -> ColumnElement[bool]: """Build a Bingo predicate using SQLAlchemy's expression coercion. diff --git a/src/molalchemy/protocols.py b/src/molalchemy/protocols.py index 3edcdb1..d834836 100644 --- a/src/molalchemy/protocols.py +++ b/src/molalchemy/protocols.py @@ -18,7 +18,7 @@ RdkitFingerprintOperand: TypeAlias = bytes | SqlOperand BingoOperand: TypeAlias = str | bytes | SqlOperand BingoParameters: TypeAlias = str | SqlOperand -BingoSimilarityBound: TypeAlias = float | SqlOperand +BingoSimilarityBound: TypeAlias = float | None | SqlOperand class BingoMolColumn(Protocol): @@ -46,6 +46,12 @@ def similar_to( metric: BingoParameters = "Tanimoto", ) -> ColumnElement[bool]: ... + def similarity_score( + self, + query: BingoOperand, + metric: BingoParameters = "Tanimoto", + ) -> ColumnElement[float]: ... + class BingoReactionColumn(Protocol): def has_substructure( diff --git a/tests/bingo/README.md b/tests/bingo/README.md index 3024086..ed647fa 100644 --- a/tests/bingo/README.md +++ b/tests/bingo/README.md @@ -24,7 +24,9 @@ The test suite covers all major components of the Bingo integration: - `mol_has_substructure()`: Molecular substructure searching - `mol_has_smarts()`: Molecular SMARTS pattern matching - `mol_equals()`: Exact molecular structure matching - - `mol_similarity()`: Similarity searching with Tanimoto/Dice metrics + - `mol_similar_to()`: Boolean similarity searching with configurable metrics + - `mol_similarity_score()`: Numeric molecular similarity scores + - `mol_similarity()`: Backward-compatible predicate spelling - `rxn_has_substructure()`: Reaction substructure searching - `rxn_has_smarts()`: Reaction SMARTS pattern matching - `rxn_equals()`: Exact reaction matching diff --git a/tests/bingo/test_comparators.py b/tests/bingo/test_comparators.py index 315413f..f6ac619 100644 --- a/tests/bingo/test_comparators.py +++ b/tests/bingo/test_comparators.py @@ -4,6 +4,7 @@ from sqlalchemy import ( Boolean, Column, + Float, Integer, MetaData, String, @@ -107,13 +108,46 @@ def test_reaction_predicates_are_boolean(rxn_columns, method, search_type): def test_similarity_defaults_and_function_parity(mol_columns): method = mol_columns.mol.similar_to("CCO") - function = bingo_func.mol_similarity(mol_columns.mol, "CCO") + function = bingo_func.mol_similar_to(mol_columns.mol, "CCO") assert isinstance(method.type, Boolean) assert sql(method) == sql(function) assert set(method.compile().params.values()) == {0.0, 1.0, "CCO", "Tanimoto"} +def test_legacy_similarity_function_preserves_old_keywords(mol_columns): + canonical = bingo_func.mol_similar_to( + mol_columns.mol, "CCO", minimum=0.2, maximum=0.8, metric="Dice" + ) + legacy = bingo_func.mol_similarity( + mol_columns.mol, "CCO", bottom=0.2, top=0.8, metric="Dice" + ) + + assert sql(canonical) == sql(legacy) + assert set(canonical.compile().params.values()) == {0.2, 0.8, "CCO", "Dice"} + + +def test_similarity_score_comparator_and_function_parity(mol_columns): + method = mol_columns.mol.similarity_score("CCO") + function = bingo_func.mol_similarity_score(mol_columns.mol, "CCO") + + assert isinstance(method.type, Float) + assert sql(method) == sql(function) + assert "bingo.getsimilarity" in sql(method) + assert set(method.compile().params.values()) == {"CCO", "Tanimoto"} + + +def test_similarity_predicate_accepts_open_bounds(mol_columns): + expression = bingo_func.mol_similar_to( + mol_columns.mol, "CCO", minimum=None, maximum=None + ) + compiled = expression.compile(dialect=postgresql.dialect()) + + assert isinstance(expression.type, Boolean) + assert "bingo.sim" in str(compiled) + assert "NULL, NULL" in str(compiled) + + def test_similarity_custom_options_and_distinct_binds(mol_columns): statement = select(mol_columns.id).where( mol_columns.mol.similar_to("CCO", 0.2, 0.8, "Dice"), @@ -174,6 +208,10 @@ def test_orm_comparator_remains_available_at_runtime(): assert isinstance(expression.type, Boolean) assert "bingo.sim" in sql(select(Compound).where(expression)) + score = Compound.mol.similarity_score("CCO") + assert isinstance(score.type, Float) + assert "bingo.getsimilarity" in sql(select(score)) + def test_orm_attributes_are_preserved_as_comparator_operands(): expression = Compound.mol.equals(Compound.other_mol, Compound.query_parameters) diff --git a/tests/bingo/test_functions.py b/tests/bingo/test_functions.py index 8ef8f41..cda2d33 100644 --- a/tests/bingo/test_functions.py +++ b/tests/bingo/test_functions.py @@ -103,12 +103,12 @@ def test_bingo_similarity_preserves_column_expression_inputs(): ) stmt = select(compounds).where( - bingo_func.mol_similarity( + bingo_func.mol_similar_to( compounds.c.structure, compounds.c.query_structure, - 0.2, - 0.9, - "Dice", + minimum=0.2, + maximum=0.9, + metric="Dice", ) ) @@ -123,6 +123,20 @@ def test_bingo_similarity_preserves_column_expression_inputs(): assert "bingo.sim" in sql +def test_similarity_score_is_typed_as_float(): + compounds = Table( + "compounds", + MetaData(), + Column("id", Integer), + Column("structure", BingoMol()), + ) + + score = bingo_func.mol_similarity_score(compounds.c.structure, "CCO") + + assert score.type.python_type is float + assert "bingo.getsimilarity" in str(score.compile(dialect=postgresql.dialect())) + + def test_bingo_search_helpers_preserve_orm_attribute_inputs(): """Mapped attributes should use their SQL expression, not become literals.""" stmt = select(Compound).where( @@ -140,6 +154,34 @@ def test_bingo_search_helpers_preserve_orm_attribute_inputs(): assert "bingo_function_compounds.query_parameters" in compiled +@pytest.mark.parametrize( + ("helper_name", "column_type", "query", "search_type"), + [ + ("mol_not_equals", BingoMol(), "CCO", "bingo.exact"), + ("rxn_not_equals", BingoReaction(), "CCO>>CC=O", "bingo.rexact"), + ], +) +def test_not_equals_helpers_negate_exact_search( + helper_name, column_type, query, search_type +): + """Negated helpers should preserve the matching exact-search operation.""" + structures = Table( + "structures", + MetaData(), + Column("id", Integer), + Column("structure", column_type), + ) + + helper = getattr(bingo_func, helper_name) + stmt = select(structures).where(helper(structures.c.structure, query)) + + compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) + + assert "NOT" in compiled + assert search_type in compiled + assert query in compiled + + @pytest.mark.parametrize( ("helper_name", "column_type", "query", "search_type"), [ diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 34d8bda..7095e9f 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -273,6 +273,12 @@ def test_bingo_proxy_helpers_accept_orm_instrumented_attributes(): assert "bingo.exact" in compiled assert "CCO" in compiled + score = bingo_col(BingoCompound.structure).similarity_score("CCO") + assert score.type.python_type is float + assert "bingo.getsimilarity" in str( + select(score).compile(dialect=postgresql.dialect()) + ) + def test_rdkit_proxy_helpers_accept_orm_instrumented_attributes(): assert rdkit_col(RdkitCompound.structure) is RdkitCompound.structure From 2d901d8ec8acaa63a786e2cd72ed59180e91b2d6 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Sat, 8 Aug 2026 22:18:39 +0200 Subject: [PATCH 11/13] improve rdkit similarity --- data/rdkit/config.json | 2 + data/rdkit/general_extra.txt | 25 ++++++ data/rdkit/general_header.txt | 8 ++ dev_scripts/validate_rdkit_helpers.py | 17 +++++ docs/ROADMAP.md | 1 - docs/migrations/bingo-comparator-api.md | 5 ++ docs/migrations/rdkit-comparator-api.md | 39 +++++++++- .../01_Getting_Started_bingo_ORM.ipynb | 37 +++++++++ .../01_Getting_Started_rdkit_ORM.ipynb | 76 ++++++++++++++++++- docs/tutorials/08_proxy_helpers.md | 10 +++ src/molalchemy/protocols.py | 20 ++++- src/molalchemy/rdkit/comparators.py | 28 +++++++ src/molalchemy/rdkit/functions/__init__.py | 4 + src/molalchemy/rdkit/functions/general.py | 33 ++++++++ src/molalchemy/rdkit/search.py | 40 ++++++++++ tests/bingo/test_functions.py | 18 ----- tests/rdkit/test_comparators.py | 49 ++++++++++++ tests/rdkit/test_functions.py | 18 ----- 18 files changed, 389 insertions(+), 41 deletions(-) diff --git a/data/rdkit/config.json b/data/rdkit/config.json index 77ff112..cf25350 100644 --- a/data/rdkit/config.json +++ b/data/rdkit/config.json @@ -1,6 +1,8 @@ { "general": { "extra_members": [ + "fp_similar_to", + "fp_similarity_score", "mol_equals", "mol_has_smarts", "mol_has_substructure", diff --git a/data/rdkit/general_extra.txt b/data/rdkit/general_extra.txt index 0fa39b2..06bf385 100644 --- a/data/rdkit/general_extra.txt +++ b/data/rdkit/general_extra.txt @@ -1,5 +1,30 @@ +def fp_similar_to( + fp_column: SqlOperand, + query: RdkitFingerprintOperand, + minimum: RdkitSimilarityBound = 0.0, + maximum: RdkitSimilarityBound = 1.0, + metric: RdkitSimilarityMetric = "Tanimoto", +) -> ColumnElement[bool]: + """Check whether fingerprint similarity is within explicit bounds. + + This helper provides a Bingo-compatible similarity API. Because it compares a + computed score, it may be slower than RDKit's native threshold and KNN + operators. + """ + return _rdkit_similar_to(fp_column, query, minimum, maximum, metric) + + +def fp_similarity_score( + fp_column: SqlOperand, + query: RdkitFingerprintOperand, + metric: RdkitSimilarityMetric = "Tanimoto", +) -> ColumnElement[float]: + """Return the numeric fingerprint similarity score.""" + return _rdkit_similarity_score(fp_column, query, metric) + + def mol_has_substructure( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike ) -> ColumnElement[bool]: diff --git a/data/rdkit/general_header.txt b/data/rdkit/general_header.txt index 0201f79..d86bd46 100644 --- a/data/rdkit/general_header.txt +++ b/data/rdkit/general_header.txt @@ -15,6 +15,14 @@ from molalchemy.rdkit.search import ( _rdkit_mol_smarts, _rdkit_predicate, _rdkit_rxn_smarts, + _rdkit_similar_to, + _rdkit_similarity_score, +) +from molalchemy.protocols import ( + RdkitFingerprintOperand, + RdkitSimilarityBound, + RdkitSimilarityMetric, + SqlOperand, ) from molalchemy.rdkit.types import ( RdkitBitFingerprint, diff --git a/dev_scripts/validate_rdkit_helpers.py b/dev_scripts/validate_rdkit_helpers.py index 3f768e1..8b810a7 100644 --- a/dev_scripts/validate_rdkit_helpers.py +++ b/dev_scripts/validate_rdkit_helpers.py @@ -249,6 +249,14 @@ def main() -> None: dice_stmt = select(molecules.c.name).where( molecules.c.morgan_fp.dice_matches(query_fp) ) + bingo_compatible_similarity_stmt = select(molecules.c.name).where( + molecules.c.morgan_fp.similar_to( + query_fp, minimum=0.9, maximum=1.0, metric="Tanimoto" + ) + ) + bingo_compatible_similarity_score_stmt = select( + molecules.c.morgan_fp.similarity_score(query_fp, metric="Tanimoto") + ).where(molecules.c.name == "ethanol") tanimoto_knn_stmt = select(molecules.c.name).order_by( molecules.c.morgan_fp.tanimoto_distance(query_fp), molecules.c.id ) @@ -342,6 +350,11 @@ def main() -> None: ): reaction_reverse_substructure_fp_stmt, ("RdkitFPComparator", "tanimoto_matches"): tanimoto_stmt, ("RdkitFPComparator", "dice_matches"): dice_stmt, + ("RdkitFPComparator", "similar_to"): bingo_compatible_similarity_stmt, + ( + "RdkitFPComparator", + "similarity_score", + ): bingo_compatible_similarity_score_stmt, ("RdkitFPComparator", "tanimoto_distance"): tanimoto_knn_stmt, ("RdkitFPComparator", "dice_distance"): dice_knn_stmt, } @@ -376,6 +389,8 @@ def main() -> None: print(explicit_not_equivalent_stmt.compile(dialect=postgresql.dialect())) print(tanimoto_stmt.compile(dialect=postgresql.dialect())) print(dice_stmt.compile(dialect=postgresql.dialect())) + print(bingo_compatible_similarity_stmt.compile(dialect=postgresql.dialect())) + print(bingo_compatible_similarity_score_stmt.compile(dialect=postgresql.dialect())) print(tanimoto_knn_stmt.compile(dialect=postgresql.dialect())) print(dice_knn_stmt.compile(dialect=postgresql.dialect())) print(function_stmt.compile(dialect=postgresql.dialect())) @@ -511,6 +526,8 @@ def main() -> None: ): ["ethanol oxidation"], ("RdkitFPComparator", "tanimoto_matches"): ["ethanol"], ("RdkitFPComparator", "dice_matches"): ["ethanol"], + ("RdkitFPComparator", "similar_to"): ["ethanol"], + ("RdkitFPComparator", "similarity_score"): [1.0], ("RdkitFPComparator", "tanimoto_distance"): [ "ethanol", "aspirin", diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e6d21d6..73cf821 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -48,7 +48,6 @@ molalchemy aims to be the **definitive Python library** for chemical database op ### Future Plans - ⬜ ChemAxon cartridge integration (closed source, requires license) -- ⬜ NextMove Author integration (closed source, requires license) - ⬜ Multi-dialect support for Bingo (e.g MySQL, Oracle) - ⬜ SQLite RDKit support (via [chemicalite](https://github.com/rvianello/chemicalite), including custom builds or custom event listeners) - ⬜ Performance benchmarking diff --git a/docs/migrations/bingo-comparator-api.md b/docs/migrations/bingo-comparator-api.md index e4caf89..ebe9e0b 100644 --- a/docs/migrations/bingo-comparator-api.md +++ b/docs/migrations/bingo-comparator-api.md @@ -56,7 +56,9 @@ The standalone helpers remain available: from molalchemy.bingo import functions as bingo_func mol_predicate = bingo_func.mol_equals(Compound.structure, query, "STE") +mol_not_equal = bingo_func.mol_not_equals(Compound.structure, query, "STE") rxn_predicate = bingo_func.rxn_equals(Reaction.reaction, query_reaction) +rxn_not_equal = bingo_func.rxn_not_equals(Reaction.reaction, query_reaction) ``` ## Storage equality is not chemical equality @@ -129,6 +131,9 @@ Molecule and reaction search methods now return `ColumnElement[bool]` backed by SQLAlchemy `Boolean`. This applies to substructure, SMARTS, exact, negated exact, and similarity predicates. +Molecule similarity score methods return `ColumnElement[float]` backed by +SQLAlchemy `Float`. + They can be composed and labeled like ordinary SQLAlchemy predicates: ```python diff --git a/docs/migrations/rdkit-comparator-api.md b/docs/migrations/rdkit-comparator-api.md index dbfb0db..6beaa9f 100644 --- a/docs/migrations/rdkit-comparator-api.md +++ b/docs/migrations/rdkit-comparator-api.md @@ -101,7 +101,8 @@ Molecule.structure != None # IS NOT NULL ## Expression result types Molecule and reaction search methods now produce `ColumnElement[bool]` backed -by SQLAlchemy `Boolean`. Fingerprint KNN methods produce +by SQLAlchemy `Boolean`. Fingerprint `similar_to()` also produces a Boolean +expression. Fingerprint KNN methods and `similarity_score()` produce `ColumnElement[float]` backed by SQLAlchemy `Float`. This makes Boolean composition and distance ordering accurately reflect the @@ -115,6 +116,34 @@ distance = Molecule.fingerprint.dice_distance(query_fp) stmt = select(Molecule).order_by(distance) ``` +## Bingo-compatible similarity API + +Fingerprint columns also expose the same explicit predicate/score split as +Bingo molecule columns: + +```python +predicate = Molecule.fingerprint.similar_to( + query_fp, + minimum=0.7, + maximum=1.0, + metric="Tanimoto", +) +score = Molecule.fingerprint.similarity_score(query_fp, metric="Dice") +``` + +The standalone equivalents are `fp_similar_to()` and +`fp_similarity_score()`. The accepted metric names are exactly `"Tanimoto"` +and `"Dice"`; unsupported names raise `ValueError` while constructing the SQL +expression. Either bound may be `None` to leave that side open. +Bounds accept numeric SQL expressions as well as Python numbers, so they may +come from another column, a bind parameter, or a computed expression. + +This convenience predicate exists to match Bingo's `similar_to()` API. It compares +`tanimoto_sml()` or `dice_sml()` directly with the requested bounds, so it may +be slower than RDKit's native `%`/`#` threshold operators or `<%>`/`<#>` KNN +operators. Keep using the metric-specific native methods when indexed search +performance matters. + ## Typed column helpers Direct comparator calls remain the runtime API. SQLAlchemy currently exposes @@ -128,6 +157,10 @@ mol_predicate = rdkit_col(Molecule.structure).equals(other_molecule) rxn_predicate = rdkit_rxn_col(Reaction.reaction).has_substructure(query_reaction) fp_predicate = rdkit_fp_col(Molecule.fingerprint).dice_matches(other_fingerprint) fp_distance = rdkit_fp_col(Molecule.fingerprint).tanimoto_distance(query_fp) +bingo_compatible_predicate = rdkit_fp_col(Molecule.fingerprint).similar_to( + query_fp, minimum=0.7 +) +bingo_compatible_score = rdkit_fp_col(Molecule.fingerprint).similarity_score(query_fp) ``` `rdkit_fp_col()` is new. All three helpers return the original SQLAlchemy @@ -147,6 +180,7 @@ The typed comparator interface reflects the corresponding bind processors: - Reactions accept reaction strings, `rdkit.Chem.rdChemReactions.ChemicalReaction`, and SQL expressions. - Fingerprints accept bytes and SQL expressions. +- Similarity bounds accept numbers, `None`, and numeric SQL expressions. - Core columns and ORM `InstrumentedAttribute` objects are valid SQL operands. ## Unchanged APIs @@ -154,3 +188,6 @@ The typed comparator interface reflects the corresponding bind processors: Constructors, conversions, descriptors, fingerprint generators, score functions, aggregates, settings, indexes, and database/file workflows remain standalone functions. Existing calls to those functions do not require changes. +The existing molecule and reaction comparator methods, including +`has_substructure()`, `has_smarts()`, `equals()`, and `not_equals()`, also keep +their established names and behavior. diff --git a/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb b/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb index 29e43b1..76a05bd 100644 --- a/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb +++ b/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb @@ -636,6 +636,43 @@ "session.execute(final_query).all()" ] }, + { + "cell_type": "markdown", + "id": "bingo-similarity-api", + "metadata": {}, + "source": [ + "### Similarity Predicate and Score APIs\n", + "\n", + "Bingo molecule columns provide two complementary high-level operations:\n", + "\n", + "- `.similarity_score()` and `functions.mol_similarity_score()` return a numeric score for selecting, labeling, or ordering results.\n", + "- `.similar_to()` and `functions.mol_similar_to()` return a Boolean predicate bounded by `minimum` and `maximum`. Either bound can be `None`.\n", + "\n", + "The cartridge-level `functions.getsimilarity()` function used above remains available. `functions.mol_similarity()` is the backward-compatible predicate spelling with the older `bottom` and `top` parameter names. All of these APIs operate directly on `BingoMol`; no explicit fingerprint column is required." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bingo-similarity-examples", + "metadata": {}, + "outputs": [], + "source": [ + "score_expr = MoleculeFP.mol.similarity_score(target_smi).label(\"similarity\")\n", + "score_function = functions.mol_similarity_score(MoleculeFP.mol, target_smi)\n", + "\n", + "bounded_query = select(MoleculeFP).where(\n", + " MoleculeFP.mol.similar_to(target_smi, minimum=0.7, maximum=1.0)\n", + ")\n", + "bounded_function_query = select(MoleculeFP).where(\n", + " functions.mol_similar_to(\n", + " MoleculeFP.mol, target_smi, minimum=0.7, maximum=1.0\n", + " )\n", + ")\n", + "\n", + "session.execute(bounded_query).scalars().all()" + ] + }, { "cell_type": "markdown", "id": "94344687", diff --git a/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb b/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb index 8468831..0a30e87 100644 --- a/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb +++ b/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb @@ -662,12 +662,48 @@ "session.execute(final_query).all()" ] }, + { + "cell_type": "markdown", + "id": "rdkit-score-api", + "metadata": {}, + "source": [ + "### Numeric Similarity Scores\n", + "\n", + "The raw `functions.tanimoto_sml()` call above can also be written as `.similarity_score()` or `functions.fp_similarity_score()`. Select `metric=\"Tanimoto\"` or `metric=\"Dice\"`; all forms return a floating-point score." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "rdkit-score-examples", + "metadata": {}, + "outputs": [], + "source": [ + "score_expr = MoleculeFP.fp.similarity_score(\n", + " target_fp, metric=\"Tanimoto\"\n", + ").label(\"similarity\")\n", + "score_function = functions.fp_similarity_score(\n", + " MoleculeFP.fp, target_fp, metric=\"Dice\"\n", + ")" + ] + }, { "cell_type": "markdown", "id": "169bac0f", "metadata": {}, "source": [ - "Alternatively, you can use `.dice` / `.tanimoto` methods on the fingerprint column directly, which return true only for the molecules with similarity above the `rdkit.tanimoto_threshold`. For more information see **Similarity Threshold Settings** tutorial." + "### Native Threshold Predicates\n", + "\n", + "The operators documented by the RDKit PostgreSQL cartridge map to these ORM methods:\n", + "\n", + "| PostgreSQL expression | Meaning | ORM equivalent | Result and use |\n", + "| --- | --- | --- | --- |\n", + "| `fp % query_fp` | Tanimoto threshold match | `fp.tanimoto_matches(query_fp)` | Boolean predicate for `WHERE` |\n", + "| `fp # query_fp` | Dice threshold match | `fp.dice_matches(query_fp)` | Boolean predicate for `WHERE` |\n", + "| `fp <%> query_fp` | Tanimoto KNN distance | `fp.tanimoto_distance(query_fp)` | Float expression for `ORDER BY` |\n", + "| `fp <#> query_fp` | Dice KNN distance | `fp.dice_distance(query_fp)` | Float expression for `ORDER BY` |\n", + "\n", + "The `%` and `#` cutoffs come from the `rdkit.tanimoto_threshold` and `rdkit.dice_threshold` connection settings. See the **Similarity Threshold Settings** tutorial for configuring them. `similar_to()` is a Bingo-compatible score comparison and does not correspond to a single native PostgreSQL operator." ] }, { @@ -697,11 +733,47 @@ ], "source": [ "q_1 = select(MoleculeFP).where(MoleculeFP.fp.tanimoto_matches(target_fp))\n", - "q_2 = select(MoleculeFP).where(MoleculeFP.fp.op(\"%\")(target_fp))\n", + "q_2 = select(MoleculeFP).where(MoleculeFP.fp.dice_matches(target_fp))\n", "display(session.execute(q_1).all())\n", "display(session.execute(q_2).all())" ] }, + { + "cell_type": "markdown", + "id": "rdkit-bounded-knn-api", + "metadata": {}, + "source": [ + "### Bingo-Compatible Bounds and Native KNN Ordering\n", + "\n", + "`.similar_to()` and `functions.fp_similar_to()` provide explicit `minimum`/`maximum` bounds to match Bingo's high-level API. They compare a computed score and can be slower than RDKit's native threshold and KNN operators. Use them when consistent cross-cartridge query structure matters; use the native methods when indexed performance matters.\n", + "\n", + "For nearest-neighbor ranking, order by `.tanimoto_distance()` or `.dice_distance()`. The raw score and distance functions (`tanimoto_sml`, `dice_sml`, `tanimoto_dist`, and `dice_dist`) also remain available." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "rdkit-bounded-knn-examples", + "metadata": {}, + "outputs": [], + "source": [ + "bounded_query = select(MoleculeFP).where(\n", + " MoleculeFP.fp.similar_to(\n", + " target_fp, minimum=0.7, maximum=1.0, metric=\"Tanimoto\"\n", + " )\n", + ")\n", + "bounded_function_query = select(MoleculeFP).where(\n", + " functions.fp_similar_to(\n", + " MoleculeFP.fp, target_fp, minimum=0.7, maximum=1.0\n", + " )\n", + ")\n", + "nearest_query = (\n", + " select(MoleculeFP)\n", + " .order_by(MoleculeFP.fp.tanimoto_distance(target_fp))\n", + " .limit(10)\n", + ")" + ] + }, { "cell_type": "markdown", "id": "4fddd3fd", diff --git a/docs/tutorials/08_proxy_helpers.md b/docs/tutorials/08_proxy_helpers.md index e4047d3..e156950 100644 --- a/docs/tutorials/08_proxy_helpers.md +++ b/docs/tutorials/08_proxy_helpers.md @@ -115,6 +115,16 @@ reaction_smarts = select(Reaction).where( nearest = select(Compound).order_by( rdkit_fp_col(Compound.fingerprint).tanimoto_distance(b"query fingerprint") ) + +bingo_compatible_match = select(Compound).where( + rdkit_fp_col(Compound.fingerprint).similar_to( + b"query fingerprint", minimum=0.7, metric="Tanimoto" + ) +) + +bingo_compatible_score = rdkit_fp_col(Compound.fingerprint).similarity_score( + b"query fingerprint", metric="Dice" +) ``` For RDKit molecule columns, `.equals()` is an explicit spelling of chemical diff --git a/src/molalchemy/protocols.py b/src/molalchemy/protocols.py index d834836..2fb82a0 100644 --- a/src/molalchemy/protocols.py +++ b/src/molalchemy/protocols.py @@ -5,7 +5,7 @@ ``molalchemy.helpers``. """ -from typing import Any, Protocol, TypeAlias +from typing import Any, Literal, Protocol, TypeAlias from rdkit import Chem from rdkit.Chem.rdChemReactions import ChemicalReaction @@ -16,6 +16,8 @@ RdkitMolOperand: TypeAlias = str | Chem.Mol | SqlOperand RdkitReactionOperand: TypeAlias = str | ChemicalReaction | SqlOperand RdkitFingerprintOperand: TypeAlias = bytes | SqlOperand +RdkitSimilarityMetric: TypeAlias = Literal["Tanimoto", "Dice"] +RdkitSimilarityBound: TypeAlias = float | None | SqlOperand BingoOperand: TypeAlias = str | bytes | SqlOperand BingoParameters: TypeAlias = str | SqlOperand BingoSimilarityBound: TypeAlias = float | None | SqlOperand @@ -101,6 +103,20 @@ def is_substructure_fp_of( class RdkitFingerprintColumn(Protocol): + def similar_to( + self, + query: RdkitFingerprintOperand, + minimum: RdkitSimilarityBound = 0.0, + maximum: RdkitSimilarityBound = 1.0, + metric: RdkitSimilarityMetric = "Tanimoto", + ) -> ColumnElement[bool]: ... + + def similarity_score( + self, + query: RdkitFingerprintOperand, + metric: RdkitSimilarityMetric = "Tanimoto", + ) -> ColumnElement[float]: ... + def tanimoto_matches( self, query: RdkitFingerprintOperand ) -> ColumnElement[bool]: ... @@ -125,5 +141,7 @@ def dice_distance(self, query: RdkitFingerprintOperand) -> ColumnElement[float]: "RdkitMolOperand", "RdkitReactionColumn", "RdkitReactionOperand", + "RdkitSimilarityBound", + "RdkitSimilarityMetric", "SqlOperand", ] diff --git a/src/molalchemy/rdkit/comparators.py b/src/molalchemy/rdkit/comparators.py index b00c8c2..b6bfec8 100644 --- a/src/molalchemy/rdkit/comparators.py +++ b/src/molalchemy/rdkit/comparators.py @@ -7,6 +7,8 @@ RdkitFingerprintOperand, RdkitMolOperand, RdkitReactionOperand, + RdkitSimilarityBound, + RdkitSimilarityMetric, SqlOperand, ) from molalchemy.rdkit.search import ( @@ -14,6 +16,8 @@ _rdkit_mol_smarts, _rdkit_predicate, _rdkit_rxn_smarts, + _rdkit_similar_to, + _rdkit_similarity_score, ) @@ -80,6 +84,30 @@ def is_substructure_fp_of(self, query: RdkitReactionOperand) -> ColumnElement[bo class RdkitFPComparator(UserDefinedType.Comparator): + def similar_to( + self, + query: RdkitFingerprintOperand, + minimum: RdkitSimilarityBound = 0.0, + maximum: RdkitSimilarityBound = 1.0, + metric: RdkitSimilarityMetric = "Tanimoto", + ) -> ColumnElement[bool]: + """Check whether fingerprint similarity is within explicit bounds. + + This Bingo-compatible convenience API compares a computed score and may + be slower than RDKit's native threshold or KNN operators. Prefer + ``tanimoto_matches()``, ``dice_matches()``, or the distance methods when + native indexed performance is required. + """ + return _rdkit_similar_to(self.expr, query, minimum, maximum, metric) + + def similarity_score( + self, + query: RdkitFingerprintOperand, + metric: RdkitSimilarityMetric = "Tanimoto", + ) -> ColumnElement[float]: + """Return the numeric fingerprint similarity score.""" + return _rdkit_similarity_score(self.expr, query, metric) + def tanimoto_matches(self, query: RdkitFingerprintOperand) -> ColumnElement[bool]: """Tanimoto similarity threshold operator (%). diff --git a/src/molalchemy/rdkit/functions/__init__.py b/src/molalchemy/rdkit/functions/__init__.py index c722241..7daa634 100644 --- a/src/molalchemy/rdkit/functions/__init__.py +++ b/src/molalchemy/rdkit/functions/__init__.py @@ -21,6 +21,8 @@ featmorganbv_fp, fmcs, fmcs_smiles, + fp_similar_to, + fp_similarity_score, is_valid_ctab, is_valid_mol_pkl, is_valid_smarts, @@ -210,6 +212,8 @@ "fmcs", "fmcs_smiles", "fmcs_smiles_transition", + "fp_similar_to", + "fp_similarity_score", "is_valid_ctab", "is_valid_mol_pkl", "is_valid_smarts", diff --git a/src/molalchemy/rdkit/functions/general.py b/src/molalchemy/rdkit/functions/general.py index 1c26f97..b6f1cf0 100644 --- a/src/molalchemy/rdkit/functions/general.py +++ b/src/molalchemy/rdkit/functions/general.py @@ -10,10 +10,18 @@ from sqlalchemy.sql.expression import Cast from sqlalchemy.sql.functions import GenericFunction +from molalchemy.protocols import ( + RdkitFingerprintOperand, + RdkitSimilarityBound, + RdkitSimilarityMetric, + SqlOperand, +) from molalchemy.rdkit.search import ( _rdkit_mol_smarts, _rdkit_predicate, _rdkit_rxn_smarts, + _rdkit_similar_to, + _rdkit_similarity_score, ) from molalchemy.rdkit.types import ( RdkitBitFingerprint, @@ -36,6 +44,31 @@ ) +def fp_similar_to( + fp_column: SqlOperand, + query: RdkitFingerprintOperand, + minimum: RdkitSimilarityBound = 0.0, + maximum: RdkitSimilarityBound = 1.0, + metric: RdkitSimilarityMetric = "Tanimoto", +) -> ColumnElement[bool]: + """Check whether fingerprint similarity is within explicit bounds. + + This helper provides a Bingo-compatible similarity API. Because it compares a + computed score, it may be slower than RDKit's native threshold and KNN + operators. + """ + return _rdkit_similar_to(fp_column, query, minimum, maximum, metric) + + +def fp_similarity_score( + fp_column: SqlOperand, + query: RdkitFingerprintOperand, + metric: RdkitSimilarityMetric = "Tanimoto", +) -> ColumnElement[float]: + """Return the numeric fingerprint similarity score.""" + return _rdkit_similarity_score(fp_column, query, metric) + + def mol_has_substructure( mol_column: ColumnElement[RdkitMol], query: AnyRdkitMolLike ) -> ColumnElement[bool]: diff --git a/src/molalchemy/rdkit/search.py b/src/molalchemy/rdkit/search.py index 94ddbdd..ddf477c 100644 --- a/src/molalchemy/rdkit/search.py +++ b/src/molalchemy/rdkit/search.py @@ -6,7 +6,14 @@ from sqlalchemy.sql import cast as sql_cast from sqlalchemy.sql import func from sqlalchemy.sql.elements import ColumnElement +from sqlalchemy.sql.expression import type_coerce +from molalchemy.protocols import ( + RdkitFingerprintOperand, + RdkitSimilarityBound, + RdkitSimilarityMetric, + SqlOperand, +) from molalchemy.types import CString @@ -24,6 +31,39 @@ def _rdkit_distance( return cast(ColumnElement[float], column.op(operator, return_type=Float())(query)) +def _rdkit_similarity_score( + column: SqlOperand, + query: RdkitFingerprintOperand, + metric: RdkitSimilarityMetric, +) -> ColumnElement[float]: + """Build a metric-specific floating-point fingerprint similarity score.""" + if metric == "Tanimoto": + function = func.tanimoto_sml + elif metric == "Dice": + function = func.dice_sml + else: + raise ValueError(f"Unsupported RDKit similarity metric: {metric}") + return cast(ColumnElement[float], function(column, query, type_=Float())) + + +def _rdkit_similar_to( + column: SqlOperand, + query: RdkitFingerprintOperand, + minimum: RdkitSimilarityBound, + maximum: RdkitSimilarityBound, + metric: RdkitSimilarityMetric, +) -> ColumnElement[bool]: + """Build an explicit bounded similarity predicate from a score expression.""" + score = _rdkit_similarity_score(column, query, metric) + if minimum is not None and maximum is not None: + return type_coerce(score.between(minimum, maximum), Boolean()) + if minimum is not None: + return score >= minimum + if maximum is not None: + return score <= maximum + return cast(ColumnElement[bool], score.is_not(None)) + + def _rdkit_mol_smarts( column: ColumnElement[Any], pattern: object ) -> ColumnElement[bool]: diff --git a/tests/bingo/test_functions.py b/tests/bingo/test_functions.py index cda2d33..462dac5 100644 --- a/tests/bingo/test_functions.py +++ b/tests/bingo/test_functions.py @@ -2,9 +2,7 @@ import pytest from sqlalchemy import ( - BinaryExpression, Column, - Function, Integer, MetaData, String, @@ -18,8 +16,6 @@ from molalchemy.bingo import functions as bingo_func from molalchemy.bingo.types import BingoMol, BingoReaction -all_funcs = bingo_func.__all__ - class Base(DeclarativeBase): pass @@ -34,20 +30,6 @@ class Compound(Base): query_parameters: Mapped[str] = mapped_column(String()) -@pytest.mark.parametrize("func", all_funcs) -def test_any_function_returns_function_object(func): - """Test that any function returns a SQLAlchemy function object.""" - random_args = ["CCO"] * 10 - random_columns = [Column("dummy", BingoMol())] * 10 - if callable(func): - try: - result = func(*random_args[: func.__code__.co_argcount]) - assert isinstance(result, Function) - except AttributeError: - result = func(*random_columns[: func.__code__.co_argcount]) - assert isinstance(result, BinaryExpression) - - def test_bingo_search_helpers_bind_literal_inputs(): """Search helper literals must compile as bind parameters, not SQL text.""" compounds = Table( diff --git a/tests/rdkit/test_comparators.py b/tests/rdkit/test_comparators.py index 3b40d3d..0408d3e 100644 --- a/tests/rdkit/test_comparators.py +++ b/tests/rdkit/test_comparators.py @@ -19,6 +19,7 @@ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from molalchemy.rdkit import RdkitFPComparator, RdkitMolComparator +from molalchemy.rdkit import functions as rdkit_func from molalchemy.rdkit.types import ( RdkitBitFingerprint, RdkitMol, @@ -139,6 +140,50 @@ def test_fingerprint_operators_have_exact_types( assert operator in sql(expression) +@pytest.mark.parametrize("fingerprint", ["bfp", "sfp"]) +@pytest.mark.parametrize( + ("metric", "score_function"), + [("Tanimoto", "tanimoto_sml"), ("Dice", "dice_sml")], +) +def test_bingo_compatible_similarity_comparator_and_function_parity( + columns, fingerprint, metric, score_function +): + column = columns[fingerprint] + query = bindparam("query_fp", b"fingerprint") + score = column.similarity_score(query, metric) + functional_score = rdkit_func.fp_similarity_score(column, query, metric) + predicate = column.similar_to(query, 0.2, 0.8, metric) + functional_predicate = rdkit_func.fp_similar_to(column, query, 0.2, 0.8, metric) + + assert isinstance(score.type, Float) + assert isinstance(predicate.type, Boolean) + assert sql(score) == sql(functional_score) + assert sql(predicate) == sql(functional_predicate) + assert score_function in sql(score) + assert " BETWEEN " in sql(predicate) + + +@pytest.mark.parametrize( + ("minimum", "maximum", "operator"), + [ + (0.2, 0.8, " BETWEEN "), + (0.2, None, " >= "), + (None, 0.8, " <= "), + (None, None, " IS NOT NULL"), + ], +) +def test_bingo_compatible_similarity_bound_shapes(columns, minimum, maximum, operator): + expression = columns.bfp.similar_to(b"fingerprint", minimum, maximum, "Tanimoto") + + assert isinstance(expression.type, Boolean) + assert operator in sql(expression) + + +def test_bingo_compatible_similarity_rejects_unsupported_metrics(columns): + with pytest.raises(ValueError, match="Unsupported RDKit similarity metric: Cosine"): + columns.bfp.similarity_score(b"fingerprint", "Cosine") + + def test_removed_fingerprint_methods_have_no_compatibility_aliases(columns): for name in ("tanimoto", "dice", "nearest_neighbors"): with pytest.raises(AttributeError): @@ -198,9 +243,13 @@ def test_native_equality_and_null_semantics(columns, name): def test_orm_comparators_remain_available_at_runtime(): predicate = Compound.mol.equals("CCO") distance = Compound.fp.tanimoto_distance(b"fingerprint") + similarity = Compound.fp.similar_to(b"fingerprint", minimum=0.7) + score = Compound.fp.similarity_score(b"fingerprint") assert isinstance(predicate.type, Boolean) + assert isinstance(similarity.type, Boolean) assert isinstance(distance.type, Float) + assert isinstance(score.type, Float) assert "ORDER BY" in sql(select(Compound).order_by(distance)) diff --git a/tests/rdkit/test_functions.py b/tests/rdkit/test_functions.py index f38dfc9..b9e3805 100644 --- a/tests/rdkit/test_functions.py +++ b/tests/rdkit/test_functions.py @@ -2,9 +2,7 @@ import pytest from sqlalchemy import ( - BinaryExpression, Column, - Function, Integer, MetaData, Table, @@ -18,8 +16,6 @@ from molalchemy.rdkit import functions as rdkit_func from molalchemy.rdkit.types import RdkitMol, RdkitQMol, RdkitReaction -all_funcs = rdkit_func.__all__ - class Base(DeclarativeBase): pass @@ -41,20 +37,6 @@ class Reaction(Base): query_reaction: Mapped[str] = mapped_column(RdkitReaction()) -@pytest.mark.parametrize("func", all_funcs) -def test_any_function_returns_function_object(func): - """Test that any function returns a SQLAlchemy function object.""" - random_args = ["CCO"] * 10 - random_columns = [Column("dummy", RdkitMol())] * 10 - if callable(func): - try: - result = func(*random_args[: func.__code__.co_argcount]) - assert isinstance(result, Function) - except AttributeError: - result = func(*random_columns[: func.__code__.co_argcount]) - assert isinstance(result, BinaryExpression) - - @pytest.mark.parametrize( ("helper_name", "query", "operator"), [ From 975cfd05a9d3ffe6bca7290fce10235234eb165d Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Sat, 8 Aug 2026 22:29:47 +0200 Subject: [PATCH 12/13] remove pool of setting update --- README.md | 2 +- dev_scripts/validate_rdkit_helpers.py | 43 ++++++++++++++++++++++++--- docs/api/rdkit/settings.md | 8 +++-- docs/index.md | 2 +- src/molalchemy/rdkit/settings.py | 6 +++- tests/rdkit/test_settings.py | 14 +++++++++ 6 files changed, 65 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 1f7af56..7933252 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ with similarity_threshold(session, tanimoto=0.1, dice=0.2): # Original thresholds are restored automatically ``` -`None` fields leave the server value unchanged. Calling `configure_engine` again replaces the previous MolAlchemy baseline, and `RdkitSettings()` removes it. See the [RDKit cartridge configuration reference](https://rdkit.org/new_docs/Cartridge.html#configuration) for the underlying settings. +`None` fields leave the server value unchanged. Calling `configure_engine` again replaces the previous MolAlchemy baseline, and `RdkitSettings()` removes it. Reconfiguration disposes idle pooled connections so they cannot retain settings from the previous baseline; connections already checked out continue normally until returned. See the [RDKit cartridge configuration reference](https://rdkit.org/new_docs/Cartridge.html#configuration) for the underlying settings. ### Chemical Reactions diff --git a/dev_scripts/validate_rdkit_helpers.py b/dev_scripts/validate_rdkit_helpers.py index 8b810a7..8a69a93 100644 --- a/dev_scripts/validate_rdkit_helpers.py +++ b/dev_scripts/validate_rdkit_helpers.py @@ -87,11 +87,17 @@ def main() -> None: atompair_fp_size=2048, avalon_fp_size=2048, ) - engine = configure_engine( - create_engine(DATABASE_URL, echo=False, pool_size=1, max_overflow=0), - baseline_settings, - ) + engine = create_engine(DATABASE_URL, echo=False, pool_size=1, max_overflow=0) wait_for_db(engine) + with engine.connect() as conn: + server_default_thresholds = { + name: conn.exec_driver_sql(f"SHOW {name}").scalar_one() + for name in ( + "rdkit.tanimoto_threshold", + "rdkit.dice_threshold", + ) + } + configure_engine(engine, baseline_settings) with engine.connect() as conn: actual_gucs = { @@ -126,6 +132,30 @@ def main() -> None: "SHOW rdkit.tanimoto_threshold" ).scalar_one() assert reconfigured_after_dispose == "0.65" + + # Reconfiguration replaces the pool so settings omitted from the new + # baseline cannot survive on reused physical connections. + configure_engine(engine, RdkitSettings(dice_threshold=0.6)) + with engine.connect() as conn: + thresholds_after_partial_replacement = { + name: conn.exec_driver_sql(f"SHOW {name}").scalar_one() + for name in server_default_thresholds + } + assert thresholds_after_partial_replacement == { + "rdkit.tanimoto_threshold": server_default_thresholds[ + "rdkit.tanimoto_threshold" + ], + "rdkit.dice_threshold": "0.6", + } + + configure_engine(engine, RdkitSettings()) + with engine.connect() as conn: + thresholds_after_removal = { + name: conn.exec_driver_sql(f"SHOW {name}").scalar_one() + for name in server_default_thresholds + } + assert thresholds_after_removal == server_default_thresholds + configure_engine(engine, baseline_settings) metadata = MetaData() @@ -449,6 +479,11 @@ def main() -> None: print(f"reapplied tanimoto threshold: {reapplied_tanimoto}") print(f"reapplied after engine disposal: {reapplied_after_dispose}") print(f"reconfigured after engine disposal: {reconfigured_after_dispose}") + print( + "thresholds after partial baseline replacement: " + f"{thresholds_after_partial_replacement}" + ) + print(f"thresholds after baseline removal: {thresholds_after_removal}") print(f"substructure(c1ccccc1): {substructure_rows}") print(f"mol_has_substructure(c1ccccc1): {functional_substructure_rows}") print(f"exact(CCO): {exact_rows}") diff --git a/docs/api/rdkit/settings.md b/docs/api/rdkit/settings.md index afcc260..d2ce96a 100644 --- a/docs/api/rdkit/settings.md +++ b/docs/api/rdkit/settings.md @@ -23,9 +23,11 @@ engine = configure_engine( Only non-`None` fields are changed. Reconfiguring the same engine replaces its previous MolAlchemy listener; passing an empty `RdkitSettings()` removes that -listener. Because the baseline is applied on every checkout, a request that -changes an RDKit GUC does not permanently change the next request's pooled -connection. +listener. Reconfiguration disposes the existing pool so idle connections +cannot retain values from the previous baseline. Connections already checked +out continue normally and retain their current session values until returned. +Because the baseline is applied on every checkout, a request that changes an +RDKit GUC does not permanently change the next request's pooled connection. The `set_*`, `get_*`, and `similarity_threshold` helpers remain useful for intentional, session-local threshold changes. `configure_engine` is for a pool diff --git a/docs/index.md b/docs/index.md index 1f7af56..7933252 100644 --- a/docs/index.md +++ b/docs/index.md @@ -293,7 +293,7 @@ with similarity_threshold(session, tanimoto=0.1, dice=0.2): # Original thresholds are restored automatically ``` -`None` fields leave the server value unchanged. Calling `configure_engine` again replaces the previous MolAlchemy baseline, and `RdkitSettings()` removes it. See the [RDKit cartridge configuration reference](https://rdkit.org/new_docs/Cartridge.html#configuration) for the underlying settings. +`None` fields leave the server value unchanged. Calling `configure_engine` again replaces the previous MolAlchemy baseline, and `RdkitSettings()` removes it. Reconfiguration disposes idle pooled connections so they cannot retain settings from the previous baseline; connections already checked out continue normally until returned. See the [RDKit cartridge configuration reference](https://rdkit.org/new_docs/Cartridge.html#configuration) for the underlying settings. ### Chemical Reactions diff --git a/src/molalchemy/rdkit/settings.py b/src/molalchemy/rdkit/settings.py index 2d42e80..79e63b6 100644 --- a/src/molalchemy/rdkit/settings.py +++ b/src/molalchemy/rdkit/settings.py @@ -145,7 +145,9 @@ def configure_engine(engine: Engine, settings: RdkitSettings | None = None) -> E Calling this function again for the same engine replaces its previous molalchemy listener. Passing an empty :class:`RdkitSettings` removes any - previous listener. The engine itself is returned for convenient assignment. + previous listener. Reconfiguration disposes the existing pool so that idle + connections cannot retain settings from the previous baseline. The engine + itself is returned for convenient assignment. Parameters ---------- @@ -175,6 +177,8 @@ def configure_engine(engine: Engine, settings: RdkitSettings | None = None) -> E if listener is not None: event.listen(engine, "checkout", listener) _engine_listeners[engine] = listener + if previous_listener is not None: + engine.dispose() return engine diff --git a/tests/rdkit/test_settings.py b/tests/rdkit/test_settings.py index ecd674b..92398a2 100644 --- a/tests/rdkit/test_settings.py +++ b/tests/rdkit/test_settings.py @@ -168,11 +168,16 @@ def test_reconfiguration_replaces_previous_listener( lambda target, name, listener: removed.append(listener), ) + original_pool = postgres_engine.pool configure_engine(postgres_engine, RdkitSettings(tanimoto_threshold=0.4)) + + assert postgres_engine.pool is original_pool + configure_engine(postgres_engine, RdkitSettings(dice_threshold=0.6)) assert len(registered) == 2 assert removed == [registered[0]] + assert postgres_engine.pool is not original_pool def test_empty_settings_remove_listener_without_registering_another( self, postgres_engine, monkeypatch @@ -190,11 +195,20 @@ def test_empty_settings_remove_listener_without_registering_another( lambda target, name, listener: removed.append(listener), ) + configured_pool = postgres_engine.pool configure_engine(postgres_engine, RdkitSettings(dice_threshold=0.6)) configure_engine(postgres_engine, RdkitSettings()) assert len(registered) == 1 assert removed == registered + assert postgres_engine.pool is not configured_pool + + def test_initial_empty_settings_do_not_replace_pool(self, postgres_engine): + original_pool = postgres_engine.pool + + configure_engine(postgres_engine, RdkitSettings()) + + assert postgres_engine.pool is original_pool def test_reconfiguration_survives_engine_dispose(self, postgres_engine): configure_engine( From 3dabdaa828bf69d0a784b863d0f25a344f7f974d Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com.> Date: Sat, 8 Aug 2026 22:37:43 +0200 Subject: [PATCH 13/13] update tutorials --- .../01_Getting_Started_bingo_ORM.ipynb | 244 +++++++++++---- .../01_Getting_Started_rdkit_ORM.ipynb | 278 +++++++++++++++--- .../02_Getting_Started_rdkit_Core.ipynb | 152 ++++++++-- .../04_Similarity_Threshold_Settings.ipynb | 101 ++++++- docs/tutorials/05_Reactions_rdkit_ORM.ipynb | 231 ++++++++++++--- .../tutorials/06_bingo_reactions_binary.ipynb | 48 ++- .../07_rdkit_descriptors_advanced.ipynb | 56 +++- 7 files changed, 918 insertions(+), 192 deletions(-) diff --git a/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb b/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb index 76a05bd..4b9f823 100644 --- a/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb +++ b/docs/tutorials/01_Getting_Started_bingo_ORM.ipynb @@ -57,15 +57,22 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 1, "id": "8965b961", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:16.893722Z", + "iopub.status.busy": "2026-08-08T20:34:16.893470Z", + "iopub.status.idle": "2026-08-08T20:34:17.981767Z", + "shell.execute_reply": "2026-08-08T20:34:17.981549Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "[('1.40.0.0-g8d9e551c1',)]\n" + "[('1.44.0',)]\n" ] } ], @@ -119,9 +126,16 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 2, "id": "5d6ff669", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:17.982981Z", + "iopub.status.busy": "2026-08-08T20:34:17.982896Z", + "iopub.status.idle": "2026-08-08T20:34:18.060766Z", + "shell.execute_reply": "2026-08-08T20:34:18.060474Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -165,9 +179,16 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 3, "id": "0f6f8b1f", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.062528Z", + "iopub.status.busy": "2026-08-08T20:34:18.062434Z", + "iopub.status.idle": "2026-08-08T20:34:18.088251Z", + "shell.execute_reply": "2026-08-08T20:34:18.087947Z" + } + }, "outputs": [], "source": [ "data = [\n", @@ -199,9 +220,16 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 4, "id": "650f4aa8", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.089577Z", + "iopub.status.busy": "2026-08-08T20:34:18.089498Z", + "iopub.status.idle": "2026-08-08T20:34:18.092131Z", + "shell.execute_reply": "2026-08-08T20:34:18.091880Z" + } + }, "outputs": [], "source": [ "autocommit_engine = eng.execution_options(isolation_level=\"AUTOCOMMIT\")\n", @@ -224,9 +252,16 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 5, "id": "ff9cc6d6", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.093277Z", + "iopub.status.busy": "2026-08-08T20:34:18.093185Z", + "iopub.status.idle": "2026-08-08T20:34:18.097150Z", + "shell.execute_reply": "2026-08-08T20:34:18.096933Z" + } + }, "outputs": [ { "data": { @@ -236,7 +271,7 @@ " (Molecule(id=5, name='Talidomide', mol='O=C1c2ccccc2C(=O)N1C3CCC(=O)NC3=O', is_nsaid=False),)]" ] }, - "execution_count": 15, + "execution_count": 5, "metadata": {}, "output_type": "execute_result" } @@ -257,9 +292,16 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 6, "id": "32f8a426", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.098307Z", + "iopub.status.busy": "2026-08-08T20:34:18.098237Z", + "iopub.status.idle": "2026-08-08T20:34:18.102430Z", + "shell.execute_reply": "2026-08-08T20:34:18.102204Z" + } + }, "outputs": [ { "data": { @@ -267,7 +309,7 @@ "[(Molecule(id=1, name='Aspirin', mol='CC(=O)OC1=CC=CC=C1C(=O)O', is_nsaid=True),)]" ] }, - "execution_count": 16, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } @@ -290,9 +332,16 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 7, "id": "c1e188a1", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.103443Z", + "iopub.status.busy": "2026-08-08T20:34:18.103373Z", + "iopub.status.idle": "2026-08-08T20:34:18.106547Z", + "shell.execute_reply": "2026-08-08T20:34:18.106352Z" + } + }, "outputs": [ { "data": { @@ -300,7 +349,7 @@ "[(Molecule(id=1, name='Aspirin', mol='CC(=O)OC1=CC=CC=C1C(=O)O', is_nsaid=True),)]" ] }, - "execution_count": 17, + "execution_count": 7, "metadata": {}, "output_type": "execute_result" } @@ -322,9 +371,16 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 8, "id": "5bccdfa6", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.107615Z", + "iopub.status.busy": "2026-08-08T20:34:18.107545Z", + "iopub.status.idle": "2026-08-08T20:34:18.111040Z", + "shell.execute_reply": "2026-08-08T20:34:18.110808Z" + } + }, "outputs": [ { "data": { @@ -333,7 +389,7 @@ " (Molecule(id=4, name='Captopril', mol='C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O', is_nsaid=False),)]" ] }, - "execution_count": 18, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -354,9 +410,16 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 9, "id": "240f140b", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.112087Z", + "iopub.status.busy": "2026-08-08T20:34:18.112015Z", + "iopub.status.idle": "2026-08-08T20:34:18.114968Z", + "shell.execute_reply": "2026-08-08T20:34:18.114775Z" + } + }, "outputs": [ { "data": { @@ -365,7 +428,7 @@ " (Molecule(id=4, name='Captopril', mol='C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O', is_nsaid=False),)]" ] }, - "execution_count": 19, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -384,9 +447,16 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 10, "id": "bingo-mol-smarts-query", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.115945Z", + "iopub.status.busy": "2026-08-08T20:34:18.115881Z", + "iopub.status.idle": "2026-08-08T20:34:18.119059Z", + "shell.execute_reply": "2026-08-08T20:34:18.118855Z" + } + }, "outputs": [ { "data": { @@ -395,7 +465,7 @@ " (Molecule(id=4, name='Captopril', mol='C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O', is_nsaid=False),)]" ] }, - "execution_count": 20, + "execution_count": 10, "metadata": {}, "output_type": "execute_result" } @@ -408,9 +478,16 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 11, "id": "af67ac59", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.120007Z", + "iopub.status.busy": "2026-08-08T20:34:18.119940Z", + "iopub.status.idle": "2026-08-08T20:34:18.122926Z", + "shell.execute_reply": "2026-08-08T20:34:18.122706Z" + } + }, "outputs": [ { "data": { @@ -419,7 +496,7 @@ " (Molecule(id=4, name='Captopril', mol='C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O', is_nsaid=False),)]" ] }, - "execution_count": 21, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -432,9 +509,16 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 12, "id": "8eb1f4b8", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.123872Z", + "iopub.status.busy": "2026-08-08T20:34:18.123810Z", + "iopub.status.idle": "2026-08-08T20:34:18.125937Z", + "shell.execute_reply": "2026-08-08T20:34:18.125736Z" + } + }, "outputs": [ { "name": "stdout", @@ -472,9 +556,16 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 13, "id": "bingo-rxn-model", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.126981Z", + "iopub.status.busy": "2026-08-08T20:34:18.126920Z", + "iopub.status.idle": "2026-08-08T20:34:18.195076Z", + "shell.execute_reply": "2026-08-08T20:34:18.194809Z" + } + }, "outputs": [], "source": [ "class Reaction(Base):\n", @@ -502,9 +593,16 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 14, "id": "bingo-rxn-functions", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.196269Z", + "iopub.status.busy": "2026-08-08T20:34:18.196195Z", + "iopub.status.idle": "2026-08-08T20:34:18.201532Z", + "shell.execute_reply": "2026-08-08T20:34:18.201261Z" + } + }, "outputs": [ { "data": { @@ -512,7 +610,7 @@ "[(Reaction(id=2, name='alkene hydrogenation', rxn='C=C>>CC'),)]" ] }, - "execution_count": 24, + "execution_count": 14, "metadata": {}, "output_type": "execute_result" } @@ -543,9 +641,16 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 15, "id": "893a6d86", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.202854Z", + "iopub.status.busy": "2026-08-08T20:34:18.202764Z", + "iopub.status.idle": "2026-08-08T20:34:18.246366Z", + "shell.execute_reply": "2026-08-08T20:34:18.246146Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -581,9 +686,16 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 16, "id": "1338370b", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.247582Z", + "iopub.status.busy": "2026-08-08T20:34:18.247516Z", + "iopub.status.idle": "2026-08-08T20:34:18.262005Z", + "shell.execute_reply": "2026-08-08T20:34:18.261691Z" + } + }, "outputs": [], "source": [ "session = SessionLocal()\n", @@ -608,9 +720,16 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 17, "id": "eeb2db50", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.263556Z", + "iopub.status.busy": "2026-08-08T20:34:18.263438Z", + "iopub.status.idle": "2026-08-08T20:34:18.268742Z", + "shell.execute_reply": "2026-08-08T20:34:18.268552Z" + } + }, "outputs": [ { "data": { @@ -622,7 +741,7 @@ " (0.17117117, MoleculeFP(id=4, name='Captopril', mol='C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O', is_nsaid=False))]" ] }, - "execution_count": 27, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } @@ -653,10 +772,28 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "id": "bingo-similarity-examples", - "metadata": {}, - "outputs": [], + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.269968Z", + "iopub.status.busy": "2026-08-08T20:34:18.269845Z", + "iopub.status.idle": "2026-08-08T20:34:18.274048Z", + "shell.execute_reply": "2026-08-08T20:34:18.273867Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[MoleculeFP(id=2, name='Loratadine', mol='O=C(OCC)N4CC/C(=C2/c1ccc(Cl)cc1CCc3cccnc23)CC4', is_nsaid=False)]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "score_expr = MoleculeFP.mol.similarity_score(target_smi).label(\"similarity\")\n", "score_function = functions.mol_similarity_score(MoleculeFP.mol, target_smi)\n", @@ -685,9 +822,16 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 19, "id": "d83fb983", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:18.274975Z", + "iopub.status.busy": "2026-08-08T20:34:18.274916Z", + "iopub.status.idle": "2026-08-08T20:34:18.276710Z", + "shell.execute_reply": "2026-08-08T20:34:18.276409Z" + } + }, "outputs": [ { "name": "stdout", @@ -754,7 +898,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4, diff --git a/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb b/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb index 0a30e87..90fa35a 100644 --- a/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb +++ b/docs/tutorials/01_Getting_Started_rdkit_ORM.ipynb @@ -53,13 +53,20 @@ "cell_type": "code", "execution_count": 1, "id": "ddcb2b72", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:35.477734Z", + "iopub.status.busy": "2026-08-08T20:34:35.477471Z", + "iopub.status.idle": "2026-08-08T20:34:36.031521Z", + "shell.execute_reply": "2026-08-08T20:34:36.031291Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "[('0.77.0', '2025.09.6')]\n" + "[('0.77.0', '2026.03.4')]\n" ] } ], @@ -121,7 +128,14 @@ "cell_type": "code", "execution_count": 2, "id": "7c1d4286", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.032634Z", + "iopub.status.busy": "2026-08-08T20:34:36.032537Z", + "iopub.status.idle": "2026-08-08T20:34:36.055595Z", + "shell.execute_reply": "2026-08-08T20:34:36.055341Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -167,7 +181,14 @@ "cell_type": "code", "execution_count": 3, "id": "9b32959c", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.056768Z", + "iopub.status.busy": "2026-08-08T20:34:36.056688Z", + "iopub.status.idle": "2026-08-08T20:34:36.075403Z", + "shell.execute_reply": "2026-08-08T20:34:36.075169Z" + } + }, "outputs": [], "source": [ "data = [\n", @@ -206,7 +227,14 @@ "cell_type": "code", "execution_count": 4, "id": "fe2028ab", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.076464Z", + "iopub.status.busy": "2026-08-08T20:34:36.076398Z", + "iopub.status.idle": "2026-08-08T20:34:36.080903Z", + "shell.execute_reply": "2026-08-08T20:34:36.080654Z" + } + }, "outputs": [], "source": [ "from rdkit import Chem\n", @@ -222,7 +250,14 @@ "cell_type": "code", "execution_count": 5, "id": "b6e65469", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.081904Z", + "iopub.status.busy": "2026-08-08T20:34:36.081838Z", + "iopub.status.idle": "2026-08-08T20:34:36.089978Z", + "shell.execute_reply": "2026-08-08T20:34:36.089805Z" + } + }, "outputs": [ { "name": "stdout", @@ -256,7 +291,14 @@ "cell_type": "code", "execution_count": 6, "id": "a5b2666e", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.090959Z", + "iopub.status.busy": "2026-08-08T20:34:36.090893Z", + "iopub.status.idle": "2026-08-08T20:34:36.094588Z", + "shell.execute_reply": "2026-08-08T20:34:36.094386Z" + } + }, "outputs": [ { "data": { @@ -290,7 +332,14 @@ "cell_type": "code", "execution_count": 7, "id": "8f356747", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.095544Z", + "iopub.status.busy": "2026-08-08T20:34:36.095483Z", + "iopub.status.idle": "2026-08-08T20:34:36.098644Z", + "shell.execute_reply": "2026-08-08T20:34:36.098433Z" + } + }, "outputs": [ { "data": { @@ -322,7 +371,14 @@ "cell_type": "code", "execution_count": 8, "id": "024ffa61", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.099600Z", + "iopub.status.busy": "2026-08-08T20:34:36.099535Z", + "iopub.status.idle": "2026-08-08T20:34:36.103152Z", + "shell.execute_reply": "2026-08-08T20:34:36.102960Z" + } + }, "outputs": [ { "data": { @@ -354,7 +410,14 @@ "cell_type": "code", "execution_count": 9, "id": "033e8261", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.104083Z", + "iopub.status.busy": "2026-08-08T20:34:36.104019Z", + "iopub.status.idle": "2026-08-08T20:34:36.106691Z", + "shell.execute_reply": "2026-08-08T20:34:36.106516Z" + } + }, "outputs": [ { "data": { @@ -384,7 +447,14 @@ "cell_type": "code", "execution_count": 10, "id": "ab2d92fd", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.107601Z", + "iopub.status.busy": "2026-08-08T20:34:36.107530Z", + "iopub.status.idle": "2026-08-08T20:34:36.111023Z", + "shell.execute_reply": "2026-08-08T20:34:36.110838Z" + } + }, "outputs": [ { "data": { @@ -423,7 +493,14 @@ "cell_type": "code", "execution_count": 11, "id": "0dd1caf0", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.111969Z", + "iopub.status.busy": "2026-08-08T20:34:36.111902Z", + "iopub.status.idle": "2026-08-08T20:34:36.114671Z", + "shell.execute_reply": "2026-08-08T20:34:36.114492Z" + } + }, "outputs": [ { "data": { @@ -456,7 +533,14 @@ "cell_type": "code", "execution_count": 12, "id": "109711ef", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.115623Z", + "iopub.status.busy": "2026-08-08T20:34:36.115562Z", + "iopub.status.idle": "2026-08-08T20:34:36.119257Z", + "shell.execute_reply": "2026-08-08T20:34:36.119071Z" + } + }, "outputs": [ { "data": { @@ -489,7 +573,14 @@ "cell_type": "code", "execution_count": 13, "id": "484b41d2", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.120185Z", + "iopub.status.busy": "2026-08-08T20:34:36.120127Z", + "iopub.status.idle": "2026-08-08T20:34:36.123460Z", + "shell.execute_reply": "2026-08-08T20:34:36.123216Z" + } + }, "outputs": [ { "data": { @@ -533,7 +624,14 @@ "cell_type": "code", "execution_count": 14, "id": "f5617b86", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.124388Z", + "iopub.status.busy": "2026-08-08T20:34:36.124328Z", + "iopub.status.idle": "2026-08-08T20:34:36.147861Z", + "shell.execute_reply": "2026-08-08T20:34:36.147617Z" + } + }, "outputs": [], "source": [ "from sqlalchemy import Computed\n", @@ -570,7 +668,14 @@ "cell_type": "code", "execution_count": 15, "id": "5e2c36e8", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.148777Z", + "iopub.status.busy": "2026-08-08T20:34:36.148718Z", + "iopub.status.idle": "2026-08-08T20:34:36.162120Z", + "shell.execute_reply": "2026-08-08T20:34:36.161932Z" + } + }, "outputs": [], "source": [ "session = SessionLocal()\n", @@ -592,7 +697,14 @@ "cell_type": "code", "execution_count": 16, "id": "45e6718a", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.163134Z", + "iopub.status.busy": "2026-08-08T20:34:36.163073Z", + "iopub.status.idle": "2026-08-08T20:34:36.166400Z", + "shell.execute_reply": "2026-08-08T20:34:36.166206Z" + } + }, "outputs": [ { "data": { @@ -638,7 +750,14 @@ "cell_type": "code", "execution_count": 17, "id": "9447c97a", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.167316Z", + "iopub.status.busy": "2026-08-08T20:34:36.167259Z", + "iopub.status.idle": "2026-08-08T20:34:36.173049Z", + "shell.execute_reply": "2026-08-08T20:34:36.172866Z" + } + }, "outputs": [ { "data": { @@ -674,9 +793,16 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "id": "rdkit-score-examples", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.173983Z", + "iopub.status.busy": "2026-08-08T20:34:36.173926Z", + "iopub.status.idle": "2026-08-08T20:34:36.175365Z", + "shell.execute_reply": "2026-08-08T20:34:36.175161Z" + } + }, "outputs": [], "source": [ "score_expr = MoleculeFP.fp.similarity_score(\n", @@ -708,9 +834,16 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 19, "id": "164cb11b", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.176296Z", + "iopub.status.busy": "2026-08-08T20:34:36.176233Z", + "iopub.status.idle": "2026-08-08T20:34:36.181428Z", + "shell.execute_reply": "2026-08-08T20:34:36.181255Z" + } + }, "outputs": [ { "data": { @@ -752,9 +885,16 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "id": "rdkit-bounded-knn-examples", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.182351Z", + "iopub.status.busy": "2026-08-08T20:34:36.182278Z", + "iopub.status.idle": "2026-08-08T20:34:36.184096Z", + "shell.execute_reply": "2026-08-08T20:34:36.183925Z" + } + }, "outputs": [], "source": [ "bounded_query = select(MoleculeFP).where(\n", @@ -786,9 +926,16 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 21, "id": "32703967", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.184913Z", + "iopub.status.busy": "2026-08-08T20:34:36.184859Z", + "iopub.status.idle": "2026-08-08T20:34:36.186561Z", + "shell.execute_reply": "2026-08-08T20:34:36.186387Z" + } + }, "outputs": [ { "name": "stdout", @@ -826,9 +973,16 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 22, "id": "68a51b79", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.187443Z", + "iopub.status.busy": "2026-08-08T20:34:36.187391Z", + "iopub.status.idle": "2026-08-08T20:34:36.197594Z", + "shell.execute_reply": "2026-08-08T20:34:36.197370Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -870,9 +1024,16 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 23, "id": "be9e0616", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.198519Z", + "iopub.status.busy": "2026-08-08T20:34:36.198458Z", + "iopub.status.idle": "2026-08-08T20:34:36.206597Z", + "shell.execute_reply": "2026-08-08T20:34:36.206406Z" + } + }, "outputs": [], "source": [ "session = SessionLocal()\n", @@ -882,18 +1043,25 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 24, "id": "e5ce3158", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.207468Z", + "iopub.status.busy": "2026-08-08T20:34:36.207412Z", + "iopub.status.idle": "2026-08-08T20:34:36.210254Z", + "shell.execute_reply": "2026-08-08T20:34:36.210064Z" + } + }, "outputs": [ { "data": { "text/plain": [ - "[(RawMoleculeFP(id=1, name='Aspirin', mol=b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\r\\x00\\x00\\x00 ... (970 characters truncated) ... 00000c76fa289010000000b9cd89e01000000c831f8a501000000a7d50bb2010000006455c5bf02000000515fd9bf04000000f9fb51d301000000afbc69ee02000000', is_nsaid=True),),\n", - " (RawMoleculeFP(id=2, name='Loratadine', mol=b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00\\x1e\\x00\\ ... (2084 characters truncated) ... 0000ac3e61ce01000000269925d3010000004aff1ee10100000030fb63e50100000056c98fe6010000003abe53ed0100000060a959ed01000000d6f410ee01000000', is_nsaid=False),)]" + "[(RawMoleculeFP(id=1, name='Aspirin', mol=b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\r\\x00\\x00\\x00 ... (970 characters truncated) ... 00000c76fa289010000000b9cd89e01000000c831f8a501000000a7d50bb2010000006455c5bf02000000515fd9bf04000000f9fb51d301000000afbc69ee02000000', is_nsaid=True),),\n", + " (RawMoleculeFP(id=2, name='Loratadine', mol=b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00\\x1e\\x00\\ ... (2084 characters truncated) ... 0000ac3e61ce01000000269925d3010000004aff1ee10100000030fb63e50100000056c98fe6010000003abe53ed0100000060a959ed01000000d6f410ee01000000', is_nsaid=False),)]" ] }, - "execution_count": 22, + "execution_count": 24, "metadata": {}, "output_type": "execute_result" } @@ -912,9 +1080,16 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 25, "id": "f6b41d01", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.211161Z", + "iopub.status.busy": "2026-08-08T20:34:36.211105Z", + "iopub.status.idle": "2026-08-08T20:34:36.230553Z", + "shell.execute_reply": "2026-08-08T20:34:36.230357Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -946,15 +1121,32 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 26, "id": "5877f080", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:36.231548Z", + "iopub.status.busy": "2026-08-08T20:34:36.231473Z", + "iopub.status.idle": "2026-08-08T20:34:36.258097Z", + "shell.execute_reply": "2026-08-08T20:34:36.257871Z" + } + }, "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "[22:34:36] Depickling from a version number (16.3)that is higher than our version (16.2).\n", + "This probably won't work.\n", + "[22:34:36] Depickling from a version number (16.3)that is higher than our version (16.2).\n", + "This probably won't work.\n" + ] + }, { "data": { "text/plain": [ - "[(ConvertedMoleculeFP(id=1, name='Aspirin', mol=, fp='\\\\x0100000004000000ffffffff190000004034df050200000 ... (252 characters truncated) ... 00000c76fa289010000000b9cd89e01000000c831f8a501000000a7d50bb2010000006455c5bf02000000515fd9bf04000000f9fb51d301000000afbc69ee02000000', is_nsaid=True),),\n", - " (ConvertedMoleculeFP(id=2, name='Loratadine', mol=, fp='\\\\x0100000004000000ffffffff3400000043892d020100 ... (688 characters truncated) ... 0000ac3e61ce01000000269925d3010000004aff1ee10100000030fb63e50100000056c98fe6010000003abe53ed0100000060a959ed01000000d6f410ee01000000', is_nsaid=False),)]" + "[(ConvertedMoleculeFP(id=1, name='Aspirin', mol=, fp='\\\\x0100000004000000ffffffff190000004034df050200000017 ... (249 characters truncated) ... 00000c76fa289010000000b9cd89e01000000c831f8a501000000a7d50bb2010000006455c5bf02000000515fd9bf04000000f9fb51d301000000afbc69ee02000000', is_nsaid=True),),\n", + " (ConvertedMoleculeFP(id=2, name='Loratadine', mol=, fp='\\\\x0100000004000000ffffffff3400000043892d020100000 ... (685 characters truncated) ... 0000ac3e61ce01000000269925d3010000004aff1ee10100000030fb63e50100000056c98fe6010000003abe53ed0100000060a959ed01000000d6f410ee01000000', is_nsaid=False),)]" ] }, "metadata": {}, @@ -964,7 +1156,7 @@ "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAcIAAACWCAIAAADCEh9HAAAABmJLR0QA/wD/AP+gvaeTAAAeZklEQVR4nO3deVgT97oH8G/CEkGQRRR3Fhcsyq2ggAuIYrWAUFlMtVV7atXaPqfF2tNTe459tN7alm6PcOu91mOlalcbCYIigohWUKig0iK4ICAgsiiL7Fsy94+hESkqAslkJu/nr+bNJPPmefDbmd/85jcihmFACCGkr8RcN0AIIfxGMUoIIf1CMUoIIf1CMUoIIf1CMUoIIf2iz3UDhKhXXV1dWFiYRCLZuHHjkCFDuG6HCJCIJjwRAbt9+7aTk1N1dTUAfX19Hx8fqVQaHBxsYmLCdWtEOChGiWCVlZX5+Pj88ccfYrHY0NCwpaWFrRsbG/v5+QUHBy9evJiOT0n/UYwSYSooKHj22Wdv3Lhha2u7b98+Ly+vmzdvxsTEyGSyc+fOsX/2EonE09PT399/+fLl1tbWXLdM+IpilAhQZmbm4sWLKysrXV1d4+Lihg0b1vXdkpKS+Pj4I0eOHD9+vKOjA4Cent7MmTOlUqlUKh01ahRHXRO+ohglQnPy5MmgoKD6+vpnnnlGLpebmpo+bMuqqqq4uDiZTJaYmNjW1gZALBbPmjUrICAgJCRkwoQJGuya8BjFKBGU77///pVXXmlvb1+1atXevXsNDAxUb126dMnR0VEikfz1UzU1NUeOHDl69OixY8caGxvZoqOjo1QqXb58+eTJkzXUPeEnilEiHBEREW+//bZSqQwNDd2xY4dYfH9adGtr6/Dhwzs6Ory9vaVSaVBQUI9HqU1NTSdPnpTJZIcPH66vr2eLbJ4GBARMnz5dQ7+E8AtDCP8plcp3330XgEgk+uyzz/66wY0bN5ydnVV/9sbGxsHBwT/88MO9e/d6/MLm5ubY2NhVq1aZm5urPmVnZxcaGpqSkqJUKtX8gwif0NEo4b2Ojo7169dHRkYaGhru27fvhRdeeNiWRUVFhw8f7nqxXnVx6WEX6xUKRVpamkwm++WXX8rLy9niuHHjAgMDpVLp7Nmzux7zEt1EMUr4rbGxUSqVxsfHm5iYyGQyHx+f3nzqzp078fHxMpms9xfrVXkaFRVVWlrKFq2srHx9faVSqY+PT9dxWKJTKEYJj1VVVQUEBKSlpVlbWx87dszFxaUP3/DXi/XOzs7+/v4rVqyYOHHiXz+iVCrT0tLkcrlcLr958yZbNDIyGjduXFhYWGBgYP9+E+EfilHCV4WFhT4+PtevX7ezs0tISOgx8nqvpqYmKSnpyJEjcrm89xfrc3JyZDLZwYMHr169CmDQoEGNjY10mq9rKEYJL2VnZ/v6+paWlk6fPj0uLm4A70Fqbm5OSkqSyWQxMTF1dXVs0dHRMSAgwN/f38PDo8dPHT58OCQkRKlUJiYmLly4cKCaIbxAMUr459SpU0FBQffu3fP29o6OjlbTffEtLS0nTpw4evRodHT0nTt32KKdnV1AQIBUKp0zZ45IJOq6vaura2Zm5jfffLNmzRp19EO0F4ezBAjpA7lcPmjQIAAhISHNzc0a2GNra2t8fPzatWu73lRqY2OzcePG7Oxs1WZhYWEA3njjDQ20RLQKxSjhk6+++oodeQwNDVUoFBreu0KhSElJCQ0NHT16NBume/fuVb2bnJwMwM3NTcNdEc7RST3hB4Zhtm3btm3bNpFItGXLlg8++IDDZpRKZXp6ulwuf++996ysrNhifX29hYWFnp5eXV1dj7ecEqGiGCU8oFAoXn/99T179ujr6+/atWvt2rVcd9QzJyeny5cvp6enu7u7c90L0RyamUG0XVNT05IlS/bs2TN48OCYmBitzVAAbHr+9ttvXDdCNIpilGi16urqRYsWxcXFWVpaJiYm+vn5cd3Ro7i5uQE4f/48140QjaJH2hHtVVRU5OPjc/XqVVtb2+PHjzs4OHDd0WPQ0ahuorFRoqVycnJ8fX1LSkqmTp0aHx8/ZswYrjt6PIVCYW5u3tjYWFlZqbr0RASPTuqJNoqJifHy8iopKfHy8kpNTeVFhgLQ09NzcXFhGCYjI4PrXojmUIwSrfP+++8HBgZWVVUtXbo0ISHBzMyM646eAA2P6iAaGyXapamp6ZNPPgHg5OR08OBB3i3zQcOjOohnf6NE8IyNjfX09ABs3ryZdxmKLjFKVx10B//+TIngsefFZWVl7EuFQvHtt9++9dZbnDbVW2PHjh01alR1dXV+fj7XvRANoRglWmfZsmUAsrOz2Zd6enqbN2+OiIgoKCjgtK/ecnV1BQ2P6hKKUaJ12PPirjHEBhNfBhxpeFTXUIwSrTNt2jSJRJKbm6taNZlfl7/ZbilGdQfFKNE6hoaG06ZNUyqVFy5cYCv8Or5zc3MTi8VZWVmtra1c90I0gWKUaKNuB3Surq5isfjSpUvsU+e0nKmp6eTJk1tbW//44w+ueyGaQDEqUG1tiInBxx/jo48QHY2WFq4bejLdhkfNzMwcHBxaWlr4Ekz8Onwm/UQxKkS5uXjqKbz8Mk6fxpkzWLsWDg7IyuK6rSfAHo2mp6d3q/BreJQv3ZJ+ohgVnNZWLFmCsWNRVITERCQk4OZN2NtjyRI0NXHdXG9NmDBh6NChZWVlt27dYiv8Or7jV7eknyhGBScmBvn52LMHqudlmpriq69w6xZkMk47ewIikajbJCd+BZOTk9PgwYPz8vKqqqq47oWoHcWo4Jw7h2HDMHHiA8WpUzF6NM6d46invug2POrk5GRkZHT9+vWamhpO++oVfX19Z2dnhmEyMzO57oWoHcWo4Ny9i5Eje6iPGYO7dzXeTd91u1hvYGDAr2Di1+Ez6Q+KUcExNsa9ez3Ua2pgbKzxbvrO3d1dJBJlZmZ2dHSoKuBPMNFVJt1BMSo4jo4oLUVj4wPF+noUFWHqVI566ouhQ4fa29s3NjZeuXKFrfArmNjQT09Pp6WeBI9iVHBCQgBg584Hil99hfZ2PP88Jx31Wbfzen4djdrY2FhbW1dVVRUWFnLdC1EvilHBGTsWYWHYvBmhoTh6FHFx2LgRW7Zg+3bY2XHd3JPplpt2dnbW1taVlZU3b97ksq1eo5vrdQTFqBC9/Taio3H1Ktatw9q1yM7GoUPYtInrtp6YMJZ64ssoBOkzilGBCghAYiLKylBWhqQkBAYiPh6bN/d89UlbOTs7SySSnJychoYGtsLH4VG+hD7pM4pRgWprQ0oKfv75fuXDD/Hxx+DVEyslEomTk5NCoeDFUk9KpfKdd95JTU1VVdgVVS5evNjEn/vHSB9QjArUvXuYOxfr1kGh6Ky4uQGAVgbQI3TLTXYNugsXLrS3t3PaV3etra0vvvjil19+KZVKVaFpZmZmZGTU2toaFRXFbXtErShGBWrYMNjZoaEBubmdFXd3AODJ6bBKt7N4c3PziRMntrS0qB4xog0aGhqWLFly8OBBExOT/fv3G/85P7empoad9Pr7779z2iBRL4pR4eqWm+zLLmsm8cJfz+K1bXi0oqLCy8srISFhxIgRZ86cWbRoEVuvrq728PBobW3V09NbunQpt00StaIYFS42N1UBZG+P4cNRWYmiIg6belKTJk2ysLC4devW7du32YpWDY8WFBR4enpevHjR3t4+JSXF2dmZrd++fXv+/Pm5ublWVlaxsbEzZ87ktk+iVhSjwsUOhnY9apsxA+DZ8KhqqSfV4af2TMbMzMycNWtWXl7ejBkz0tLSJkyYwNZzc3Nnzpz5xx9/TJky5dKlS35+ftz2SdSNYlS4XFxgaIjLl/HnbCFeD4+qcnPatGlGRkZXr16tra3lsKvk5OQFCxZUVlYuWLAgOTl5+PDhbD09Pd3Ly6ukpGTmzJm//vrrmDFjOGySaAbFqHANGgQnJygUuHixs9LtNJ8nuk1iNzAwePrppxmGUc2C0rwffvjB19e3rq5u5cqV8fHxpqambD02Ntbb2/vu3btLlixJTk4eOnQoVx0STaIYFbRuuenqCpEIFy5Ay2YLPRoboxkZGYo/J29xOzwaERHx0ksvtbW1hYaG7t+/38DAgK3v27cvJCSkubl59erVhw4dMjIy4qQ9onkUo4LWbXjU0hITJqC5GTk5HDb1pIYNG2Zra1tfX3/16lW2wtXFeoZhPvjgg7feeothmE8//TQiIkIs7vwX9Omnn65evbqjo2PTpk2RkZH6+voa7o1wiSECduUKAzBjx96vrFzJAMzXX3PXU18sW7YMwN69e9mXN27cADBixAhN9tDe3r5mzRoAhoaGP/zwg6re0dHx+uuvA9DT09u1a5cmWyJago5GBc3BARYWKCnBn7OFhDE8am9v7+fnt2LFCo09tr6xsfG5557bu3fv4MGDY2JiXnzxRbbO3ry0a9cuiUTy888/v/baa5rph2gXrnOcqNnChQzAREd3vvztNwZgpkzhtKcnxt6oPm3aNE72XlVVNWvWLABDhw5NS0tT1WtqaubOnQvA3Nz8zJkznPRGtAEdjQpdt0lO06ZBIsGVK6ir47CpJ+Xi4mJgYJCdnd3YbVV/9bt58+bs2bPT0tLs7OzOnTunmkhfVlY2f/78M2fOjBw58vTp056enhpujGgPilGh67YiiaFh46JFBbNm3cjK4rCpJ2VkZMQu9aTh59ldvnzZw8Pj2rVrTk5OKSkpkyZNYuv5+fmenp5ZWVlPPfVUenr6008/rcmuiLahGBU6Nzfl0KG3FQqlUskW/m1nN/7sWdnZs9z29UTa29tbWlqGDx/+3HPPvfTSS0eOHNHAqOjp06c9PDxKS0vnz5+fmpo6evRotp6RkTFr1qz8/Hw3N7czZ86MGzdO3Z0Qbcf1qAJRO1tbWwCXL19mX37//fcAAgMDue2q9+rr6318fAAYd3myqYWFxd/+9reYmJjm5mZ17FQulw8aNAhAcHBw110kJiayk+39/f0bGxvVsWvCOxSjwsfOFoqMjGRf5uXlARg5ciS3XfVSVVXV7NmzAVhbW2dmZl6+fHnr1q3Tp09X5amRkZG/v//+/fvv3bs3UDvduXMnOyH0zTffVCgUqvqBAwfYyfbs9PuB2h3hO4pR4fvyyy8BrF+/nn2pVCqtrKwAFBcXc9vYYxUWFjo4OACws7O7fv1617cKCgrCw8PnzJkjEonYPB00aJC/v//u3bsrKyv7vEelUrl161YAIpFo69atXd8KDw9n9xUaGqpUKvu8CyI8FKPCx84WcnZ2VlV8fX0ByGQyDrt6rOzsbHY40snJqbS09GGbFRUVsXmquqFIT09vzpw54eHhZWVlT7THjo6OdevWsd/wn//8R1Vnnw7CZusXX3zR959EBIpiVPiampoMDAz09fUbGhrYCnvA9c9//pPbxh7h1KlTZmZmALy9vXt5tn7nzp39+/f7+/urbnIXi8Vsnt66das339DQ0ODu7j548OC4uDhVsbW1dfny5QAMDQ1/+umnPv4eImgUozqBXU44JSWFfXns2DEAc+fO5barh1Fd3mFX+njSj1dVVbF5KpFIVEOojo6OW7duvXbt2qM/e+fOnfPnz6te1tfXP/vsswBMTEwSEhKe+JcQ3UAxqhPYmxRVJ6RVVVUikcjY2Li9vZ3bxv5KdXknNDS06+WdPmhsbIyNjV21apWJiUm3PM3JyXnsx8vLy11cXACMGDHi4sWL/emECBvFqE6IjIwE8Pzzz6sq7FLtWVlZHHbVzSMu7/RTU1MTm6dDhgxR5am9vX1oaGhKSkqP14sKCgomTpzIbpaXlzeAzRDhoRjVCTk5OQBsbGxUFXZxja4XUjjW3v7jv/8NwMDAYP/+/WraSXNz84kTJ0JDQ1WL1QOwtbXtlqeZmZnsBjNmzKioqFBTM0QwKEZ1glKpNDc3B1BeXs5WIiIiAKxZs4bbxjo1NjL+/gqxePW8eceOHdPADtva2hISEl599dWueTp27NgNGzbs2LGDPWhdsGBBXV2dBpohfEcxqisWLFgAIDY2ln2Znp4OYOrUqdx2xTAMU13NzJnDAIylJXP2rIZ3rlAoUlJSNm3aNH78eDZM2QxdtWoVTbAnvUT31OuKrg+Gy8rKmjp1qkQiyc3NreN2qafbt+HlhbNnYWODs2cxe7aG9y8Wiz08PMLCwvLy8tLT09etW1dfX29padn16SCEPBrFqK5gVz5OT093dnZ2dnYeMWKEiYmJUqnU/KM47svJwcyZyM7GlClITcXkyZx1AohEInd39927d5ubm1dXV5eVlXHYDOEXilFdwcbor7/+mpWVBaChoaGqqgpASEjImjVr4uLiWltbNdpQejq8vFBS0nk0qh0PIhaJRDNmzAAXD3oi/EUxqitMTEwGDRrU0dEhkUg+//xzdo0PR0fHurq6yMhIf39/S0vLgICAAwcO1NfXq72bmBh4e6OqCoGBiI+HmZna99hr3D52lPAS14OzRBPKysrYG5lGjBhx6dKlrm/l5+d3W+NDtWZSbW2tWrqJjGT09RmAeeUVRvvm/8fGxgLw9vbmuhHCGxSjwpefn89Oth8/fvwjZpLfuHHj008/dXd3V+WpRCJZHhTEREYyd+8OWDdhYQzAAMymTQP2nQOqoqICgKmpaUdHB9e9EH6gGBW4jIwMdmqkq6trL1eQKykp2b17t7+/v76+/odubgzA6Okxc+Yw4eHMw1da6pXXXuv8tj17+vU9atZtoWtCHo1iVMiSkpLYWZDPPPNMH2aSV1RUFB84wCxaxBgYdB5CisWMpyezYwdTVPSYD5eXM+fPM7//zrS23i+GhTESCaPdC/Qxfy50vXfvXq4bIfxAMSpY3333HTvzcQBmkldXM/v3M1IpM3hwZ54CjKMjs3Urc+VK943z85n58xmAMTJiRCJmyBBm+3ZGdd96fn6/OtGIbgtdE/JoFKPCFB4ePlDrJD2gsZGJjWVWrWJMTR/I002bGHYVvupqZtw4xsODyc5mFAqmro7Zu5eRSJgtWwasB/VjF7qeNm0a140QfqAYFRqlUrlp0yYAIpHos88+U9dumpoYuZxZuZIxN+8MUz09pqKC2b6dkUiYkpIHNv7nPxkjI6aqSl3NDDR2oWs9PT3VQteEPIKIYRhNzq8iatXR0bF+/frIyEhDQ8N9+/a98MILat9lWxtOnkRUFGpqEBWFuXNhYoJjxx7YJjcXU6YgOhqBgWrvZ4BMnz794sWLZ86c8fT05LoXou1o+r1wNDY2Pvfcc5GRkSYmJjExMZrIUACGhvD1xTffICoKAG7dwl+f225nB5EIJSWa6GeAsEsQ0L1MpDcoRgWiqqpq4cKF8fHx1tbWp0+fZh/szgGRCApF96JCAYaBnh4XDfUR3ctEek+f6wbIACgsLPTx8bl+/bqdnV1CQgK7bDs3bG1RVNS9WFjY+RZ/UIyS3qOjUd7Lzs729PS8fv26k5NTamoqlxkKwNcXp0515qbKwYMYMgS8GmScPHmyubl5cXExLfVEHotilN9OnTrl6elZWlrq7e2dmpo6atQojhtavx62tli2DBcuoKMDtbX4v//D559jyxaYmnLc25MQiUTTp08HkJGRwXUvRNtRjPJYdHS0n5/fvXv3QkJC4uLiuj6vjTOmpjh1CsOGwc0NJiawsMCWLfj8c/zjH1x39sTovJ70Eo2N8tXOnTs3bNigVCpDQ0N37NjBTrbXCmPGIC4O1dW4eRNGRpg0iV8Xl1QoRkkv0bxR/mEYZtu2bdu2bROJRFu2bPnggw+47kiYKisrra2tTU1Na2trtej/UkT7UIzyjEKheP311/fs2aOvr79r1661a9dy3ZGQ2djYFBcX5+bmPvXUU1z3QrQX/T+WT5qampYsWbJnz57BgwfHxMRQhqobndeT3qAY5Y3q6upFixbFxcVZWlomJib6+flx3ZHwdX2cKiEPQ5eY+KGoqMjHx+fq1au2trbHjx93cHDguiOdwB6N0i2h5NFobJQHcnJyfH19S0pKpk6dGh8fP0Y7HqKpC5qamszMzEQiUW1trbGxMdftEC1FJ/U8cODAgZKSknnz5qWmplKGapKxsfHUqVPb29svXbrEdS9Ee1GM8sAnn3wSHh5+/PhxM216ELGOoKtM5LEoRnlALBZv2LBBIpFw3YguohXzyGNRjBLyKHQ0Sh6LLjER8ihKpdLCwqKurq68vNza2prrdog2oqNRQh5FLBbPmDEDdF5PHo5ilJDHYIdHN2zY8PXXX5eXl3PdDtE6dFJPyGMcPnw4KCiI/W+xWDxr1qyAgICQkJAJEyZw2xjREhSjhDxGcXGxjY2NWCwODg6Oj49vbGxk646OjlKpdPny5ZMnT+a2Q8ItilFCHkOpVBoYGCiVyhMnTsyePfvkyZMymezw4cP19fXsBo6OjgEBAf7+/h4eHty2SjhBMUrIo7S2tq5cufLQoUP6+vrnz593dnZm683NzcePH5fL5UePHq2trWWLDg4OwcHBy5YufdrFhbuWiaZRjBLyUA0NDcHBwSdOnDA2Nt69e/fKlSv/uo1CoUhLS5PJZL/88gt7Aeqr2bPfuHULgYEICMC8edCnBYAEjmKUkJ6Vl5f7+fmp7qbX09ObOXOmVCqVSqU9PjpQoVD8+uuvcrn8vby8MYmJndWRIxEUhOBgzJvH04epkMeiGCWkB/n5+T4+Pjdu3HBwcFi9evWpU6eSk5Pb29vx58X6kJCQ4OBgGxubnj+fkwOZDD/9hOvXOyuWlli8GFIpFi0C3dcrLBSjhHSXkZGxePHiO3fuuLm5xcXFWVlZAaitrT1x4sSRI0fkcnm3i/XLli176FNG2DyVyZCb21kxNoa3N6RSBAfDxEQTv4eoGcUoIQ9ISkoKDg6ur6/39/c/ePDgX5cZbW5uTkpKkslkMTExdXV1bPHxF+tzchAVBbkcv//eWTE2hp8fXnkFvr7q+jFEMxhCyJ++++47AwMDAC+99FJbW9ujN25qajp8+PCqVavMzc3Zf01DJJKOadOY995jMjIYpbLnjxUWMuHhzJw5jEjEAMzmzZ3Fl19mRo1iDA2Z0aOZV15hiooG+scRdaGjUUI6RUREvP3220qlMjQ0NDw8XCQS9fKDbW1tycnJcrncoaDgHydPdlZtbBAcjOBgzJ6NHp/PXFICuRyLFsHYGO7usLfHhg0YPx43buCLL1BaivPnMXbsAP04okYUo4QASmXY5s3/CgsTi8URERFvvPFGn78H585BJkNUFEpLO4tWVvD1hVQKHx8YGPTwqWXLkJWFrCwYGXVW6usxcSK8vfHjj33shGgQxSjReW1tePnlpqwsx4qKsP/93+XLlw/M1/byYn1bG8zMsGUL/vWvBz6+ZQu+/BK1tT0nL9EmFKNEt9XXIzgYSUkYMqQpNtbYy2vgd3HxIuRyREXh6tXOipkZFi9GSAiWLEFBASZNwi+/QCp94FM//ogVK1BQADu7gW+JDChaKI/osIoKzJuHpCSMGIHTp9WSoQBcXLB9O65cQX4+wsMxZw7q6vDjj/j73yESoaMDwP3TeRV2LlRbm1paIgOKblMjuqqwEM8+i7w82Nvj+HFMnKj2PbIXkTZsQH4+oqJgYACxGNbWEInuD6SqFBdDJMKIEWrvivQbndQTnXThAhYvRkUFZsxAXByGD+eyGScnODri4MEHikFBKCrCxYsc9USeAJ3UE92TnAxvb1RUYMECnDzJcYYCeO89HDqE77+/X/n2W8TEdL/oRLQVHY0SHRMVhZUr0dKCFSvw7bfach38o4/w3/+N0aMxcSKuX8ft2/jwQ7z7LtdtkV6hGCW65H/+Bxs3QqlEaCh27Oh5VjxXbt3CqVMoK8OoUfD2Rk+LSBHtRDFKdAPDYNs2bNsGkQiffIJNm7huiAgHxSjRDTU1cHVFcTG+/RYrVnDdDREUbTqpIeTRLl/GpEm4du2B4vvvo+t9RxUVePNNTJgAS0vY2mLdOhQXA4CFBRISEBdHGUoGHM0bJfzR0oK8PLS2PlAsL+8MSgAVFXB3x5Ah2LwZkyahsBAREXB1RVoa7O0xfjzGj9d810TwKEaJgLz/PurrcekSLCwAYM4cBAXBwQHvvAO5nOvmiGDRST0RCqUShw5hzZrODGUNHoy//x1Hj6K5mbvOiMDR0Sjhm507H5gwf+FC5w3plZWorYWDQ/ftHR3R3o6CAkyZorkmiS6hGCV8U16Olpb7LxsaOmOUXcXD1LT79myl24gqIQOHYpTwzfbt+K//uv9y7drOp8VZWUFPD7dudd+evQBFa3wQtaGxUSIUxsZwcUFcXPf60aOYMIFuCiLqQzFKBOTdd5GcjH377leioxEdTTenE7Wik3oiIEuX4qOP8Oqr+PhjODigoADXruHdd7F2LdedESGjm0EJf9TUIDERPj4wM7tfzMhAXR0WLLhfKS7GiRO4exfm5li4EPb2mu+U6BSKUUII6RcaGyWEkH6hGCWEkH6hGCWEkH6hGCWEkH6hGCWEkH6hGCWEkH75f0XDISGcnXRAAAABGnpUWHRyZGtpdFBLTCByZGtpdCAyMDI1LjAzLjYAAHice79v7T0GIBAAYiYGCOCF4gZGNoYEIM3IzMagAaSZWTggNBOMZnOAiLM5ZIBoZka8DKhaDLPAChgZuRkYGRiZNJgYmRWYWRRYWDOYWNkS2NgzmNg5Ejg4M5g4uRS4uDWYuHgUOFkSnBiBmthYODnY2VjFl4EcyQBzfd6f4gMPti7ZD+K0b9c5cMR3wj4QO+GEw4H766bbg9gTDi/avzjNDqxG5JzivrI9rXYg9vncj/tyDe+C1WyOUbF/91LPAcR+k8Pi8C9SEMw+UivhEPHYF6xmT+Eie8k2X7D5uZNP2QsXXwWbWTbfwaHKk+MAiN2g9sHuIJc2mC0GAK25Q1Mf5VwoAAABdHpUWHRNT0wgcmRraXQgMjAyNS4wMy42AAB4nH2TUW7DIAyG33MKX6DINgabx7appmlqIm3d7rD33V+zU3WkEhrEEZAPG347E0R7n9++f+Cv8TxNAPjP01qDr4yI0xViAKfLy+sC59vx9Fg5r5/L7QMox4PRn9njbb0+VgjOcMjJiNkYDpTYqqFvSbi1vpeD5FSbKTqJTpJJHpAZ1vCJ7jMiJLKCLANQAvSQSqXlcKmStYzIEsExUTGMOyWuxDiKXe+guEshj61sqDQA1UFMVdxNA06aM7INOHOOE9ZGYj7wsxKNuLZx2bhq9c+GwmUkI3l+/FxcG7a6yYioqCOSNrK4S1fPdapVi47UIXYhXXBsfo1IEnETKyMycuPyeHSRLZ3KJY/0uSzzU6HcS+e0LnMvnejc6yN67kXg30B6qsmt9Hz6BGrPmrhpz424WU+BuLWutLjRXlHaXrRTjuNFvFOItpW8U0JiV9lfeH+9mD/+Kh9PvzErr8LHNVvZAAAAvXpUWHRTTUlMRVMgcmRraXQgMjAyNS4wMy42AAB4nCWOyw0CUQhFW3GpCUP4w8vE1RRgEbZh8d6n7Dgc4F7X/fl6vN763qX/7va5H86jZkOHsk0NnYdxrWk6BEAnHMhZIDkp66QYCOzWXNvq8M4AE9YcUSdslpr4jwW8UKy2jTSdwhWYLTJu9y0ZSy1NANxU28DHkEV4JCzpxDcYv0giva8oJxTbsas6QZBRVjshv9qK2Z+ilkRsVG3p9Ph8AaOXNexrmcq5AAAAAElFTkSuQmCC", "text/plain": [ - "" + "" ] }, "metadata": {}, @@ -1028,7 +1220,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4, diff --git a/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb b/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb index 3baabbe..69acc82 100644 --- a/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb +++ b/docs/tutorials/02_Getting_Started_rdkit_Core.ipynb @@ -57,13 +57,20 @@ "cell_type": "code", "execution_count": 1, "id": "ddcb2b72", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.089561Z", + "iopub.status.busy": "2026-08-08T20:34:48.089318Z", + "iopub.status.idle": "2026-08-08T20:34:48.407087Z", + "shell.execute_reply": "2026-08-08T20:34:48.406856Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "[('0.77.0', '2025.09.4')]\n" + "[('0.77.0', '2026.03.4')]\n" ] } ], @@ -119,7 +126,14 @@ "cell_type": "code", "execution_count": 2, "id": "7c1d4286", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.408276Z", + "iopub.status.busy": "2026-08-08T20:34:48.408194Z", + "iopub.status.idle": "2026-08-08T20:34:48.427741Z", + "shell.execute_reply": "2026-08-08T20:34:48.427509Z" + } + }, "outputs": [], "source": [ "metadata = MetaData()\n", @@ -159,7 +173,14 @@ "cell_type": "code", "execution_count": 3, "id": "9b32959c", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.428861Z", + "iopub.status.busy": "2026-08-08T20:34:48.428798Z", + "iopub.status.idle": "2026-08-08T20:34:48.446672Z", + "shell.execute_reply": "2026-08-08T20:34:48.446455Z" + } + }, "outputs": [], "source": [ "data = [\n", @@ -204,7 +225,14 @@ "cell_type": "code", "execution_count": 4, "id": "a5b2666e", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.447666Z", + "iopub.status.busy": "2026-08-08T20:34:48.447593Z", + "iopub.status.idle": "2026-08-08T20:34:48.455256Z", + "shell.execute_reply": "2026-08-08T20:34:48.455049Z" + } + }, "outputs": [ { "name": "stdout", @@ -238,7 +266,14 @@ "cell_type": "code", "execution_count": 5, "id": "8f356747", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.456241Z", + "iopub.status.busy": "2026-08-08T20:34:48.456177Z", + "iopub.status.idle": "2026-08-08T20:34:48.459042Z", + "shell.execute_reply": "2026-08-08T20:34:48.458850Z" + } + }, "outputs": [ { "name": "stdout", @@ -271,7 +306,14 @@ "cell_type": "code", "execution_count": 6, "id": "024ffa61", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.459989Z", + "iopub.status.busy": "2026-08-08T20:34:48.459929Z", + "iopub.status.idle": "2026-08-08T20:34:48.462729Z", + "shell.execute_reply": "2026-08-08T20:34:48.462538Z" + } + }, "outputs": [ { "name": "stdout", @@ -315,7 +357,14 @@ "cell_type": "code", "execution_count": 7, "id": "f5617b86", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.463700Z", + "iopub.status.busy": "2026-08-08T20:34:48.463638Z", + "iopub.status.idle": "2026-08-08T20:34:48.475511Z", + "shell.execute_reply": "2026-08-08T20:34:48.475265Z" + } + }, "outputs": [], "source": [ "from sqlalchemy import Computed\n", @@ -361,7 +410,14 @@ "cell_type": "code", "execution_count": 8, "id": "5e2c36e8", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.476420Z", + "iopub.status.busy": "2026-08-08T20:34:48.476361Z", + "iopub.status.idle": "2026-08-08T20:34:48.482483Z", + "shell.execute_reply": "2026-08-08T20:34:48.482284Z" + } + }, "outputs": [], "source": [ "with SessionLocal() as session:\n", @@ -373,7 +429,14 @@ "cell_type": "code", "execution_count": 9, "id": "45e6718a", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.483387Z", + "iopub.status.busy": "2026-08-08T20:34:48.483320Z", + "iopub.status.idle": "2026-08-08T20:34:48.486743Z", + "shell.execute_reply": "2026-08-08T20:34:48.486550Z" + } + }, "outputs": [ { "data": { @@ -417,9 +480,16 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 10, "id": "9447c97a", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.487843Z", + "iopub.status.busy": "2026-08-08T20:34:48.487776Z", + "iopub.status.idle": "2026-08-08T20:34:48.492028Z", + "shell.execute_reply": "2026-08-08T20:34:48.491838Z" + } + }, "outputs": [ { "data": { @@ -431,7 +501,7 @@ " (0.030303030303030304, 4, 'Captopril', 'C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O', False, '\\\\x0100000004000000ffffffff20000000f2e0751a01000000b355c52c0100000027b38933010000008afa8d330200000097c53336010000006299573901000000e5a0353d0100000061 ... (249 characters truncated) ... 00000e066839001000000c198c39501000000c8551fa7010000009edbf6b003000000fbab62b101000000886e83c8010000001b29d4d2010000006c006fd701000000417193f501000000')]" ] }, - "execution_count": 11, + "execution_count": 10, "metadata": {}, "output_type": "execute_result" } @@ -455,16 +525,23 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 11, "id": "32703967", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.492963Z", + "iopub.status.busy": "2026-08-08T20:34:48.492905Z", + "iopub.status.idle": "2026-08-08T20:34:48.494454Z", + "shell.execute_reply": "2026-08-08T20:34:48.494257Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "SELECT tanimoto_sml(molecules_fp.fp, morgan_fp('Clc4cc2c(C(c1ncccc1CC2)=C3CCNCC3)cc4', 2)) AS similarity, molecules_fp.id, molecules_fp.name, molecules_fp.mol, molecules_fp.is_nsaid, molecules_fp.fp \n", - "FROM molecules_fp ORDER BY similarity DESC\n" + "SELECT tanimoto_sml(molalchemy_tutorial_molecules_fp.fp, morgan_fp('Clc4cc2c(C(c1ncccc1CC2)=C3CCNCC3)cc4', 2)) AS similarity, molalchemy_tutorial_molecules_fp.id, molalchemy_tutorial_molecules_fp.name, molalchemy_tutorial_molecules_fp.mol, molalchemy_tutorial_molecules_fp.is_nsaid, molalchemy_tutorial_molecules_fp.fp \n", + "FROM molalchemy_tutorial_molecules_fp ORDER BY similarity DESC\n" ] } ], @@ -495,9 +572,16 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 12, "id": "68a51b79", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.495329Z", + "iopub.status.busy": "2026-08-08T20:34:48.495272Z", + "iopub.status.idle": "2026-08-08T20:34:48.509448Z", + "shell.execute_reply": "2026-08-08T20:34:48.509188Z" + } + }, "outputs": [], "source": [ "metadata = MetaData()\n", @@ -534,9 +618,16 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 13, "id": "be9e0616", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.510799Z", + "iopub.status.busy": "2026-08-08T20:34:48.510727Z", + "iopub.status.idle": "2026-08-08T20:34:48.521464Z", + "shell.execute_reply": "2026-08-08T20:34:48.521210Z" + } + }, "outputs": [], "source": [ "with SessionLocal() as session:\n", @@ -546,18 +637,25 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 14, "id": "e5ce3158", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:34:48.522626Z", + "iopub.status.busy": "2026-08-08T20:34:48.522553Z", + "iopub.status.idle": "2026-08-08T20:34:48.525334Z", + "shell.execute_reply": "2026-08-08T20:34:48.525137Z" + } + }, "outputs": [ { "data": { "text/plain": [ - "[(1, 'Aspirin', b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\r\\x00\\x00\\x00\\x80\\x01\\x06\\x00`\\x00\\x00\\x00\\x01\\x03\\x0 ... (472 characters truncated) ... 2\\n\\x0c \\t\\x04h\\x0cB\\x01\\x00\\x00\\x00\\x06\\x04\\t\\x08\\x07\\x06\\x05\\x17\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00?\\x00\\x00\\x00\\x00\\x12\\x02\\x00\\x00\\x00\\x00\\x00\\x13\\x16', True, '\\\\x0100000004000000ffffffff190000004034df0502000000177ce7070100000050d6601e01000000bc8d1f280100000027b3893301000000b7e28933010000008afa8d3302000000d6 ... (137 characters truncated) ... 00000215cea8501000000c76fa289010000000b9cd89e01000000c831f8a501000000a7d50bb2010000006455c5bf02000000515fd9bf04000000f9fb51d301000000afbc69ee02000000'),\n", - " (2, 'Loratadine', b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00\\x1e\\x00\\x00\\x00\\x80\\x01\\x08\\x00(\\x00\\x00\\x00\\x03\\x0 ... (1150 characters truncated) ... \\x10\\n\\x07\\x11\\x10\\n\\t\\x18\\x13\\x12\\x06\\x14\\x15\\x16\\x17\\x18\\x13\\x17\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00?\\x00\\x00\\x00\\x00\\x12\\x02\\x00\\x00\\x00\\x00\\x00\\x13\\x16', False, '\\\\x0100000004000000ffffffff3400000043892d0201000000727bf204010000004034df05010000003a8b1c0d010000008126ca0f020000000b074611010000003b52981201000000d9 ... (569 characters truncated) ... 000003182c9cd01000000ac3e61ce01000000269925d3010000004aff1ee10100000030fb63e50100000056c98fe6010000003abe53ed0100000060a959ed01000000d6f410ee01000000')]" + "[(1, 'Aspirin', b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\r\\x00\\x00\\x00\\x80\\x01\\x06\\x00`\\x00\\x00\\x00\\x01\\x03\\x0 ... (472 characters truncated) ... 2\\n\\x0c \\t\\x04h\\x0cB\\x01\\x00\\x00\\x00\\x06\\x04\\t\\x08\\x07\\x06\\x05\\x17\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00?\\x00\\x00\\x00\\x00\\x12\\x02\\x00\\x00\\x00\\x00\\x00\\x13\\x16', True, '\\\\x0100000004000000ffffffff190000004034df0502000000177ce7070100000050d6601e01000000bc8d1f280100000027b3893301000000b7e28933010000008afa8d3302000000d6 ... (137 characters truncated) ... 00000215cea8501000000c76fa289010000000b9cd89e01000000c831f8a501000000a7d50bb2010000006455c5bf02000000515fd9bf04000000f9fb51d301000000afbc69ee02000000'),\n", + " (2, 'Loratadine', b'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00\\x1e\\x00\\x00\\x00\\x80\\x01\\x08\\x00(\\x00\\x00\\x00\\x03\\x0 ... (1150 characters truncated) ... \\x10\\n\\x07\\x11\\x10\\n\\t\\x18\\x13\\x12\\x06\\x14\\x15\\x16\\x17\\x18\\x13\\x17\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00?\\x00\\x00\\x00\\x00\\x12\\x02\\x00\\x00\\x00\\x00\\x00\\x13\\x16', False, '\\\\x0100000004000000ffffffff3400000043892d0201000000727bf204010000004034df05010000003a8b1c0d010000008126ca0f020000000b074611010000003b52981201000000d9 ... (569 characters truncated) ... 000003182c9cd01000000ac3e61ce01000000269925d3010000004aff1ee10100000030fb63e50100000056c98fe6010000003abe53ed0100000060a959ed01000000d6f410ee01000000')]" ] }, - "execution_count": 15, + "execution_count": 14, "metadata": {}, "output_type": "execute_result" } @@ -614,7 +712,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4, diff --git a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb index 5e35b8c..321550e 100644 --- a/docs/tutorials/04_Similarity_Threshold_Settings.ipynb +++ b/docs/tutorials/04_Similarity_Threshold_Settings.ipynb @@ -45,7 +45,14 @@ { "cell_type": "code", "execution_count": 1, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:03.783671Z", + "iopub.status.busy": "2026-08-08T20:35:03.783429Z", + "iopub.status.idle": "2026-08-08T20:35:04.215152Z", + "shell.execute_reply": "2026-08-08T20:35:04.214850Z" + } + }, "outputs": [], "source": [ "import os\n", @@ -105,7 +112,14 @@ { "cell_type": "code", "execution_count": 2, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.216408Z", + "iopub.status.busy": "2026-08-08T20:35:04.216303Z", + "iopub.status.idle": "2026-08-08T20:35:04.241065Z", + "shell.execute_reply": "2026-08-08T20:35:04.240760Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -138,7 +152,14 @@ { "cell_type": "code", "execution_count": 3, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.242116Z", + "iopub.status.busy": "2026-08-08T20:35:04.242047Z", + "iopub.status.idle": "2026-08-08T20:35:04.260658Z", + "shell.execute_reply": "2026-08-08T20:35:04.260456Z" + } + }, "outputs": [], "source": [ "data = [\n", @@ -185,7 +206,14 @@ { "cell_type": "code", "execution_count": 4, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.261660Z", + "iopub.status.busy": "2026-08-08T20:35:04.261595Z", + "iopub.status.idle": "2026-08-08T20:35:04.264002Z", + "shell.execute_reply": "2026-08-08T20:35:04.263835Z" + } + }, "outputs": [ { "name": "stdout", @@ -215,7 +243,14 @@ { "cell_type": "code", "execution_count": 5, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.277409Z", + "iopub.status.busy": "2026-08-08T20:35:04.277313Z", + "iopub.status.idle": "2026-08-08T20:35:04.284304Z", + "shell.execute_reply": "2026-08-08T20:35:04.284084Z" + } + }, "outputs": [ { "name": "stdout", @@ -259,7 +294,14 @@ { "cell_type": "code", "execution_count": 6, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.285293Z", + "iopub.status.busy": "2026-08-08T20:35:04.285230Z", + "iopub.status.idle": "2026-08-08T20:35:04.289548Z", + "shell.execute_reply": "2026-08-08T20:35:04.289354Z" + } + }, "outputs": [ { "name": "stdout", @@ -300,7 +342,14 @@ { "cell_type": "code", "execution_count": 7, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.290501Z", + "iopub.status.busy": "2026-08-08T20:35:04.290439Z", + "iopub.status.idle": "2026-08-08T20:35:04.293857Z", + "shell.execute_reply": "2026-08-08T20:35:04.293662Z" + } + }, "outputs": [ { "name": "stdout", @@ -341,7 +390,14 @@ { "cell_type": "code", "execution_count": 8, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.294812Z", + "iopub.status.busy": "2026-08-08T20:35:04.294746Z", + "iopub.status.idle": "2026-08-08T20:35:04.300303Z", + "shell.execute_reply": "2026-08-08T20:35:04.300112Z" + } + }, "outputs": [ { "name": "stdout", @@ -380,7 +436,14 @@ { "cell_type": "code", "execution_count": 9, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.301216Z", + "iopub.status.busy": "2026-08-08T20:35:04.301153Z", + "iopub.status.idle": "2026-08-08T20:35:04.304901Z", + "shell.execute_reply": "2026-08-08T20:35:04.304689Z" + } + }, "outputs": [ { "name": "stdout", @@ -414,7 +477,14 @@ { "cell_type": "code", "execution_count": 10, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.305847Z", + "iopub.status.busy": "2026-08-08T20:35:04.305768Z", + "iopub.status.idle": "2026-08-08T20:35:04.310687Z", + "shell.execute_reply": "2026-08-08T20:35:04.310492Z" + } + }, "outputs": [ { "name": "stdout", @@ -460,7 +530,14 @@ { "cell_type": "code", "execution_count": 11, - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:04.311630Z", + "iopub.status.busy": "2026-08-08T20:35:04.311568Z", + "iopub.status.idle": "2026-08-08T20:35:04.313060Z", + "shell.execute_reply": "2026-08-08T20:35:04.312868Z" + } + }, "outputs": [ { "name": "stdout", @@ -520,7 +597,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4, diff --git a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb index a272991..9e552d6 100644 --- a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb +++ b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb @@ -49,13 +49,20 @@ "cell_type": "code", "execution_count": 1, "id": "cell-2", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:17.990179Z", + "iopub.status.busy": "2026-08-08T20:35:17.989972Z", + "iopub.status.idle": "2026-08-08T20:35:18.300447Z", + "shell.execute_reply": "2026-08-08T20:35:18.300200Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "[('0.77.0', '2025.09.6')]\n" + "[('0.77.0', '2026.03.4')]\n" ] } ], @@ -115,7 +122,14 @@ "cell_type": "code", "execution_count": 2, "id": "cell-4", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.301599Z", + "iopub.status.busy": "2026-08-08T20:35:18.301520Z", + "iopub.status.idle": "2026-08-08T20:35:18.321547Z", + "shell.execute_reply": "2026-08-08T20:35:18.321292Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -161,7 +175,14 @@ "cell_type": "code", "execution_count": 3, "id": "cell-6", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.322620Z", + "iopub.status.busy": "2026-08-08T20:35:18.322555Z", + "iopub.status.idle": "2026-08-08T20:35:18.331319Z", + "shell.execute_reply": "2026-08-08T20:35:18.331094Z" + } + }, "outputs": [], "source": [ "data = [\n", @@ -211,7 +232,14 @@ "cell_type": "code", "execution_count": 4, "id": "cell-8", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.332302Z", + "iopub.status.busy": "2026-08-08T20:35:18.332242Z", + "iopub.status.idle": "2026-08-08T20:35:18.342670Z", + "shell.execute_reply": "2026-08-08T20:35:18.342463Z" + } + }, "outputs": [], "source": [ "from rdkit.Chem import AllChem\n", @@ -226,7 +254,14 @@ "cell_type": "code", "execution_count": 5, "id": "cell-9", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.343584Z", + "iopub.status.busy": "2026-08-08T20:35:18.343515Z", + "iopub.status.idle": "2026-08-08T20:35:18.353139Z", + "shell.execute_reply": "2026-08-08T20:35:18.352958Z" + } + }, "outputs": [ { "data": { @@ -262,7 +297,14 @@ "cell_type": "code", "execution_count": 6, "id": "cell-11", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.354102Z", + "iopub.status.busy": "2026-08-08T20:35:18.354026Z", + "iopub.status.idle": "2026-08-08T20:35:18.357302Z", + "shell.execute_reply": "2026-08-08T20:35:18.357097Z" + } + }, "outputs": [ { "name": "stdout", @@ -270,18 +312,18 @@ "text": [ "Error adding invalid reaction: (molalchemy.exceptions.InvalidReactionError) Invalid reaction SMARTS string: 'not_a_>>reaction'\n", "[SQL: INSERT INTO molalchemy_tutorial_reactions (name, rxn_class, rxn) VALUES (%(name)s::VARCHAR, %(rxn_class)s::VARCHAR, reaction_from_smarts(%(rxn)s)) RETURNING molalchemy_tutorial_reactions.id]\n", - "[parameters: [{'rxn_class': 'Invalid>>BAD', 'name': 'Bad', 'rxn': 'not_a_>>reaction'}]]\n" + "[parameters: [{'name': 'Bad', 'rxn': 'not_a_>>reaction', 'rxn_class': 'Invalid>>BAD'}]]\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ - "[19:50:03] SMARTS Parse Error: syntax error while parsing: not_a_\n", - "[19:50:03] SMARTS Parse Error: check for mistakes around position 3:\n", - "[19:50:03] not_a_\n", - "[19:50:03] ~~^\n", - "[19:50:03] SMARTS Parse Error: Failed parsing SMARTS 'not_a_' for input: 'not_a_'\n" + "[22:35:18] SMARTS Parse Error: syntax error while parsing: not_a_\n", + "[22:35:18] SMARTS Parse Error: check for mistakes around position 3:\n", + "[22:35:18] not_a_\n", + "[22:35:18] ~~^\n", + "[22:35:18] SMARTS Parse Error: Failed parsing SMARTS 'not_a_' for input: 'not_a_'\n" ] } ], @@ -311,7 +353,14 @@ "cell_type": "code", "execution_count": 7, "id": "cell-13", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.358247Z", + "iopub.status.busy": "2026-08-08T20:35:18.358184Z", + "iopub.status.idle": "2026-08-08T20:35:18.361277Z", + "shell.execute_reply": "2026-08-08T20:35:18.361100Z" + } + }, "outputs": [ { "data": { @@ -345,7 +394,14 @@ "cell_type": "code", "execution_count": 8, "id": "cell-15", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.362198Z", + "iopub.status.busy": "2026-08-08T20:35:18.362139Z", + "iopub.status.idle": "2026-08-08T20:35:18.365675Z", + "shell.execute_reply": "2026-08-08T20:35:18.365492Z" + } + }, "outputs": [ { "data": { @@ -377,7 +433,14 @@ "cell_type": "code", "execution_count": 9, "id": "cell-17", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.366604Z", + "iopub.status.busy": "2026-08-08T20:35:18.366547Z", + "iopub.status.idle": "2026-08-08T20:35:18.370461Z", + "shell.execute_reply": "2026-08-08T20:35:18.370277Z" + } + }, "outputs": [ { "data": { @@ -409,7 +472,14 @@ "cell_type": "code", "execution_count": 10, "id": "0d7cc4b1", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.371332Z", + "iopub.status.busy": "2026-08-08T20:35:18.371274Z", + "iopub.status.idle": "2026-08-08T20:35:18.374515Z", + "shell.execute_reply": "2026-08-08T20:35:18.374318Z" + } + }, "outputs": [ { "data": { @@ -432,7 +502,14 @@ "cell_type": "code", "execution_count": 11, "id": "92b27581", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.375381Z", + "iopub.status.busy": "2026-08-08T20:35:18.375319Z", + "iopub.status.idle": "2026-08-08T20:35:18.378245Z", + "shell.execute_reply": "2026-08-08T20:35:18.378052Z" + } + }, "outputs": [ { "data": { @@ -461,9 +538,16 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 12, "id": "ef470eef", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.379185Z", + "iopub.status.busy": "2026-08-08T20:35:18.379126Z", + "iopub.status.idle": "2026-08-08T20:35:18.382678Z", + "shell.execute_reply": "2026-08-08T20:35:18.382518Z" + } + }, "outputs": [ { "data": { @@ -471,7 +555,7 @@ "[(Reaction(id=6, name='Acylation', rxn_class='Substitution', rxn='O=[C:2]Cl.[OH][C:1]>>O=[C:2]O[C:1]'),)]" ] }, - "execution_count": 20, + "execution_count": 12, "metadata": {}, "output_type": "execute_result" } @@ -492,9 +576,16 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 13, "id": "926e778d", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.383566Z", + "iopub.status.busy": "2026-08-08T20:35:18.383509Z", + "iopub.status.idle": "2026-08-08T20:35:18.386188Z", + "shell.execute_reply": "2026-08-08T20:35:18.386018Z" + } + }, "outputs": [ { "data": { @@ -503,7 +594,7 @@ " (Reaction(id=4, name='Reductive amination', rxn_class='Reduction', rxn='O=[CH2:1].[NH3:2]>>[C:1][N:2]'),)]" ] }, - "execution_count": 22, + "execution_count": 13, "metadata": {}, "output_type": "execute_result" } @@ -528,9 +619,16 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 14, "id": "6ab91663", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.387179Z", + "iopub.status.busy": "2026-08-08T20:35:18.387118Z", + "iopub.status.idle": "2026-08-08T20:35:18.389950Z", + "shell.execute_reply": "2026-08-08T20:35:18.389779Z" + } + }, "outputs": [ { "data": { @@ -539,7 +637,7 @@ " (Reaction(id=4, name='Reductive amination', rxn_class='Reduction', rxn='O=[CH2:1].[NH3:2]>>[C:1][N:2]'),)]" ] }, - "execution_count": 23, + "execution_count": 14, "metadata": {}, "output_type": "execute_result" } @@ -564,9 +662,16 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 15, "id": "cell-19", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.390937Z", + "iopub.status.busy": "2026-08-08T20:35:18.390881Z", + "iopub.status.idle": "2026-08-08T20:35:18.394688Z", + "shell.execute_reply": "2026-08-08T20:35:18.394540Z" + } + }, "outputs": [ { "data": { @@ -579,7 +684,7 @@ " ('Acylation', 2, 1, 0)]" ] }, - "execution_count": 16, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -607,9 +712,16 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 16, "id": "cell-21", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.395650Z", + "iopub.status.busy": "2026-08-08T20:35:18.395595Z", + "iopub.status.idle": "2026-08-08T20:35:18.399650Z", + "shell.execute_reply": "2026-08-08T20:35:18.399405Z" + } + }, "outputs": [ { "data": { @@ -619,7 +731,7 @@ " ('Suzuki coupling', 'Br[c:1].OB(O)[c:2]>>[c:1][c:2]', '[c:1]Br.[c:2]B(O)O>>[c:1][c:2]')]" ] }, - "execution_count": 17, + "execution_count": 16, "metadata": {}, "output_type": "execute_result" } @@ -654,9 +766,16 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 17, "id": "cell-23", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.400530Z", + "iopub.status.busy": "2026-08-08T20:35:18.400475Z", + "iopub.status.idle": "2026-08-08T20:35:18.419582Z", + "shell.execute_reply": "2026-08-08T20:35:18.419372Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -678,9 +797,16 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 18, "id": "cell-24", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.420579Z", + "iopub.status.busy": "2026-08-08T20:35:18.420518Z", + "iopub.status.idle": "2026-08-08T20:35:18.432503Z", + "shell.execute_reply": "2026-08-08T20:35:18.432306Z" + } + }, "outputs": [ { "name": "stdout", @@ -690,6 +816,18 @@ "Num reactants: 2\n", "Num products: 1\n" ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "[22:35:18] Depickling from a version number (16.3)that is higher than our version (16.2).\n", + "This probably won't work.\n", + "[22:35:18] Depickling from a version number (16.3)that is higher than our version (16.2).\n", + "This probably won't work.\n", + "[22:35:18] Depickling from a version number (16.3)that is higher than our version (16.2).\n", + "This probably won't work.\n" + ] } ], "source": [ @@ -724,17 +862,24 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 19, "id": "cell-26", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:18.433513Z", + "iopub.status.busy": "2026-08-08T20:35:18.433434Z", + "iopub.status.idle": "2026-08-08T20:35:18.436043Z", + "shell.execute_reply": "2026-08-08T20:35:18.435839Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "SELECT reactions.id, reactions.name, reactions.rxn_class, reactions.rxn \n", - "FROM reactions \n", - "WHERE substruct(reactions.rxn, reaction_from_smarts(CAST(%(param_1)s AS cstring)))\n" + "SELECT molalchemy_tutorial_reactions.id, molalchemy_tutorial_reactions.name, molalchemy_tutorial_reactions.rxn_class, molalchemy_tutorial_reactions.rxn \n", + "FROM molalchemy_tutorial_reactions \n", + "WHERE substruct(molalchemy_tutorial_reactions.rxn, reaction_from_smarts(CAST(%(param_1)s AS cstring)))\n" ] } ], @@ -789,7 +934,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4, diff --git a/docs/tutorials/06_bingo_reactions_binary.ipynb b/docs/tutorials/06_bingo_reactions_binary.ipynb index 053514f..be585f4 100644 --- a/docs/tutorials/06_bingo_reactions_binary.ipynb +++ b/docs/tutorials/06_bingo_reactions_binary.ipynb @@ -14,15 +14,22 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 1, "id": "bb495784", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:30.246819Z", + "iopub.status.busy": "2026-08-08T20:35:30.246505Z", + "iopub.status.idle": "2026-08-08T20:35:30.810613Z", + "shell.execute_reply": "2026-08-08T20:35:30.810348Z" + } + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "1.40.0.0-g8d9e551c1\n" + "1.44.0\n" ] } ], @@ -73,9 +80,16 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 2, "id": "5187d3a4", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:30.811778Z", + "iopub.status.busy": "2026-08-08T20:35:30.811685Z", + "iopub.status.idle": "2026-08-08T20:35:30.865546Z", + "shell.execute_reply": "2026-08-08T20:35:30.865292Z" + } + }, "outputs": [ { "name": "stdout", @@ -147,9 +161,16 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 3, "id": "cb1be3b3", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:30.866630Z", + "iopub.status.busy": "2026-08-08T20:35:30.866554Z", + "iopub.status.idle": "2026-08-08T20:35:30.940495Z", + "shell.execute_reply": "2026-08-08T20:35:30.940251Z" + } + }, "outputs": [ { "name": "stdout", @@ -239,9 +260,16 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 4, "id": "4b3934aa", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:30.941556Z", + "iopub.status.busy": "2026-08-08T20:35:30.941486Z", + "iopub.status.idle": "2026-08-08T20:35:30.945165Z", + "shell.execute_reply": "2026-08-08T20:35:30.944963Z" + } + }, "outputs": [ { "name": "stdout", @@ -304,7 +332,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4, diff --git a/docs/tutorials/07_rdkit_descriptors_advanced.ipynb b/docs/tutorials/07_rdkit_descriptors_advanced.ipynb index 2b0325a..29d9e05 100644 --- a/docs/tutorials/07_rdkit_descriptors_advanced.ipynb +++ b/docs/tutorials/07_rdkit_descriptors_advanced.ipynb @@ -16,7 +16,14 @@ "cell_type": "code", "execution_count": 1, "id": "c059ac5c", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:44.854881Z", + "iopub.status.busy": "2026-08-08T20:35:44.854684Z", + "iopub.status.idle": "2026-08-08T20:35:45.354047Z", + "shell.execute_reply": "2026-08-08T20:35:45.353797Z" + } + }, "outputs": [ { "name": "stdout", @@ -77,7 +84,14 @@ "cell_type": "code", "execution_count": 2, "id": "53b4a779", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:45.355239Z", + "iopub.status.busy": "2026-08-08T20:35:45.355148Z", + "iopub.status.idle": "2026-08-08T20:35:45.400551Z", + "shell.execute_reply": "2026-08-08T20:35:45.400269Z" + } + }, "outputs": [], "source": [ "class Base(MappedAsDataclass, DeclarativeBase):\n", @@ -135,7 +149,14 @@ "cell_type": "code", "execution_count": 3, "id": "6ab7dd5b", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:45.401673Z", + "iopub.status.busy": "2026-08-08T20:35:45.401593Z", + "iopub.status.idle": "2026-08-08T20:35:45.407927Z", + "shell.execute_reply": "2026-08-08T20:35:45.407733Z" + } + }, "outputs": [ { "name": "stdout", @@ -184,7 +205,14 @@ "cell_type": "code", "execution_count": 4, "id": "71c91a0b", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:45.408996Z", + "iopub.status.busy": "2026-08-08T20:35:45.408923Z", + "iopub.status.idle": "2026-08-08T20:35:45.414051Z", + "shell.execute_reply": "2026-08-08T20:35:45.413859Z" + } + }, "outputs": [ { "name": "stdout", @@ -231,7 +259,14 @@ "cell_type": "code", "execution_count": 5, "id": "b46b6e37", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:45.415034Z", + "iopub.status.busy": "2026-08-08T20:35:45.414968Z", + "iopub.status.idle": "2026-08-08T20:35:45.418788Z", + "shell.execute_reply": "2026-08-08T20:35:45.418617Z" + } + }, "outputs": [ { "name": "stdout", @@ -275,7 +310,14 @@ "cell_type": "code", "execution_count": 6, "id": "b53112dc", - "metadata": {}, + "metadata": { + "execution": { + "iopub.execute_input": "2026-08-08T20:35:45.419733Z", + "iopub.status.busy": "2026-08-08T20:35:45.419668Z", + "iopub.status.idle": "2026-08-08T20:35:45.423021Z", + "shell.execute_reply": "2026-08-08T20:35:45.422851Z" + } + }, "outputs": [ { "name": "stdout", @@ -318,7 +360,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.19" + "version": "3.10.20" } }, "nbformat": 4,