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
50 changes: 45 additions & 5 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**: 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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
64 changes: 62 additions & 2 deletions dev_scripts/validate_bingo_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,16 @@ 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(
"molalchemy_bingo_reaction_helper_validation",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String, nullable=False),
Column("reaction_data", BingoBinaryReaction(), nullable=False),
Column("reaction_data", BingoBinaryReaction()),
Column("query_reaction", String, nullable=False),
)

with engine.begin() as conn:
Expand All @@ -79,6 +80,12 @@ def main() -> None:
"id": 2,
"name": "ethanol",
"structure": "CCO",
"query_structure": "OCC",
},
{
"id": 3,
"name": "unknown",
"structure": None,
"query_structure": "CCO",
},
],
Expand All @@ -90,6 +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",
},
],
)
Expand Down Expand Up @@ -144,6 +158,24 @@ 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))
.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,
Expand All @@ -170,6 +202,18 @@ 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()))

with engine.connect() as conn:
Expand All @@ -181,6 +225,12 @@ 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()

print()
Expand All @@ -192,6 +242,12 @@ 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)}")

assert substructure_rows == ["benzene"]
Expand All @@ -211,6 +267,10 @@ 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
assert reaction_function_row["reaction_smiles"]
assert reaction_function_row["rxnfile_len"] > 100
Expand Down
50 changes: 49 additions & 1 deletion dev_scripts/validate_rdkit_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -119,15 +151,25 @@ 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()))
print(exact_stmt.compile(dialect=postgresql.dialect()))
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()
Expand All @@ -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}")
Expand All @@ -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"]
Expand All @@ -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__":
Expand Down
Loading
Loading