### Install Pip using get-pip.py Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/install.rst Instructions for installing pip if it is not already present on your system. ```bash curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py ``` -------------------------------- ### Install ChemSpiPy from Release Tarball Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/install.rst Manual installation by downloading the latest release tarball and running setup.py. ```bash tar -xzvf ChemSpiPy-2.0.0.tar.gz cd ChemSpiPy-2.0.0 python setup.py install ``` -------------------------------- ### Install ChemSpiPy from GitHub Repository Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/install.rst Installs the latest development version from the GitHub repository. This version may not be stable. ```bash git clone https://github.com/mcs07/ChemSpiPy.git cd ChemSpiPy python setup.py install ``` -------------------------------- ### Install ChemSpiPy using Pip Source: https://github.com/mcs07/chemspipy/blob/master/README.rst Install the ChemSpiPy library using the pip package manager. ```bash pip install chemspipy ``` -------------------------------- ### Initialize ChemSpider and Get Compound by ID Source: https://github.com/mcs07/chemspipy/blob/master/README.rst Instantiate the ChemSpider client with an API key and retrieve a compound using its unique ChemSpider ID. ```python from chemspipy import ChemSpider cs = ChemSpider('') c1 = cs.get_compound(236) # Specify compound by ChemSpider ID ``` -------------------------------- ### Install ChemSpiPy using Conda Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/install.rst Recommended method for installing ChemSpiPy and its dependencies. Adds the 'conda-forge' channel to your configuration. ```bash conda config --add channels conda-forge conda install chemspipy ``` -------------------------------- ### Get Data Sources with ChemSpiderPy Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/misc.rst Retrieve a list of available data sources from ChemSpider. Ensure the ChemSpider API client is initialized. ```python cs.get_datasources() ``` -------------------------------- ### Set API Key as Environment Variable Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/advanced.rst Store your API key as an environment variable to prevent accidental sharing. This example shows how to export it in bash. ```bash export CHEMSPIDER_API_KEY= ``` -------------------------------- ### Get Data Sources Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/misc.rst Retrieves a list of available data sources from ChemSpider. ```APIDOC ## Get Data Sources ### Description Retrieves a list of available data sources from ChemSpider. ### Method chemspipy.api.ChemSpider.get_datasources() ### Request Example ```python cs.get_datasources() ``` ### Response Example ```json ["Abacipharm", "Abblis Chemicals", "Abcam", "ABI Chemicals", "Abmole Bioscience", "ACB Blocks", "Accela ChemBio", ... ] ``` ``` -------------------------------- ### Asynchronous Search Result Container with Results Source: https://context7.com/mcs07/chemspipy/llms.txt The Results class wraps an asynchronous search. It starts a background thread immediately on creation and exposes list-like access, status inspection, and SDF export. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) results = cs.search('Benzene') # Non-blocking status check print(results.ready()) # False while search is running print(results.status) # 'Created' | 'Processing' | 'Complete' | 'Failed' # Block until complete results.wait() ``` -------------------------------- ### Results — Asynchronous Search Result Container Source: https://context7.com/mcs07/chemspipy/llms.txt The `Results` class wraps an asynchronous search. It starts a background thread immediately on creation and exposes list-like access, status inspection, and SDF export. ```APIDOC ## `Results` — Asynchronous Search Result Container The `Results` class wraps an asynchronous search. It starts a background thread immediately on creation and exposes list-like access, status inspection, and SDF export. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) results = cs.search('Benzene') # Non-blocking status check print(results.ready()) # False while search is running print(results.status) # 'Created' | 'Processing' | 'Complete' | 'Failed' # Block until complete results.wait() ``` ``` -------------------------------- ### Iterating Through Search Results Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst You can iterate over the `Results` object returned by `cs.search()` to access individual compound records. This example shows how to print the `record_id` for each result. ```python >>> for result in cs.search('Glucose'): ... print(result.record_id) 5589 58238 71358 96749 2006622 5341883 5360239 9129332 9281077 9312824 9484839 9655623 ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/mcs07/chemspipy/blob/master/CONTRIBUTING.rst Create and activate a conda environment with the necessary development requirements. ```bash conda env create -n chemspipy -f environment.yml source activate chemspipy ``` -------------------------------- ### Initialize API Client Source: https://context7.com/mcs07/chemspipy/llms.txt Create a ChemSpider session using your API key. Optionally supply a custom user_agent string and specify API URL and version. ```APIDOC ## Initialize API Client Create a `ChemSpider` session using your API key. All subsequent operations are performed through this object. Optionally supply a custom `user_agent` string to identify your application on ChemSpider servers. ```python import os from chemspipy import ChemSpider # Use an environment variable to keep the API key out of source code api_key = os.environ['CHEMSPIDER_API_KEY'] cs = ChemSpider(api_key) # Optional: custom user-agent and non-default API URL / version cs_custom = ChemSpider( api_key, user_agent='MyApp/1.0 ChemSpiPy/2.0.0 Python/3.10', api_url='https://api.rsc.org', api_version='v1' ) print(cs) # ChemSpider() ``` ``` -------------------------------- ### Initialize API Client with ChemSpider Source: https://context7.com/mcs07/chemspipy/llms.txt Create a ChemSpider session using your API key. Optionally supply a custom user_agent string. You can also specify a custom API URL and version. ```python import os from chemspipy import ChemSpider # Use an environment variable to keep the API key out of source code api_key = os.environ['CHEMSPIDER_API_KEY'] cs = ChemSpider(api_key) # Optional: custom user-agent and non-default API URL / version cs_custom = ChemSpider( api_key, user_agent='MyApp/1.0 ChemSpiPy/2.0.0 Python/3.10', api_url='https://api.rsc.org', api_version='v1' ) print(cs) ``` -------------------------------- ### Accessing Compound Data and Exporting SDF Source: https://context7.com/mcs07/chemspipy/llms.txt Demonstrates list-like access to compound results and exporting them to an SDF file. Ensure results are available before accessing. ```python print(results[0]) # Compound(236) print(results[0:3]) # [Compound(236), Compound(...), ...] for compound in results: print(compound.record_id, compound.smiles) # Export all results as an SDF file sdf_bytes = results.sdf with open('benzene_results.sdf', 'wb') as f: f.write(sdf_bytes) ``` -------------------------------- ### Initialize ChemSpider and Get/Search Compounds Source: https://github.com/mcs07/chemspipy/blob/master/docs/index.rst Initialize the ChemSpider client with an API key. Use get_compound to retrieve a specific compound by its ID, or search to find compounds by name, SMILES, InChI, InChIKey, formula, or mass. ```python >>> from chemspipy import ChemSpider >>> cs = ChemSpider('') >>> c1 = cs.get_compound(236) # Specify compound by ChemSpider ID >>> c2 = cs.search('benzene') # Search using name, SMILES, InChI, InChIKey, etc. ``` -------------------------------- ### Import ChemSpiPy Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/gettingstarted.rst Import the main ChemSpider class to begin using the library. ```python from chemspipy import ChemSpider ``` -------------------------------- ### Retrieve all External References for a Compound Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/compound.rst Access the external_references property to get a list of all associated external references for a compound. This list can be very large for popular compounds. ```python >>> refs = compound.external_references >>> print(len(refs)) 28181 ``` ```python >>> print(refs[0]) {'source': 'ChemBank', 'sourceUrl': 'http://chembank.broadinstitute.org/', 'externalId': 'DivK1c_000555', 'externalUrl': 'http://chembank.broad.harvard.edu/chemistry/viewMolecule.htm?cbid=1171'} ``` -------------------------------- ### Chemical Format Conversion (SMILES, InChI, Mol) Source: https://context7.com/mcs07/chemspipy/llms.txt Demonstrates converting between various chemical representations like SMILES, InChI, and Mol file format using the ChemSpider API. Ensure your API key is configured. ```python from chemspipy import ChemSpider import os cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) smiles = 'CC(=O)Oc1ccccc1C(=O)O' # SMILES → InChI inchi = cs.convert(smiles, 'SMILES', 'InChI') print(inchi) # InChI=1S/C9H8O4/... # InChI → InChIKey inchikey = cs.convert(inchi, 'InChI', 'InChIKey') print(inchikey) # BSYNRYMUTXBXSQ-UHFFFAOYSA-N # InChIKey → InChI inchi2 = cs.convert(inchikey, 'InChIKey', 'InChI') print(inchi2) # InChI → Mol mol = cs.convert(inchi, 'InChI', 'Mol') print(mol[:60]) ``` -------------------------------- ### Initialize ChemSpider Connection Source: https://github.com/mcs07/chemspipy/blob/master/examples/Getting Started.ipynb Connect to the ChemSpider API by creating a ChemSpider instance. Ensure your security token is stored securely, preferably as an environment variable. ```python # Tip: Store your security token as an environment variable to reduce the chance of accidentally sharing it import os mytoken = os.environ['CHEMSPIDER_SECURITY_TOKEN'] cs = ChemSpider(security_token=mytoken) ``` -------------------------------- ### Connect to ChemSpider Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/gettingstarted.rst Instantiate the ChemSpider class with your API key to establish a connection. ```python cs = ChemSpider('') ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/mcs07/chemspipy/blob/master/CONTRIBUTING.rst Stage, commit, and push your changes to your fork on GitHub. ```bash git add . git commit -m "" git push origin ``` -------------------------------- ### Clone ChemSpiPy Repository Source: https://github.com/mcs07/chemspipy/blob/master/CONTRIBUTING.rst Clone your forked repository to your local machine to begin making changes. ```bash git clone https://github.com//ChemSpiPy.git cd ChemSpiPy ``` -------------------------------- ### Search by Molecular Mass Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst The `cs.search_by_mass()` method allows searching for compounds within a specified mass range. Provide the desired mass and the acceptable ± range as parameters. ```python >>> cs.search_by_mass(680, 0.001) [Compound(8298180), Compound(12931939), Compound(12931969), Compound(21182158)] ``` -------------------------------- ### Create a New Branch Source: https://github.com/mcs07/chemspipy/blob/master/CONTRIBUTING.rst Create a new branch for your specific changes to keep your work organized. ```bash git checkout -b ``` -------------------------------- ### ChemSpiPy Exception Handling Source: https://context7.com/mcs07/chemspipy/llms.txt Demonstrates how to catch specific ChemSpiPy exceptions for different HTTP error codes and timeouts, enabling granular error management. Also shows how to access exception attributes like http_code and message. ```python from chemspipy import ChemSpider from chemspipy.errors import ( ChemSpiPyAuthError, ChemSpiPyNotFoundError, ChemSpiPyRateError, ChemSpiPyTimeoutError, ChemSpiPyServerError, ChemSpiPyHTTPError, ChemSpiPyError, ) import os cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) try: details = cs.get_details(999999999) except ChemSpiPyAuthError as e: print('Invalid API key:', e) # HTTP 401 except ChemSpiPyNotFoundError as e: print('Record not found:', e) # HTTP 404 except ChemSpiPyRateError as e: print('Rate limit exceeded:', e) # HTTP 429 except ChemSpiPyServerError as e: print('Server error:', e) # HTTP 500 except ChemSpiPyHTTPError as e: print(f'HTTP error {e.http_code}: {e.message}') except ChemSpiPyTimeoutError: print('Search timed out') except ChemSpiPyError as e: print('ChemSpiPy error:', e) # Exception attributes try: cs.get_details(-1) except ChemSpiPyHTTPError as e: print(e.http_code) # e.g. 400 print(e.message) # e.g. 'Bad request.' print(repr(e)) # ChemSpiPyBadRequestError(message='Bad request.', http_code=400) ``` -------------------------------- ### Create Compound using get_compound Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/compound.rst Instantiate a Compound object using the ChemSpider API's get_compound method. No server requests are made until a property is accessed. ```python >>> compound = cs.get_compound(2157) ``` -------------------------------- ### Run Tests Source: https://github.com/mcs07/chemspipy/blob/master/CONTRIBUTING.rst Ensure your changes pass all existing tests by running the pytest command. ```bash pytest ``` -------------------------------- ### List Available Data Sources with ChemSpider.get_datasources Source: https://context7.com/mcs07/chemspipy/llms.txt Returns the full list of datasource names registered in ChemSpider, which can be used to filter searches and reference lookups. Requires a ChemSpider API key. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) sources = cs.get_datasources() print(sources[:5]) # ['Abblis Chemicals', 'ABI Chemicals', 'Absolute Standards', ...] print(len(sources)) # e.g. 450+ ``` -------------------------------- ### Retrieve Compound Details using API Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/compound.rst Directly use the get_details API method to fetch compound information as a dictionary. This bypasses the Compound object abstraction and returns raw API response data. ```python >>> info = cs.get_details(2157) >>> print(info.keys()) dict_keys(['id', 'smiles', 'formula', 'averageMass', 'molecularWeight', 'monoisotopicMass', 'nominalMass', 'commonName', 'referenceCount', 'dataSourceCount', 'pubMedCount', 'rscCount', 'mol2D', 'mol3D']) ``` ```python >>> print(info['smiles']) CC(=O)Oc1ccccc1C(=O)O ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/advanced.rst Configure Python's logging module to display DEBUG level messages from the 'chemspipy' logger. This is helpful for detailed troubleshooting. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Batch Fetch Compound Details with ChemSpider.get_details_batch Source: https://context7.com/mcs07/chemspipy/llms.txt Retrieves details for multiple compound records (up to 100) in a single API request. Requires a ChemSpider API key. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) records = cs.get_details_batch([2157, 5589, 236], fields=['SMILES', 'Formula', 'CommonName']) for r in records: print(r['id'], r['commonName'], r['formula']) # 2157 Aspirin C_{9}H_{8}O_{4} # 5589 D-Glucose C_{6}H_{12}O_{6} # 236 Ethanol C_{2}H_{6}O ``` -------------------------------- ### Fetch 2D Structure Depiction with ChemSpider.get_image Source: https://context7.com/mcs07/chemspipy/llms.txt Downloads a PNG image of a compound's 2D chemical structure as bytes. Requires a ChemSpider API key. Compound objects also expose this directly. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) image_bytes = cs.get_image(2157) with open('aspirin.png', 'wb') as f: f.write(image_bytes) print(type(image_bytes)) # # Compound objects also expose this directly (cached after first access) c = cs.get_compound(2157) image_bytes = c.image ``` -------------------------------- ### Fetch Raw Compound Details with ChemSpider.get_details Source: https://context7.com/mcs07/chemspipy/llms.txt Fetches all available fields for a single compound record. Useful for direct JSON inspection or custom processing. Requires a ChemSpider API key. ```python from chemspipy import ChemSpider, FIELDS cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # Full details (all fields) info = cs.get_details(2157) print(info.keys()) # dict_keys(['id', 'smiles', 'formula', 'averageMass', 'molecularWeight', # 'monoisotopicMass', 'nominalMass', 'commonName', 'referenceCount', # 'dataSourceCount', 'pubMedCount', 'rscCount', 'mol2D', 'mol3D']) print(info['smiles']) # CC(=O)Oc1ccccc1C(=O)O print(info['commonName']) # Aspirin # Request only specific fields info_slim = cs.get_details(2157, fields=['SMILES', 'Formula', 'MolecularWeight']) print(info_slim['formula']) # C_{9}H_{8}O_{4} ``` -------------------------------- ### ChemSpider.get_image Source: https://context7.com/mcs07/chemspipy/llms.txt Fetch 2D Structure Depiction: Downloads a PNG image of a compound's 2D chemical structure as bytes. ```APIDOC ## ChemSpider.get_image — Fetch 2D Structure Depiction Download a PNG image of a compound's 2D chemical structure as bytes. ### Parameters - **chemspider_id** (int) - Required - The ChemSpider ID of the compound. ### Request Example ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) image_bytes = cs.get_image(2157) with open('aspirin.png', 'wb') as f: f.write(image_bytes) ``` ### Response Example #### Success Response (200) - **bytes** - The raw bytes of the PNG image. ``` ``` ``` -------------------------------- ### Convert Molecular Formats with ChemSpiderPy Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/misc.rst Convert molecular structures between different formats such as SMILES, InChI, and Mol. Specify the input string, input format, and desired output format. ```python cs.convert('c1ccccc1', 'SMILES', 'InChI') ``` -------------------------------- ### Compound Search with ChemSpiPy Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst Use the `cs.search()` method to find compounds by systematic names, synonyms, trade names, registry numbers, molecular formula, SMILES, InChI, and InChIKey. The returned `Results` object behaves like a Python list. ```python >>> cs.search('O=C(OCC)C') Results([Compound(8525)]) ``` ```python >>> cs.search('glucose') Results([Compound(5589), Compound(58238), Compound(71358), Compound(96749), Compound(2006622), Compound(5341883), Compound(5360239), Compound(9129332), Compound(9281077), Compound(9312824), Compound(9484839), Compound(9655623)]) ``` ```python >>> cs.search('2157') Results([Compound(2157)]) ``` -------------------------------- ### Retrieve API Key from Environment Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/advanced.rst Access your API key stored as an environment variable using Python's os.environ. This is useful for initializing the ChemSpider client securely. ```python import os from chemspipy import ChemSpider api_key = os.environ['CHEMSPIDER_API_KEY'] cs = ChemSpider(api_key) ``` -------------------------------- ### Fetch MOL File with ChemSpider.get_mol Source: https://context7.com/mcs07/chemspipy/llms.txt Retrieves the MOL file string for a compound record, including 2D coordinates from the API. Requires a ChemSpider API key. Also available via Compound.mol_2d and Compound.mol_3d. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) mol = cs.get_mol(2157) print(mol[:80]) # "\n RDKit 2D\n\n ..." # Also available via Compound.mol_2d and Compound.mol_3d c = cs.get_compound(2157) print(c.mol_2d[:60]) print(c.mol_3d[:60]) ``` -------------------------------- ### Configure Logging for ChemSpiPy Source: https://context7.com/mcs07/chemspipy/llms.txt Enables debug logging for the ChemSpiPy library using Python's standard logging module. This is useful for tracing HTTP requests, query IDs, and response timings. ```python import logging from chemspipy import ChemSpider import os logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s %(message)s' ) # Optionally silence other loggers: # logging.getLogger('urllib3').setLevel(logging.WARNING) cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) results = cs.search('Ethanol') results.wait() # DEBUG chemspipy.api POST .../compounds/v1/filter/name ... # DEBUG chemspipy.api Request duration: 0:00:00.312 # DEBUG chemspipy.search Checking status: ``` -------------------------------- ### Export Search Results as SDF Source: https://context7.com/mcs07/chemspipy/llms.txt Filters compounds by chemical formula and exports the results as a compressed SDF file. Requires a valid ChemSpider API key. ```python from chemspipy import ChemSpider import time import os cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) qid = cs.filter_formula('C6H6') while cs.filter_status(qid)['status'] != 'Complete': time.sleep(0.3) sdf_data = cs.filter_results_sdf(qid) # returns decompressed bytes with open('benzene_compounds.sdf', 'wb') as f: f.write(sdf_data) print(len(sdf_data), 'bytes written') ``` -------------------------------- ### Search by Molecular Formula Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst Use `cs.search_by_formula()` for specifically searching by molecular formula to avoid ambiguity with other query types. This method returns a list of matching compounds. ```python >>> cs.search_by_formula('C44H30N4Zn') [Compound(436642), Compound(3232330), Compound(24746832), Compound(26995124)] ``` -------------------------------- ### Specify Custom User Agent Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/advanced.rst Identify your program to ChemSpider servers by providing a custom User-Agent string during ChemSpider class initialization. This helps in tracking usage and debugging. ```python from chemspipy import ChemSpider cs = ChemSpider('', user_agent='My program 1.3, ChemSpiPy 2.0.0, Python 3.6') ``` -------------------------------- ### ChemSpider.get_details_batch Source: https://context7.com/mcs07/chemspipy/llms.txt Batch Fetch Compound Details: Retrieves details for up to 100 compound records in a single API request, allowing for efficient retrieval of multiple compound data. ```APIDOC ## ChemSpider.get_details_batch — Batch Fetch Compound Details Retrieve details for up to 100 compound records in a single API request. ### Parameters - **chemspider_ids** (list[int]) - Required - A list of ChemSpider IDs for the compounds. - **fields** (list[str]) - Optional - A list of specific fields to retrieve for each compound. If not provided, a default set of fields is fetched. ### Request Example ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) records = cs.get_details_batch([2157, 5589, 236], fields=['SMILES', 'Formula', 'CommonName']) ``` ### Response Example #### Success Response (200) - **list[dict]** - A list of dictionaries, where each dictionary contains the details for a requested compound. ```json [ { "id": 2157, "commonName": "Aspirin", "formula": "C9H8O4", "smiles": "CC(=O)Oc1ccccc1C(=O)O" }, { "id": 5589, "commonName": "D-Glucose", "formula": "C6H12O6", "smiles": "C(C(C(C(C(O)O)O)O)O)O" }, { "id": 236, "commonName": "Ethanol", "formula": "C2H6O", "smiles": "CCO" } ] ``` ``` -------------------------------- ### Create Compound directly Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/compound.rst Instantiate a Compound object directly by passing the ChemSpider API instance and a ChemSpider ID. This method also defers server requests until properties are accessed. ```python >>> compound = Compound(cs, 2157) ``` -------------------------------- ### Retrieve Multiple Compounds by ID with ChemSpider Source: https://context7.com/mcs07/chemspipy/llms.txt Return a list of Compound objects from a list of ChemSpider record IDs in a single API call. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) compounds = cs.get_compounds([2157, 5589, 236]) for c in compounds: print(c.record_id, c.common_name) # 2157 Aspirin # 5589 D-Glucose # 236 Ethanol ``` -------------------------------- ### Retrieve Cross-Database References with ChemSpider.get_external_references Source: https://context7.com/mcs07/chemspipy/llms.txt Fetches external database links for a compound. Can be filtered by datasource name. Requires a ChemSpider API key. Compound objects also expose this as a cached property. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # All references for Aspirin (can be very large for popular compounds) refs = cs.get_external_references(2157) print(len(refs)) # e.g. 28181 print(refs[0]) # {'source': 'ChemBank', 'sourceUrl': '...', 'externalId': '...', 'externalUrl': '...'} # Filter to a single datasource pubchem_refs = cs.get_external_references(2157, datasources=['PubChem']) print(pubchem_refs) # [{'source': 'PubChem', 'sourceUrl': 'http://pubchem.ncbi.nlm.nih.gov/', # 'externalId': 2244, 'externalUrl': 'http://pubchem.ncbi.nlm.nih.gov/...'}] # Use Compound.external_references (cached property, all datasources) c = cs.get_compound(2157) print(c.external_references[0]['source']) ``` -------------------------------- ### Search for Compounds by Name Source: https://github.com/mcs07/chemspipy/blob/master/examples/Getting Started.ipynb Search the ChemSpider database for compounds using a name or other identifier. The search method returns an iterable of Compound objects. ```python for result in cs.search('glucose'): print(result) ``` -------------------------------- ### ChemSpider.get_mol Source: https://context7.com/mcs07/chemspipy/llms.txt Fetch MOL File: Retrieves the MOL file string for a compound record, typically containing 2D coordinates from the API. ```APIDOC ## ChemSpider.get_mol — Fetch MOL File Retrieve the MOL file string for a compound record (2D coordinates from the API). ### Parameters - **chemspider_id** (int) - Required - The ChemSpider ID of the compound. ### Request Example ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) mol = cs.get_mol(2157) ``` ### Response Example #### Success Response (200) - **str** - The MOL file content as a string. ``` ## RDKit 2D 3 4 0 0 0 0 0 0 0 0 0 0 ... (MOL file content) ... ``` ``` -------------------------------- ### Retrieve Multiple Compounds by ID Source: https://context7.com/mcs07/chemspipy/llms.txt Return a list of `Compound` objects from a list of ChemSpider record IDs in a single call. ```APIDOC ## `ChemSpider.get_compounds` — Retrieve Multiple Compounds by ID Return a list of `Compound` objects from a list of ChemSpider record IDs in a single call. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) compounds = cs.get_compounds([2157, 5589, 236]) for c in compounds: print(c.record_id, c.common_name) # 2157 Aspirin # 5589 D-Glucose # 236 Ethanol ``` ``` -------------------------------- ### ChemSpider.get_datasources Source: https://context7.com/mcs07/chemspipy/llms.txt List Available Data Sources: Returns the full list of datasource names registered in ChemSpider. These names can be used to filter searches and external reference lookups. ```APIDOC ## ChemSpider.get_datasources — List Available Data Sources Return the full list of datasource names registered in ChemSpider. Use these names to filter searches and external reference lookups. ### Request Example ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) sources = cs.get_datasources() ``` ### Response Example #### Success Response (200) - **list[str]** - A list of available datasource names. ```json [ "Abblis Chemicals", "ABI Chemicals", "Absolute Standards", "..." ] ``` ``` -------------------------------- ### Search by Molecular Weight and Filter Results Source: https://context7.com/mcs07/chemspipy/llms.txt Searches for compounds with a specific molecular weight range and filters the results. Ensure the API key is set in the environment variable CHEMSPIDER_API_KEY. ```python import os import time from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) qid = cs.filter_intrinsicproperty( molecular_weight=180.16, molecular_weight_range=0.05, complexity='single', isotopic='unlabeled' ) while cs.filter_status(qid)['status'] != 'Complete': time.sleep(0.3) ids = cs.filter_results(qid, count=10) for c in cs.get_compounds(ids): print(c.record_id, c.molecular_weight, c.common_name) ``` -------------------------------- ### Waiting for Asynchronous Search Results Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst To manually block the main thread until asynchronous search results are ready, use the `results.wait()` method. You can then check `results.ready()` again. ```python >>> results.wait() >>> results.ready() True ``` -------------------------------- ### Search for Compounds by Name or Identifier Source: https://github.com/mcs07/chemspipy/blob/master/README.rst Perform searches for chemical compounds using various identifiers such as names, SMILES, InChI, or InChIKey. ```python c2 = cs.search('benzene') # Search using name, SMILES, InChI, InChIKey, etc. ``` -------------------------------- ### Search Compounds by Element Composition Source: https://context7.com/mcs07/chemspipy/llms.txt Use `filter_element` to find compounds based on their elemental composition, including options for including/excluding specific elements, complexity, and isotopic labeling. Results can be ordered and paginated. ```python from chemspipy import ChemSpider, MOLECULAR_WEIGHT, ASCENDING import time cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # Compounds containing only C, H, and O (no other elements, include all three) qid = cs.filter_element( include_elements=['C', 'H', 'O'], exclude_elements=['N', 'S', 'P', 'Cl', 'Br'], include_all=True, complexity='single', isotopic='unlabeled', order=MOLECULAR_WEIGHT, direction=ASCENDING ) while cs.filter_status(qid)['status'] != 'Complete': time.sleep(0.5) ids = cs.filter_results(qid, start=0, count=5) compounds = cs.get_compounds(ids) for c in compounds: print(c.record_id, c.molecular_formula, c.molecular_weight) ``` -------------------------------- ### Batch Search Compounds by Multiple Masses Source: https://context7.com/mcs07/chemspipy/llms.txt Employ `filter_mass_batch` to submit a list of (mass, range) tuples for batch processing. Retrieve the results for each mass entry after the batch job completes. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) masses = [(180.0, 0.001), (78.0, 0.001), (342.0, 0.005)] query_id = cs.filter_mass_batch(masses=masses) import time while True: status = cs.filter_mass_batch_status(query_id) if status['status'] == 'Complete': break time.sleep(0.5) batch = cs.filter_mass_batch_results(query_id) for entry in batch: print(entry) ``` -------------------------------- ### ChemSpider.convert Source: https://context7.com/mcs07/chemspipy/llms.txt Performs chemical format conversion between various representations such as SMILES, InChI, InChIKey, and Mol file format. ```APIDOC ## ChemSpider.convert — Chemical Format Conversion Convert between chemical representations: SMILES, InChI, InChIKey, and Mol file format. ### Method `convert(input_data, input_format, output_format)` ### Parameters * **input_data** (string): The chemical structure data to convert. * **input_format** (string): The format of the input data (e.g., 'SMILES', 'InChI', 'InChIKey', 'Mol'). * **output_format** (string): The desired output format (e.g., 'SMILES', 'InChI', 'InChIKey', 'Mol'). ### Request Example ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) smiles = 'CC(=O)Oc1ccccc1C(=O)O' # SMILES → InChI inchi = cs.convert(smiles, 'SMILES', 'InChI') print(inchi) # InChI → InChIKey inchikey = cs.convert(inchi, 'InChI', 'InChIKey') print(inchikey) # InChIKey → InChI inchi2 = cs.convert(inchikey, 'InChIKey', 'InChI') print(inchi2) # InChI → Mol mol = cs.convert(inchi, 'InChI', 'Mol') print(mol[:60]) ``` ### Response Returns the converted chemical structure data in the specified output format. ``` -------------------------------- ### Search Compounds by Molecular Mass Source: https://context7.com/mcs07/chemspipy/llms.txt Use `filter_mass` to find compounds within a specified mass tolerance. The query status must be checked until 'Complete' before fetching the record IDs. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # Find compounds with mass 180 ± 0.001 AMU query_id = cs.filter_mass(mass=180.0, mass_range=0.001) import time while cs.filter_status(query_id)['status'] != 'Complete': time.sleep(0.3) record_ids = cs.filter_results(query_id) print(record_ids[:5]) # [2157, 5589, ...] ``` -------------------------------- ### Retrieve Compound by ID Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/gettingstarted.rst Fetch a specific compound's data using its ChemSpider ID. ```python c = cs.get_compound(2157) ``` -------------------------------- ### ChemSpider.get_details Source: https://context7.com/mcs07/chemspipy/llms.txt Fetch Raw Compound Details: Retrieves a dictionary of all available fields for a single compound record. This is useful for direct JSON inspection or custom processing without using the Compound object. ```APIDOC ## ChemSpider.get_details — Fetch Raw Compound Details Fetch a dict of all available fields for a single record. Useful for direct JSON inspection or custom processing without going through the `Compound` object. ### Parameters - **chemspider_id** (int) - Required - The ChemSpider ID of the compound. - **fields** (list[str]) - Optional - A list of specific fields to retrieve. If not provided, all fields are fetched. ### Request Example ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # Full details (all fields) info = cs.get_details(2157) # Request only specific fields info_slim = cs.get_details(2157, fields=['SMILES', 'Formula', 'MolecularWeight']) ``` ### Response Example #### Success Response (200) - **dict** - A dictionary containing the requested compound details. ```json { "id": 2157, "smiles": "CC(=O)Oc1ccccc1C(=O)O", "formula": "C9H8O4", "averageMass": 180.156, "molecularWeight": 180.156, "monoisotopicMass": 180.042259728, "nominalMass": 180, "commonName": "Aspirin", "referenceCount": 1234, "dataSourceCount": 56, "pubMedCount": 78, "rscCount": 9, "mol2D": "...", "mol3D": "..." } ``` ``` -------------------------------- ### Accessing Search Metadata Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst The `Results` object provides metadata such as the search duration and a message explaining how the query was resolved. Access these using the `.duration` and `.message` attributes. ```python >>> r = cs.search('Glucose') >>> print(r.duration) 0:00:00.513406 >>> print(r.message) Found by approved synonym ``` -------------------------------- ### Retrieve Compound by ID with ChemSpider Source: https://context7.com/mcs07/chemspipy/llms.txt Return a Compound object for a known ChemSpider record ID. Network requests are deferred until a property is accessed, and subsequent reads use a cache. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # Aspirin — ChemSpider ID 2157 c = cs.get_compound(2157) print(c.record_id) # 2157 print(c.common_name) # Aspirin print(c.molecular_formula) # C_{9}H_{8}O_{4} print(c.molecular_weight) # 180.1574 print(c.smiles) # CC(=O)Oc1ccccc1C(=O)O print(c.average_mass) # 180.1574 print(c.monoisotopic_mass) # 180.042374 print(c.nominal_mass) # 180 print(c.inchi) # InChI=1S/C9H8O4/c1-6(10)13-... print(c.inchikey) # BSYNRYMUTXBXSQ-UHFFFAOYSA-N print(c.image_url) # http://www.chemspider.com/ImagesHandler.ashx?id=2157 ``` -------------------------------- ### Access Compound Properties Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/gettingstarted.rst Retrieve various properties of a Compound object, such as molecular formula, weight, SMILES, and common name. ```python print(c.molecular_formula) print(c.molecular_weight) print(c.smiles) print(c.common_name) ``` -------------------------------- ### Search Compounds by Molecular Formula Source: https://context7.com/mcs07/chemspipy/llms.txt Use `filter_formula` to find compounds matching an exact molecular formula. Results can be ordered and filtered by data source. The status of the query must be checked periodically until completion before retrieving results. ```python from chemspipy import ChemSpider, RECORD_ID, ASCENDING cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) query_id = cs.filter_formula('C6H12O6', order=RECORD_ID, direction=ASCENDING) status = cs.filter_status(query_id) while status['status'] != 'Complete': import time; time.sleep(0.3) status = cs.filter_status(query_id) record_ids = cs.filter_results(query_id) compounds = cs.get_compounds(record_ids) for c in compounds[:3]: print(c.record_id, c.common_name) # 5589 D-Glucose # 58238 D-Mannose # 71358 D-Galactose ``` -------------------------------- ### Monitoring Asynchronous Search Status Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst The `results.status` property provides detailed information about the search's progress. Possible statuses include 'Created', 'Failed', 'Unknown', 'Suspended', and 'Complete'. ```python >>> results.status 'Created' >>> results.wait() >>> results.status 'Complete' ``` -------------------------------- ### Search for Compound by Name Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/gettingstarted.rst Search the ChemSpider database for compounds using a name or other identifier. This method returns an iterator of Compound objects. ```python for result in cs.search('Glucose'): print(result) ``` -------------------------------- ### Constants Source: https://github.com/mcs07/chemspipy/blob/master/docs/api.rst Provides access to various constants used within the ChemSpiPy library, such as sorting orders and field identifiers. ```APIDOC ## Constants ### Description ChemSpiPy provides several constants that can be used for various operations, such as specifying sort orders or identifying data fields. ### Available Constants: - `ASCENDING`: Represents ascending order for sorting. - `DESCENDING`: Represents descending order for sorting. - `RECORD_ID`: Identifier for record ID field. - `MASS_DEFECT`: Identifier for mass defect field. - `MOLECULAR_WEIGHT`: Identifier for molecular weight field. - `REFERENCE_COUNT`: Identifier for reference count field. - `DATASOURCE_COUNT`: Identifier for datasource count field. - `PUBMED_COUNT`: Identifier for PubMed count field. - `RSC_COUNT`: Identifier for RSC count field. - `ORDERS`: Represents order-related constants. - `DIRECTIONS`: Represents direction-related constants. - `FIELDS`: Represents field-related constants. ``` -------------------------------- ### Batch Search Compounds by Molecular Formulas Source: https://context7.com/mcs07/chemspipy/llms.txt Utilize `filter_formula_batch` to submit multiple molecular formulas in one request. Monitor the batch job status and retrieve results for each formula once complete. ```python from chemspipy import ChemSpider cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) query_id = cs.filter_formula_batch(['C6H12O6', 'C9H8O4', 'C2H6O']) import time while True: status = cs.filter_formula_batch_status(query_id) if status['status'] == 'Complete': break time.sleep(0.5) batch_results = cs.filter_formula_batch_results(query_id) for entry in batch_results: print(entry['formula'], '->', entry['results'][:3]) # C6H12O6 -> [5589, 58238, 71358] # C9H8O4 -> [2157, ...] # C2H6O -> [682, 236, ...] ``` -------------------------------- ### Retrieve Compound by ID Source: https://github.com/mcs07/chemspipy/blob/master/examples/Getting Started.ipynb Fetch a specific compound's data from ChemSpider using its unique ChemSpider ID. This returns a Compound object. ```python comp = cs.get_compound(2157) comp ``` -------------------------------- ### Search Compounds by SMILES String Source: https://context7.com/mcs07/chemspipy/llms.txt Perform an exact structure search using `filter_smiles` with a SMILES string. After the query completes, retrieve the record IDs and optionally fetch compound details. ```python from chemspipy import ChemSpider import time cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) qid = cs.filter_smiles('CC(=O)Oc1ccccc1C(=O)O') while cs.filter_status(qid)['status'] != 'Complete': time.sleep(0.3) ids = cs.filter_results(qid) print(ids) # [2157] c = cs.get_compound(ids[0]) print(c.common_name) # Aspirin ``` -------------------------------- ### Search Compounds by InChI or InChIKey Source: https://context7.com/mcs07/chemspipy/llms.txt Use `filter_inchi` or `filter_inchikey` for exact structure searches. Ensure the query status is 'Complete' before retrieving the resulting record IDs. ```python from chemspipy import ChemSpider import time cs = ChemSpider(os.environ['CHEMSPIDER_API_KEY']) # Search by InChI qid = cs.filter_inchi('InChI=1S/C9H8O4/c1-6(10)13-8-5-3-2-4-7(8)9(11)12/h2-5H,1H3,(H,11,12)') while cs.filter_status(qid)['status'] != 'Complete': time.sleep(0.3) print(cs.filter_results(qid)) # [2157] # Search by InChIKey qid = cs.filter_inchikey('BSYNRYMUTXBXSQ-UHFFFAOYSA-N') while cs.filter_status(qid)['status'] != 'Complete': time.sleep(0.3) print(cs.filter_results(qid)) # [2157] ``` -------------------------------- ### Convert Molecular Format Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/misc.rst Converts molecular data between different representations like SMILES, InChI, and Mol. ```APIDOC ## Convert Molecular Format ### Description Converts molecular data between different representations such as SMILES, InChI, and Mol. ### Method chemspipy.api.ChemSpider.convert(input_data, from_format, to_format) ### Parameters #### Path Parameters - **input_data** (string) - The molecular data to convert. - **from_format** (string) - The current format of the molecular data (e.g., 'SMILES', 'InChI', 'Mol'). - **to_format** (string) - The desired format for the molecular data (e.g., 'SMILES', 'InChI', 'Mol'). ### Allowed Conversions - From ``InChI`` to ``InChIKey`` - From ``InChI`` to ``Mol`` - From ``InChI`` to ``SMILES`` - From ``InChIKey`` to ``InChI`` - From ``InChIKey`` to ``Mol`` - From ``Mol`` to ``InChI`` - From ``Mol`` to ``InChIKey`` - From ``SMILES`` to ``InChI`` ### Request Example ```python cs.convert('c1ccccc1', 'SMILES', 'InChI') ``` ### Response Example ``` 'InChI=1S/C6H6/c1-2-4-6-5-3-1/h1-6H' ``` ``` -------------------------------- ### Access Compound Properties Source: https://github.com/mcs07/chemspipy/blob/master/examples/Getting Started.ipynb Once a Compound object is retrieved, access its various properties such as molecular formula, weight, SMILES, and common name. ```python print(comp.molecular_formula) print(comp.molecular_weight) print(comp.smiles) print(comp.common_name) ``` -------------------------------- ### Checking Asynchronous Search Status Source: https://github.com/mcs07/chemspipy/blob/master/docs/guide/searching.rst ChemSpiPy performs searches asynchronously. Use `results.ready()` to check if the results are available without blocking the main thread. The `Results` object is initially empty. ```python >>> results = cs.search('O=C(OCC)C') >>> print(results.ready()) False ```