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: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ molalchemy provides seamless integration between python and chemical databases,

**This project was originally supposed to be a part of RDKit UGM 2025 hackathon, but COVID had other plans for me. Currently it is in alpha stage as a proof of concept. Contributions are welcome!**

**To give it a hackathon vibe, I build this PoC in couple hours, so expect some rough edges and missing features.**

## 🚀 Features

- **Chemical Data Types**: Custom SQLAlchemy types for molecules, reactions and fingerprints
Expand Down
48 changes: 24 additions & 24 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,45 +14,45 @@ molalchemy aims to be the **definitive Python library** for chemical database op
## 📊 Current Status

- **Bingo PostgreSQL Integration**
- [x] **Chemical indices** (`BingoMolIndex`, etc.)
- [x] **Data types** (`BingoMol`, `BingoBinaryMol`, `BingoReaction`, `BingoBinaryReaction`)
- [x] **Functions** : all function autogenerated from extracted metadata
- [X] **Migration**: Alembic support for schema changes
- [ ] **Full functions annotations and type hints**
- ✅ **Chemical indices** (`BingoMolIndex`, etc.)
- ✅ **Data types** (`BingoMol`, `BingoBinaryMol`, `BingoReaction`, `BingoBinaryReaction`)
- ✅ **Functions** : all function autogenerated from extracted metadata
- ✅ **Migration**: Alembic support for schema changes
- ⬜ **Full functions annotations and type hints**


- **RDKit PostgreSQL Integration**
- [x] **Core data types** (`RdkitMol`, fingerprint types)
- [x] **Chemical indices** (`RDKitMolIndex`, etc.)
- [x] **Functions**: most common functions autogenerated from extracted metadata
- [X] **Migration**: Alembic support for schema changes
- [ ] **Full functions annotations and type hints**
- ✅ **Core data types** (`RdkitMol`, fingerprint types)
- ✅ **Chemical indices** (`RDKitMolIndex`, etc.)
- ✅ **Functions**: most common functions autogenerated from extracted metadata
- ✅ **Migration**: Alembic support for schema changes
- ⬜ **Full functions annotations and type hints**


- **Tutorials and Examples**
- [x] Basic usage examples for Bingo and RDKit
- [ ] FastAPI/SQLModel integration examples
- [ ] Advanced tutorials covering complex queries and optimizations
- [ ] Jupyter notebooks demonstrating real-world use cases
- ✅ Basic usage examples for Bingo and RDKit
- ⬜ FastAPI/SQLModel integration examples
- ⬜ Advanced tutorials covering complex queries and optimizations
- ⬜ Jupyter notebooks demonstrating real-world use cases


- **Infrastructure**
- [x] **Modern development setup** (uv, ruff, pytest, pre-commit)
- [x] **CI/CD pipeline setup**
- [x] **Documentation framework** (MkDocs + mkdocstrings)
- [ ] **Docker images** for Bingo and RDKit
- ✅ **Modern development setup** (uv, ruff, pytest, pre-commit)
- ✅ **CI/CD pipeline setup**
- ✅ **Documentation framework** (MkDocs + mkdocstrings)
- ✅ **Docker images** for Bingo and RDKit





