diff --git a/README.md b/README.md index f3e3377..6d37a6b 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,9 @@ molalchemy provides seamless integration between python and chemical databases, - **Chemical Cartridge Integration**: Support for Bingo and RDKit PostgreSQL cartridges - **Substructure Search**: Efficient substructure and similarity searching - **Chemical Indexing**: High-performance chemical structure indexing -- **Alembic Integration**: Automatic handling of extensions and imports in database migrations +- **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 - **Easy Integration**: Drop-in replacement for standard SQLAlchemy types @@ -88,8 +90,9 @@ molalchemy/ │ │ └── functions/ # Bingo database functions │ └── rdkit/ # RDKit PostgreSQL cartridge support │ ├── types.py # RDKit-specific types -│ ├── index.py # RDKit indexing +│ ├── index.py # RDKit indexing │ ├── comparators.py # SQLAlchemy comparators +│ ├── settings.py # Similarity threshold management │ └── functions/ # RDKit database functions ├── tests/ # Test suite ├── docs/ # Documentation @@ -99,7 +102,13 @@ molalchemy/ ## 🔧 Quick Start -To learn how to use molalchemy, check out the [Quick Start - RDKit](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM/) and [Quick Start - Bingo](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM/) tutorials in the documentation. +To learn how to use molalchemy, check out the tutorials in the [documentation](https://molalchemy.readthedocs.io/): + +- [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 +- [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 ## 🏗️ Supported Cartridges @@ -131,13 +140,18 @@ from molalchemy.rdkit.types import ( RdkitMol, # RDKit molecule type with configurable return formats RdkitBitFingerprint, # Binary fingerprints (bfp) RdkitSparseFingerprint,# Sparse fingerprints (sfp) - RdkitReaction, # Chemical reactions + RdkitReaction, # Chemical reactions with input validation RdkitQMol, # Query molecules RdkitXQMol, # Extended query molecules ) from molalchemy.rdkit.index import ( RdkitIndex, # RDKit molecule indexing (GIST index) ) +from molalchemy.rdkit.settings import ( + get_tanimoto_threshold, set_tanimoto_threshold, # Tanimoto threshold management + get_dice_threshold, set_dice_threshold, # Dice threshold management + similarity_threshold, # Context manager for temporary thresholds +) from molalchemy.rdkit.functions import ( # Individual function imports available, see documentation # for complete list of 150+ RDKit functions @@ -182,6 +196,51 @@ class MoleculeWithFormats(Base): structure_bytes: Mapped[bytes] = mapped_column(RdkitMol(return_type="bytes")) ``` +### Similarity Threshold Management + +RDKit PostgreSQL uses GUC variables to control similarity search behavior. MolAlchemy provides helpers to manage these thresholds: + +```python +from molalchemy.rdkit.settings import ( + get_tanimoto_threshold, + set_tanimoto_threshold, + similarity_threshold, +) + +# Get/set thresholds directly +print(get_tanimoto_threshold(session)) # 0.5 (default) +set_tanimoto_threshold(session, 0.3) + +# Use context manager for temporary changes +with similarity_threshold(session, tanimoto=0.1, dice=0.2): + # Thresholds are active inside the block + results = session.execute(query).all() +# Original thresholds are restored automatically +``` + +### Chemical Reactions + +Store and query chemical reactions using `RdkitReaction`: + +```python +from molalchemy.rdkit.types import RdkitReaction +from molalchemy.rdkit.functions import rxn_has_smarts, reaction_numreactants + +class Reaction(Base): + __tablename__ = 'reactions' + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + rxn: Mapped[str] = mapped_column(RdkitReaction()) + +# Insert with validation (invalid SMARTS raises ValueError) +session.add(Reaction(name="Amide formation", rxn="[C:1](=O)[OH].[N:2]>>[C:1](=O)[N:2]")) + +# Reaction substructure search +results = session.execute( + select(Reaction).where(rxn_has_smarts(Reaction.rxn, ">>[C:1][N:2]")) +).all() +``` + ### Using Chemical Functions The chemical functions are available as individual imports from the functions modules. Under the hood they use SQLAlchemy's `func` to call the corresponding database functions, and provide type hints and syntax highlighting in IDEs. diff --git a/docs/context7.json b/docs/context7.json new file mode 100644 index 0000000..3739eed --- /dev/null +++ b/docs/context7.json @@ -0,0 +1,4 @@ +{ + "public_key": "pk_XPkXoR6AoOpfdY22PcCcY", + "url": "https://context7.com/websites/molalchemy_readthedocs_io" +} diff --git a/docs/index.md b/docs/index.md index f3e3377..6d37a6b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -32,7 +32,9 @@ molalchemy provides seamless integration between python and chemical databases, - **Chemical Cartridge Integration**: Support for Bingo and RDKit PostgreSQL cartridges - **Substructure Search**: Efficient substructure and similarity searching - **Chemical Indexing**: High-performance chemical structure indexing -- **Alembic Integration**: Automatic handling of extensions and imports in database migrations +- **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 - **Easy Integration**: Drop-in replacement for standard SQLAlchemy types @@ -88,8 +90,9 @@ molalchemy/ │ │ └── functions/ # Bingo database functions │ └── rdkit/ # RDKit PostgreSQL cartridge support │ ├── types.py # RDKit-specific types -│ ├── index.py # RDKit indexing +│ ├── index.py # RDKit indexing │ ├── comparators.py # SQLAlchemy comparators +│ ├── settings.py # Similarity threshold management │ └── functions/ # RDKit database functions ├── tests/ # Test suite ├── docs/ # Documentation @@ -99,7 +102,13 @@ molalchemy/ ## 🔧 Quick Start -To learn how to use molalchemy, check out the [Quick Start - RDKit](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM/) and [Quick Start - Bingo](https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM/) tutorials in the documentation. +To learn how to use molalchemy, check out the tutorials in the [documentation](https://molalchemy.readthedocs.io/): + +- [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 +- [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 ## 🏗️ Supported Cartridges @@ -131,13 +140,18 @@ from molalchemy.rdkit.types import ( RdkitMol, # RDKit molecule type with configurable return formats RdkitBitFingerprint, # Binary fingerprints (bfp) RdkitSparseFingerprint,# Sparse fingerprints (sfp) - RdkitReaction, # Chemical reactions + RdkitReaction, # Chemical reactions with input validation RdkitQMol, # Query molecules RdkitXQMol, # Extended query molecules ) from molalchemy.rdkit.index import ( RdkitIndex, # RDKit molecule indexing (GIST index) ) +from molalchemy.rdkit.settings import ( + get_tanimoto_threshold, set_tanimoto_threshold, # Tanimoto threshold management + get_dice_threshold, set_dice_threshold, # Dice threshold management + similarity_threshold, # Context manager for temporary thresholds +) from molalchemy.rdkit.functions import ( # Individual function imports available, see documentation # for complete list of 150+ RDKit functions @@ -182,6 +196,51 @@ class MoleculeWithFormats(Base): structure_bytes: Mapped[bytes] = mapped_column(RdkitMol(return_type="bytes")) ``` +### Similarity Threshold Management + +RDKit PostgreSQL uses GUC variables to control similarity search behavior. MolAlchemy provides helpers to manage these thresholds: + +```python +from molalchemy.rdkit.settings import ( + get_tanimoto_threshold, + set_tanimoto_threshold, + similarity_threshold, +) + +# Get/set thresholds directly +print(get_tanimoto_threshold(session)) # 0.5 (default) +set_tanimoto_threshold(session, 0.3) + +# Use context manager for temporary changes +with similarity_threshold(session, tanimoto=0.1, dice=0.2): + # Thresholds are active inside the block + results = session.execute(query).all() +# Original thresholds are restored automatically +``` + +### Chemical Reactions + +Store and query chemical reactions using `RdkitReaction`: + +```python +from molalchemy.rdkit.types import RdkitReaction +from molalchemy.rdkit.functions import rxn_has_smarts, reaction_numreactants + +class Reaction(Base): + __tablename__ = 'reactions' + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + rxn: Mapped[str] = mapped_column(RdkitReaction()) + +# Insert with validation (invalid SMARTS raises ValueError) +session.add(Reaction(name="Amide formation", rxn="[C:1](=O)[OH].[N:2]>>[C:1](=O)[N:2]")) + +# Reaction substructure search +results = session.execute( + select(Reaction).where(rxn_has_smarts(Reaction.rxn, ">>[C:1][N:2]")) +).all() +``` + ### Using Chemical Functions The chemical functions are available as individual imports from the functions modules. Under the hood they use SQLAlchemy's `func` to call the corresponding database functions, and provide type hints and syntax highlighting in IDEs. diff --git a/docs/logo.png b/docs/logo.png deleted file mode 100644 index 34c6202..0000000 Binary files a/docs/logo.png and /dev/null differ diff --git a/docs/tutorials/05_Reactions_rdkit_ORM.ipynb b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb new file mode 100644 index 0000000..cc0f05d --- /dev/null +++ b/docs/tutorials/05_Reactions_rdkit_ORM.ipynb @@ -0,0 +1,636 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cell-0", + "metadata": {}, + "source": [ + "# Working with Chemical Reactions in MolAlchemy RDKit\n", + "\n", + "This tutorial demonstrates how to use MolAlchemy's `RdkitReaction` type to store and query chemical reactions in PostgreSQL using the RDKit cartridge. You'll learn how to:\n", + "\n", + "- Define SQLAlchemy models with chemical reaction data types\n", + "- Store reactions from SMILES/SMARTS strings and `ChemicalReaction` objects\n", + "- Perform reaction substructure searches\n", + "- Use reaction-specific functions (counting reactants, products, agents)\n", + "- Work with different return types (`\"smiles\"`, `\"bytes\"`, `\"mol\"`)\n", + "\n", + "## Prerequisites\n", + "\n", + "Before starting this tutorial, make sure you have:\n", + "- A PostgreSQL database with RDKit extension installed\n", + "- MolAlchemy installed\n", + "- A running PostgreSQL instance (you can use the provided Docker setup)\n", + "\n", + "## Setting Up the Database\n", + "To set up a PostgreSQL database with the RDKit extension, you can use our docker images from [Docker Hub](https://hub.docker.com/repository/docker/antonsiomchen/cheminfo-db), e.g `antonsiomchen/cheminfo-db:postgres18.1-rdkit2025.09.4`\n", + "\n", + "```sh\n", + "docker run -d \\\n", + " --name molalchemy-tutorial-rdkit-reactions \\\n", + " -e POSTGRES_PASSWORD=postgres \\\n", + " -e POSTGRES_DB=postgres \\\n", + " -p 5432:5432 \\\n", + " antonsiomchen/cheminfo-db:postgres18.1-rdkit2025.09.4\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "cell-1", + "metadata": {}, + "source": [ + "## Database Setup and Connection\n", + "\n", + "First, let's establish a connection to PostgreSQL and ensure the RDKit extension is enabled." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "cell-2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('0.77.0', '2025.09.4')]\n" + ] + } + ], + "source": [ + "from sqlalchemy import (\n", + " Integer,\n", + " String,\n", + " engine,\n", + " select,\n", + " text,\n", + ")\n", + "from sqlalchemy.orm import (\n", + " DeclarativeBase,\n", + " Mapped,\n", + " MappedAsDataclass,\n", + " mapped_column,\n", + " sessionmaker,\n", + ")\n", + "\n", + "from molalchemy.rdkit import functions, types\n", + "\n", + "eng = engine.create_engine(\n", + " \"postgresql+psycopg://postgres:postgres@localhost:5432/postgres\"\n", + ")\n", + "SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=eng)\n", + "with SessionLocal() as session:\n", + " session.execute(text(\"CREATE EXTENSION IF NOT EXISTS rdkit\"))\n", + " session.commit()\n", + " print(\n", + " session.execute(\n", + " select(functions.rdkit_version(), functions.rdkit_toolkit_version())\n", + " ).all()\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "cell-3", + "metadata": {}, + "source": [ + "## Defining a Reaction Model\n", + "\n", + "Let's create a SQLAlchemy model to store chemical reactions. The model uses:\n", + "\n", + "- `molalchemy.rdkit.types.RdkitReaction` for storing reaction data\n", + "- Standard SQLAlchemy columns for metadata like name and reaction class\n", + "\n", + "The `RdkitReaction` type maps to the PostgreSQL `reaction` type provided by the RDKit cartridge. It accepts reaction SMILES/SMARTS strings and `ChemicalReaction` objects as input, validating them before sending to the database." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "cell-4", + "metadata": {}, + "outputs": [], + "source": [ + "class Base(MappedAsDataclass, DeclarativeBase):\n", + " pass\n", + "\n", + "\n", + "class Reaction(Base):\n", + " __tablename__ = \"reactions\"\n", + " id: Mapped[int] = mapped_column(\n", + " Integer, primary_key=True, autoincrement=True, init=False\n", + " )\n", + " name: Mapped[str] = mapped_column(String(100), unique=True)\n", + " rxn_class: Mapped[str] = mapped_column(String(100))\n", + " rxn: Mapped[str] = mapped_column(types.RdkitReaction())\n", + "\n", + "\n", + "Reaction.__table__.drop(eng, checkfirst=True)\n", + "Reaction.metadata.create_all(eng, checkfirst=False)" + ] + }, + { + "cell_type": "markdown", + "id": "cell-5", + "metadata": {}, + "source": [ + "## Adding Sample Reaction Data\n", + "\n", + "Let's insert some well-known organic chemistry reactions using reaction SMARTS. Each reaction is stored with:\n", + "\n", + "- **Name**: A descriptive name for the reaction\n", + "- **Reaction class**: The category of the reaction\n", + "- **Reaction SMARTS**: The transformation pattern\n", + "\n", + "Our dataset includes:\n", + "- **Amide bond formation**: Carboxylic acid + amine condensation\n", + "- **Fischer esterification**: Carboxylic acid + alcohol condensation\n", + "- **Suzuki coupling**: Aryl halide + boronic acid cross-coupling\n", + "- **Reductive amination**: Aldehyde/ketone + amine reduction\n", + "- **Williamson ether synthesis**: Alkoxide + alkyl halide substitution" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "cell-6", + "metadata": {}, + "outputs": [], + "source": [ + "data = [\n", + " {\n", + " \"name\": \"Amide bond formation\",\n", + " \"rxn_class\": \"Condensation\",\n", + " \"rxn\": \"[C:1](=O)[OH].[N:2]>>[C:1](=O)[N:2]\",\n", + " },\n", + " {\n", + " \"name\": \"Fischer esterification\",\n", + " \"rxn_class\": \"Condensation\",\n", + " \"rxn\": \"[C:1](=O)[OH].[OH:2]>>[C:1](=O)[O:2]\",\n", + " },\n", + " {\n", + " \"name\": \"Suzuki coupling\",\n", + " \"rxn_class\": \"Cross-coupling\",\n", + " \"rxn\": \"[c:1][Br].[c:2][B](O)O>>[c:1][c:2]\",\n", + " },\n", + " {\n", + " \"name\": \"Reductive amination\",\n", + " \"rxn_class\": \"Reduction\",\n", + " \"rxn\": \"[C:1]=[O].[N:2]>>[C:1][N:2]\",\n", + " },\n", + " {\n", + " \"name\": \"Williamson ether synthesis\",\n", + " \"rxn_class\": \"Substitution\",\n", + " \"rxn\": \"[O-:1].[C:2][Br]>>[O:1][C:2]\",\n", + " },\n", + "]\n", + "\n", + "session = SessionLocal()\n", + "session.add_all([Reaction(**d) for d in data])\n", + "session.commit()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-7", + "metadata": {}, + "source": [ + "### Inserting from ChemicalReaction Objects\n", + "\n", + "You can also insert reactions using RDKit `ChemicalReaction` objects directly. The `RdkitReaction` type handles the conversion automatically." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "cell-8", + "metadata": {}, + "outputs": [], + "source": [ + "from rdkit.Chem import AllChem\n", + "\n", + "rxn_obj = AllChem.ReactionFromSmarts(\"[C:1][OH].[C:2](=O)[Cl]>>[C:1][O][C:2]=O\")\n", + "acylation = Reaction(name=\"Acylation\", rxn_class=\"Substitution\", rxn=rxn_obj)\n", + "session.add(acylation)\n", + "session.commit()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "cell-9", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(Reaction(id=1, name='Amide bond formation', rxn_class='Condensation', rxn='O=[C:1][OH].[NH3:2]>>O=[C:1][N:2]'),),\n", + " (Reaction(id=2, name='Fischer esterification', rxn_class='Condensation', rxn='O=[C:1][OH].[OH:2]>>O=[C:1][O:2]'),),\n", + " (Reaction(id=3, name='Suzuki coupling', rxn_class='Cross-coupling', rxn='Br[c:1].OB(O)[c:2]>>[c:1][c:2]'),),\n", + " (Reaction(id=4, name='Reductive amination', rxn_class='Reduction', rxn='O=[CH2:1].[NH3:2]>>[C:1][N:2]'),),\n", + " (Reaction(id=5, name='Williamson ether synthesis', rxn_class='Substitution', rxn='Br[C:2].[OH-:1]>>[O:1][C:2]'),),\n", + " (Reaction(id=6, name='Acylation', rxn_class='Substitution', rxn='O=[C:2]Cl.[OH][C:1]>>O=[C:2]O[C:1]'),)]" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "session.execute(select(Reaction)).all()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-10", + "metadata": {}, + "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`." + ] + }, + { + "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", + "[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" + ] + } + ], + "source": [ + "try:\n", + " bad_rxn = Reaction(name=\"Bad\", rxn_class=\"Invalid\", rxn=\"not_a_reaction\")\n", + " session.add(bad_rxn)\n", + " session.commit()\n", + "except Exception as e:\n", + " session.rollback()\n", + " print(f\"Error adding invalid reaction: {e}\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-12", + "metadata": {}, + "source": [ + "## Querying Reactions\n", + "\n", + "### Standard Database Queries\n", + "\n", + "You can use regular SQLAlchemy operations to filter reactions by metadata:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "cell-13", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(Reaction(id=1, name='Amide bond formation', rxn_class='Condensation', rxn='O=[C:1][OH].[NH3:2]>>O=[C:1][N:2]'),),\n", + " (Reaction(id=2, name='Fischer esterification', rxn_class='Condensation', rxn='O=[C:1][OH].[OH:2]>>O=[C:1][O:2]'),)]" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "session.execute(select(Reaction).where(Reaction.rxn_class == \"Condensation\")).all()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-14", + "metadata": {}, + "source": [ + "### Reaction Substructure Search\n", + "\n", + "Use `molalchemy.rdkit.functions.rxn_has_smarts` to find reactions that contain a specific transformation pattern. This uses the PostgreSQL `substruct` function under the hood.\n", + "\n", + "Let's search for all reactions that involve forming a bond to nitrogen (`[N]`):" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "cell-15", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(Reaction(id=1, name='Amide bond formation', rxn_class='Condensation', rxn='O=[C:1][OH].[NH3:2]>>O=[C:1][N:2]'),),\n", + " (Reaction(id=4, name='Reductive amination', rxn_class='Reduction', rxn='O=[CH2:1].[NH3:2]>>[C:1][N:2]'),)]" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "session.execute(\n", + " select(Reaction).where(functions.rxn_has_smarts(Reaction.rxn, \">>[C:1][N:2]\"))\n", + ").all()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-16", + "metadata": {}, + "source": [ + "Search for reactions that produce an ester bond (`C(=O)O`):" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "cell-17", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(Reaction(id=2, name='Fischer esterification', rxn_class='Condensation', rxn='O=[C:1][OH].[OH:2]>>O=[C:1][O:2]'),),\n", + " (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, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "session.execute(\n", + " select(Reaction).where(functions.rxn_has_smarts(Reaction.rxn, \">>[C:1](=O)[O:2]\"))\n", + ").all()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-18", + "metadata": {}, + "source": [ + "## Reaction Analysis Functions\n", + "\n", + "MolAlchemy exposes RDKit PostgreSQL functions for analyzing reaction components. You can count the number of reactants, products, and agents in each reaction." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "cell-19", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[('Amide bond formation', 2, 1, 0),\n", + " ('Fischer esterification', 2, 1, 0),\n", + " ('Suzuki coupling', 2, 1, 0),\n", + " ('Reductive amination', 2, 1, 0),\n", + " ('Williamson ether synthesis', 2, 1, 0),\n", + " ('Acylation', 2, 1, 0)]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "session.execute(\n", + " select(\n", + " Reaction.name,\n", + " functions.reaction_numreactants(Reaction.rxn).label(\"reactants\"),\n", + " functions.reaction_numproducts(Reaction.rxn).label(\"products\"),\n", + " functions.reaction_numagents(Reaction.rxn).label(\"agents\"),\n", + " )\n", + ").all()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-20", + "metadata": {}, + "source": [ + "### Converting Reactions to SMILES and SMARTS\n", + "\n", + "Use `reaction_to_smiles` and `reaction_to_smarts` to retrieve reactions in different text formats:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "cell-21", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[('Amide bond formation', 'O=[C:1][OH].[NH3:2]>>O=[C:1][N:2]', '[C:1](=O)[O&H1].[N:2]>>[C:1](=O)[N:2]'),\n", + " ('Fischer esterification', 'O=[C:1][OH].[OH:2]>>O=[C:1][O:2]', '[C:1](=O)[O&H1].[O&H1:2]>>[C:1](=O)[O:2]'),\n", + " ('Suzuki coupling', 'Br[c:1].OB(O)[c:2]>>[c:1][c:2]', '[c:1]Br.[c:2]B(O)O>>[c:1][c:2]')]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "session.execute(\n", + " select(\n", + " Reaction.name,\n", + " functions.reaction_to_smiles(Reaction.rxn).label(\"smiles\"),\n", + " functions.reaction_to_smarts(Reaction.rxn).label(\"smarts\"),\n", + " ).limit(3)\n", + ").all()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-22", + "metadata": {}, + "source": [ + "## Working with Different Return Types\n", + "\n", + "By default, `RdkitReaction` returns reactions as SMILES strings. You can change this behavior with the `return_type` parameter:\n", + "\n", + "- `\"smiles\"` (default): Returns reaction SMILES strings\n", + "- `\"bytes\"`: Returns raw binary data\n", + "- `\"mol\"`: Returns `rdkit.Chem.AllChem.ChemicalReaction` objects\n", + "\n", + "### Returning ChemicalReaction Objects\n", + "\n", + "Set `return_type=\"mol\"` to get `ChemicalReaction` objects back from the database, which you can use directly with RDKit:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "cell-23", + "metadata": {}, + "outputs": [], + "source": [ + "class Base(MappedAsDataclass, DeclarativeBase):\n", + " pass\n", + "\n", + "\n", + "class ReactionMol(Base):\n", + " __tablename__ = \"reactions_mol\"\n", + " id: Mapped[int] = mapped_column(\n", + " Integer, primary_key=True, autoincrement=True, init=False\n", + " )\n", + " name: Mapped[str] = mapped_column(String(100), unique=True)\n", + " rxn: Mapped[bytes] = mapped_column(types.RdkitReaction(return_type=\"mol\"))\n", + "\n", + "\n", + "ReactionMol.__table__.drop(eng, checkfirst=True)\n", + "ReactionMol.__table__.create(eng, checkfirst=True)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "cell-24", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Type: ChemicalReaction\n", + "Num reactants: 2\n", + "Num products: 1\n" + ] + } + ], + "source": [ + "session = SessionLocal()\n", + "session.add(\n", + " ReactionMol(\n", + " name=\"Amide bond formation\",\n", + " rxn=\"[C:1](=O)[OH].[N:2]>>[C:1](=O)[N:2]\",\n", + " )\n", + ")\n", + "session.commit()\n", + "\n", + "result = session.execute(\n", + " select(ReactionMol).where(ReactionMol.name == \"Amide bond formation\")\n", + ").scalar_one()\n", + "\n", + "rxn = result.rxn\n", + "print(f\"Type: {type(rxn).__name__}\")\n", + "print(f\"Num reactants: {rxn.GetNumReactantTemplates()}\")\n", + "print(f\"Num products: {rxn.GetNumProductTemplates()}\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-25", + "metadata": {}, + "source": [ + "### Inspecting the Generated SQL\n", + "\n", + "Let's examine the SQL generated for a reaction substructure search:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "cell-26", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "SELECT reactions.id, reactions.name, reactions.rxn_class, reactions.rxn \n", + "FROM reactions \n", + "WHERE substruct(reactions.rxn, reaction_from_smarts(CAST(%(param_1)s AS cstring)))\n" + ] + } + ], + "source": [ + "query = select(Reaction).where(functions.rxn_has_smarts(Reaction.rxn, \">>[C:1][N:2]\"))\n", + "print(query.compile(eng))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-27", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "This tutorial demonstrated how to work with chemical reactions in MolAlchemy:\n", + "\n", + "1. **Model Definition**: Using `RdkitReaction` type to store reactions in PostgreSQL\n", + "2. **Data Storage**: Inserting reactions from SMARTS strings and `ChemicalReaction` objects\n", + "3. **Input Validation**: Invalid reaction strings are caught before reaching the database\n", + "4. **Substructure Search**: Using `rxn_has_smarts` to find reactions by transformation pattern\n", + "5. **Analysis Functions**: Counting reactants, products, and agents with `reaction_numreactants`, `reaction_numproducts`, `reaction_numagents`\n", + "6. **Format Conversion**: Converting between SMILES and SMARTS with `reaction_to_smiles`, `reaction_to_smarts`\n", + "7. **Return Types**: Retrieving reactions as strings, bytes, or `ChemicalReaction` objects\n", + "\n", + "### Next Steps\n", + "\n", + "- Explore reaction fingerprints with `reaction_difference_fp` and `reaction_structural_bfp`\n", + "- Combine reaction queries with molecule queries for reaction product analysis\n", + "- Use `reaction_to_svg` to generate visual representations of stored reactions\n", + "\n", + "### Additional Resources\n", + "\n", + "- [SQLAlchemy Documentation](https://docs.sqlalchemy.org/)\n", + "- [RDKit Reaction SMARTS Documentation](https://www.rdkit.org/docs/RDKit_Book.html#reaction-smarts)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "molalchemy (3.10.19)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.19" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}