PubChemPy Documentation

repository·main·Indexed 19 days ago

https://github.com/mcs07/pubchempy

A Python wrapper around the PubChem PUG REST API for interacting with the PubChem database. It supports chemical searches by name, substructure, or similarity, as well as chemical standardization, file format conversion, and retrieval of properties for Substances, Compounds, and Assays. Features include pandas integration for data analysis, support for 3D compound records, and utilities for downloading data in formats such as SDF, JSON, CSV, and PNG.

Tokens
9.7K
Snippets
38
Records
52
Agent score
64%

What's inside PubChemPy

  1. Get started with PubChemPy

    main

    PubChemPy is a Python library that provides a Pythonic interface for interacting with the PubChem database via the PUG REST API. It is used for chemical informatics workflows, such as retrieving chemical structures, properties, molecular descriptors, fingerprints, and biological assay results. It supports searching by name, SMILES, InChI, and SDF, and allows for format conversion and chemical standardization.

    Requirements:

    • Python 3.9 or higher.
  2. How PubChemPy works

    main

    PubChemPy is a Python client that interfaces with the PubChem database via the PUG REST web service.

    Key Characteristics

    • Remote Execution: Every request made through PubChemPy is transmitted to PubChem servers, processed, and returned.
    • Internet Dependency: A constant internet connection is required to perform any operations.
    • Resource Offloading: Complex tasks like similarity and substructure searching are performed on PubChem's infrastructure. This allows you to query tens of millions of compounds without requiring local storage or high computational power.
    • Privacy Note: Because data is sent to external servers, PubChemPy is less suitable for confidential or sensitive chemical work.
  3. Understanding the difference between Substances and Compounds

    main

    In PubChemPy, it is important to distinguish between Substance and Compound objects:

    • Substances (pubchempy.Substance): These represent the raw chemical records deposited in PubChem. Because they are unprocessed, they may contain duplicates, mixtures, or non-sensical records. They contain additional information about the original source that deposited the record but have fewer calculated properties.
    • Compounds (pubchempy.Compound): These are derived from the Substance database through a standardization and deduplication process. A single Compound may be derived from multiple different Substance records.
  4. Understand the PUG REST architecture used by PubChemPy

    main

    PubChemPy interacts with the PubChem database via the PUG (Power User Gateway) REST web service. The underlying API follows a modular three-part request pattern that PubChemPy abstracts for you:

    1. Input: Identifies the records of interest (e.g., using a CID, name, or SMILES string).
    2. Operation: Defines the action to perform (e.g., retrieving properties or searching).
    3. Output: Specifies the data format (e.g., JSON, XML, or CSV).

    By using PubChemPy, you can combine these components (for example, providing a SMILES string as input to retrieve properties in a specific format) without manually constructing URLs or handling raw HTTP requests.

  5. Understand PubChem record types: Substances, Compounds, and Assays

    main

    The PubChem database is organized into three main record types, each represented by a specific class in PubChemPy:

    • Substances: Raw chemical records deposited by data contributors. Use the pubchempy.Substance class.
    • Compounds: Standardized and deduplicated chemical records derived from substances. Use the pubchempy.Compound class.
    • Assays: Experimental data from biological screening and testing. Use the pubchempy.Assay class.

    Additionally, Compound objects contain Atom and Bond objects to represent molecular structure.

  6. Work with Compound objects

    main

    You can obtain pubchempy.Compound objects in two ways:

    1. Via search: Use pubchempy.get_compounds to return a list of Compound objects based on a search criteria.
    2. Via CID: If you already know the Compound ID (CID), you can instantiate the object directly using Compound.from_cid(cid).
    import pubchempy as pcp
    
    # Instantiate directly via CID
    c = pcp.Compound.from_cid(6819)
  7. Importing PubChemPy

    main

    You can import the library in two ways:

    1. Standard import: Import the whole package as pcp to access all functions and classes via the namespace.
    2. Specific imports: Import specific classes like Compound or functions like get_compounds directly to use them without a prefix.
    # Option 1: Namespace import
    import pubchempy as pcp
    c = pcp.Compound.from_cid(1423)
    
    # Option 2: Direct import
    from pubchempy import Compound, get_compounds
    c = Compound.from_cid(1423)
    cs = get_compounds("Aspirin", "name")
  8. Install PubChemPy via pip or conda

    main

    You can install PubChemPy using either pip or conda.

    To install via pip:

    pip install pubchempy

    To install via conda (using the conda-forge channel):

    conda install -c conda-forge pubchempy
    pip install pubchempy
  9. Get a full results list for common compound names

    main

    PubChem uses a filtered whitelist for common names (like 'Glucose') to return a single 'correct' result, which may hide other valid CIDs. To bypass this and retrieve all associated CIDs, you can search the Substance database instead of the Compound database.

    1. Use pcp.get_cids with the searchtype="substance" and list_return="flat" to get a list of all unique CIDs associated with that substance name.
    2. Use pcp.Compound.from_cid(cid) to instantiate full Compound objects for each CID found.
    import pubchempy as pcp
    
    # 1. Get all unique CIDs for a common name by searching substances
    cids = pcp.get_cids("2-nonenal", "name", "substance", list_return="flat")
    
    # 2. Convert those CIDs into full Compound objects
    compounds = [pcp.Compound.from_cid(cid) for cid in cids]
  10. Use pandas integration for data analysis

    main

    PubChemPy provides built-in support for pandas to facilitate data analysis. You can obtain data in a pandas.DataFrame format in two ways:

    1. Directly from search functions: The following functions include an as_dataframe parameter. Setting as_dataframe=True will return a pandas.DataFrame containing the extracted properties instead of a list of objects:

      • get_compounds
      • get_substances
      • get_properties
    2. Converting existing lists: If you already have a list of Compound or Substance objects, you can convert them to a DataFrame using:

      • compounds_to_frame
      • substances_to_frame
  11. Configure logging for PubChemPy

    main

    PubChemPy uses a logger named 'pubchempy'. You can enable logging globally or specifically for the PubChemPy module to debug requests and operations.

    Logging levels (from least to most verbose): CRITICAL, ERROR, WARNING, INFO, DEBUG.

    import logging
    
    # Option 1: Global configuration
    logging.basicConfig(level=logging.DEBUG)
    
    # Option 2: Specific PubChemPy logger configuration
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
    pcp_logger = logging.getLogger("pubchempy")
    pcp_logger.setLevel(logging.DEBUG)
    pcp_logger.addHandler(console_handler)