From f0523fe29572cec6bbfd93edc99b35a3ac498a38 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sat, 23 May 2026 22:47:34 +0200 Subject: [PATCH 1/8] Enhance comparators and proxies with not_equals functionality and improve type hinting in helper functions --- src/molalchemy/bingo/comparators.py | 54 +++++++++++++++ src/molalchemy/bingo/proxy.py | 72 +++++++++++++++----- src/molalchemy/helpers.py | 40 ++++++++++- src/molalchemy/rdkit/__init__.py | 3 + src/molalchemy/rdkit/comparators.py | 26 +++++++ src/molalchemy/rdkit/proxy.py | 98 ++++++++++++++++++++++++++ tests/bingo/test_comparators.py | 83 ++++++++++++++++++++++ tests/bingo/test_index.py | 16 +++++ tests/rdkit/test_comparators.py | 24 +++++++ tests/test_helpers.py | 56 ++++++++++++++- update_proxy_stubs.py | 102 ++++++++++++++++++++-------- 11 files changed, 527 insertions(+), 47 deletions(-) create mode 100644 src/molalchemy/rdkit/proxy.py diff --git a/src/molalchemy/bingo/comparators.py b/src/molalchemy/bingo/comparators.py index e1028fe..d1c77f4 100644 --- a/src/molalchemy/bingo/comparators.py +++ b/src/molalchemy/bingo/comparators.py @@ -23,6 +23,15 @@ class BingoMolComparator(UserDefinedType.Comparator): """ def __eq__(self, other: Any) -> ColumnElement[bool]: + 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, parameters: Any = "") -> ColumnElement[bool]: @@ -91,6 +100,24 @@ 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]: + """ + 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. + """ + return ~self.equals(query, parameters) + class BingoRxnComparator(UserDefinedType.Comparator): """ @@ -101,6 +128,15 @@ class BingoRxnComparator(UserDefinedType.Comparator): """ def __eq__(self, other: Any) -> ColumnElement[bool]: + 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, parameters: Any = "") -> ColumnElement[bool]: @@ -168,3 +204,21 @@ def equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: >>> rxn_column.has_equals('CCO>>CC=O') # ethanol to acetaldehyde exact match """ return _bingo_search(self.expr, query, parameters, "bingo.rexact") + + def not_equals(self, query: Any, parameters: Any = "") -> ColumnElement[bool]: + """ + 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. + """ + return ~self.equals(query, parameters) diff --git a/src/molalchemy/bingo/proxy.py b/src/molalchemy/bingo/proxy.py index 601a305..7496c91 100644 --- a/src/molalchemy/bingo/proxy.py +++ b/src/molalchemy/bingo/proxy.py @@ -24,14 +24,14 @@ def has_substructure(query: str, parameters: str = ""): Parameters ---------- - query : str + query : Any The substructure query as a SMILES or MOL string. - parameters : str, optional + parameters : Any, optional Additional parameters for the substructure search, by default "". Returns ------- - sqlalchemy expression + ColumnElement[bool] A SQLAlchemy expression for the substructure match operation. Examples @@ -46,14 +46,14 @@ def has_smarts(query: str, parameters: str = ""): Parameters ---------- - query : str + query : Any The SMARTS pattern string for pattern matching. - parameters : str, optional + parameters : Any, optional Additional parameters for the SMARTS search, by default "". Returns ------- - sqlalchemy expression + ColumnElement[bool] A SQLAlchemy expression for the SMARTS pattern match operation. Examples @@ -68,14 +68,14 @@ def equals(query: str, parameters: str = ""): Parameters ---------- - query : str + query : Any The molecular structure query as a SMILES or MOL string. - parameters : str, optional + parameters : Any, optional Additional parameters for the exact match search, by default "". Returns ------- - sqlalchemy expression + ColumnElement[bool] A SQLAlchemy expression for the exact structure match operation. Examples @@ -84,6 +84,24 @@ def equals(query: str, parameters: str = ""): """ 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: """ @@ -99,14 +117,14 @@ def has_substructure(query: str, parameters: str = ""): Parameters ---------- - query : str + query : Any The reaction substructure query as a reaction SMILES or RXN string. - parameters : str, optional + parameters : Any, optional Additional parameters for the reaction substructure search, by default "". Returns ------- - sqlalchemy expression + ColumnElement[bool] A SQLAlchemy expression for the reaction substructure match operation. Examples @@ -121,14 +139,14 @@ def has_smarts(query: str, parameters: str = ""): Parameters ---------- - query : str + query : Any The reaction SMARTS pattern string for pattern matching. - parameters : str, optional + parameters : Any, optional Additional parameters for the reaction SMARTS search, by default "". Returns ------- - sqlalchemy expression + ColumnElement[bool] A SQLAlchemy expression for the reaction SMARTS pattern match operation. Examples @@ -143,14 +161,14 @@ def equals(query: str, parameters: str = ""): Parameters ---------- - query : str + query : Any The reaction query as a reaction SMILES or RXN string. - parameters : str, optional + parameters : Any, optional Additional parameters for the exact reaction match search, by default "". Returns ------- - sqlalchemy expression + ColumnElement[bool] A SQLAlchemy expression for the exact reaction match operation. Examples @@ -158,3 +176,21 @@ def equals(query: str, parameters: str = ""): >>> 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/helpers.py b/src/molalchemy/helpers.py index 4df64ed..d24decd 100644 --- a/src/molalchemy/helpers.py +++ b/src/molalchemy/helpers.py @@ -1,4 +1,4 @@ -"""Helper functions for working with Bingo molecule and reaction columns in modern IDEs. Work iprogress""" +"""Helper functions for typed molecule and reaction column autocomplete.""" from sqlalchemy import Column from sqlalchemy.orm.attributes import InstrumentedAttribute @@ -10,6 +10,8 @@ BingoReaction, ) from molalchemy.bingo.proxy import BingoMolProxy, BingoRxnProxy +from molalchemy.rdkit import RdkitMol, RdkitReaction +from molalchemy.rdkit.proxy import RdkitMolProxy, RdkitRxnProxy def bingo_col(column: Column | InstrumentedAttribute) -> BingoMolProxy: @@ -88,3 +90,39 @@ def bingo_rxn_col(column: Column | InstrumentedAttribute) -> BingoRxnProxy: raise TypeError( f"Input is not a SQLAlchemy InstrumentedAttribute or Column, got {type(column)}" ) + + +def rdkit_col(column: Column | InstrumentedAttribute) -> RdkitMolProxy: + """ + Create an RDKit molecule proxy from a SQLAlchemy column. + + 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 + else: + raise TypeError("Column is not of type RdkitMol") + else: + raise TypeError( + f"Input is not a SQLAlchemy Column or InstrumentedAttribute, got {type(column)}" + ) + + +def rdkit_rxn_col(column: Column | InstrumentedAttribute) -> RdkitRxnProxy: + """ + Create an RDKit reaction proxy from a SQLAlchemy column. + + 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 + else: + raise TypeError("Column is not of type RdkitReaction") + else: + raise TypeError( + f"Input is not a SQLAlchemy InstrumentedAttribute or Column, got {type(column)}" + ) diff --git a/src/molalchemy/rdkit/__init__.py b/src/molalchemy/rdkit/__init__.py index 0110356..3fa25e6 100644 --- a/src/molalchemy/rdkit/__init__.py +++ b/src/molalchemy/rdkit/__init__.py @@ -1,5 +1,6 @@ from .comparators import RdkitFPComparator, RdkitMolComparator, RdkitReactionComparator from .index import RdkitIndex +from .proxy import RdkitMolProxy, RdkitRxnProxy from .settings import ( get_dice_threshold, get_tanimoto_threshold, @@ -22,9 +23,11 @@ "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 54c0dbb..d2ab402 100644 --- a/src/molalchemy/rdkit/comparators.py +++ b/src/molalchemy/rdkit/comparators.py @@ -8,6 +8,20 @@ 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 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]: """Check if this molecule contains `query` as a substructure (@>).""" return self.expr.op("@>")(query) @@ -38,6 +52,18 @@ def is_query_substructure_of(self, query: Any) -> ColumnElement[bool]: class RdkitReactionComparator(UserDefinedType.Comparator): + def __eq__(self, other: Any) -> ColumnElement[bool]: + 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]: """Check if this reaction contains `query` as a substructure (@>).""" return self.expr.op("@>")(query) diff --git a/src/molalchemy/rdkit/proxy.py b/src/molalchemy/rdkit/proxy.py new file mode 100644 index 0000000..a23392e --- /dev/null +++ b/src/molalchemy/rdkit/proxy.py @@ -0,0 +1,98 @@ +""" +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/tests/bingo/test_comparators.py b/tests/bingo/test_comparators.py index 1cbc479..219a81a 100644 --- a/tests/bingo/test_comparators.py +++ b/tests/bingo/test_comparators.py @@ -97,6 +97,16 @@ def test_equals_query_generation(self): 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_equals_with_parameters(self): """Test exact match query with parameters.""" query = "CCO" @@ -109,6 +119,30 @@ def test_equals_with_parameters(self): 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_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" @@ -239,6 +273,40 @@ def test_reaction_equals_query_generation(self): 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_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_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})) + + assert "NOT" in compiled + assert "bingo.rexact" in compiled + assert query in compiled + assert parameters in compiled + def test_binary_reaction_has_substructure(self): """Test reaction comparator works with binary reaction type.""" query = "C=C>>CC" @@ -294,6 +362,7 @@ def setup_method(self): self.metadata, Column("id", Integer, primary_key=True), Column("mol", BingoMol()), + Column("rxn", BingoReaction()), ) def test_has_substructure_returns_column_element(self): @@ -308,6 +377,14 @@ 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_reaction_not_equals_returns_column_element(self): + result = self.test_table.c.rxn.not_equals("CCO>>CC=O") + assert isinstance(result, ColumnElement) + class TestBingoComparatorExports: """Test comparators are exported from bingo subpackage.""" @@ -322,6 +399,12 @@ def test_import_rxn_comparator_from_bingo(self): 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.""" diff --git a/tests/bingo/test_index.py b/tests/bingo/test_index.py index aa81474..c279aa5 100644 --- a/tests/bingo/test_index.py +++ b/tests/bingo/test_index.py @@ -66,6 +66,22 @@ def test_bingo_mol_index_with_table(self): assert index.table is self.test_table assert index in self.test_table.indexes + def test_bingo_index_membership_with_multiple_columns(self): + """Column membership checks should not invoke chemical exact matching.""" + metadata = MetaData() + test_table = Table( + "test_compounds", + metadata, + Column("id", Integer, primary_key=True), + Column("mol", BingoMol()), + Column("name", String(100)), + ) + + index = Index("idx_compounds_mol_name", test_table.c.mol, test_table.c.name) + + assert test_table.c.mol in index.expressions + assert test_table.c.name in index.expressions + class TestBingoBinaryMolIndex: """Test BingoBinaryMolIndex class.""" diff --git a/tests/rdkit/test_comparators.py b/tests/rdkit/test_comparators.py index ac5cfcc..1bb8cea 100644 --- a/tests/rdkit/test_comparators.py +++ b/tests/rdkit/test_comparators.py @@ -75,6 +75,15 @@ def test_query_with_special_characters(self): # 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_string_queries_compile_via_molecule_coercion(self): stmt = select(self.test_table).where( self.mol_column.has_substructure("x' OR 1=1 --") @@ -278,6 +287,15 @@ def test_bindparam_queries_compile_via_reaction_coercion(self): 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_query_column_expressions_are_preserved(self): stmt = select(self.test_table).where( self.rxn_column.has_substructure(self.test_table.c.query_rxn) @@ -384,6 +402,12 @@ def test_import_mol_comparator_from_rdkit(self): 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.""" diff --git a/tests/test_helpers.py b/tests/test_helpers.py index bd27efb..c38f446 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -7,7 +7,8 @@ BingoMol, BingoReaction, ) -from molalchemy.helpers import bingo_col, bingo_rxn_col +from molalchemy.helpers import bingo_col, bingo_rxn_col, rdkit_col, rdkit_rxn_col +from molalchemy.rdkit.types import RdkitMol, RdkitReaction @pytest.fixture(params=[BingoMol, BingoBinaryMol]) @@ -22,6 +23,16 @@ def good_bingo_rxn_col(request: pytest.FixtureRequest): return Column("reaction", column_type) +@pytest.fixture() +def good_rdkit_mol_col(): + return Column("structure", RdkitMol()) + + +@pytest.fixture() +def good_rdkit_rxn_col(): + return Column("reaction", RdkitReaction()) + + @pytest.mark.parametrize("bad_type", [String, BINARY]) def test_bingo_mol_col_type_error(bad_type): col = Column("bad_structure", bad_type) @@ -57,3 +68,46 @@ def test_bingo_rxn_col_invalid_input(): def test_bingo_mol_col_success(good_bingo_mol_col): result = bingo_col(good_bingo_mol_col) assert result is good_bingo_mol_col + + +def test_bingo_rxn_col_success(good_bingo_rxn_col): + result = bingo_rxn_col(good_bingo_rxn_col) + assert result is good_bingo_rxn_col + + +@pytest.mark.parametrize("bad_type", [String, BINARY]) +def test_rdkit_mol_col_type_error(bad_type): + col = Column("bad_structure", bad_type) + with pytest.raises(TypeError, match="Column is not of type RdkitMol"): + rdkit_col(col) + + +@pytest.mark.parametrize("bad_type", [String, BINARY]) +def test_rdkit_rxn_col_type_error(bad_type): + col = Column("bad_reaction", bad_type) + with pytest.raises(TypeError, match="Column is not of type RdkitReaction"): + rdkit_rxn_col(col) + + +def test_rdkit_mol_col_invalid_input(): + with pytest.raises( + TypeError, match="Input is not a SQLAlchemy Column or InstrumentedAttribute" + ): + rdkit_col("not_a_column") + + +def test_rdkit_rxn_col_invalid_input(): + with pytest.raises( + TypeError, match="Input is not a SQLAlchemy InstrumentedAttribute or Column" + ): + rdkit_rxn_col(123) + + +def test_rdkit_mol_col_success(good_rdkit_mol_col): + result = rdkit_col(good_rdkit_mol_col) + assert result is good_rdkit_mol_col + + +def test_rdkit_rxn_col_success(good_rdkit_rxn_col): + result = rdkit_rxn_col(good_rdkit_rxn_col) + assert result is good_rdkit_rxn_col diff --git a/update_proxy_stubs.py b/update_proxy_stubs.py index 7821b2b..0762bff 100644 --- a/update_proxy_stubs.py +++ b/update_proxy_stubs.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -Script to create BingoMolProxy and BingoRxnProxy stubs in a separate proxy.py file. +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. @@ -8,9 +8,31 @@ """ 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]]: """ @@ -46,9 +68,9 @@ def extract_method_info(class_node: ast.ClassDef) -> list[dict[str, Any]]: default = node.args.defaults[default_idx] if isinstance(default, ast.Constant): if isinstance(default.value, str): - default_value = f'="{default.value}"' + default_value = f' = "{default.value}"' else: - default_value = f"={default.value}" + default_value = f" = {default.value}" args.append(f"{arg_name}: {arg_type}{default_value}") @@ -60,7 +82,7 @@ def extract_method_info(class_node: ast.ClassDef) -> list[dict[str, Any]]: and isinstance(node.body[0].value, ast.Constant) and isinstance(node.body[0].value.value, str) ): - docstring = node.body[0].value.value + docstring = textwrap.dedent(node.body[0].value.value) methods.append( {"name": node.name, "args": args, "docstring": docstring.strip()} @@ -111,7 +133,9 @@ def {method_name}({args_str}): def create_proxy_file( - mol_methods: list[dict[str, Any]], rxn_methods: list[dict[str, Any]] + 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. @@ -123,11 +147,14 @@ def create_proxy_file( rxn_methods : List[Dict[str, Any]] List of reaction comparator methods. """ - proxy_path = Path("src/molalchemy/bingo/proxy.py") + proxy_path = config["proxy_path"] + label = config["label"] + mol_proxy = config["mol_proxy"] + rxn_proxy = config["rxn_proxy"] # Generate file header - header = '''""" -Proxy classes for Bingo database operations. + 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 @@ -139,40 +166,42 @@ def create_proxy_file( ''' - # Generate BingoMolProxy class + # 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 BingoMolProxy: + mol_proxy_class = f"""class {mol_proxy}: \"\"\" - Proxy class for molecular operations using Bingo database. - + 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. \"\"\" -{chr(10).join(mol_proxy_methods)} +{mol_proxy_methods_code} """ - # Generate BingoRxnProxy class + # 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 BingoRxnProxy: + rxn_proxy_class = f"""class {rxn_proxy}: \"\"\" - Proxy class for chemical reaction operations using Bingo database. - + 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. \"\"\" -{chr(10).join(rxn_proxy_methods)} +{rxn_proxy_methods_code} """ # Write the complete proxy file - with open(proxy_path, "w") as f: + with proxy_path.open("w") as f: f.write(header) f.write(mol_proxy_class) f.write("\n\n\n") @@ -182,16 +211,18 @@ def create_proxy_file( print(f"Created {proxy_path} with proxy stubs!") -def main(): +def generate_proxy(target: str) -> None: """Main function to create proxy stubs from comparators.""" + config = TARGETS[target] + # Read the comparators file - comparators_path = Path("src/molalchemy/bingo/comparators.py") + comparators_path = config["comparators_path"] if not comparators_path.exists(): print(f"Error: {comparators_path} not found!") return - with open(comparators_path) as f: + with comparators_path.open() as f: source_code = f.read() # Parse the AST @@ -203,18 +234,35 @@ def main(): for node in tree.body: if isinstance(node, ast.ClassDef): - if node.name == "BingoMolComparator": + if node.name == config["mol_comparator"]: mol_methods = extract_method_info(node) - print(f"Found {len(mol_methods)} methods in BingoMolComparator") - elif node.name == "BingoRxnComparator": + 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 BingoRxnComparator") + print(f"Found {len(rxn_methods)} methods in {config['rxn_comparator']}") if mol_methods or rxn_methods: - create_proxy_file(mol_methods, 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() From 4f8a1b1b5963e31bb1e665b8ffe73d2c903cdf02 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sat, 23 May 2026 22:58:39 +0200 Subject: [PATCH 2/8] improve bingo comparators --- src/molalchemy/bingo/comparators.py | 24 +++++++++++++ tests/bingo/test_comparators.py | 52 +++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/src/molalchemy/bingo/comparators.py b/src/molalchemy/bingo/comparators.py index d1c77f4..33b253f 100644 --- a/src/molalchemy/bingo/comparators.py +++ b/src/molalchemy/bingo/comparators.py @@ -34,6 +34,18 @@ def __eq__(self, other: Any) -> ColumnElement[bool]: return super().__eq__(other) return self.equals(other) + def __ne__(self, other: Any) -> ColumnElement[bool]: + 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]: """ Check if the molecular structure contains a given substructure. @@ -139,6 +151,18 @@ def __eq__(self, other: Any) -> ColumnElement[bool]: return super().__eq__(other) return self.equals(other) + def __ne__(self, other: Any) -> ColumnElement[bool]: + 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]: """ Check if the reaction contains a given substructure pattern. diff --git a/tests/bingo/test_comparators.py b/tests/bingo/test_comparators.py index 219a81a..6437a72 100644 --- a/tests/bingo/test_comparators.py +++ b/tests/bingo/test_comparators.py @@ -130,6 +130,23 @@ def test_not_equals_query_generation(self): 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_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" @@ -218,6 +235,16 @@ def test_binary_mol_equals(self): assert "bingo.exact" in compiled assert query 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 + class TestBingoRxnComparator: """Test BingoRxnComparator methods.""" @@ -294,6 +321,23 @@ def test_reaction_not_equals_query_generation(self): 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_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 + def test_reaction_not_equals_with_parameters(self): """Test negative exact reaction query with parameters.""" query = "CCO>>CC=O" @@ -381,10 +425,18 @@ 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.""" From f3e03e6dc51eb453d60a94ecec604edec6353fa9 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sat, 23 May 2026 23:10:31 +0200 Subject: [PATCH 3/8] support NULL check --- src/molalchemy/bingo/comparators.py | 4 ++++ src/molalchemy/rdkit/comparators.py | 4 ++++ tests/bingo/test_comparators.py | 21 +++++++++++++++++++++ tests/rdkit/test_comparators.py | 18 ++++++++++++++++++ 4 files changed, 47 insertions(+) diff --git a/src/molalchemy/bingo/comparators.py b/src/molalchemy/bingo/comparators.py index 33b253f..51809d1 100644 --- a/src/molalchemy/bingo/comparators.py +++ b/src/molalchemy/bingo/comparators.py @@ -35,6 +35,8 @@ def __eq__(self, other: Any) -> ColumnElement[bool]: 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 ): @@ -152,6 +154,8 @@ def __eq__(self, other: Any) -> ColumnElement[bool]: 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 ): diff --git a/src/molalchemy/rdkit/comparators.py b/src/molalchemy/rdkit/comparators.py index d2ab402..98ea763 100644 --- a/src/molalchemy/rdkit/comparators.py +++ b/src/molalchemy/rdkit/comparators.py @@ -11,6 +11,8 @@ 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 ): @@ -53,6 +55,8 @@ def is_query_substructure_of(self, query: Any) -> ColumnElement[bool]: 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 ): diff --git a/tests/bingo/test_comparators.py b/tests/bingo/test_comparators.py index 6437a72..fc4cc65 100644 --- a/tests/bingo/test_comparators.py +++ b/tests/bingo/test_comparators.py @@ -140,6 +140,13 @@ def test_ne_operator_delegates_to_negative_exact_match(self): 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())) + + 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})) @@ -245,6 +252,13 @@ def test_binary_mol_ne_operator_delegates_to_negative_exact_match(self): 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.""" @@ -331,6 +345,13 @@ def test_reaction_ne_operator_delegates_to_negative_exact_match(self): 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})) diff --git a/tests/rdkit/test_comparators.py b/tests/rdkit/test_comparators.py index 1bb8cea..fd4a760 100644 --- a/tests/rdkit/test_comparators.py +++ b/tests/rdkit/test_comparators.py @@ -84,6 +84,15 @@ def test_eq_operator_delegates_to_exact_match(self): 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 --") @@ -296,6 +305,15 @@ def test_eq_operator_delegates_to_exact_match(self): 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) From e45b27414b298546df1ce91d8aafcb03090cdfb7 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sat, 23 May 2026 23:14:15 +0200 Subject: [PATCH 4/8] update smoke tests --- dev_scripts/validate_bingo_helpers.py | 33 ++++++++++++++++-- dev_scripts/validate_rdkit_helpers.py | 50 ++++++++++++++++++++++++++- 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/dev_scripts/validate_bingo_helpers.py b/dev_scripts/validate_bingo_helpers.py index 972411a..7daf9e0 100644 --- a/dev_scripts/validate_bingo_helpers.py +++ b/dev_scripts/validate_bingo_helpers.py @@ -49,7 +49,7 @@ def main() -> None: metadata, Column("id", Integer, primary_key=True), Column("name", String, nullable=False), - Column("structure", BingoMol(), nullable=False), + Column("structure", BingoMol()), Column("query_structure", String, nullable=False), ) reactions = Table( @@ -57,7 +57,7 @@ def main() -> None: metadata, Column("id", Integer, primary_key=True), Column("name", String, nullable=False), - Column("reaction_data", BingoBinaryReaction(), nullable=False), + Column("reaction_data", BingoBinaryReaction()), ) with engine.begin() as conn: @@ -81,6 +81,12 @@ def main() -> None: "structure": "CCO", "query_structure": "CCO", }, + { + "id": 3, + "name": "unknown", + "structure": None, + "query_structure": "CCO", + }, ], ) conn.execute( @@ -91,6 +97,11 @@ def main() -> None: "name": "ethanol oxidation", "reaction_data": "CCO>>CC=O", }, + { + "id": 2, + "name": "unknown reaction", + "reaction_data": None, + }, ], ) @@ -144,6 +155,16 @@ def main() -> None: reaction_exact_stmt = select(reactions.c.name).where( reactions.c.reaction_data.equals("CCO>>CC=O") ) + molecule_not_null_stmt = ( + select(compounds.c.name) + .where(compounds.c.structure.__ne__(None)) + .order_by(compounds.c.id) + ) + reaction_not_null_stmt = ( + select(reactions.c.name) + .where(reactions.c.reaction_data.__ne__(None)) + .order_by(reactions.c.id) + ) reaction_function_stmt = ( select( reactions.c.name, @@ -170,6 +191,8 @@ def main() -> None: ) print(function_stmt.compile(dialect=postgresql.dialect())) print(reaction_exact_stmt.compile(dialect=postgresql.dialect())) + print(molecule_not_null_stmt.compile(dialect=postgresql.dialect())) + print(reaction_not_null_stmt.compile(dialect=postgresql.dialect())) print(reaction_function_stmt.compile(dialect=postgresql.dialect())) with engine.connect() as conn: @@ -181,6 +204,8 @@ 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() + 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() print() @@ -192,6 +217,8 @@ 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"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)}") assert substructure_rows == ["benzene"] @@ -211,6 +238,8 @@ def main() -> None: assert function_row["fingerprint_len"] > 0 assert "invalid character" in invalid_check assert reaction_exact_rows == ["ethanol oxidation"] + assert molecule_not_null_rows == ["benzene", "ethanol"] + assert reaction_not_null_rows == ["ethanol oxidation"] assert reaction_function_row["check_result"] is None assert reaction_function_row["reaction_smiles"] assert reaction_function_row["rxnfile_len"] > 100 diff --git a/dev_scripts/validate_rdkit_helpers.py b/dev_scripts/validate_rdkit_helpers.py index 4f2e5e5..f9aed32 100644 --- a/dev_scripts/validate_rdkit_helpers.py +++ b/dev_scripts/validate_rdkit_helpers.py @@ -20,7 +20,7 @@ from sqlalchemy.schema import CreateTable from molalchemy.rdkit import functions as rdkit_func -from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitMol +from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitMol, RdkitReaction from molalchemy.types import CString DATABASE_URL = os.environ.get( @@ -59,8 +59,26 @@ def main() -> None: Computed("morganbv_fp(mol)", persisted=True), ), ) + nullable_molecules = Table( + "molalchemy_rdkit_null_validation", + metadata, + Column("id", Integer, primary_key=True), + Column("name", String, nullable=False), + Column("mol", RdkitMol()), + ) + nullable_reactions = Table( + "molalchemy_rdkit_reaction_null_validation", + metadata, + Column("id", Integer, primary_key=True), + Column("name", String, nullable=False), + Column("rxn", RdkitReaction()), + ) with engine.begin() as conn: + conn.exec_driver_sql( + "DROP TABLE IF EXISTS molalchemy_rdkit_reaction_null_validation" + ) + conn.exec_driver_sql("DROP TABLE IF EXISTS molalchemy_rdkit_null_validation") conn.exec_driver_sql("DROP TABLE IF EXISTS molalchemy_rdkit_helper_validation") metadata.create_all(conn) conn.execute( @@ -75,6 +93,20 @@ def main() -> None: }, ], ) + conn.execute( + nullable_molecules.insert(), + [ + {"id": 1, "name": "benzene", "mol": "c1ccccc1"}, + {"id": 2, "name": "unknown", "mol": None}, + ], + ) + conn.execute( + nullable_reactions.insert(), + [ + {"id": 1, "name": "ethanol oxidation", "rxn": "CCO>>CC=O"}, + {"id": 2, "name": "unknown reaction", "rxn": None}, + ], + ) substructure_stmt = ( select(molecules.c.name) @@ -119,8 +151,16 @@ def main() -> None: .where(molecules.c.name == "ethanol") .limit(1) ) + molecule_null_stmt = select(nullable_molecules.c.name).where( + nullable_molecules.c.mol.__eq__(None) + ) + reaction_null_stmt = select(nullable_reactions.c.name).where( + nullable_reactions.c.rxn.__eq__(None) + ) 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(functional_substructure_stmt.compile(dialect=postgresql.dialect())) @@ -128,6 +168,8 @@ def main() -> None: print(tanimoto_stmt.compile(dialect=postgresql.dialect())) print(dice_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())) with engine.connect() as conn: version = conn.exec_driver_sql("SELECT rdkit_version()").scalar_one() @@ -139,6 +181,8 @@ def main() -> None: tanimoto_rows = conn.execute(tanimoto_stmt).scalars().all() dice_rows = conn.execute(dice_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() print() print(f"RDKit version: {version}") @@ -148,6 +192,8 @@ def main() -> None: print(f"tanimoto fingerprint threshold(CCO): {tanimoto_rows}") print(f"dice fingerprint threshold(CCO): {dice_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}") assert substructure_rows == ["benzene", "aspirin"] assert functional_substructure_rows == ["benzene", "aspirin"] @@ -168,6 +214,8 @@ def main() -> None: assert function_row["dice_score"] == 1 assert function_row["ctab_len"] > 100 assert function_row["pkl_len"] > 0 + assert molecule_null_rows == ["unknown"] + assert reaction_null_rows == ["unknown reaction"] if __name__ == "__main__": From 2de8e58e2545b5beb8489303a9771dbd71f4282c Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sat, 23 May 2026 23:23:45 +0200 Subject: [PATCH 5/8] fix rhs behavior for bingp --- dev_scripts/validate_bingo_helpers.py | 33 +++++++++++++++- src/molalchemy/bingo/comparators.py | 14 ++----- src/molalchemy/bingo/search.py | 20 +++++++++- tests/bingo/test_comparators.py | 55 +++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 13 deletions(-) diff --git a/dev_scripts/validate_bingo_helpers.py b/dev_scripts/validate_bingo_helpers.py index 7daf9e0..372afdd 100644 --- a/dev_scripts/validate_bingo_helpers.py +++ b/dev_scripts/validate_bingo_helpers.py @@ -58,6 +58,7 @@ def main() -> None: Column("id", Integer, primary_key=True), Column("name", String, nullable=False), Column("reaction_data", BingoBinaryReaction()), + Column("query_reaction", String, nullable=False), ) with engine.begin() as conn: @@ -79,7 +80,7 @@ def main() -> None: "id": 2, "name": "ethanol", "structure": "CCO", - "query_structure": "CCO", + "query_structure": "OCC", }, { "id": 3, @@ -96,11 +97,13 @@ def main() -> None: "id": 1, "name": "ethanol oxidation", "reaction_data": "CCO>>CC=O", + "query_reaction": "CCO>>CC=O", }, { "id": 2, "name": "unknown reaction", "reaction_data": None, + "query_reaction": "CCO>>CC=O", }, ], ) @@ -155,6 +158,14 @@ def main() -> None: reaction_exact_stmt = select(reactions.c.name).where( reactions.c.reaction_data.equals("CCO>>CC=O") ) + exact_with_column_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)) @@ -191,6 +202,16 @@ 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( + dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True} + ) + ) print(molecule_not_null_stmt.compile(dialect=postgresql.dialect())) print(reaction_not_null_stmt.compile(dialect=postgresql.dialect())) print(reaction_function_stmt.compile(dialect=postgresql.dialect())) @@ -204,6 +225,10 @@ 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() + ) 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() @@ -217,6 +242,10 @@ 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"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)}") @@ -238,6 +267,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"] 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/src/molalchemy/bingo/comparators.py b/src/molalchemy/bingo/comparators.py index 51809d1..dd38dc7 100644 --- a/src/molalchemy/bingo/comparators.py +++ b/src/molalchemy/bingo/comparators.py @@ -23,15 +23,12 @@ class BingoMolComparator(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 __ne__(self, other: Any) -> ColumnElement[bool]: @@ -142,15 +139,12 @@ class BingoRxnComparator(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 __ne__(self, other: Any) -> ColumnElement[bool]: diff --git a/src/molalchemy/bingo/search.py b/src/molalchemy/bingo/search.py index 88344e3..5a23fea 100644 --- a/src/molalchemy/bingo/search.py +++ b/src/molalchemy/bingo/search.py @@ -3,7 +3,15 @@ from typing import Any from sqlalchemy import types as sqltypes -from sqlalchemy.sql.elements import ColumnElement +from sqlalchemy.sql import operators +from sqlalchemy.sql.elements import BinaryExpression, ColumnElement + + +class _BingoExactSearchExpression(BinaryExpression[bool]): + inherit_cache = True + + def __bool__(self) -> bool: + return self._orig[0] == self._orig[1] class _BingoSearchType(sqltypes.UserDefinedType): @@ -36,4 +44,12 @@ def _bingo_search( query_tuple: Any, search_type: str, ) -> ColumnElement[bool]: - return column.op("@")(query_tuple.cast(_BingoSearchType(search_type))) + 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) diff --git a/tests/bingo/test_comparators.py b/tests/bingo/test_comparators.py index fc4cc65..f5edd50 100644 --- a/tests/bingo/test_comparators.py +++ b/tests/bingo/test_comparators.py @@ -24,6 +24,7 @@ def setup_method(self): 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 @@ -107,6 +108,26 @@ def test_eq_operator_delegates_to_exact_match(self): 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" @@ -206,6 +227,7 @@ def setup_method(self): 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 @@ -242,6 +264,19 @@ def test_binary_mol_equals(self): 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" @@ -324,6 +359,26 @@ def test_reaction_eq_operator_delegates_to_exact_match(self): 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())) + + 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" From df22e94b0584879081c59c07f9811320b2b18918 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sun, 24 May 2026 20:21:39 +0200 Subject: [PATCH 6/8] add comment on exact search --- src/molalchemy/bingo/search.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/molalchemy/bingo/search.py b/src/molalchemy/bingo/search.py index 5a23fea..b1bfece 100644 --- a/src/molalchemy/bingo/search.py +++ b/src/molalchemy/bingo/search.py @@ -8,9 +8,19 @@ 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 ec10122100b6686076234c7fd848293fdd615608 Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sun, 24 May 2026 20:43:47 +0200 Subject: [PATCH 7/8] add proxy tutorials --- docs/tutorials/08_proxy_helpers.md | 175 +++++++++++++++++++++++++++++ mkdocs.yml | 1 + tests/test_helpers.py | 136 +++++++++++++++++++++- 3 files changed, 311 insertions(+), 1 deletion(-) create mode 100644 docs/tutorials/08_proxy_helpers.md diff --git a/docs/tutorials/08_proxy_helpers.md b/docs/tutorials/08_proxy_helpers.md new file mode 100644 index 0000000..8a017ec --- /dev/null +++ b/docs/tutorials/08_proxy_helpers.md @@ -0,0 +1,175 @@ +# Typed Proxy 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` +are a small typing bridge for that case. + +```python +from molalchemy.helpers import bingo_col + +stmt = select(Compound).where( + bingo_col(Compound.structure).has_substructure("c1ccccc1") +) +``` + +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. + +## Bingo ORM + +```python +from sqlalchemy import Integer, String, select +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +from molalchemy.bingo.types import BingoMol, BingoReaction +from molalchemy.helpers import bingo_col, bingo_rxn_col + + +class Base(DeclarativeBase): + pass + + +class Compound(Base): + __tablename__ = "compounds" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + structure: Mapped[str] = mapped_column(BingoMol()) + + +class Reaction(Base): + __tablename__ = "reactions" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + reaction: Mapped[str] = mapped_column(BingoReaction()) + + +benzene_query = select(Compound).where( + bingo_col(Compound.structure).has_substructure("c1ccccc1") +) + +ethanol_query = select(Compound).where( + bingo_col(Compound.structure).equals("CCO") +) + +reaction_query = select(Reaction).where( + bingo_rxn_col(Reaction.reaction).equals("CCO>>CC=O") +) +``` + +These statements compile to the same SQL as calling the comparator methods +directly on the mapped attributes. + +## RDKit ORM + +```python +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 + + +class Base(DeclarativeBase): + pass + + +class Compound(Base): + __tablename__ = "rdkit_compounds" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + structure: Mapped[str] = mapped_column(RdkitMol()) + + +class Reaction(Base): + __tablename__ = "rdkit_reactions" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + reaction: Mapped[str] = mapped_column(RdkitReaction()) + + +exact_match = select(Compound).where( + rdkit_col(Compound.structure).equals("CCO") +) + +reaction_smarts = select(Reaction).where( + rdkit_rxn_col(Reaction.reaction).has_smarts("[C:1]>>[C:1][O]") +) +``` + +## SQLAlchemy Core + +The helpers also accept Core table columns. + +```python +from sqlalchemy import Column, Integer, MetaData, String, Table, select + +from molalchemy.bingo.types import BingoMol +from molalchemy.helpers import bingo_col + + +metadata = MetaData() + +compounds = Table( + "compounds", + metadata, + Column("id", Integer, primary_key=True), + Column("name", String(100)), + Column("structure", BingoMol()), +) + +stmt = select(compounds).where( + bingo_col(compounds.c.structure).has_substructure("c1ccccc1") +) +``` + +## Validation + +Each helper checks that the input is a SQLAlchemy `Column` or ORM +`InstrumentedAttribute` with the expected MolAlchemy type. + +```python +from sqlalchemy import Column, String + +from molalchemy.helpers import bingo_col + + +name = Column("name", String) + +bingo_col(name) +# TypeError: Column is not of type BingoMol or BingoBinaryMol +``` + +Use the matching helper for the cartridge and data kind: + +| Helper | Accepted types | +| --- | --- | +| `bingo_col` | `BingoMol`, `BingoBinaryMol` | +| `bingo_rxn_col` | `BingoReaction`, `BingoBinaryReaction` | +| `rdkit_col` | `RdkitMol` | +| `rdkit_rxn_col` | `RdkitReaction` | + +## When To Use Them + +Use proxy helpers when your like ypur autocomplete or want to use static code analysis. + +For a more explicit functional style, use the cartridge function modules: + +```python +from molalchemy.bingo import functions as bingo_func +# instead of +# select(Compound).where(Compound.structure.has_substructure("c1ccccc1")) +# use +stmt = select(Compound).where( + bingo_func.mol_has_substructure(Compound.structure, "c1ccccc1") +) +``` diff --git a/mkdocs.yml b/mkdocs.yml index b2f167d..169f6b1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -99,6 +99,7 @@ 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 - Contributing: tutorials/contribute.md - API: - molalchemy.exceptions: api/exceptions.md diff --git a/tests/test_helpers.py b/tests/test_helpers.py index c38f446..c2becf2 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1,5 +1,7 @@ import pytest -from sqlalchemy import BINARY, Column, String +from sqlalchemy import BINARY, Column, Integer, String, Table, select +from sqlalchemy.dialects import postgresql +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from molalchemy.bingo.types import ( BingoBinaryMol, @@ -11,6 +13,27 @@ from molalchemy.rdkit.types import RdkitMol, RdkitReaction +class Base(DeclarativeBase): + pass + + +class BingoCompound(Base): + __tablename__ = "helper_bingo_compounds" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + structure: Mapped[str] = mapped_column(BingoMol()) + binary_structure: Mapped[bytes] = mapped_column(BingoBinaryMol()) + reaction: Mapped[str] = mapped_column(BingoReaction()) + + +class RdkitCompound(Base): + __tablename__ = "helper_rdkit_compounds" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + structure: Mapped[str] = mapped_column(RdkitMol()) + reaction: Mapped[str] = mapped_column(RdkitReaction()) + + @pytest.fixture(params=[BingoMol, BingoBinaryMol]) def good_bingo_mol_col(request: pytest.FixtureRequest): column_type = request.param @@ -111,3 +134,114 @@ def test_rdkit_mol_col_success(good_rdkit_mol_col): def test_rdkit_rxn_col_success(good_rdkit_rxn_col): result = rdkit_rxn_col(good_rdkit_rxn_col) assert result is good_rdkit_rxn_col + + +def test_bingo_mol_proxy_helper_core_column_compiles_substructure(): + table = Table( + "compounds", + Base.metadata, + Column("id", Integer, primary_key=True), + Column("structure", BingoMol()), + extend_existing=True, + ) + + stmt = select(table).where( + bingo_col(table.c.structure).has_substructure("c1ccccc1") + ) + compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) + + assert "bingo.sub" in compiled + assert "c1ccccc1" in compiled + + +def test_bingo_binary_mol_proxy_helper_core_column_compiles_exact_search(): + table = Table( + "binary_compounds", + Base.metadata, + Column("id", Integer, primary_key=True), + Column("structure", BingoBinaryMol()), + extend_existing=True, + ) + + stmt = select(table).where(bingo_col(table.c.structure).equals("CCO")) + compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) + + assert "bingo.exact" in compiled + assert "CCO" in compiled + + +def test_bingo_rxn_proxy_helper_core_column_compiles_exact_search(): + table = Table( + "reactions", + Base.metadata, + Column("id", Integer, primary_key=True), + Column("reaction", BingoReaction()), + extend_existing=True, + ) + + stmt = select(table).where(bingo_rxn_col(table.c.reaction).equals("CCO>>CC=O")) + compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) + + assert "bingo.rexact" in compiled + assert "CCO>>CC=O" in compiled + + +def test_rdkit_mol_proxy_helper_core_column_compiles_substructure(): + table = Table( + "rdkit_compounds", + Base.metadata, + Column("id", Integer, primary_key=True), + Column("structure", RdkitMol()), + extend_existing=True, + ) + + stmt = select(table).where( + rdkit_col(table.c.structure).has_substructure("c1ccccc1") + ) + compiled = str(stmt.compile(dialect=postgresql.dialect())) + + assert "@>" in compiled + assert "structure_" in compiled + + +def test_rdkit_rxn_proxy_helper_core_column_compiles_smarts_search(): + table = Table( + "rdkit_reactions", + Base.metadata, + Column("id", Integer, primary_key=True), + Column("reaction", RdkitReaction()), + extend_existing=True, + ) + + stmt = select(table).where( + rdkit_rxn_col(table.c.reaction).has_smarts("[C:1]>>[C:1][O]") + ) + compiled = str(stmt.compile(dialect=postgresql.dialect())) + + assert "substruct" in compiled + assert "reaction_from_smarts" in compiled + + +def test_bingo_proxy_helpers_accept_orm_instrumented_attributes(): + assert bingo_col(BingoCompound.structure) is BingoCompound.structure + assert bingo_col(BingoCompound.binary_structure) is BingoCompound.binary_structure + assert bingo_rxn_col(BingoCompound.reaction) is BingoCompound.reaction + + stmt = select(BingoCompound).where(bingo_col(BingoCompound.structure).equals("CCO")) + compiled = str(stmt.compile(compile_kwargs={"literal_binds": True})) + + assert "bingo.exact" in compiled + assert "CCO" in compiled + + +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 + + stmt = select(RdkitCompound).where( + rdkit_rxn_col(RdkitCompound.reaction).has_smarts("[C:1]>>[C:1][O]") + ) + compiled = str(stmt.compile(dialect=postgresql.dialect())) + + assert "substruct" in compiled + assert "reaction_from_smarts" in compiled From cd06bb63f530c2ff1e4783b8b20b3aa157fe30ae Mon Sep 17 00:00:00 2001 From: Anton Siomchen <41703271+asiomchen@users.noreply.github.com> Date: Sun, 24 May 2026 20:53:38 +0200 Subject: [PATCH 8/8] updaet readme --- README.md | 50 +++++++++++++++++++++++++++++++++++++++++++++----- docs/index.md | 50 +++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 90 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index b2f3f54..aa09e3c 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**: As much type hints as possible - no need to remember yet another abstract function name +- **Typing Helpers**: Proxy helpers for IDE autocomplete on SQLAlchemy molecule and reaction columns - **Easy Integration**: Drop-in replacement for standard SQLAlchemy types ## 📦 Installation @@ -58,7 +58,7 @@ pip install . ### Prerequisites -- Python 3.10+ +- Python 3.10-3.14 - SQLAlchemy 2.0+ - rdkit 2024.3.1+ - Running PostgreSQL with chemical cartridge (Bingo or RDKit) (see [`docker-compose.yaml`](https://github.com/asiomchen/molalchemy/blob/main/docker-compose.yaml) for a ready-to-use setup) @@ -93,17 +93,20 @@ molalchemy/ ├── src/molalchemy/ │ ├── types.py # Base type definitions │ ├── exceptions.py # Custom exception hierarchy -│ ├── helpers.py # Common utilities +│ ├── helpers.py # Typed proxy helper functions │ ├── 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 @@ -119,8 +122,12 @@ To learn how to use molalchemy, check out the tutorials in the [documentation](h - [Quick Start - RDKit ORM](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM/) - Molecules, substructure search, fingerprints, similarity - [Quick Start - RDKit Core](https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core/) - Same features using SQLAlchemy Core API - [Quick Start - Bingo ORM](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM/) - Bingo cartridge with ORM +- [Migrations with Alembic](https://molalchemy.readthedocs.io/en/latest/tutorials/03_alembic_migrations/) - Autogenerate-friendly MolAlchemy migrations - [Similarity Thresholds](https://molalchemy.readthedocs.io/en/latest/tutorials/04_Similarity_Threshold_Settings/) - Managing RDKit similarity thresholds -- [Chemical Reactions](https://molalchemy.readthedocs.io/en/latest/tutorials/05_Reactions_rdkit_ORM/) - Storing and querying reactions +- [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 ## 🏗️ Supported Cartridges @@ -143,6 +150,10 @@ from molalchemy.bingo.functions import ( # Individual function imports available, see documentation # for complete list of chemical analysis functions ) +from molalchemy.helpers import ( + bingo_col, # Typed molecule-column helper for IDE autocomplete + bingo_rxn_col, # Typed reaction-column helper for IDE autocomplete +) ``` ### RDKit Cartridge @@ -168,6 +179,10 @@ from molalchemy.rdkit.functions import ( # Individual function imports available, see documentation # for complete list of 150+ RDKit functions ) +from molalchemy.helpers import ( + rdkit_col, # Typed molecule-column helper for IDE autocomplete + rdkit_rxn_col, # Typed reaction-column helper for IDE autocomplete +) ``` ## 🎯 Advanced Features @@ -182,7 +197,7 @@ class Molecule(Base): __tablename__ = 'molecules' id: Mapped[int] = mapped_column(Integer, primary_key=True) - structure: Mapped[str] = mapped_column(BingoMol) + structure: Mapped[str] = mapped_column(BingoMol()) name: Mapped[str] = mapped_column(String(100)) # Add chemical index for faster searching @@ -191,6 +206,31 @@ class Molecule(Base): ) ``` +### Typed Proxy 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 +can see cartridge-specific comparator methods. + +```python +from sqlalchemy import select + +from molalchemy.helpers import bingo_col, rdkit_col + +# Bingo exact/substructure search with autocomplete-friendly column typing +bingo_stmt = select(Molecule).where( + bingo_col(Molecule.structure).has_substructure("c1ccccc1") +) + +# RDKit exact search with autocomplete-friendly column typing +rdkit_stmt = select(MoleculeWithFormats).where( + rdkit_col(MoleculeWithFormats.structure_smiles).equals("CCO") +) +``` + +Use the matching helper for the cartridge and data kind: +`bingo_col`, `bingo_rxn_col`, `rdkit_col`, or `rdkit_rxn_col`. + ### Configurable Return Types ```python diff --git a/docs/index.md b/docs/index.md index b2f3f54..aa09e3c 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**: As much type hints as possible - no need to remember yet another abstract function name +- **Typing Helpers**: Proxy helpers for IDE autocomplete on SQLAlchemy molecule and reaction columns - **Easy Integration**: Drop-in replacement for standard SQLAlchemy types ## 📦 Installation @@ -58,7 +58,7 @@ pip install . ### Prerequisites -- Python 3.10+ +- Python 3.10-3.14 - SQLAlchemy 2.0+ - rdkit 2024.3.1+ - Running PostgreSQL with chemical cartridge (Bingo or RDKit) (see [`docker-compose.yaml`](https://github.com/asiomchen/molalchemy/blob/main/docker-compose.yaml) for a ready-to-use setup) @@ -93,17 +93,20 @@ molalchemy/ ├── src/molalchemy/ │ ├── types.py # Base type definitions │ ├── exceptions.py # Custom exception hierarchy -│ ├── helpers.py # Common utilities +│ ├── helpers.py # Typed proxy helper functions │ ├── 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 @@ -119,8 +122,12 @@ To learn how to use molalchemy, check out the tutorials in the [documentation](h - [Quick Start - RDKit ORM](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM/) - Molecules, substructure search, fingerprints, similarity - [Quick Start - RDKit Core](https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core/) - Same features using SQLAlchemy Core API - [Quick Start - Bingo ORM](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM/) - Bingo cartridge with ORM +- [Migrations with Alembic](https://molalchemy.readthedocs.io/en/latest/tutorials/03_alembic_migrations/) - Autogenerate-friendly MolAlchemy migrations - [Similarity Thresholds](https://molalchemy.readthedocs.io/en/latest/tutorials/04_Similarity_Threshold_Settings/) - Managing RDKit similarity thresholds -- [Chemical Reactions](https://molalchemy.readthedocs.io/en/latest/tutorials/05_Reactions_rdkit_ORM/) - Storing and querying reactions +- [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 ## 🏗️ Supported Cartridges @@ -143,6 +150,10 @@ from molalchemy.bingo.functions import ( # Individual function imports available, see documentation # for complete list of chemical analysis functions ) +from molalchemy.helpers import ( + bingo_col, # Typed molecule-column helper for IDE autocomplete + bingo_rxn_col, # Typed reaction-column helper for IDE autocomplete +) ``` ### RDKit Cartridge @@ -168,6 +179,10 @@ from molalchemy.rdkit.functions import ( # Individual function imports available, see documentation # for complete list of 150+ RDKit functions ) +from molalchemy.helpers import ( + rdkit_col, # Typed molecule-column helper for IDE autocomplete + rdkit_rxn_col, # Typed reaction-column helper for IDE autocomplete +) ``` ## 🎯 Advanced Features @@ -182,7 +197,7 @@ class Molecule(Base): __tablename__ = 'molecules' id: Mapped[int] = mapped_column(Integer, primary_key=True) - structure: Mapped[str] = mapped_column(BingoMol) + structure: Mapped[str] = mapped_column(BingoMol()) name: Mapped[str] = mapped_column(String(100)) # Add chemical index for faster searching @@ -191,6 +206,31 @@ class Molecule(Base): ) ``` +### Typed Proxy 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 +can see cartridge-specific comparator methods. + +```python +from sqlalchemy import select + +from molalchemy.helpers import bingo_col, rdkit_col + +# Bingo exact/substructure search with autocomplete-friendly column typing +bingo_stmt = select(Molecule).where( + bingo_col(Molecule.structure).has_substructure("c1ccccc1") +) + +# RDKit exact search with autocomplete-friendly column typing +rdkit_stmt = select(MoleculeWithFormats).where( + rdkit_col(MoleculeWithFormats.structure_smiles).equals("CCO") +) +``` + +Use the matching helper for the cartridge and data kind: +`bingo_col`, `bingo_rxn_col`, `rdkit_col`, or `rdkit_rxn_col`. + ### Configurable Return Types ```python