### Install ChemicalX via pip Source: https://chemicalx.readthedocs.io/en/latest/notes/installation.html Standard installation command for the ChemicalX package. ```bash $ pip install chemicalx ``` -------------------------------- ### Install ChemicalX with PyTorch 1.10.0 Source: https://chemicalx.readthedocs.io/en/latest/notes/installation.html Install the required torch-scatter binaries and the ChemicalX package. Replace ${CUDA} with cpu, cu102, or cu111 based on your environment. ```bash $ pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.10.0+${CUDA}.html $ pip install torchdrug $ pip install chemicalx ``` -------------------------------- ### Check ChemicalX Version Source: https://chemicalx.readthedocs.io/en/latest/notes/installation.html Verify the currently installed version of the ChemicalX package. ```bash $ pip freeze | grep chemicalx ``` -------------------------------- ### Upgrade ChemicalX Source: https://chemicalx.readthedocs.io/en/latest/notes/installation.html Update an existing installation of ChemicalX to the latest version. ```bash $ pip install chemicalx --upgrade ``` -------------------------------- ### GET /batch/next Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/batchgenerator.html Retrieves the next batch of drug-pair data from the generator, handling index management and batch slicing. ```APIDOC ## GET /batch/next ### Description Retrieves the next batch of drug-pair data from the generator. It calculates the slice of the labeled triples based on the current index and batch size, returning a DrugPairBatch object. ### Method GET ### Response #### Success Response (200) - **batch** (DrugPairBatch) - The next batch of processed drug-pair data. ### Error Handling - **StopIteration** - Raised when the generator has reached the end of the labeled triples dataset. ``` -------------------------------- ### Load Dataset Features with DrugCombDB Source: https://chemicalx.readthedocs.io/en/latest/notes/introduction.html Demonstrates how to initialize a dataset loader and retrieve drug features, context features, and labeled triples for the DrugCombDB dataset. ```python from chemicalx.data import DrugCombDB loader = DrugCombDB() context_set = loader.get_context_features() drug_set = loader.get_drug_features() triples = loader.get_labeled_triples() ``` -------------------------------- ### GET /batch/length Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/batchgenerator.html Returns the total number of batches available in the generator. ```APIDOC ## GET /batch/length ### Description Calculates and returns the maximal index of batches, useful for progress tracking tools like tqdm. ### Method GET ### Response #### Success Response (200) - **length** (int) - The total number of batches calculated as ceil(total_samples / batch_size). ``` -------------------------------- ### Initialize the MRGNN Model Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/mrgnn.html Instantiates the MRGNN model with configurable channels and layer counts. ```python """An implementation of the MR-GNN model.""" from typing import Any import torch from torchdrug.layers import MeanReadout from torchdrug.models import GraphConvolutionalNetwork from chemicalx.compat import PackedGraph from chemicalx.constants import TORCHDRUG_NODE_FEATURES from chemicalx.data import DrugPairBatch from chemicalx.models import Model __all__ = [ "MRGNN", ] [docs]class MRGNN(Model): """An implementation of the MR-GNN model from [xu2019]_. .. seealso:: This model was suggested in https://github.com/AstraZeneca/chemicalx/issues/12 .. [xu2019] Xu, N., *et al.* (2019). `MR-GNN: Multi-resolution and dual graph neural network for predicting structured entity interactions `_. *IJCAI International Joint Conference on Artificial Intelligence*, 2019, 3968–3974. """ def __init__( self, *, molecule_channels: int = TORCHDRUG_NODE_FEATURES, hidden_channels: int = 32, middle_channels: int = 16, layer_count: int = 4, out_channels: int = 1, ): """Instantiate the MRGNN model. :param molecule_channels: The number of molecular features. :param hidden_channels: The number of graph convolutional filters. :param middle_channels: The number of hidden layer neurons in the last layer. :param layer_count: The number of graph convolutional and recurrent blocks. :param out_channels: The number of output channels. """ super().__init__() self.graph_convolutions = torch.nn.ModuleList() self.graph_convolutions.append(GraphConvolutionalNetwork(molecule_channels, hidden_channels)) for _ in range(1, layer_count): self.graph_convolutions.append(GraphConvolutionalNetwork(hidden_channels, hidden_channels)) self.border_rnn = torch.nn.LSTM(hidden_channels, hidden_channels, 1) self.middle_rnn = torch.nn.LSTM(2 * hidden_channels, 2 * hidden_channels, 1) self.readout = MeanReadout() self.final = torch.nn.Sequential( # First two are the "bottleneck" torch.nn.Linear(6 * hidden_channels, middle_channels), torch.nn.ReLU(), # Second to are the "final" torch.nn.Linear(middle_channels, out_channels), torch.nn.Sigmoid(), ) ``` -------------------------------- ### Labeled Triples API Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Provides methods to get and write labeled triples. ```APIDOC ## GET /labeled_triples ### Description Retrieves the labeled triples dataframe, containing relationships between drugs, contexts, and labels. ### Method GET ### Endpoint /labeled_triples ### Response #### Success Response (200) - **LabeledTriples** (DataFrame) - The labeled triples data. #### Response Example ```json { "drug_1": ["drug1", "drug2"], "drug_2": ["drug2", "drug1"], "context": ["context1", "context1"], "label": [1, 0] } ``` ## POST /write_labels ### Description Writes the labeled triples dataframe to the dataset. ### Method POST ### Endpoint /write_labels ### Parameters #### Request Body - **df** (DataFrame) - The labeled triples data to write. ### Request Example ```json { "df": { "drug_1": ["drug1", "drug2"], "drug_2": ["drug2", "drug1"], "context": ["context1", "context1"], "label": [1, 0] } } ``` ``` -------------------------------- ### Initialize LocalDatasetLoader Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Initializes a local dataset loader, setting up paths for structures, features, contexts, and labels. It uses `pystow` for directory management and triggers preprocessing if any data files are missing. ```python def __init__(self, directory: Optional[Path] = None): """Instantiate the local dataset loader.""" self.directory = directory or pystow.join("chemicalx", self.__class__.__name__.lower()) self.drug_structures_path = self.directory.joinpath(self.structures_name) self.drug_features_path = self.directory.joinpath(self.features_name) self.contexts_path = self.directory.joinpath(self.contexts_name) self.labels_path = self.directory.joinpath(self.labels_name) if any( not path.exists() for path in (self.drug_features_path, self.drug_structures_path, self.contexts_path, self.labels_path) ): self.preprocess() ``` -------------------------------- ### MHCADDI Model Initialization Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/mhcaddi.html Initializes the MHCADDI network with specified feature channels and dropout configuration. ```python [docs]class MHCADDI(Model): """An implementation of the MHCADDI model from [deac2019]_. .. seealso:: This model was suggested in https://github.com/AstraZeneca/chemicalx/issues/13 .. [deac2019] Deac, A., *et al.* (2019). `Drug-Drug Adverse Effect Prediction with Graph Co-Attention `_. *arXiv*, 1905.00534. """ def __init__( self, *, atom_feature_channels: int = 16, atom_type_channels: int = 16, bond_type_channels: int = 16, node_channels: int = 16, edge_channels: int = 16, hidden_channels: int = 16, readout_channels: int = 16, output_channels: int = 1, dropout: float = 0.5, ): """Instantiate the MHCADDI network. :param atom_feature_channels: Number of atom features. :param atom_type_channels: Number of atom types. :param bond_type_channels: Number of bonds. :param node_channels: Node feature number. :param edge_channels: Edge feature number. :param hidden_channels: Number of hidden layers. :param readout_channels: Readout dimensions. :param output_channels: Number of labels. :param dropout: Dropout rate. """ super().__init__() self.dropout = nn.Dropout(dropout) self.atom_projection = nn.Linear(node_channels + atom_feature_channels, node_channels) self.atom_embedding = nn.Embedding(atom_type_channels, node_channels, padding_idx=0) self.bond_embedding = nn.Embedding(bond_type_channels, edge_channels, padding_idx=0) nn.init.xavier_normal_(self.atom_embedding.weight) nn.init.xavier_normal_(self.bond_embedding.weight) self.encoder = CoAttentionMessagePassingNetwork( hidden_channels=hidden_channels, readout_channels=readout_channels, dropout=dropout, ) self.head_layer = nn.Linear(readout_channels * 2, output_channels) ``` -------------------------------- ### Context Feature Set API Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Provides methods to get and write context features. ```APIDOC ## GET /context_features ### Description Retrieves the context feature set, mapping context IDs to their feature vectors. ### Method GET ### Endpoint /context_features ### Response #### Success Response (200) - **ContextFeatureSet** (object) - A set containing context features. #### Response Example ```json { "context1": [0.1, 0.2, 0.3], "context2": [0.4, 0.5, 0.6] } ``` ## POST /write_contexts ### Description Writes context feature data to the dataset. ### Method POST ### Endpoint /write_contexts ### Parameters #### Request Body - **contexts** (object) - A mapping of context IDs to their feature vectors (lists of floats). ### Request Example ```json { "contexts": { "context1": [0.1, 0.2, 0.3], "context2": [0.4, 0.5, 0.6] } } ``` ``` -------------------------------- ### POST /pipeline Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/pipeline.html Executes the training and evaluation pipeline for a specified dataset and model. ```APIDOC ## POST /pipeline ### Description Runs the training and evaluation pipeline using the provided dataset, model, and configuration parameters. ### Method POST ### Parameters #### Request Body - **dataset** (HintOrType) - Required - The name, class, or instance of the DatasetLoader. - **model** (HintOrType) - Required - The name, class, or instance of the Model. - **model_kwargs** (Mapping) - Optional - Keyword arguments for the model constructor. - **optimizer_cls** (Type) - Optional - The optimizer class (defaults to torch.optim.Adam). - **optimizer_kwargs** (Mapping) - Optional - Keyword arguments for the optimizer. - **loss_cls** (Type) - Optional - The loss function class (defaults to torch.nn.BCELoss). - **loss_kwargs** (Mapping) - Optional - Keyword arguments for the loss function. - **batch_size** (int) - Required - The batch size for training. - **epochs** (int) - Required - The number of training epochs. - **context_features** (bool) - Required - Whether to include biological context features. - **drug_features** (bool) - Required - Whether to include drug features. - **drug_molecules** (bool) - Required - Whether to include drug molecules. - **train_size** (float) - Optional - The ratio of training triples. - **random_state** (int) - Optional - The random seed for data splitting. - **metrics** (Sequence) - Optional - List of metrics to evaluate. - **device** (Device) - Optional - The device to use for computation. ### Response #### Success Response (200) - **Result** (Object) - A result object containing the trained model, predictions, losses, and metrics. ``` -------------------------------- ### Drug Feature Set API Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Provides methods to get and write drug features. ```APIDOC ## GET /drug_features ### Description Retrieves the drug feature set, including drug IDs, SMILES, and their corresponding features. ### Method GET ### Endpoint /drug_features ### Response #### Success Response (200) - **DrugFeatureSet** (object) - A set containing drug features. #### Response Example ```json { "drug1": {"smiles": "CCO", "features": [0.1, 0.2, 0.3]}, "drug2": {"smiles": "CCC", "features": [0.4, 0.5, 0.6]} } ``` ## POST /write_drugs ### Description Writes drug data (drug IDs and SMILES) to the dataset. ### Method POST ### Endpoint /write_drugs ### Parameters #### Request Body - **drugs** (object) - A mapping of drug IDs to their SMILES strings. ### Request Example ```json { "drugs": { "drug1": "CCO", "drug2": "CCC" } } ``` ``` -------------------------------- ### forward Method Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.models.MatchMaker.html Details on how to run a forward pass of the MatchMaker model. ```APIDOC ## POST /matchmaker/forward ### Description Run a forward pass of the MatchMaker model to predict synergy scores. ### Method POST ### Endpoint /matchmaker/forward ### Parameters #### Request Body - **context_features** (FloatTensor) - Required - A matrix of biological context features. - **drug_features_left** (FloatTensor) - Required - A matrix of head drug features. - **drug_features_right** (FloatTensor) - Required - A matrix of tail drug features. ### Response #### Success Response (200) - **predicted_synergy_scores** (FloatTensor) - A column vector of predicted synergy scores. #### Response Example ```json { "predicted_synergy_scores": [[0.1], [0.5], [0.3]] } ``` ``` -------------------------------- ### Get Labeled Triple Count Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Returns the total number of triples (rows) in the dataset. ```python def get_labeled_triple_count(self) -> int: """Get the number of triples in the labeled triples dataset.""" triple_count = self.data.shape[0] return triple_count ``` -------------------------------- ### Get Context Count Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Returns the number of unique contexts found in the 'context' column of the dataset. ```python def get_context_count(self) -> int: """Get the number of unique contexts in the labeled triples dataset.""" return self.data["context"].nunique() ``` -------------------------------- ### Initialize RemoteDatasetLoader Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Instantiates the dataset loader with a specific dataset name. Asserts that the provided dataset name is one of the supported options. ```python def __init__(self, dataset_name: str): """Instantiate the dataset loader. :param dataset_name: The name of the dataset. """ self.base_url = "https://raw.githubusercontent.com/AstraZeneca/chemicalx/main/dataset" self.dataset_name = dataset_name assert dataset_name in ["drugcombdb", "drugcomb", "twosides", "drugbankddi"] ``` -------------------------------- ### unpack Method Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.models.MatchMaker.html Details on how to unpack the batch data for the MatchMaker model. ```APIDOC ## POST /matchmaker/unpack ### Description Unpack the batch data into context features, left drug features, and right drug features. ### Method POST ### Endpoint /matchmaker/unpack ### Parameters #### Request Body - **batch** (object) - Required - The batch data to unpack. ### Response #### Success Response (200) - **context_features** (FloatTensor) - A matrix of biological context features. - **drug_features_left** (FloatTensor) - A matrix of head drug features. - **drug_features_right** (FloatTensor) - A matrix of tail drug features. #### Response Example ```json { "context_features": [[1.0, 2.0], [3.0, 4.0]], "drug_features_left": [[0.1, 0.2], [0.3, 0.4]], "drug_features_right": [[0.5, 0.6], [0.7, 0.8]] } ``` ``` -------------------------------- ### RemoteDatasetLoader - Get Labeled Triples Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Retrieves the labeled triples file from the storage. This method is cached for performance. ```APIDOC ## GET /get_labeled_triples ### Description Retrieves the labeled triples file from the storage. This operation is cached. ### Method GET ### Endpoint /get_labeled_triples ### Response #### Success Response (200) - **labeled_triples** (LabeledTriples) - An object containing the labeled triples. #### Response Example ```json { "labeled_triples": [ {"drug_1": "drugA", "drug_2": "drugB", "context": "context1", "label": 0.5}, {"drug_1": "drugC", "drug_2": "drugD", "context": "context2", "label": 0.8} ] } ``` ``` -------------------------------- ### RemoteDatasetLoader - Get Drug Features Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Retrieves the drug feature set for the dataset. This method is cached for performance. ```APIDOC ## GET /get_drug_features ### Description Retrieves the drug feature set for the dataset. This operation is cached. ### Method GET ### Endpoint /get_drug_features ### Response #### Success Response (200) - **drug_features** (DrugFeatureSet) - An object containing the drug features. #### Response Example ```json { "drug_features": { "drug_id_1": {"smiles": "CCO", "features": [[0.1, 0.2]]}, "drug_id_2": {"smiles": "CCC", "features": [[0.3, 0.4]]} } } ``` ``` -------------------------------- ### DatasetLoader Class Overview Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.data.DatasetLoader.html Provides an overview of the DatasetLoader class, its base class, and a general description. ```APIDOC ## DatasetLoader Class ### Description A generic dataset. Bases: `abc.ABC` ``` -------------------------------- ### Execute the training and evaluation pipeline Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/pipeline.html Runs the full training loop and evaluation process using specified datasets, models, and hyperparameters. ```python def pipeline( *, dataset: HintOrType[DatasetLoader], model: HintOrType[Model], model_kwargs: Optional[Mapping[str, Any]] = None, optimizer_cls: Type[Optimizer] = torch.optim.Adam, optimizer_kwargs: Optional[Mapping[str, Any]] = None, loss_cls: Type[_Loss] = torch.nn.BCELoss, loss_kwargs: Optional[Mapping[str, Any]] = None, batch_size: int = 512, epochs: int, context_features: bool, drug_features: bool, drug_molecules: bool, train_size: Optional[float] = None, random_state: Optional[int] = None, metrics: Optional[Sequence[str]] = None, device: Device = None, ) -> Result: """Run the training and evaluation pipeline. :param dataset: The dataset can be specified in one of three ways: 1. The name of the dataset 2. A subclass of :class:`chemicalx.DatasetLoader` 3. An instance of a :class:`chemicalx.DatasetLoader` :param model: The model can be specified in one of three ways: 1. The name of the model 2. A subclass of :class:`chemicalx.Model` 3. An instance of a :class:`chemicalx.Model` :param model_kwargs: Keyword arguments to pass through to the model constructor. Relevant if passing model by string or class. :param optimizer_cls: The class for the optimizer to use. Currently defaults to :class:`torch.optim.Adam`. :param optimizer_kwargs: Keyword arguments to pass through to the optimizer construction. :param loss_cls: The loss to use. If none given, uses :class:`torch.nn.BCELoss`. :param loss_kwargs: Keyword arguments to pass through to the loss construction. :param batch_size: The batch size :param epochs: The number of epochs to train :param context_features: Indicator whether the batch should include biological context features. :param drug_features: Indicator whether the batch should include drug features. :param drug_molecules: Indicator whether the batch should include drug molecules :param train_size: The ratio of training triples. Default is 0.8 if None is passed. :param random_state: The random seed for splitting the triples. Default is 42. Set to none for no fixed seed. :param metrics: The list of metrics to use. :param device: The device to use :returns: A result object with the trained model and evaluation results """ device = resolve_device(device) loader = dataset_resolver.make(dataset) train_generator, test_generator = loader.get_generators( batch_size=batch_size, context_features=context_features, ``` -------------------------------- ### RemoteDatasetLoader - Get Context Features Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Retrieves the context feature set for the dataset. This method is cached for performance. ```APIDOC ## GET /get_context_features ### Description Retrieves the context feature set for the dataset. This operation is cached. ### Method GET ### Endpoint /get_context_features ### Response #### Success Response (200) - **context_features** (ContextFeatureSet) - An object containing the context features. #### Response Example ```json { "context_features": { "feature_name_1": [[0.1, 0.2, 0.3]], "feature_name_2": [[0.4, 0.5, 0.6]] } } ``` ``` -------------------------------- ### Get Negative Rate Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Calculates and returns the ratio of negative triples in the dataset (1.0 - positive rate). ```python def get_negative_rate(self) -> float: """Get the ratio of positive triples in the dataset.""" return 1.0 - self.data["label"].mean() ``` -------------------------------- ### MatchMaker Model Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.models.MatchMaker.html Documentation for the MatchMaker class, including its initialization parameters and base class. ```APIDOC ## MatchMaker Class ### Description An implementation of the MatchMaker model from [kuru2021]. This model is designed for drug synergy prediction. ### Parameters - **context_channels** (int) - The number of channels for biological context features. - **drug_channels** (int) - The number of channels for drug features. - **input_hidden_channels** (int) - The number of hidden channels in the input layer. Defaults to 32. - **middle_hidden_channels** (int) - The number of hidden channels in the middle layer. Defaults to 32. - **final_hidden_channels** (int) - The number of hidden channels in the final layer. Defaults to 32. - **out_channels** (int) - The number of output channels. Defaults to 1. - **dropout_rate** (float) - The dropout rate for regularization. Defaults to 0.5. ### Bases `chemicalx.models.base.Model` ``` -------------------------------- ### MatchMaker Model Initialization Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/matchmaker.html Initializes the MatchMaker model with specific channel configurations and dropout rates for the neural network layers. ```APIDOC ## MatchMaker.__init__ ### Description Instantiates the MatchMaker model architecture with configurable hidden layers and dropout rates. ### Parameters #### Request Body - **context_channels** (int) - Required - The number of context features. - **drug_channels** (int) - Required - The number of drug features. - **input_hidden_channels** (int) - Optional - The number of hidden layer neurons in the input layer (default: 32). - **middle_hidden_channels** (int) - Optional - The number of hidden layer neurons in the middle layer (default: 32). - **final_hidden_channels** (int) - Optional - The number of hidden layer neurons in the final layer (default: 32). - **out_channels** (int) - Optional - The number of output channels (default: 1). - **dropout_rate** (float) - Optional - The rate of dropout before the scoring head is used (default: 0.5). ``` -------------------------------- ### Get Positive Rate Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Calculates and returns the ratio of positive triples in the dataset (positive count / total count). ```python def get_positive_rate(self) -> float: """Get the ratio of positive triples in the dataset.""" return self.data["label"].mean() ``` -------------------------------- ### BatchGenerator Initialization Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/batchgenerator.html Initializes the BatchGenerator with configuration for batch size and feature inclusion, along with necessary data sets. ```APIDOC ## BatchGenerator Constructor ### Description Initializes a batch generator with specified parameters for batch size, feature inclusion, and data sources. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **batch_size** (int) - Required - Number of drug pairs per batch. - **context_features** (bool) - Required - Indicator whether the batch should include biological context features. - **drug_features** (bool) - Required - Indicator whether the batch should include drug features. - **drug_molecules** (bool) - Required - Indicator whether the batch should include drug molecules. - **context_feature_set** (Optional[ContextFeatureSet]) - Optional - A context feature set for feature generation. - **drug_feature_set** (Optional[DrugFeatureSet]) - Optional - A drug feature set for feature generation. - **labeled_triples** (LabeledTriples) - Required - A labeled triples object used to generate batches. ### Request Example ```python # Example initialization (assuming necessary objects are defined) # batch_generator = BatchGenerator( # batch_size=32, # context_features=True, # drug_features=True, # drug_molecules=True, # context_feature_set=my_context_feature_set, # drug_feature_set=my_drug_feature_set, # labeled_triples=my_labeled_triples # ) ``` ### Response #### Success Response (200) Initializes the BatchGenerator object. #### Response Example None (initialization does not return a value) ``` -------------------------------- ### Get Positive Count Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Calculates and returns the number of triples with a positive label (where the 'label' column sums to a positive value). ```python def get_positive_count(self) -> int: """Get the number of positive triples in the dataset.""" return int(self.data["label"].sum()) ``` -------------------------------- ### Run Training Pipeline Source: https://chemicalx.readthedocs.io/en/latest/modules/pipeline.html Executes the full training and evaluation pipeline for a given dataset and model. ```APIDOC ## POST /pipeline ### Description Runs the training and evaluation pipeline using specified dataset, model, and training configurations. ### Parameters #### Request Body - **dataset** (Union[str, DatasetLoader]) - Required - The dataset name, class, or instance. - **model** (Union[str, Model]) - Required - The model name, class, or instance. - **model_kwargs** (Mapping) - Optional - Arguments for the model constructor. - **optimizer_cls** (Type) - Optional - Optimizer class (default: torch.optim.Adam). - **optimizer_kwargs** (Mapping) - Optional - Arguments for the optimizer. - **loss_cls** (Type) - Optional - Loss function class (default: torch.nn.BCELoss). - **loss_kwargs** (Mapping) - Optional - Arguments for the loss function. - **batch_size** (int) - Required - The batch size. - **epochs** (int) - Required - Number of training epochs. - **context_features** (bool) - Required - Include biological context features. - **drug_features** (bool) - Required - Include drug features. - **drug_molecules** (bool) - Required - Include drug molecules. - **train_size** (float) - Optional - Ratio of training triples (default: 0.8). - **random_state** (int) - Optional - Random seed (default: 42). - **metrics** (Sequence) - Optional - List of metrics to use. - **device** (Union[device, str]) - Optional - Device to use for computation. ### Response #### Success Response (200) - **Result** (Object) - A result object containing the trained model and evaluation metrics. ``` -------------------------------- ### Get Drug Count Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Calculates and returns the total number of unique drugs present in the 'drug_1' and 'drug_2' columns of the dataset. ```python def get_drug_count(self) -> int: """Get the number of drugs in the labeled triples dataset.""" return pd.unique(self.data[["drug_1", "drug_2"]].values.ravel("K")).shape[0] ``` -------------------------------- ### LocalDatasetLoader - Preprocess Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Downloads and preprocesses the dataset, writing to local files. This is an abstract method and must be implemented by subclasses. ```APIDOC ## POST /preprocess ### Description Downloads and preprocesses the dataset. This method is abstract and intended for subclass implementation. ### Method POST ### Endpoint /preprocess ### Response #### Success Response (200) - **message** (str) - Dataset preprocessing initiated. #### Response Example ```json { "message": "Dataset preprocessing initiated. Data will be saved locally." } ``` ``` -------------------------------- ### Get Labeled Triples with Caching Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Loads labeled triples from a tab-separated CSV file into a pandas DataFrame. Uses LRU cache. ```python @lru_cache(maxsize=1) # noqa: B019 def get_labeled_triples(self) -> LabeledTriples: """Get the labeled triples dataframe.""" return LabeledTriples(pd.read_csv(self.labels_path, sep="\t")) ``` -------------------------------- ### Initialize DrugCombDB Loader Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Instantiates the dataset loader specifically for the DrugCombDB dataset. It inherits from `RemoteDatasetLoader` and calls the parent constructor with the dataset name 'drugcombdb'. ```python class DrugCombDB(RemoteDatasetLoader): """A dataset loader for `DrugCombDB `_.""" def __init__(self): """Instantiate the DrugCombDB dataset loader.""" super().__init__("drugcombdb") ``` -------------------------------- ### Preprocess OncoPolyPharmacology Dataset Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Downloads and processes the OncoPolyPharmacology dataset by writing drug, context, and label data using the respective write methods. ```python def preprocess(self) -> None: """Download and process the OncoPolyPharmacology dataset.""" tdc_directory = get_tdc_synergy("OncoPolyPharmacology") df = pd.read_pickle(tdc_directory.joinpath("oncopolypharmacology.pkl")) drugs = dict( chain( df[["Drug1_ID", "Drug1"]].values, df[["Drug2_ID", "Drug2"]].values, ) ) self.write_drugs(drugs) contexts = {key: values.round(4).tolist() for key, values in df[["Cell_Line_ID", "Cell_Line"]].values} self.write_contexts(contexts) labels_df = df[["Drug1_ID", "Drug2_ID", "Cell_Line_ID", "Y"]].rename( columns={ "Drug1_ID": "drug_1", "Drug2_ID": "drug_2", "Cell_Line_ID": "context", "Y": "label", } ) self.write_labels(labels_df) ``` -------------------------------- ### Get Context Features with Caching Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Loads context features from a tab-separated CSV file. Uses LRU cache for efficient retrieval. ```python @lru_cache(maxsize=1) # noqa: B019 def get_context_features(self) -> ContextFeatureSet: """Get the context feature set.""" with self.contexts_path.open() as file: return ContextFeatureSet.from_dict( {key: [float(v) for v in values] for key, *values in csv.reader(file, delimiter="\t")} ) ``` -------------------------------- ### EPGCNDS Model Initialization Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/epgcnds.html Initializes the EPGCN-DS model with specified channel configurations. ```APIDOC ## EPGCNDS.__init__ ### Description Instantiate the EPGCN-DS model with configurable channel dimensions. ### Parameters - **molecule_channels** (int) - Optional - The number of molecular features (default: TORCHDRUG_NODE_FEATURES) - **hidden_channels** (int) - Optional - The number of graph convolutional filters (default: 32) - **middle_channels** (int) - Optional - The number of hidden layer neurons in the last layer (default: 16) - **out_channels** (int) - Optional - The number of output channels (default: 1) ``` -------------------------------- ### Get Negative Count Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Calculates and returns the number of triples with a negative label by subtracting the positive count from the total triple count. ```python def get_negative_count(self) -> int: """Get the number of negative triples in the dataset.""" return self.get_labeled_triple_count() - self.get_positive_count() ``` -------------------------------- ### DeepSynergy Model Initialization Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/deepsynergy.html Initializes the DeepSynergy model with specific channel configurations and dropout settings. ```APIDOC ## DeepSynergy.__init__ ### Description Instantiates the DeepSynergy model architecture. ### Parameters - **context_channels** (int) - Required - The number of context features. - **drug_channels** (int) - Required - The number of drug features. - **input_hidden_channels** (int) - Optional - The number of hidden layer neurons in the input layer (default: 32). - **middle_hidden_channels** (int) - Optional - The number of hidden layer neurons in the middle layer (default: 32). - **final_hidden_channels** (int) - Optional - The number of hidden layer neurons in the final layer (default: 32). - **out_channels** (int) - Optional - The number of output channels (default: 1). - **dropout_rate** (float) - Optional - The rate of dropout before the scoring head is used (default: 0.5). ``` -------------------------------- ### Get Combination Count Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Calculates and returns the number of unique drug pairs (combinations) present in the dataset by looking at 'drug_1' and 'drug_2'. ```python def get_combination_count(self) -> int: """Get the number of unique drug pairs in the labeled triples dataset.""" combination_count = self.data[["drug_1", "drug_2"]].drop_duplicates().shape[0] return combination_count ``` -------------------------------- ### Get Drug Features with Caching Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Retrieves drug features from CSV files, combining structure and feature data. Uses LRU cache for performance. ```python @lru_cache(maxsize=1) # noqa: B019 def get_drug_features(self) -> DrugFeatureSet: """Get the drug feature set.""" with self.drug_structures_path.open() as struct_file, self.drug_features_path.open() as feat_file: struct_reader = csv.reader(struct_file, delimiter="\t") feat_reader = csv.reader(feat_file, delimiter="\t") return DrugFeatureSet.from_dict( { drug: {"smiles": smiles, "features": [float(f) for f in features]} for (drug, smiles), (_, *features) in zip(struct_reader, feat_reader) } ) ``` -------------------------------- ### Initialize DrugComb Loader Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Instantiates the dataset loader for the DrugComb dataset. It inherits from `RemoteDatasetLoader` and initializes with 'drugcomb'. ```python class DrugComb(RemoteDatasetLoader): """A dataset loader for `DrugComb `_.""" def __init__(self): """Instantiate the DrugComb dataset loader.""" super().__init__("drugcomb") ``` -------------------------------- ### Get Labeled Triples Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Loads labeled triples from a CSV file. It generates the path, loads the data using `load_raw_csv_data`, and returns it as a LabeledTriples object. ```python @lru_cache(maxsize=1) # noqa: B019 def get_labeled_triples(self) -> LabeledTriples: """Get the labeled triples file from the storage.""" path = self.generate_path("labeled_triples.csv") df = self.load_raw_csv_data(path) return LabeledTriples(df) ``` -------------------------------- ### Abstract Preprocess Method for Local Datasets Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Defines an abstract method for preprocessing datasets. Implementations in subclasses should handle downloading and preparing data, writing to specified file paths. ```python @abstractmethod def preprocess(self): """Download and preprocess the dataset. The implementation of this function should write to all three of ``self.drugs_path``, ``` -------------------------------- ### MHCADDI Initialization Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/mhcaddi.html Initializes the MHCADDI network with configurable parameters for atom and bond features, network dimensions, and dropout rate. ```APIDOC ## MHCADDI Initialization ### Description Initializes the MHCADDI network with configurable parameters for atom and bond features, network dimensions, and dropout rate. ### Method __init__ ### Parameters #### Keyword Parameters - **atom_feature_channels** (int) - Optional - Number of atom features. - **atom_type_channels** (int) - Optional - Number of atom types. - **bond_type_channels** (int) - Optional - Number of bonds. - **node_channels** (int) - Optional - Node feature number. - **edge_channels** (int) - Optional - Edge feature number. - **hidden_channels** (int) - Optional - Number of hidden layers. - **readout_channels** (int) - Optional - Readout dimensions. - **output_channels** (int) - Optional - Number of labels. - **dropout** (float) - Optional - Dropout rate. ### Request Example ```python MHCADDI( atom_feature_channels=16, atom_type_channels=16, bond_type_channels=16, node_channels=16, edge_channels=16, hidden_channels=16, readout_channels=16, output_channels=1, dropout=0.5 ) ``` ``` -------------------------------- ### Get Drug Features Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Loads drug features from a JSON file. It processes the raw data to extract SMILES strings and feature arrays, then returns a DrugFeatureSet. ```python @lru_cache(maxsize=1) # noqa: B019 def get_drug_features(self) -> DrugFeatureSet: """Get the drug feature set.""" path = self.generate_path("drug_set.json") raw_data = self.load_raw_json_data(path) raw_data = { key: {"smiles": value["smiles"], "features": np.array(value["features"]).reshape(1, -1)} for key, value in raw_data.items() } return DrugFeatureSet.from_dict(raw_data) ``` -------------------------------- ### POST /unpack Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.models.SSIDDI.html Unpacks a batch into the constituent left and right molecular graphs. ```APIDOC ## POST /unpack ### Description Return the left molecular graph and right molecular graph from a provided batch. ### Method POST ### Endpoint /unpack ### Parameters #### Request Body - **batch** (Object) - Required - The batch data to be unpacked. ### Response #### Success Response (200) - **molecules_left** (PackedGraph) - The left molecular graph. - **molecules_right** (PackedGraph) - The right molecular graph. ``` -------------------------------- ### Get Context Features Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Retrieves context features from a JSON file. It generates the path, loads the raw JSON data, reshapes the feature values into PyTorch tensors, and returns a ContextFeatureSet. ```python @lru_cache(maxsize=1) # noqa: B019 def get_context_features(self) -> ContextFeatureSet: """Get the context feature set.""" path = self.generate_path("context_set.json") raw_data = self.load_raw_json_data(path) raw_data = {k: torch.FloatTensor(np.array(v).reshape(1, -1)) for k, v in raw_data.items()} return ContextFeatureSet(raw_data) ``` -------------------------------- ### MHCADDI Model Initialization Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.models.MHCADDI.html Initializes the MHCADDI model with specified channel sizes and dropout rate. ```APIDOC ## MHCADDI Class ### Description An implementation of the MHCADDI model from [deac2019]. This model is designed for predicting drug-drug adverse effects. ### Parameters - **atom_feature_channels** (int) - Optional - Number of channels for atom features. - **atom_type_channels** (int) - Optional - Number of channels for atom type. - **bond_type_channels** (int) - Optional - Number of channels for bond type. - **node_channels** (int) - Optional - Number of channels for node embeddings. - **edge_channels** (int) - Optional - Number of channels for edge embeddings. - **hidden_channels** (int) - Optional - Number of channels for hidden layers. - **readout_channels** (int) - Optional - Number of channels for the readout layer. - **output_channels** (int) - Optional - Number of output channels. - **dropout** (float) - Optional - Dropout rate for regularization. ``` -------------------------------- ### Initialize DrugbankDDI Loader Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/datasetloader.html Instantiates the dataset loader for the Drugbank DDI dataset. It inherits from `RemoteDatasetLoader` and initializes with 'drugbankddi'. ```python class DrugbankDDI(RemoteDatasetLoader): """A dataset loader for `Drugbank DDI `_.""" def __init__(self): """Instantiate the Drugbank DDI dataset loader.""" super().__init__("drugbankddi") ``` -------------------------------- ### POST /unpack Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.models.DeepDrug.html Unpacks a batch into left and right drug molecules. ```APIDOC ## POST /unpack ### Description Return the left drug molecules, and right drug molecules from a batch. ### Parameters - **batch** (object) - Required - The input batch to be unpacked. ``` -------------------------------- ### DatasetLoader Methods Source: https://chemicalx.readthedocs.io/en/latest/api/chemicalx.data.DatasetLoader.html Documentation for the methods of the DatasetLoader class. ```APIDOC ## DatasetLoader Methods ### `get_context_features()` Get the context feature set. **Return type:** `ContextFeatureSet` ### `get_drug_features()` Get the drug feature set. ### `get_generator(batch_size, context_features, drug_features, drug_molecules, labeled_triples=None)` Initialize a batch generator. #### Parameters * **batch_size** (`int`) – Number of drug pairs per batch. * **context_features** (`bool`) – Indicator whether the batch should include biological context features. * **drug_features** (`bool`) – Indicator whether the batch should include drug features. * **drug_molecules** (`bool`) – Indicator whether the batch should include drug molecules. * **labeled_triples** (`Optional[LabeledTriples]`) – A labeled triples object used to generate batches. If none is given, will use all triples from the dataset. **Return type:** `BatchGenerator` **Returns:** A batch generator ### `get_generators(batch_size, context_features, drug_features, drug_molecules, train_size=None, random_state=None)` Generate a pre-stratified pair of batch generators. **Return type:** `Tuple[BatchGenerator, BatchGenerator]` ### `get_labeled_triples()` Get the labeled triples file from the storage. **Return type:** `LabeledTriples` ### `summarize()` Summarize the dataset. **Return type:** `None` ``` -------------------------------- ### Initialize LabeledTriples Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/data/labeledtriples.html Initializes the LabeledTriples object with data, converting it to a pandas DataFrame if necessary. Ensures the data conforms to the defined columns and data types. ```python def __init__(self, data: Union[pd.DataFrame, Iterable[Sequence]]): """Initialize the labeled triples object.""" if not isinstance(data, pd.DataFrame): data = pd.DataFrame(data, columns=self.columns).astype(self.dtype) self.data = data ``` -------------------------------- ### Initialize SSIDDIBlock Source: https://chemicalx.readthedocs.io/en/latest/_modules/chemicalx/models/ssiddi.html Initializes an SSI-DDI Block with Graph Attention Convolution and Mean Readout layers. ```python class SSIDDIBlock(torch.nn.Module): """SSIDDI Block with convolution and pooling.""" def __init__(self, head_number: int, in_channels: int, out_channels: int): """Initialize an SSI-DDI Block. :param head_number: Number of attention heads. :param in_channels: Number of input channels. :param out_channels: Number of convolutional filters. """ super().__init__() self.conv = GraphAttentionConv(input_dim=in_channels, output_dim=out_channels, num_head=head_number) self.readout = MeanReadout() ```