Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: `uv run ty check src`
- [ ] Documentation builds: `uv run mkdocs serve`
- [ ] Changelog updated (if applicable)

Expand Down
15 changes: 14 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -24,7 +34,10 @@ 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

docs-serve:
@$(DOCS_CAIRO_ENV) JUPYTER_PLATFORM_DIRS=1 uv run mkdocs serve

sync-docs:
@cp README.md docs/index.md
Expand Down
47 changes: 36 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -127,7 +126,9 @@ 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
- [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

Expand Down Expand Up @@ -206,16 +207,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(
Expand All @@ -228,8 +229,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

Expand All @@ -248,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)
Expand All @@ -270,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. 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

Store and query chemical reactions using `RdkitReaction`:
Expand Down
4 changes: 4 additions & 0 deletions data/bingo/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
]
Expand Down
2 changes: 1 addition & 1 deletion data/bingo/functions.json
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@
"name": "getsimilarity",
"return_type": {
"description": "SQLAlchemy function",
"type": "float | sqltypes.Float"
"type": "sqltypes.Float"
}
},
"getstructurescount": {
Expand Down
105 changes: 71 additions & 34 deletions data/bingo/general_extra.txt
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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.

Expand All @@ -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.

Expand All @@ -65,50 +65,80 @@ 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(
mol: ColumnElement[AnyBingoMol],
query: TextLike,
bottom: float = 0.0,
top: float = 1.0,
metric: TextLike = "Tanimoto",
) -> BinaryExpression:
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.

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, (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(
rxn: ColumnElement[AnyBingoReaction], query: TextLike, parameters: TextLike = ""
) -> BinaryExpression:
) -> ColumnElement[bool]:
"""
Perform substructure search on a reaction column.

Expand All @@ -123,16 +153,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.

Expand All @@ -147,16 +177,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.

Expand All @@ -171,8 +201,15 @@ 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")


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)
Loading
Loading