ChemicalX

repository·main·Indexed 21 days ago

https://github.com/astrazeneca/chemicalx

A deep learning library for drug pair scoring tasks, including drug-drug interaction, polypharmacy side effect, and synergy prediction. It provides integrated benchmark datasets (such as Drugbank DDI and TwoSides), data loaders, and state-of-the-art neural network architectures. The library includes a high-level pipeline for orchestrating model training and evaluation, supporting both SMILES string-based techniques and neural message passing-based models.

Tokens
4.9K
Snippets
9
Records
20
Agent score
73%

What's inside ChemicalX

  1. Overview of ChemicalX capabilities

    main

    ChemicalX is a deep learning library designed for drug pair scoring tasks, specifically focusing on:

    • Drug-drug interaction prediction
    • Polypharmacy side effect prediction
    • Synergy prediction

    The library provides:

    • Data loaders and integrated benchmark datasets.
    • State-of-the-art deep neural network architectures.
    • Support for both traditional SMILES string-based techniques and neural message passing-based models.
  2. Understand the TwoSides benchmark dataset

    main

    The TwoSides benchmark dataset in ChemicalX is a subsample of the original TwoSides dataset, processed as follows:

    • Scope: Includes only the 100 most common side effects.
    • Identifiers: Drug identifiers use DrugBank IDs.
    • Contexts: Represented by the top 10 most common side effects in TwoSides.
    • Fingerprints: 256-dimensional Morgan fingerprints generated using RDKit 2021.09.03.
    • Labels: Indicate the presence or absence of a specific drug-drug interaction.
    • Context Features: One-hot encoded binary vectors.
    • Sampling: The dataset contains an equal number of positive and negative samples, with negative samples guaranteed to be collision-free.
  3. How DrugFeatureSet and ContextFeatureSet work

    main

    ChemicalX uses specialized feature sets to manage molecular and biological data:

    • DrugFeatureSet: A UserDict object that enables fast retrieval of molecular graphs and drug-level features (like Morgan fingerprints). It provides get_feature_matrix and get_molecules class methods to batch drugs and molecular graphs using drug identifiers. Molecule-level features are returned as torch.FloatTensor matrices, and molecular graphs are returned as torchdrug.PackedGraph objects.
    • ContextFeatureSet: A UserDict object used to store biological or chemical context-specific feature vectors as torch.FloatTensor instances, keyed by context identifiers.
  4. Use LabeledTriples for managing drug pair data

    main

    The LabeledTriples class is a wrapper around pandas DataFrames that manages labeled drug pairs where labels are context-specific. It supports:

    • Shuffling the triples.
    • Generating training and test splits via the train_test_split class method.
    • Providing descriptive statistics regarding the number of labeled triples and negatively labeled instances.
  5. Understand the structure of ChemicalX models

    main

    Drug pair scoring models in ChemicalX inherit from torch.nn.Module. Every model implements two key methods:

    • unpack: Used to unpack the DrugPairBatch object.
    • forward: Performs the forward pass to make predictions and return propensities for the drug pairs in the batch.

    Models include sensible default parameters for hyperparameters that are not dependent on the specific dataset.

  6. Understand the Drugbank DDI benchmark dataset

    main

    The Drugbank DDI benchmark dataset used in ChemicalX is derived from the Therapeutic Data Commons. It is structured as follows:

    • Identifiers: Drug identifiers use DrugBank IDs.
    • Contexts: Represented by drug-drug interaction identifiers from DrugBank.
    • Fingerprints: 256-dimensional Morgan fingerprints generated using RDKit 2021.09.03.
    • Labels: Indicate the presence or absence of a specific drug-drug interaction.
    • Context Features: One-hot encoded binary vectors.
    • Sampling: The dataset contains an equal number of positive and negative samples, with negative samples guaranteed to be collision-free.
  7. Quickstart: Train and evaluate a drug pair scoring model

    main

    You can use the chemicalx.pipeline function to orchestrate the training and evaluation of drug pair scoring models. The pipeline requires a dataset and a model instance. It supports various data arguments to configure feature extraction and training arguments to control the learning process. After running the pipeline, you can use the returned results object to summarize performance metrics (like AUC-ROC) or save the model and metadata to disk.

    from chemicalx import pipeline
    from chemicalx.models import DeepSynergy
    from chemicalx.data import DrugCombDB
    
    model = DeepSynergy(context_channels=112, drug_channels=256)
    dataset = DrugCombDB()
    
    results = pipeline(
        dataset=dataset,
        model=model,
        # Data arguments
        batch_size=5120,
        context_features=True,
        drug_features=True,
        drug_molecules=False,
        # Training arguments
        epochs=100,
    )
    
    # Outputs information about the AUC-ROC, etc. to the console.
    results.summarize()
    
    # Save the model, losses, evaluation, and other metadata.
    results.save("~/test_results/")
  8. Update or check the ChemicalX version

    main

    You can manage your ChemicalX installation using standard pip commands.

    To upgrade an existing installation to the latest version, use the --upgrade flag. To verify which version is currently installed in your environment, use pip freeze and filter for chemicalx.

    # Upgrade ChemicalX
    $ pip install chemicalx --upgrade
    
    # Check current version
    $ pip freeze | grep chemicalx
  9. Install ChemicalX with PyTorch 1.10.0

    main

    ChemicalX requires specific prerequisites, particularly from PyTorch Geometric. If you are using PyTorch 1.10.0, you must install the compatible torch-scatter binaries, torchdrug, and then chemicalx.

    Replace ${CUDA} in the command below with cpu, cu102, or cu111 to match your specific PyTorch/CUDA installation.

    $ pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.10.0+${CUDA}.html
    $ pip install torchdrug
    $ pip install chemicalx
  10. Score data using a trained model

    main

    To perform inference (scoring), set the model to evaluation mode using model.eval(). Update the BatchGenerator.labeled_triples attribute with your test set.

    Iterate through the generator, making predictions on batch.context_features, batch.drug_features_left, and batch.drug_features_right. To associate predictions with their original data, attach the prediction values to the batch.identifiers DataFrame. Finally, use pandas.concat() to combine the results from all batches into a single DataFrame.

    import pandas as pd
    
    model.eval()
    generator.labeled_triples = test
    
    predictions = []
    for batch in generator:
        prediction = model(batch.context_features,
                           batch.drug_features_left,
                           batch.drug_features_right)
        prediction = prediction.detach().cpu().numpy()
        identifiers = batch.identifiers
        identifiers["prediction"] = prediction
        predictions.append(identifiers)
    
    predictions = pd.concat(predictions)
  11. Run end-to-end training and evaluation with pipeline()

    main

    The pipeline function provides a high-level abstraction for the complete lifecycle of a ChemicalX model. Given a dataset and a model, the pipeline handles training, score generation, and evaluation metric calculation.

    from chemicalx import pipeline
    from chemicalx.models import DeepSynergy
    from chemicalx.data import DrugCombDB
    
    model = DeepSynergy(context_channels=112,
                        drug_channels=256)
    
    dataset = DrugCombDB()
    
    results = pipeline(dataset=dataset,
                       model=model,
                       batch_size=1024,
                       context_features=True,
                       drug_features=True,
                       drug_molecules=False,
                       labels=True,
                       epochs=100)
    
    results.summarize()
    results.save("~/test_results/")