### Connect to PostgreSQL and Enable RDKit Extension with SQLAlchemy Core Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core Establishes a connection to a PostgreSQL database using SQLAlchemy and ensures the RDKit extension is enabled. It then queries and prints the RDKit and RDKit toolkit versions. This snippet requires `sqlalchemy` and `molalchemy` to be installed, and a running PostgreSQL instance with the RDKit extension. ```python from sqlalchemy import ( Boolean, Integer, String, engine, select, text, ) from sqlalchemy import Column, Table, MetaData from molalchemy.rdkit import functions, index, types from sqlalchemy.orm import sessionmaker eng = engine.create_engine( "postgresql+psycopg://postgres:example@localhost:5432/postgres" ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=eng) with SessionLocal() as session: session.execute(text("CREATE EXTENSION IF NOT EXISTS rdkit")) session.commit() print( session.execute( select(functions.rdkit_version(), functions.rdkit_toolkit_version()) ).all() ) ``` -------------------------------- ### Run PostgreSQL with Bingo cartridge using Docker Source: https://molalchemy.readthedocs.io/en/latest_q= Starts a PostgreSQL database with the Bingo chemical cartridge enabled using Docker Compose. This provides a ready-to-use setup for working with the Bingo cartridge. ```bash docker-compose up bingo ``` -------------------------------- ### Query Raw Molecule Data (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core Demonstrates how to query data from the 'molecules_fp_raw' table using SQLAlchemy. The example selects the first two records and retrieves all columns, including the raw binary molecule data. ```python from sqlalchemy import select from molalchemy.db import SessionLocal # Assuming 'molecules_fp_raw' is the defined table # with SessionLocal() as session: # result = session.execute(select(molecules_fp_raw).limit(2)).all() # print(result) ``` -------------------------------- ### Install molalchemy from source Source: https://molalchemy.readthedocs.io/en/latest_q= Installs molalchemy directly from its GitHub repository. This is useful for development or when you need the latest unreleased features. It requires Git to be installed. ```bash pip install git+https://github.com/asiomchen/molalchemy.git # or clone the repo and install git clone https://github.com/asiomchen/molalchemy.git cd molalchemy pip install . ``` -------------------------------- ### Installing Dependencies with uv (Bash) Source: https://molalchemy.readthedocs.io/en/latest_q= Shows the command to install project dependencies using the 'uv' package manager. This command should be run after cloning the repository and activating the virtual environment. ```bash uv sync ``` -------------------------------- ### Connect to PostgreSQL and Enable RDKit Extension Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Establishes a connection to a PostgreSQL database using SQLAlchemy and ensures the RDKit extension is enabled. It then prints the RDKit and RDKit toolkit versions. This requires SQLAlchemy and psycopg2. ```python from sqlalchemy import ( Boolean, Integer, String, engine, select, text, ) from sqlalchemy.orm import ( DeclarativeBase, Mapped, MappedAsDataclass, mapped_column, sessionmaker, ) from molalchemy.rdkit import functions, index, types eng = engine.create_engine( "postgresql+psycopg://postgres:example@localhost:5432/postgres" ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=eng) with SessionLocal() as session: session.execute(text("CREATE EXTENSION IF NOT EXISTS rdkit")) session.commit() print( session.execute( select(functions.rdkit_version(), functions.rdkit_toolkit_version()) ).all() ) ``` -------------------------------- ### Start Development Database with Docker Compose Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING_q= Commands to start the Bingo and RDKit development databases using Docker Compose. These commands ensure the databases are running in detached mode (-d) for background operation. ```bash # Bingo database docker-compose up -d bingo # RDKit database docker-compose up -d rdkit ``` -------------------------------- ### Python Type Hinting Example Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING_q= Illustrates the use of type hints in Python function signatures, including optional parameters and return types. This enhances code readability and maintainability, and aids static analysis. ```python from typing import Optional, Union, List from sqlalchemy import ColumnElement from sqlalchemy.sql.functions import Function def chemical_function( column: ColumnElement, query: str, threshold: Optional[float] = None ) -> Function[bool]: """Function with proper type hints.""" pass ``` -------------------------------- ### Python Type Hinting Example Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING Illustrates the use of type hints in Python functions for improved code clarity and maintainability. This includes type annotations for parameters and return values. ```python from typing import Optional, Union, List from sqlalchemy import ColumnElement from sqlalchemy.sql.functions import Function def chemical_function( column: ColumnElement, query: str, threshold: Optional[float] = None ) -> Function[bool]: """Function with proper type hints.""" pass ``` -------------------------------- ### Python Error Handling Example Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING_q= Shows an example of raising a `ValueError` with an informative message in Python. This is crucial for providing clear feedback when invalid input is detected. ```python if not query.strip(): raise ValueError( "Query string cannot be empty. " "Please provide a valid SMILES or SMARTS pattern." ) ``` -------------------------------- ### Install molalchemy using pip Source: https://molalchemy.readthedocs.io/en/latest_q= Installs the molalchemy library using pip, making it available for use in your Python projects. Ensure you have Python 3.10+ and pip installed. ```bash pip install molalchemy ``` -------------------------------- ### Python Function for Substructure Search with NumPy Docstring Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING A Python function demonstrating substructure search using SQLAlchemy. It includes a detailed NumPy-style docstring with parameters, return type, and a practical example. ```python def substructure_search(mol_column: ColumnElement, pattern: str) -> BinaryExpression: """Search for substructures in molecule column. Parameters ---------- mol_column : ColumnElement SQLAlchemy column containing molecular data. pattern : str SMILES or SMARTS pattern to search for. Returns ------- BinaryExpression SQLAlchemy expression for use in WHERE clauses. Examples -------- >>> # Find molecules containing benzene ring >>> session.query(Molecule).filter( ... substructure_search(Molecule.structure, "c1ccccc1") ... ).all() """ ``` -------------------------------- ### Python Function with NumPy Docstring Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING_q= Demonstrates a Python function with a NumPy-style docstring, including parameter descriptions, return value explanations, examples, and notes. This adheres to the API documentation requirements for public functions. ```python def example_function(param: str) -> str: """Short description of the function. Longer description if needed, explaining the purpose, behavior, and any important details. Parameters ---------- param : str Description of the parameter. Returns ------- str Description of the return value. Examples -------- >>> example_function("input") 'output' Notes ----- Any important notes about usage, limitations, or implementation details. """ return f"processed_{param}" ``` -------------------------------- ### Define Enhanced Model with Computed Fingerprints Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core This Python code defines a SQLAlchemy table `molecules_fp` that includes a computed column for storing Morgan fingerprints. The `sqlalchemy.Computed` construct automatically calculates fingerprints using `molalchemy.rdkit.functions.morgan_fp` upon insertion. It also sets up GiST indexes for efficient fingerprint operations. Requires `sqlalchemy`, `molalchemy.rdkit.types`, `molalchemy.rdkit.functions`, and `sqlalchemy.index`. ```python from sqlalchemy import Computed metadata = MetaData() molecules_fp = Table( "molecules_fp", metadata, Column("id", Integer, primary_key=True, autoincrement=True), Column("name", String(100), unique=True), Column("mol", types.RdkitMol), Column("is_nsaid", Boolean, default=False), index.RdkitIndex("mol_gist_idx_2", "mol"), ) molecules_fp.append_column( Column( "fp", types.RdkitSparseFingerprint, Computed(functions.morgan_fp(molecules_fp.c.mol, 2), persisted=True), ) ) molecules_fp.append_constraint(index.RdkitIndex("fp_idx_2", "fp")) molecules_fp.drop(eng, checkfirst=True) metadata.create_all(eng) ``` -------------------------------- ### Query Raw Molecule Data from Database (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Retrieves a limited number of entries from the RawMoleculeFP table using SQLAlchemy. This demonstrates basic querying capabilities for raw molecular data. ```python session.execute(select(RawMoleculeFP).limit(2)).all() ``` -------------------------------- ### Insert Raw Molecule Data into Database (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Inserts raw molecular data into the RawMoleculeFP model using SQLAlchemy. It retrieves data in its original binary format and commits it to the database. ```python session = SessionLocal() session.add_all([RawMoleculeFP(**d) for d in data]) session.commit() ``` -------------------------------- ### Connect to Development Databases with Docker Compose Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING_q= Instructions for connecting to the Bingo and RDKit databases using Docker Compose's exec command. This allows interactive SQL sessions with the PostgreSQL instances. ```bash # Connect to Bingo docker-compose exec bingo psql -U postgres # Connect to RDKit docker-compose exec rdkit psql -U postgres ``` -------------------------------- ### Connect to PostgreSQL with MolAlchemy and SQLAlchemy Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM Establishes a connection to a PostgreSQL database using SQLAlchemy's create_engine and sessionmaker, and verifies the Bingo extension version. It requires SQLAlchemy and MolAlchemy libraries. ```python from sqlalchemy import ( Boolean, Integer, String, engine, select, text, ) from sqlalchemy.orm import ( DeclarativeBase, Mapped, MappedAsDataclass, mapped_column, sessionmaker, ) from molalchemy.bingo import functions, index, types eng = engine.create_engine( "postgresql+psycopg://postgres:example@localhost:5432/postgres" ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=eng) with SessionLocal() as session: print(session.execute(select(functions.getversion())).all()) ``` -------------------------------- ### Retrieve Molecule by Name Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM This Python snippet shows how to retrieve a specific molecule from the database by its name using SQLAlchemy's select and scalar_one methods. The retrieved Molecule object is then printed to the console. ```python retrieved = session.execute( select(Molecule).where(Molecule.name == "Levodopa") ).scalar_one() print(retrieved) ``` -------------------------------- ### Activating Virtual Environment (Bash) Source: https://molalchemy.readthedocs.io/en/latest_q= Demonstrates how to activate the Python virtual environment created by 'uv'. This command is necessary to ensure that project dependencies are correctly loaded. ```bash source .venv/bin/activate ``` -------------------------------- ### Query Data from Enhanced Model Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM_q= Retrieves a single record from the 'MoleculeFP' table using SQLAlchemy's `select` and `limit` functions. This query will return the molecule data along with its automatically generated fingerprint. ```python from sqlalchemy import select from sqlalchemy.orm import Session # Assuming 'session' is your SQLAlchemy session instance result = session.execute(select(MoleculeFP).limit(1)).first() if result: molecule_data = result[0] print(molecule_data) ``` -------------------------------- ### xqmol_in Source: https://molalchemy.readthedocs.io/en/latest/api/rdkit/functions_q= Constructs a query molecule from an input string. This is an internal function. ```APIDOC ## `xqmol_in(arg_1, **kwargs)` ### Description Internal function: Constructs a query molecule from an input string. ### Method Internal Function (details not specified, likely part of a class) ### Endpoint N/A (Internal function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "arg_1": "", "kwargs": {} } ``` ### Response #### Success Response (200) - **Return Value** (Function[RdkitXQMol]) - A query molecule (RdkitXQMol) object. #### Response Example ```json { "result": "" } ``` ``` -------------------------------- ### Inserting Data with Automatic Fingerprint Generation Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core_q= Demonstrates inserting data into a table with a computed fingerprint column. The fingerprints are automatically generated and stored upon commit. Requires a database session and the table definition. ```python from molalchemy.db.session import SessionLocal from sqlalchemy import select # Assuming 'molecules_fp' is your defined table and 'data' contains the records # with SessionLocal() as session: # session.execute(molecules_fp.insert(), data) # session.commit() # Example of selecting data after insertion # session.execute(select(molecules_fp).limit(1)).all() ``` -------------------------------- ### Insert Sample Molecular Data into SQLAlchemy Table Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core Inserts a list of pharmaceutical compounds with their names, SMILES strings, and NSAID classifications into the 'molecules' table. This uses SQLAlchemy's session and insert functionality. ```python data = [ {"name": "Aspirin", "mol": "CC(=O)OC1=CC=CC=C1C(=O)O", "is_nsaid": True}, { "name": "Loratadine", "mol": "O=C(OCC)N4CC/C(=C2/c1ccc(Cl)cc1CCc3cccnc23)CC4", "is_nsaid": False, }, { "name": "Rofecoxib", "mol": "O=C2OC\C(=C2\c1ccccc1)c3ccc(cc3)S(C)(=O)=O", "is_nsaid": True, }, {"name": "Captopril", "mol": "C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O", "is_nsaid": False}, { "name": "Talidomide", "mol": "O=C1c2ccccc2C(=O)N1C3CCC(=O)NC3=O", "is_nsaid": False, }, ] with SessionLocal() as session: session.execute(molecule_table.insert(), data) session.commit() ``` -------------------------------- ### Alembic Database Migrations with MolAlchemy Helpers (Python) Source: https://molalchemy.readthedocs.io/en/latest_q= Illustrates how to integrate MolAlchemy with Alembic for database migrations. It shows the usage of `alembic_helpers.render_item` to ensure proper type rendering for MolAlchemy types within migration scripts. ```python # ... from molalchemy import alembic_helpers # ... def run_migrations_offline(): # ... context.configure( # ... render_item=alembic_helpers.render_item, ) # ... def run_migrations_online(): # ... context.configure( # ... render_item=alembic_helpers.render_item, ) # ... ``` -------------------------------- ### Cloning the MolAlchemy Repository (Bash) Source: https://molalchemy.readthedocs.io/en/latest_q= Provides the command to clone the MolAlchemy project repository from GitHub using Git. This is the first step in setting up the development environment. ```bash git clone https://github.com/asiomchen/molalchemy.git cd molalchemy ``` -------------------------------- ### Add Sample Molecular Data Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM_q= Inserts sample pharmaceutical compounds with their SMILES representations, names, and NSAID classifications into the database. It initializes a database session, creates Molecule objects from the data, and commits the changes. ```python data = [ {"name": "Aspirin", "mol": "CC(=O)OC1=CC=CC=C1C(=O)O", "is_nsaid": True}, { "name": "Loratadine", "mol": "O=C(OCC)N4CC/C(=C2/c1ccc(Cl)cc1CCc3cccnc23)CC4", "is_nsaid": False, }, { "name": "Rofecoxib", "mol": "O=C2OC\\C(=C2\\c1ccccc1)c3ccc(cc3)S(C)(=O)=O", "is_nsaid": True, }, {"name": "Captopril", "mol": "C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O", "is_nsaid": False}, { "name": "Talidomide", "mol": "O=C1c2ccccc2C(=O)N1C3CCC(=O)NC3=O", "is_nsaid": False, }, ] session = SessionLocal() mols = [Molecule(**d) for d in data] session.add_all(mols) session.commit() ``` -------------------------------- ### Substructure Search for Sulfur Atoms Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM This Python code uses MolAlchemy's `has_substructure` function in a SQLAlchemy query to find molecules containing a sulfur atom ('S'). It returns all matching molecules from the database. ```python session.execute( select(Molecule).where(functions.has_substructure(Molecule.mol, "S")) ).all() ``` -------------------------------- ### Run PostgreSQL with RDKit cartridge using Docker Source: https://molalchemy.readthedocs.io/en/latest_q= Starts a PostgreSQL database with the RDKit chemical cartridge enabled using Docker Compose. This is a convenient way to set up a development or testing environment. ```bash docker-compose up rdkit ``` -------------------------------- ### Reset Development Databases with Docker Compose Source: https://molalchemy.readthedocs.io/en/latest/CONTRIBUTING_q= Commands to reset the development environment by stopping and removing containers and volumes, then restarting them. This is useful for a clean slate. ```bash # Remove containers and volumes docker-compose down -v # Restart containers docker-compose up -d ``` -------------------------------- ### Perform Substructure Search in SQLAlchemy Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core This code snippet demonstrates how to query a database for molecules that contain a specific substructure using SQLAlchemy's `functions.mol_has_substructure`. It iterates through the results and prints them. Assumes `SessionLocal` and `molecule_table` are defined. ```python with SessionLocal() as session: stmt = select(molecule_table).where( functions.mol_has_substructure(molecule_table.c.mol, "S") ) results = session.execute(stmt).all() for row in results: print(row) ``` -------------------------------- ### Insert and Query Converted Molecule Data (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Inserts data into the ConvertedMoleculeFP model and then queries it, demonstrating how RDKit Mol objects are stored and retrieved. The 'mol' attribute directly returns RDKit Mol objects. ```python session = SessionLocal() session.add_all([ConvertedMoleculeFP(**d) for d in data]) session.commit() results = session.execute(select(ConvertedMoleculeFP).limit(2)).all() display(results) display(results[0][0].mol) ``` -------------------------------- ### qmol_send Source: https://molalchemy.readthedocs.io/en/latest/api/rdkit/functions_q= Converts a query molecule into a binary string (bytea). ```APIDOC ## qmol_send(mol, **kwargs) ### Description Returns a binary string (bytea) for a query molecule. ### Method POST ### Endpoint /websites/molalchemy_readthedocs_io/qmol_send ### Parameters #### Path Parameters None #### Query Parameters * **mol** (RdkitQMol) - Required - The query molecule to be converted. * **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "mol": "" } ``` ### Response #### Success Response (200) * **binary_string** (Function[LargeBinary]) - A binary string representation of the query molecule. #### Response Example ```json { "binary_string": "" } ``` ``` -------------------------------- ### Substructure Search for Sulfur Atom Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM This Python code performs a substructure search to find molecules containing a sulfur atom ('S'). It utilizes the 'mol_has_substructure' function provided by the database integration, applied to the 'mol' column. ```python session.execute( select(Molecule).where(functions.mol_has_substructure(Molecule.mol, "S")) ).all() ``` -------------------------------- ### Running Tests with pytest and uv (Bash) Source: https://molalchemy.readthedocs.io/en/latest_q= Provides commands for running tests in the MolAlchemy project using pytest, with options for coverage and running specific test modules. It utilizes 'uv run' to execute pytest within the project's virtual environment. ```bash # Run all tests with coverage make test # Or use uv directly uv run pytest # Run specific test module uv run pytest tests/bingo/ # Run with coverage uv run pytest --cov=src/molalchemy ``` -------------------------------- ### Query Non-NSAID Molecules using SQLAlchemy Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_bingo_ORM This Python code snippet uses SQLAlchemy to query a database for all molecules where the 'is_nsaid' attribute is False. It assumes a 'session' object and a 'Molecule' model are already defined and available. ```python # simple query to get all non-nsaid molecules session.execute(select(Molecule).where(Molecule.is_nsaid == False)).all() ``` -------------------------------- ### Define SQLAlchemy Model for Raw Molecule Data (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM_q= Illustrates the definition of a SQLAlchemy model (`RawMoleculeFP`) using MolAlchemy for storing raw molecule data as bytes. It includes RDKit-specific indexing and computed fingerprint generation. ```python from sqlalchemy.orm import Mapped, MappedAsDataclass from sqlalchemy.orm import DeclarativeBase from sqlalchemy import Integer, String, Boolean from sqlalchemy import index, Computed from molalchemy import types, functions class Base(MappedAsDataclass, DeclarativeBase): pass class RawMoleculeFP(Base): __tablename__ = "raw_molecules_fp" __table_args__ = ( index.RdkitIndex("mol_gist_idx_3", "mol"), index.RdkitIndex("fp_gist_idx_3", "fp"), ) id: Mapped[int] = mapped_column( Integer, primary_key=True, autoincrement=True, init=False ) name: Mapped[str] = mapped_column(String(100), unique=True) mol: Mapped[bytes] = mapped_column(types.RdkitMol(return_type="bytes")) fp: Mapped[bytes] = mapped_column( types.RdkitSparseFingerprint, Computed(functions.morgan_fp(mol, 2), persisted=True), init=False, ) is_nsaid: Mapped[bool] = mapped_column(Boolean, default=False) # Example of table creation/dropping (assuming 'eng' is your SQLAlchemy engine) # RawMoleculeFP.__table__.drop(eng, checkfirst=True) # RawMoleculeFP.__table__.create(eng, checkfirst=True) ``` -------------------------------- ### Substructure Search with SQLAlchemy Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core_q= Performs a substructure search in the database using SQLAlchemy. It queries for molecules containing a specific substructure, 'S' in this case, and prints the matching rows. Requires a database session and a defined molecule table. ```python from sqlalchemy import select, functions from molalchemy.db.tables import molecule_table from molalchemy.db.session import SessionLocal with SessionLocal() as session: stmt = select(molecule_table).where( functions.mol_has_substructure(molecule_table.c.mol, "S") ) results = session.execute(stmt).all() for row in results: print(row) ``` -------------------------------- ### molalchemy.rdkit.functions.general Source: https://molalchemy.readthedocs.io/en/latest/api/rdkit/functions_q= Provides wrappers for general RDKit PostgreSQL functions, including fingerprint calculations and comparisons. ```APIDOC ## `add(fp_1, fp_2, **kwargs)` ### Description Calls the rdkit cartridge function `add` to perform element-wise addition of two sparse fingerprints. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fp_1** (RdkitSparseFingerprint) - Required - The first sparse fingerprint. - **fp_2** (RdkitSparseFingerprint) - Required - The second sparse fingerprint. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "fp_1": "", "fp_2": "" } ``` ### Response #### Success Response (200) - **return_value** (Function[RdkitSparseFingerprint]) - An sfp formed by the element-wise addition of the two sfp arguments. #### Response Example ```json { "return_value": "" } ``` ``` ```APIDOC ## `all_values_gt(fp, value, **kwargs)` ### Description Returns a boolean indicating whether or not all elements of the sparse fingerprint argument are greater than the provided integer value. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fp** (RdkitSparseFingerprint) - Required - The sparse fingerprint to check. - **value** (int | Integer) - Required - The integer value to compare against. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "fp": "", "value": 10 } ``` ### Response #### Success Response (200) - **return_value** (Function[Boolean]) - A boolean indicating whether or not all elements of the sfp argument are greater than the int argument. #### Response Example ```json { "return_value": true } ``` ``` ```APIDOC ## `all_values_lt(fp, value, **kwargs)` ### Description Returns a boolean indicating whether or not all elements of the sparse fingerprint argument are less than the provided integer value. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fp** (RdkitSparseFingerprint) - Required - The sparse fingerprint (sfp) to check. - **value** (int | Integer) - Required - The integer value to compare against the sfp elements. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "fp": "", "value": 5 } ``` ### Response #### Success Response (200) - **return_value** (Function[Boolean]) - A boolean indicating whether or not all elements of the sfp argument are less than the int argument. #### Response Example ```json { "return_value": false } ``` ``` ```APIDOC ## `atompair_fp(mol, **kwargs)` ### Description Returns a sparse fingerprint (sfp) which is the count-based atom-pair fingerprint for a given molecule. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **mol** (RdkitMol) - Required - The molecule for which to generate the fingerprint. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "mol": "" } ``` ### Response #### Success Response (200) - **return_value** (Function[RdkitSparseFingerprint]) - The count-based atom-pair fingerprint (sfp) for the molecule. #### Response Example ```json { "return_value": "" } ``` ``` ```APIDOC ## `atompairbv_fp(mol, **kwargs)` ### Description Returns a bit vector atom-pair fingerprint for a given molecule. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **mol** (RdkitMol) - Required - The molecule to compute the fingerprint for. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "mol": "" } ``` ### Response #### Success Response (200) - **return_value** (Function[RdkitBitFingerprint]) - A bit vector atom-pair fingerprint. #### Response Example ```json { "return_value": "" } ``` ``` ```APIDOC ## `avalon_fp(mol, arg_2, arg_3, **kwargs)` ### Description Generates Avalon fingerprints for a molecule. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **mol** (RdkitMol) - Required - The RDKit molecule for which to generate the fingerprint. - **arg_2** (Boolean) - Required - TODO - **arg_3** (int | Integer) - Required - TODO - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "mol": "", "arg_2": true, "arg_3": 1 } ``` ### Response #### Success Response (200) - **return_value** (Function[RdkitBitFingerprint]) - A bit vector fingerprint (bfp). #### Response Example ```json { "return_value": "" } ``` ``` ```APIDOC ## `bfp_from_binary_text(input, **kwargs)` ### Description Constructs a bit vector fingerprint (bfp) from a binary string representation of the fingerprint. ### Method N/A (Function wrapper) ### Endpoint N/A (Function wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (LargeBinary) - Required - The binary string representation of the fingerprint. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Request Example ```json { "input": "" } ``` ### Response #### Success Response (200) - **return_value** (Function[RdkitBitFingerprint]) - A bit vector fingerprint (bfp). #### Response Example ```json { "return_value": "" } ``` ``` -------------------------------- ### Reaction Handling Source: https://molalchemy.readthedocs.io/en/latest/api/rdkit/functions_q= Functions for converting reactions to and from string representations, and for comparing reactions. ```APIDOC ## POST /reaction_in ### Description Converts a string representation of a chemical reaction into an RDKit reaction object. ### Method POST ### Endpoint /reaction_in ### Parameters #### Request Body - **rxn_str** (CString) - Required - The string representation of the chemical reaction, typically in reaction SMILES format. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "rxn_str": "CC.O>>CO", "kwargs": {} } ``` ### Response #### Success Response (200) - **reaction** (RdkitReaction) - An RDKit reaction object representing the parsed chemical reaction. #### Response Example ```json { "reaction": "" } ``` ## POST /reaction_out ### Description Internal function: Converts an RDKit reaction object to its string representation. ### Method POST ### Endpoint /reaction_out ### Parameters #### Request Body - **rxn** (RdkitReaction) - Required - The RDKit reaction object to convert. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "rxn": "", "kwargs": {} } ``` ### Response #### Success Response (200) - **rxn_string** (CString) - The string representation of the RDKit reaction. #### Response Example ```json { "rxn_string": "CC.O>>CO" } ``` ## POST /reaction_eq ### Description Checks if two RDKit reactions are equivalent. Used internally for the operator overloading. ### Method POST ### Endpoint /reaction_eq ### Parameters #### Request Body - **rxn_1** (RdkitReaction) - Required - The first RDKit reaction. - **rxn_2** (RdkitReaction) - Required - The second RDKit reaction. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "rxn_1": "", "rxn_2": "", "kwargs": {} } ``` ### Response #### Success Response (200) - **are_equal** (Boolean) - True if the reactions are equivalent, False otherwise. #### Response Example ```json { "are_equal": true } ``` ## POST /reaction_ne ### Description Returns true if the two reactions are not equal. Used internally for the operator overloading. ### Method POST ### Endpoint /reaction_ne ### Parameters #### Request Body - **rxn_1** (RdkitReaction) - Required - The first RDKit reaction. - **rxn_2** (RdkitReaction) - Required - The second RDKit reaction. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "rxn_1": "", "rxn_2": "", "kwargs": {} } ``` ### Response #### Success Response (200) - **are_not_equal** (Boolean) - True if the reactions are not equal, False otherwise. #### Response Example ```json { "are_not_equal": false } ``` ``` -------------------------------- ### Perform Standard SQLAlchemy Query for Non-NSAID Molecules Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core Executes a standard SQLAlchemy query to retrieve all molecules from the 'molecules' table where the 'is_nsaid' column is False. It demonstrates basic filtering using SQLAlchemy's select and where clauses. ```python # simple query to get all non-nsaid molecules with SessionLocal() as session: stmt = select(molecule_table).where(molecule_table.c.is_nsaid == False) # noqa results = session.execute(stmt).all() for row in results: print(row) ``` -------------------------------- ### Convert Raw Bytes to RDKit Molecule (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Demonstrates how to convert raw binary molecule data, retrieved from a database, back into an RDKit molecule object. This is useful for custom processing or when avoiding automatic conversion overhead. ```python from rdkit import Chem mol_bytes = b'...' # Retrieved from the database mol = Chem.Mol(mol_bytes) ``` -------------------------------- ### Create BingoBinaryRxnIndex in Python with SQLAlchemy Source: https://molalchemy.readthedocs.io/en/latest/api/bingo/db_index This snippet demonstrates how to define a SQLAlchemy model with a binary reaction column and create a BingoBinaryRxnIndex for it. It requires SQLAlchemy and molalchemy libraries. The index is created using the `bingo.breaction` operator class for efficient searching on binary-encoded reaction data. ```python from sqlalchemy import Integer from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from molalchemy.bingo.index import BingoBinaryRxnIndex from molalchemy.bingo.types import BingoBinaryRxn class Base(DeclarativeBase): pass class Reaction(Base): __tablename__ = 'reactions' id: Mapped[int] = mapped_column(Integer, primary_key=True) reaction_bin: Mapped[BingoBinaryRxn] = mapped_column(BingoBinaryRxn) __table_args__ = ( BingoBinaryRxnIndex('idx_reaction_structure_bin', 'reaction_bin'), ) ``` -------------------------------- ### Export RDF Source: https://molalchemy.readthedocs.io/en/latest/api/bingo/functions_q= Exports reactions to an RDF format. Requires four string or text arguments. ```APIDOC ## POST /exportrdf ### Description Exports reactions to an RDF format. ### Method POST ### Endpoint /exportrdf ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **arg_1** (str | Text) - Required - Description for arg_1 - **arg_2** (str | Text) - Required - Description for arg_2 - **arg_3** (str | Text) - Required - Description for arg_3 - **arg_4** (str | Text) - Required - Description for arg_4 - **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "arg_1": "value1", "arg_2": "value2", "arg_3": "value3", "arg_4": "value4" } ``` ### Response #### Success Response (200) - **None | NullType** - SQLAlchemy function #### Response Example ```json { "status": "success", "data": null } ``` ``` -------------------------------- ### Query Molecule by Exact SMILES String Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM This Python snippet demonstrates how to find a molecule that exactly matches a given SMILES string. It uses SQLAlchemy's select and where clauses, comparing the 'mol' attribute to the target SMILES. ```python session.execute( select(Molecule).where(Molecule.mol == "CC(=O)OC1=CC=CC=C1C(=O)O") ).all() ``` -------------------------------- ### Insert Data into Raw Molecule Model (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core Shows how to insert data into the 'molecules_fp_raw' table using SQLAlchemy's session. The data is expected to be in a format compatible with the table definition, including raw binary molecule data. ```python from molalchemy.db import SessionLocal # Assuming 'molecules_fp_raw' is the defined table and 'data' contains the records # with SessionLocal() as session: # session.execute(molecules_fp_raw.insert(), data) # session.commit() ``` -------------------------------- ### importsmiles Source: https://molalchemy.readthedocs.io/en/latest/api/bingo/functions_q= Imports data from SMILES strings. Requires four arguments specifying the file and import details. ```APIDOC ## POST /websites/molalchemy_readthedocs_io/importsmiles ### Description Imports data from SMILES strings. Requires four arguments specifying the file and import details. ### Method POST ### Endpoint /websites/molalchemy_readthedocs_io/importsmiles ### Parameters #### Query Parameters - **arg_1** (str | Text) - Required -. - **arg_2** (str | Text) - Required -. - **arg_3** (str | Text) - Required -. - **arg_4** (str | Text) - Required -. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the `GenericFunction`. ### Response #### Success Response (200) - **Function[None | NullType]** - SQLAlchemy function returning None or NullType. ``` -------------------------------- ### Query Data with Computed Fingerprints Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core This Python code queries the `molecules_fp` table to retrieve the first row of data, including the automatically generated fingerprint. It uses `session.execute` with a `select` statement and `limit(1)`. Assumes `SessionLocal` is defined. ```python session.execute(select(molecules_fp).limit(1)).all() ``` -------------------------------- ### Insert Data with Automatic Fingerprint Generation Source: https://molalchemy.readthedocs.io/en/latest/tutorials/02_Getting_Started_rdkit_Core This Python snippet shows how to insert data into a SQLAlchemy table (`molecules_fp`) where fingerprints are automatically computed and stored. It uses `session.execute` with the `insert` method and commits the transaction. Assumes `SessionLocal` and `data` are defined. ```python with SessionLocal() as session: session.execute(molecules_fp.insert(), data) session.commit() ``` -------------------------------- ### Updating Function Bindings with make (Bash) Source: https://molalchemy.readthedocs.io/en/latest_q= Shows the 'make' commands used to update the chemical function bindings for Bingo and RDKit. These commands regenerate the bindings from cartridge documentation, ensuring consistency between the database cartridges and the Python library. ```bash # Update RDKit function bindings make update-rdkit-func # Update Bingo function bindings make update-bingo-func # Update all function bindings make update-func ``` -------------------------------- ### Define Converted Molecule Model with RDKit Type (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Defines a SQLAlchemy model 'ConvertedMoleculeFP' that stores molecular data using RDKit's Mol type. It includes computed fingerprints and RDKit-specific GIST indexes for efficient searching. ```python class Base(MappedAsDataclass, DeclarativeBase): pass class ConvertedMoleculeFP(Base): __tablename__ = "converted_molecules_fp" __table_args__ = ( index.RdkitIndex("mol_gist_idx_4", "mol"), index.RdkitIndex("fp_gist_idx_4", "fp"), ) id: Mapped[int] = mapped_column( Integer, primary_key=True, autoincrement=True, init=False, ) name: Mapped[str] = mapped_column(String(100), unique=True) mol: Mapped[bytes] = mapped_column(types.RdkitMol(return_type="mol")) fp: Mapped[bytes] = mapped_column( types.RdkitSparseFingerprint, Computed(functions.morgan_fp(mol, 2), persisted=True), init=False, ) is_nsaid: Mapped[bool] = mapped_column(Boolean, default=False) ConvertedMoleculeFP.__table__.drop(eng, checkfirst=True) ConvertedMoleculeFP.__table__.create(eng, checkfirst=True) ``` -------------------------------- ### File to Blob Source: https://molalchemy.readthedocs.io/en/latest/api/bingo/functions_q= Calls the RDKit cartridge function `filetoblob`. Requires one string or text argument. ```APIDOC ## POST /filetoblob ### Description Calls the rdkit cartridge function `filetoblob`. ### Method POST ### Endpoint /filetoblob ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **arg_1** (str | Text) - Required - Description for arg_1 - **kwargs** (Any) - Optional - Additional keyword arguments passed to the GenericFunction. ### Request Example ```json { "arg_1": "file_path" } ``` ### Response #### Success Response (200) - **bytes | LargeBinary** - SQLAlchemy function #### Response Example ```json { "status": "success", "data": "binary_data" } ``` ``` -------------------------------- ### Define SQLAlchemy Model for Raw Molecule Data and Fingerprint (Python) Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM Defines a SQLAlchemy model `RawMoleculeFP` that stores raw molecule data as bytes and automatically computes and persists a Morgan fingerprint. It includes RDKit-specific indexing for efficient querying. ```python from sqlalchemy.orm import MappedAsDataclass, DeclarativeBase, Mapped, mapped_column from sqlalchemy import Integer, String, Boolean from sqlalchemy.ext.computed import Computed from molalchemy import index, types, functions class Base(MappedAsDataclass, DeclarativeBase): pass class RawMoleculeFP(Base): __tablename__ = "raw_molecules_fp" __table_args__ = ( index.RdkitIndex("mol_gist_idx_3", "mol"), index.RdkitIndex("fp_gist_idx_3", "fp"), ) id: Mapped[int] = mapped_column( Integer, primary_key=True, autoincrement=True, init=False ) name: Mapped[str] = mapped_column(String(100), unique=True) mol: Mapped[bytes] = mapped_column(types.RdkitMol(return_type="bytes")) fp: Mapped[bytes] = mapped_column( types.RdkitSparseFingerprint, Computed(functions.morgan_fp(mol, 2), persisted=True), init=False, ) is_nsaid: Mapped[bool] = mapped_column(Boolean, default=False) # Example of dropping and creating the table (assuming 'eng' is your SQLAlchemy engine) # RawMoleculeFP.__table__.drop(eng, checkfirst=True) # RawMoleculeFP.__table__.create(eng, checkfirst=True) ``` -------------------------------- ### Create Sparse Fingerprint from String (Python) Source: https://molalchemy.readthedocs.io/en/latest/api/rdkit/functions_q= Constructs an RDKit sparse fingerprint (sfp) object from its string representation. This is an internal function used for fingerprint initialization. ```python def sfp_in(fp_string: CString, **kwargs) -> Function[RdkitSparseFingerprint]: """Internal function, that constructs an RDKit sparse fingerprint (sfp) from a string representation.""" pass ``` -------------------------------- ### Add Sample Molecular Data to Database Source: https://molalchemy.readthedocs.io/en/latest/tutorials/01_Getting_Started_rdkit_ORM This snippet shows how to create a list of dictionaries, each representing a molecule with its name, SMILES string, and NSAID classification. It then converts these dictionaries into Molecule objects and adds them to the database session, followed by committing the transaction. ```python data = [ {"name": "Aspirin", "mol": "CC(=O)OC1=CC=CC=C1C(=O)O", "is_nsaid": True}, { "name": "Loratadine", "mol": "O=C(OCC)N4CC/C(=C2/c1ccc(Cl)cc1CCc3cccnc23)CC4", "is_nsaid": False, }, { "name": "Rofecoxib", "mol": "O=C2OC\C(=C2\c1ccccc1)c3ccc(cc3)S(C)(=O)=O", "is_nsaid": True, }, {"name": "Captopril", "mol": "C[C@H](CS)C(=O)N1CCC[C@H]1C(=O)O", "is_nsaid": False}, { "name": "Talidomide", "mol": "O=C1c2ccccc2C(=O)N1C3CCC(=O)NC3=O", "is_nsaid": False, }, ] mols = [Molecule(**d) for d in data] session.add_all(mols) session.commit() ```