### Future Plans
- [ ] ChemAxon cartridge integration (closed source, requires license)
- [ ] NextMove Author integration (closed source, requires license)
- [ ] Multi-dialect support for Bingo (e.g MySQL, Oracle)
- [ ] SQLite RDKit support (via [chemicalite](https://github.com/rvianello/chemicalite), including custom builds or custom event listeners)
- [ ] Performance benchmarking
- [ ] Advanced chemical operations
- ⬜ ChemAxon cartridge integration (closed source, requires license)
- ⬜ NextMove Author integration (closed source, requires license)
- ⬜ Multi-dialect support for Bingo (e.g MySQL, Oracle)
- ⬜ SQLite RDKit support (via [chemicalite](https://github.com/rvianello/chemicalite), including custom builds or custom event listeners)
- ⬜ Performance benchmarking
- ⬜ Advanced chemical operations

---

Expand Down
7 changes: 5 additions & 2 deletions data/rdkit/general_extra.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def mol_has_substructure(
mol_column : ColumnElement[molalchemy.rdkit.types.RdkitMol]
The database column containing the molecular structure to search.
query : str
The query substructure as a string (SMILES, SMARTS, or other format).
The query substructure as a string (SMILES, or SMARTS)

Returns
-------
Expand All @@ -23,8 +23,11 @@ def mol_has_substructure(

Examples
--------
>>> from sqlalchemy import select
>>> from sqlalchemy import select, cast
>>> from molalchemy.rdkit.types import RdkitQMol
>>> query = select(Molecule).where(has_substructure(Molecule.structure, "C=O"))
>>> # Search for molecules containing a aromatic carbon as SMARTS
>>> query = select(Molecule).where(has_substructure(Molecule.structure, cast("[cH]", RdkitQMol)))
"""
return mol_column.op("@>")(query)

Expand Down
31 changes: 22 additions & 9 deletions data/rdkit/general_header.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,30 @@ This file defines public RDKit PostgreSQL function wrappers for use with SQLAlch
"""


from sqlalchemy import BinaryExpression, Function
from typing import Any

from sqlalchemy import BinaryExpression, Function, String, type_coerce
from sqlalchemy import types as sqltypes
from sqlalchemy.sql import cast, func
from sqlalchemy.sql.elements import ColumnElement
from sqlalchemy.sql.expression import Cast
from sqlalchemy.sql.functions import GenericFunction

from molalchemy.rdkit.types import RdkitBitFingerprint, RdkitMol, RdkitSparseFingerprint, RdkitQMol, RdkitXQMol, RdkitReaction
from molalchemy.rdkit.types import (
RdkitBitFingerprint,
RdkitMol,
RdkitQMol,
RdkitReaction,
RdkitSparseFingerprint,
RdkitXQMol,
)
from molalchemy.types import CString
from ._types import AnyRdkitFingerprintLike, AnyRdkitMolLike, AnyRdkitQMolLike, AnyRdkitSparseFingerprintLike, AnyRdkitBitFingerprintLike, AnyRdkitReactionLike, AnyRdkitXQMolLike



from sqlalchemy.sql.functions import GenericFunction
from sqlalchemy import types as sqltypes
from sqlalchemy.sql.expression import Cast
from typing import Any
from ._types import (
AnyRdkitBitFingerprintLike,
AnyRdkitFingerprintLike,
AnyRdkitMolLike,
AnyRdkitQMolLike,
AnyRdkitReactionLike,
AnyRdkitSparseFingerprintLike,
AnyRdkitXQMolLike)
6 changes: 3 additions & 3 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@ services:
# tmpfs:
# size: 134217728 # 128*2^20 bytes = 128Mb
environment:
POSTGRES_PASSWORD: example
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
# volumes:
# - db_data:/var/lib/postgresql/data
rdkit:
image: antonsiomchen/cheminfo-db:postgres18.3-rdkit2025.09.6
image: antonsiomchen/cheminfo-db:postgres18-rdkit2025.09.6
restart: always
ports:
- 5432:5432
environment:
POSTGRES_USER: postgres
POSTGRES_DB: postgres
POSTGRES_PASSWORD: example
POSTGRES_PASSWORD: postgres



Expand Down
2 changes: 0 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ molalchemy provides seamless integration between python and chemical databases,

**This project was originally supposed to be a part of RDKit UGM 2025 hackathon, but COVID had other plans for me. Currently it is in alpha stage as a proof of concept. Contributions are welcome!**

**To give it a hackathon vibe, I build this PoC in couple hours, so expect some rough edges and missing features.**

## 🚀 Features

- **Chemical Data Types**: Custom SQLAlchemy types for molecules, reactions and fingerprints
Expand Down
107 changes: 86 additions & 21 deletions docs/tutorials/05_Reactions_rdkit_ORM.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
"[('0.77.0', '2025.09.4')]\n"
"[('0.77.0', '2025.09.6')]\n"
]
}
],
Expand Down Expand Up @@ -250,38 +250,39 @@
"source": [
"### Input Validation\n",
"\n",
"The `RdkitReaction` type validates input before sending it to the database. Invalid reaction SMARTS strings and unsupported types raise a `ValueError`."
"The `RdkitReaction` type validates input before sending it to the database. Invalid reaction SMARTS strings and unsupported types raise a `InvalidReactionError`."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "4f4c4102",
"metadata": {},
"outputs": [],
"source": [
"session.rollback()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "cell-11",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error adding invalid reaction: (builtins.ValueError) Invalid reaction SMILES/SMARTS string: 'not_a_reaction'\n",
"Error adding invalid reaction: (molalchemy.exceptions.InvalidReactionError) Invalid reaction SMARTS string: 'not_a_>>reaction'\n",
"[SQL: INSERT INTO reactions (name, rxn_class, rxn) VALUES (%(name)s::VARCHAR, %(rxn_class)s::VARCHAR, reaction_from_smarts(%(rxn)s)) RETURNING reactions.id]\n",
"[parameters: [{'rxn_class': 'Invalid', 'rxn': 'not_a_reaction', 'name': 'Bad'}]]\n"
"[parameters: [{'rxn_class': 'Invalid>>BAD', 'name': 'Bad', 'rxn': 'not_a_>>reaction'}]]\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"[13:23:03] SMARTS Parse Error: syntax error while parsing: not_a_\n",
"[13:23:03] SMARTS Parse Error: check for mistakes around position 3:\n",
"[13:23:03] not_a_\n",
"[13:23:03] ~~^\n",
"[13:23:03] SMARTS Parse Error: Failed parsing SMARTS 'not_a_' for input: 'not_a_'\n"
]
}
],
"source": [
"try:\n",
" bad_rxn = Reaction(name=\"Bad\", rxn_class=\"Invalid\", rxn=\"not_a_reaction\")\n",
" bad_rxn = Reaction(name=\"Bad\", rxn_class=\"Invalid>>BAD\", rxn=\"not_a_>>reaction\")\n",
" session.add(bad_rxn)\n",
" session.commit()\n",
"except Exception as e:\n",
Expand All @@ -303,7 +304,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 11,
"id": "cell-13",
"metadata": {},
"outputs": [
Expand All @@ -314,7 +315,7 @@
" (Reaction(id=2, name='Fischer esterification', rxn_class='Condensation', rxn='O=[C:1][OH].[OH:2]>>O=[C:1][O:2]'),)]"
]
},
"execution_count": 13,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -337,7 +338,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 16,
"id": "cell-15",
"metadata": {},
"outputs": [
Expand All @@ -348,7 +349,7 @@
" (Reaction(id=4, name='Reductive amination', rxn_class='Reduction', rxn='O=[CH2:1].[NH3:2]>>[C:1][N:2]'),)]"
]
},
"execution_count": 14,
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -359,6 +360,16 @@
").all()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "190f18ac",
"metadata": {},
"outputs": [],
"source": [
"session.rollback()"
]
},
{
"cell_type": "markdown",
"id": "cell-16",
Expand All @@ -369,7 +380,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 23,
"id": "cell-17",
"metadata": {},
"outputs": [
Expand All @@ -380,7 +391,7 @@
" (Reaction(id=6, name='Acylation', rxn_class='Substitution', rxn='O=[C:2]Cl.[OH][C:1]>>O=[C:2]O[C:1]'),)]"
]
},
"execution_count": 15,
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -391,6 +402,60 @@
").all()"
]
},
{
"cell_type": "markdown",
"id": "f01cf743",
"metadata": {},
"source": [
"As the `rxn_has_smarts` expects a second argument to be a reaction SMARTS, you need to add \">>\" to the end of the SMARTS string if searching for a product substructure and \">>\" to the beginning if searching for a reactant substructure. For example, to search for reactions that have a chlorine atom in the reactants, you would use `\"[Cl]>>\"` as the SMARTS pattern."
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "0d7cc4b1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Reaction(id=6, name='Acylation', rxn_class='Substitution', rxn='O=[C:2]Cl.[OH][C:1]>>O=[C:2]O[C:1]'),)]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"session.execute(\n",
" select(Reaction).where(functions.rxn_has_smarts(Reaction.rxn, \"[Cl]>>\"))\n",
").all()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "92b27581",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Reaction(id=6, name='Acylation', rxn_class='Substitution', rxn='O=[C:2]Cl.[OH][C:1]>>O=[C:2]O[C:1]'),)]"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"session.execute(\n",
" select(Reaction).where(functions.rxn_has_smarts(Reaction.rxn, \"[C]Cl>>\"))\n",
").all()"
]
},
{
"cell_type": "markdown",
"id": "cell-18",
Expand Down
4 changes: 2 additions & 2 deletions src/molalchemy/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ class MolAlchemyError(Exception):
"""Base exception for all molalchemy errors."""


class InvalidMoleculeError(MolAlchemyError):
class InvalidMoleculeError(MolAlchemyError, ValueError):
"""Raised when an invalid molecule representation is encountered."""


class InvalidReactionError(MolAlchemyError):
class InvalidReactionError(MolAlchemyError, ValueError):
"""Raised when an invalid reaction representation is encountered."""
Loading
Loading