diff --git a/README.md b/README.md index b3e0d7b..a83eefc 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/ROADMAP.md b/ROADMAP.md index e5e0d4d..e6d21d6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 --- diff --git a/data/rdkit/general_extra.txt b/data/rdkit/general_extra.txt index 6b94d63..3dec92f 100644 --- a/data/rdkit/general_extra.txt +++ b/data/rdkit/general_extra.txt @@ -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 ------- @@ -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) diff --git a/data/rdkit/general_header.txt b/data/rdkit/general_header.txt index 89fdd2f..c37da49 100644 --- a/data/rdkit/general_header.txt +++ b/data/rdkit/general_header.txt @@ -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) \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index f1484e7..83b5d3e 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -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 diff --git a/docs/index.md b/docs/index.md index b3e0d7b..a83eefc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 diff --git a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb index dd24423..96f973b 100644 --- a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb +++ b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb @@ -55,7 +55,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "[('0.77.0', '2025.09.4')]\n" + "[('0.77.0', '2025.09.6')]\n" ] } ], @@ -250,22 +250,12 @@ "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": [ @@ -273,15 +263,26 @@ "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", @@ -303,7 +304,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 11, "id": "cell-13", "metadata": {}, "outputs": [ @@ -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" } @@ -337,7 +338,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 16, "id": "cell-15", "metadata": {}, "outputs": [ @@ -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" } @@ -359,6 +360,16 @@ ").all()" ] }, + { + "cell_type": "code", + "execution_count": 22, + "id": "190f18ac", + "metadata": {}, + "outputs": [], + "source": [ + "session.rollback()" + ] + }, { "cell_type": "markdown", "id": "cell-16", @@ -369,7 +380,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 23, "id": "cell-17", "metadata": {}, "outputs": [ @@ -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" } @@ -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", diff --git a/src/molalchemy/exceptions.py b/src/molalchemy/exceptions.py index cdf0901..ca70e2a 100644 --- a/src/molalchemy/exceptions.py +++ b/src/molalchemy/exceptions.py @@ -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.""" diff --git a/src/molalchemy/rdkit/functions/general.py b/src/molalchemy/rdkit/functions/general.py index 120c395..dd51390 100644 --- a/src/molalchemy/rdkit/functions/general.py +++ b/src/molalchemy/rdkit/functions/general.py @@ -46,7 +46,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 ------- @@ -55,8 +55,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)