### Install MolGraph for GPU Source: https://molgraph.readthedocs.io/en/latest/get_started/installation.html Use this command to install MolGraph with GPU support. ```bash pip install molgraph[gpu] ``` -------------------------------- ### Install MolGraph for CPU Source: https://molgraph.readthedocs.io/en/latest/get_started/installation.html Use this command to install MolGraph for CPU-only usage. ```bash pip install molgraph ``` -------------------------------- ### Get ESOL dataset with molgraph.chemistry.datasets.get Source: https://molgraph.readthedocs.io/en/latest/api/chemistry.html Shows how to obtain a dataset by name using the DatasetFactory.get method. The example retrieves the 'esol' dataset. ```python >>> esol_dataset = molgraph.chemistry.datasets.get('esol') ``` -------------------------------- ### GradientActivationMapping example usage Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to encode molecular graphs, train a GNN model, and generate gradient activation maps using molgraph.models.GradientActivationMapping. The example uses the ESOL dataset and a sequential GCN model. ```python >>> encoder = molgraph.chemistry.MolecularGraphEncoder( ... atom_encoder=molgraph.chemistry.Featurizer([ ... molgraph.chemistry.features.Symbol(), ... molgraph.chemistry.features.Hybridization() ... ]) ... ) >>> esol = molgraph.chemistry.datasets.get('esol') >>> esol['train']['x'] = encoder(esol['train']['x']) >>> esol['test']['x'] = encoder(esol['test']['x']) ... >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GCNConv(units=128, name='gcn_conv_1'), ... molgraph.layers.GCNConv(units=128, name='gcn_conv_2'), ... molgraph.layers.GCNConv(units=128, name='gcn_conv_3'), ... molgraph.layers.Readout('mean'), ... tf.keras.layers.Dense(units=512), ... tf.keras.layers.Dense(units=1) ... ]) ... >>> gnn_model.compile(optimizer='adam', loss='mse') >>> _ = gnn_model.fit( ... esol['train']['x'], esol['train']['y'], epochs=10, verbose=0) ... >>> gam_model = molgraph.models.GradientActivationMapping( ... model=gnn_model, ... discard_negative_values=False, ... ) >>> maps = gam_model(esol['test']['x'].separate()) ``` -------------------------------- ### GraphAutoEncoder usage example Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to create a GraphTensor, adapt embeddings, build an encoder-decoder model, compile, fit, evaluate, and save/load the encoder. The example uses a small graph tensor and trains for 50 epochs. ```python >>> # Replace this graph_tensor with a large dataset of graphs >>> # Also accepts featurized graph tensors (via `chemistry.Featurizer`) >>> graph_tensor = molgraph.GraphTensor( ... sizes=[5], ... edge_src=[1, 4, 0, 2, 3, 1, 1, 0], ... edge_dst=[0, 0, 1, 1, 1, 2, 3, 4], ... node_feature=['Sym:C|Hyb:SP3', 'Sym:C|Hyb:SP2', 'Sym:O|Hyb:SP2', ... 'Sym:O|Hyb:SP2', 'Sym:N|Hyb:SP3'], ... edge_feature=['BonTyp:SINGLE|Rot:1', 'BonTyp:SINGLE|Rot:0', ... 'BonTyp:SINGLE|Rot:1', 'BonTyp:DOUBLE|Rot:0', ... 'BonTyp:SINGLE|Rot:0', 'BonTyp:DOUBLE|Rot:0', ... 'BonTyp:SINGLE|Rot:0', 'BonTyp:SINGLE|Rot:0'], ... ) >>> node_embedding = molgraph.layers.NodeEmbeddingLookup( ... 32, mask_token='[MASK]') >>> edge_embedding = molgraph.layers.EdgeEmbeddingLookup( ... 32, mask_token='[MASK]') >>> node_embedding.adapt(graph_tensor) >>> edge_embedding.adapt(graph_tensor) >>> # Obtain GraphAutoEncoder model >>> encoder = tf.keras.Sequential([ ... tf.keras.layers.Input(type_spec=graph_tensor.spec), ... node_embedding, ... edge_embedding, ... molgraph.layers.GATv2Conv(128), ... molgraph.layers.GATv2Conv(128), ... molgraph.layers.GATv2Conv(128), ... ]) >>> decoder = molgraph.layers.DotProductIncident(normalize=True) >>> gae = molgraph.models.GraphAutoEncoder(encoder, decoder) >>> gae.compile('adam') >>> _ = gae.fit(graph_tensor, batch_size=32, epochs=50, verbose=0) >>> reconstruction_loss = gae.evaluate(graph_tensor, verbose=0) >>> encoder.save( ... '/tmp/my_pretrained_encoder_model' ... ) >>> loaded_encoder = tf.saved_model.load( ... '/tmp/my_pretrained_encoder_model' ... ) ``` -------------------------------- ### Setup and imports for DTNN QM7 benchmark Source: https://molgraph.readthedocs.io/en/latest/examples/tutorials/06_benchmark-DTNN-QM7.html Adds the project root to the Python path and imports necessary libraries including pandas, numpy, matplotlib, tensorflow, and molgraph modules for benchmarking. ```python import sys sys.path.append('../../../../') import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from molgraph.chemistry.benchmark import configs from molgraph.chemistry.benchmark import tf_records from molgraph.chemistry import datasets ``` -------------------------------- ### DMPNN usage example Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to create a GraphTensor, build a functional model with DMPNN, and make predictions. The example outputs a prediction shape of (2, 10). ```python >>> # Obtain GraphTensor >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_feature=[[1., 0.], [0., 1.], [0., 1.], [0., 1.], ... [1., 0.], [0., 1.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> # Build Functional model >>> inputs = tf.keras.layers.Input(type_spec=graph_tensor.spec) >>> x = molgraph.models.DMPNN(units=32, name='dmpnn')(inputs) >>> x = molgraph.layers.Readout(name='readout')(x) >>> outputs = tf.keras.layers.Dense(10, activation='sigmoid')(x) >>> dmpnn_classifier = tf.keras.Model(inputs, outputs) >>> # Make predictions >>> preds = dmpnn_classifier.predict(graph_tensor, verbose=0) >>> preds.shape (2, 10) ``` -------------------------------- ### GINConv basic usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to create a GraphTensor and a sequential model with three GINConv layers and a Readout layer. The output shape is TensorShape([2, 16]). ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GINConv(units=16), ... molgraph.layers.GINConv(units=16), ... molgraph.layers.GINConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### GraphVariationalAutoEncoder example usage Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to create a GraphTensor, apply node and edge embeddings, build an encoder with GATv2Conv layers, define a decoder, and train/evaluate the GraphVariationalAutoEncoder. The example also demonstrates saving and loading the encoder model. ```python >>> # Replace this graph_tensor with a large dataset of graphs >>> # Also accepts featurized graph tensors (via `chemistry.Featurizer`) >>> graph_tensor = molgraph.GraphTensor( ... sizes=[5], ... edge_src=[1, 4, 0, 2, 3, 1, 1, 0], ... edge_dst=[0, 0, 1, 1, 1, 2, 3, 4], ... node_feature=['Sym:C|Hyb:SP3', 'Sym:C|Hyb:SP2', 'Sym:O|Hyb:SP2', ... 'Sym:O|Hyb:SP2', 'Sym:N|Hyb:SP3'], ... edge_feature=['BonTyp:SINGLE|Rot:1', 'BonTyp:SINGLE|Rot:0', ... 'BonTyp:SINGLE|Rot:1', 'BonTyp:DOUBLE|Rot:0', ... 'BonTyp:SINGLE|Rot:0', 'BonTyp:DOUBLE|Rot:0', ... 'BonTyp:SINGLE|Rot:0', 'BonTyp:SINGLE|Rot:0'], ... ) >>> graph_tensor = graph_tensor.separate() >>> node_embedding = molgraph.layers.NodeEmbeddingLookup( ... 32, mask_token='[MASK]') >>> edge_embedding = molgraph.layers.EdgeEmbeddingLookup( ... 32, mask_token='[MASK]') >>> node_embedding.adapt(graph_tensor) >>> edge_embedding.adapt(graph_tensor) >>> # Obtain the encoder of GVAE >>> encoder_inputs = tf.keras.layers.Input(type_spec=graph_tensor.spec) >>> encoder_x = node_embedding(encoder_inputs) >>> encoder_x = edge_embedding(encoder_x) >>> encoder_x = molgraph.layers.GATv2Conv(128, name='shared_conv')(encoder_x) >>> encoder_x_mean = molgraph.layers.GATv2Conv(128, name='loc_conv')(encoder_x) >>> encoder_x_log_var = molgraph.layers.GATv2Conv(128, name='log_var_conv')(encoder_x) >>> encoder = tf.keras.Model(encoder_inputs, [encoder_x_mean, encoder_x_log_var]) >>> # Obtain the decoder of GVAE >>> decoder = molgraph.layers.DotProductIncident(normalize=True) >>> # Obtain, train and evaluate GVAE model >>> gvae = molgraph.models.GraphVariationalAutoEncoder(encoder, decoder) >>> gvae.compile('adam') >>> _ = gvae.fit(graph_tensor, batch_size=32, epochs=50, verbose=0) >>> total_loss, rec_loss, kl_loss = gvae.evaluate(graph_tensor, verbose=0) >>> encoder.save( ... '/tmp/my_pretrained_encoder_model' ... ) >>> loaded_encoder = tf.saved_model.load( ... '/tmp/my_pretrained_encoder_model' ... ) ``` -------------------------------- ### Tokenizer: Atom tokenizer example Source: https://molgraph.readthedocs.io/en/latest/api/chemistry.html Creates a Tokenizer with Symbol and Hybridization features, then tokenizes an RDKit atom. The output is a string token like 'Sym:C|Hyb:SP3'. ```python >>> atom_tokenizer = molgraph.chemistry.Tokenizer([ ... molgraph.chemistry.features.Symbol( ... allowable_set={'C', 'N'}, # irrelevant ... ordinal=False, # irrelevant ... oov_size=0 # irrelevant ... ), ... molgraph.chemistry.features.Hybridization( ... allowable_set={'SP', 'SP2', 'SP3'}, ... ) ... ]) >>> # Obtain an Atom >>> rdkit_mol = rdkit.Chem.MolFromSmiles('CC') >>> rdkit_atom = rdkit_mol.GetAtomWithIdx(0) >>> # Encode Atom as a token >>> atom_tokenizer(rdkit_atom) array('Sym:C|Hyb:SP3', dtype='>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GTConv(units=16), ... molgraph.layers.GTConv(units=16), ... molgraph.layers.GTConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### Basic GATConv usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Constructs a GraphTensor with node features and edges, builds a sequential model with three GATConv layers and a Readout layer, and outputs a TensorShape of [2, 16]. ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GATConv(units=16), ... molgraph.layers.GATConv(units=16), ... molgraph.layers.GATConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### GMMConv usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Constructs a GraphTensor and a Sequential model with three GMMConv layers and a Readout layer, then applies the model to the graph tensor and prints the output shape. ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GMMConv(units=16), ... molgraph.layers.GMMConv(units=16), ... molgraph.layers.GMMConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### Build a Featurizer with built-in features Source: https://molgraph.readthedocs.io/en/latest/examples/walk_through/02_molecules.html Constructs a chemistry.Featurizer from a list of chemistry.Feature instances (Symbol and Hybridization). Note that if ordinal=False (default), the allowable_set is sorted internally via sort(). The example prints the atom's symbol and hybridization, then encodes the atom, showing that the first and fifth bins are allotted to OOVs. ```python atom_encoder = chemistry.Featurizer([ chemistry.features.Symbol(['C', 'N', 'O'], oov_size=1), chemistry.features.Hybridization(['SP', 'SP2', 'SP3'], oov_size=1) ]) print('Symbol: ', atom.GetSymbol()) print('Hybridization:', atom.GetHybridization().name) # first and fifth bin is alloted to OOVs print(atom_encoder(atom)) ``` ```output Symbol: O Hybridization: SP3 [0. 0. 0. 1. 0. 0. 0. 1.] ``` -------------------------------- ### First MolGraph Program: ESOL GNN Training Source: https://molgraph.readthedocs.io/en/latest/get_started/installation.html Complete example that loads the ESOL dataset, encodes molecular graphs, builds a GAT-based model, trains it, and computes gradient activation maps. ```python from tensorflow import keras from molgraph import chemistry from molgraph import layers from molgraph import models # Obtain dataset, specifically ESOL esol = chemistry.datasets.get('esol') # Define molecular graph encoder atom_encoder = chemistry.Featurizer([ chemistry.features.Symbol(), chemistry.features.Hybridization(), # ... ]) bond_encoder = chemistry.Featurizer([ chemistry.features.BondType(), # ... ]) encoder = chemistry.MolecularGraphEncoder(atom_encoder, bond_encoder) # Obtain features and associated labels x_train = encoder(esol['train']['x']) y_train = esol['train']['y'] x_test = encoder(esol['test']['x']) y_test = esol['test']['y'] # Build model via Keras API gnn_model = keras.Sequential([ layers.GATConv(units=32, name='gat_conv_1'), layers.GATConv(units=32, name='gat_conv_2'), layers.Readout(), keras.layers.Dense(units=1024, activation='relu'), keras.layers.Dense(units=y_train.shape[-1]) ]) # Compile, fit and evaluate gnn_model.compile(optimizer='adam', loss='mae') gnn_model.fit(x_train, y_train, epochs=50) scores = gnn_model.evaluate(x_test, y_test) # Compute gradient activation maps gam_model = models.GradientActivationMapping(gnn_model) maps = gam_model(x_train.separate()) ``` -------------------------------- ### Load TF records as tf.data.Dataset Source: https://molgraph.readthedocs.io/en/latest/api/chemistry.html Loads TF records from a path (excluding file names) and returns a tf.data.Dataset. The example shows chaining shuffle, batch, and prefetch operations, then iterating over one batch and printing the 'x' field. ```python >>> ds = molgraph.chemistry.tf_records.load( ... path='/tmp/dummy_records/', # extract_tuple=('x', 'y') ... ) >>> ds = ds.shuffle(3) >>> ds = ds.batch(2) >>> ds = ds.prefetch(-1) >>> for batch in ds.take(1): ... print(batch['x']) ``` -------------------------------- ### LaplacianPositionalEncoding usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to create a GraphTensor, wrap the LaplacianPositionalEncoding layer in a Sequential model, and apply it. The output demonstrates that the node features are updated (all values become non-1.0). ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> model = tf.keras.Sequential([ ... molgraph.layers.LaplacianPositionalEncoding(16), ... ]) >>> graph_tensor = model(graph_tensor) >>> graph_tensor.node_feature != 1.0 ``` -------------------------------- ### SaliencyMapping example usage Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to use molgraph.models.SaliencyMapping to compute vanilla saliency maps. It encodes the ESOL dataset, builds a GNN regression model, trains it, and then generates saliency maps on the test set. ```python >>> encoder = molgraph.chemistry.MolecularGraphEncoder( ... atom_encoder=molgraph.chemistry.Featurizer([ ... molgraph.chemistry.features.Symbol(), ... molgraph.chemistry.features.Hybridization() ... ]) ... ) ... >>> esol = molgraph.chemistry.datasets.get('esol') >>> esol['train']['x'] = encoder(esol['train']['x']) >>> esol['test']['x'] = encoder(esol['test']['x']) ... >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GCNConv(units=128, name='gcn_conv_1'), ... molgraph.layers.GCNConv(units=128, name='gcn_conv_2'), ... molgraph.layers.GCNConv(units=128, name='gcn_conv_3'), ... molgraph.layers.Readout('mean'), ... tf.keras.layers.Dense(units=512), ... tf.keras.layers.Dense(units=1) ... ]) ... >>> gnn_model.compile(optimizer='adam', loss='mse') >>> _ = gnn_model.fit( ... esol['train']['x'], esol['train']['y'], epochs=10, verbose=0) ... >>> saliency = molgraph.models.SaliencyMapping(model=gnn_model) >>> saliency_maps = saliency(esol['test']['x'].separate()) ``` -------------------------------- ### GCNConv example usage Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to create a GraphTensor and a Keras Sequential model with three GCNConv layers and a Readout layer, then apply the model to the graph tensor and print the output shape. ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GCNConv(units=16), ... molgraph.layers.GCNConv(units=16), ... molgraph.layers.GCNConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### MPNNConv default usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to create a GraphTensor and a sequential GNN model with three MPNNConv layers and a Readout layer. The output shape is TensorShape([2, 16]). ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_feature=[[1., 0.], [0., 1.], [0., 1.], [0., 1.], ... [1., 0.], [0., 1.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.MPNNConv(units=16), ... molgraph.layers.MPNNConv(units=16), ... molgraph.layers.MPNNConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### GINConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration dictionary. ```APIDOC ## GINConv.from_config ### Description Initializes and builds the layer based on a configuration. ### Method from_config (classmethod) ### Parameters #### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns A layer instance. ``` -------------------------------- ### GraphSageConv usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to create a GraphTensor and a Keras Sequential model with three GraphSageConv layers and a Readout layer, then call the model to get output shape TensorShape([2, 16]). ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GraphSageConv(units=16), ... molgraph.layers.GraphSageConv(units=16), ... molgraph.layers.GraphSageConv(units=16), ... molgraph.layers.Readout(), ... ]) >>> gnn_model(graph_tensor).shape TensorShape([2, 16]) ``` -------------------------------- ### GCNIIConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration. ```APIDOC ## GCNIIConv.from_config ### Description Initializes and builds the layer based on a configuration. ### Method from_config (classmethod) ### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns - **layer instance** - A layer instance. ``` -------------------------------- ### GCNConv.from_config(config) Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration. ```APIDOC ## GCNConv.from_config(config) ### Description Initializes and builds the layer based on a configuration. ### Method from_config (classmethod) ### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns - **layer instance** - A layer instance. ``` -------------------------------- ### GatedGCNConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration. ```APIDOC ## from_config(config) ### Description Initializes and builds the layer based on a configuration. ### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns - **A layer instance** - A layer instance. ``` -------------------------------- ### SetGatherReadout usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to use molgraph.layers.SetGatherReadout in a tf.keras.Sequential model. The layer doubles the output dimension (from 2 to 4) as noted in the comment. The example creates a GraphTensor with node features and edge indices. ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> model = tf.keras.Sequential([ ... # molgraph.layers.GCNConv(2), ... molgraph.layers.SetGatherReadout() ... ]) >>> # Note: SetGatherReadout doubles output dim (from 2 to 4) >>> model(graph_tensor).shape TensorShape([2, 4]) ``` -------------------------------- ### AttentiveFPConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration. ```APIDOC ## from_config(config) ### Description Initializes and builds the layer based on a configuration. ### Method from_config (class method) ### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns - **layer instance** - A layer instance. ``` -------------------------------- ### SmoothGradSaliencyMapping usage example Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to encode molecular graphs, train a GNN model, and compute saliency maps with SmoothGradSaliencyMapping. The example uses the ESOL dataset and a sequential GNN model with GCNConv layers. ```python >>> encoder = molgraph.chemistry.MolecularGraphEncoder( ... atom_encoder=molgraph.chemistry.Featurizer([ ... molgraph.chemistry.features.Symbol(), ... molgraph.chemistry.features.Hybridization() ... ]) ... ) >>> esol = molgraph.chemistry.datasets.get('esol') >>> esol['train']['x'] = encoder(esol['train']['x']) >>> esol['test']['x'] = encoder(esol['test']['x']) ... >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.GCNConv(units=128, name='gcn_conv_1'), ... molgraph.layers.GCNConv(units=128, name='gcn_conv_2'), ... molgraph.layers.GCNConv(units=128, name='gcn_conv_3'), ... molgraph.layers.Readout('mean'), ... tf.keras.layers.Dense(units=512), ... tf.keras.layers.Dense(units=1) ... ]) ... >>> gnn_model.compile(optimizer='adam', loss='mse') >>> _ = gnn_model.fit( ... esol['train']['x'], esol['train']['y'], epochs=10, verbose=0) ... >>> saliency = molgraph.models.SmoothGradSaliencyMapping(model=gnn_model) >>> saliency_maps = saliency(esol['test']['x'].separate()) ``` -------------------------------- ### GTConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration dictionary. ```APIDOC ## GTConv.from_config ### Description Initializes and builds the layer based on a configuration. ### Method from_config (classmethod) ### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns - **layer instance** - A layer instance. ``` -------------------------------- ### Create GradientActivationMapping instance Source: https://molgraph.readthedocs.io/en/latest/examples/walk_through/04_activation_maps.html Instantiates GradientActivationMapping with the sequential model and a list of layer names ('conv_1' to 'conv_4'). Disables output activation and negative value discarding. Then computes the activation maps by calling the instance on the separated input data. ```python gam_model = GradientActivationMapping( sequential_model, ['conv_1', 'conv_2', 'conv_3', 'conv_4'], output_activation=None, discard_negative_values=False, ) gam = gam_model(x_data.separate()) ``` -------------------------------- ### GATv2Conv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration. ```APIDOC ## GATv2Conv.from_config ### Description Initializes and builds the layer based on a configuration. ### Parameters - **config** – (not fully documented in source) – Configuration dictionary. ``` -------------------------------- ### MPNN model usage example Source: https://molgraph.readthedocs.io/en/latest/api/models.html Shows how to create a GraphTensor, build a functional model with MPNN, and make predictions. The example uses molgraph.GraphTensor, tf.keras.layers.Input, molgraph.models.MPNN, molgraph.layers.SetGatherReadout, and tf.keras.layers.Dense. The output shape is (2, 10). ```python >>> # Obtain GraphTensor >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_feature=[[1., 0.], [0., 1.], [0., 1.], [0., 1.], ... [1., 0.], [0., 1.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> # Build Functional model >>> inputs = tf.keras.layers.Input(type_spec=graph_tensor.spec) >>> x = molgraph.models.MPNN(units=32, steps=4, name='mpnn')(inputs) >>> x = molgraph.layers.SetGatherReadout(name='readout')(x) >>> outputs = tf.keras.layers.Dense(10, activation='sigmoid')(x) >>> mpnn_classifier = tf.keras.Model(inputs, outputs) >>> # Make predictions >>> preds = mpnn_classifier.predict(graph_tensor, verbose=0) >>> preds.shape (2, 10) ``` -------------------------------- ### MPNNConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration. ```APIDOC ## MPNNConv.from_config ### Description Initializes and builds the layer based on a configuration. ### Method from_config (classmethod) ### Parameters - **config** (dict) - Required - A Python dictionary of parameters to initialize and build a layer instance. The config is usually obtained from `get_config()` of another layer instance (of the same class). ### Returns A layer instance. ``` -------------------------------- ### GraphTensor propagate example Source: https://molgraph.readthedocs.io/en/latest/api/tensors.html Creates a GraphTensor with node features and edge indices, then calls propagate() to perform message passing. The example uses sizes [2,3] and edge lists to define a graph with 5 nodes. ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[ ... [1.0, 0.0], ... [1.0, 0.0], ... [1.0, 0.0], ... [1.0, 0.0], ... [0.0, 1.0] ... ], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> graph_tensor = graph_tensor.propagate() ``` -------------------------------- ### SegmentPoolingReadout usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to use molgraph.layers.Readout (alias for SegmentPoolingReadout) in a tf.keras.Sequential model to pool node features of a GraphTensor. The example creates a GraphTensor with sizes [2, 3] and node features, then applies the readout layer with mode 'mean', producing a tensor of shape (2, 2). ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> model = tf.keras.Sequential([ ... # molgraph.layers.GCNConv(4), ... molgraph.layers.Readout('mean') # alias for SegmentPoolingReadout ... ]) >>> model(graph_tensor) ``` -------------------------------- ### GMMConv.from_config Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Initializes and builds the layer based on a configuration dictionary. ```APIDOC ## GMMConv.from_config ### Description Initializes and builds the layer based on a configuration. ### Parameters - **config** (dict) - A Python dictionary of parameters to initialize and build a layer instance. Usually obtained from `get_config()` of another layer instance. ### Returns - **Layer instance** - A layer instance. ``` -------------------------------- ### GraphMasking pretraining example Source: https://molgraph.readthedocs.io/en/latest/api/models.html Example usage of GraphMasking for pretraining a graph transformer encoder on a tokenized molecular graph. It creates a GraphTensor, embeds node and edge features with masking tokens, builds a sequential encoder with GTConv layers, and trains the GraphMasking model. The encoder is then saved and loaded. ```python >>> # Replace this graph_tensor with a large dataset of graphs >>> graph_tensor = molgraph.GraphTensor( ... sizes=[5], ... edge_src=[1, 4, 0, 2, 3, 1, 1, 0], ... edge_dst=[0, 0, 1, 1, 1, 2, 3, 4], ... node_feature=['Sym:C|Hyb:SP3', 'Sym:C|Hyb:SP2', 'Sym:O|Hyb:SP2', ... 'Sym:O|Hyb:SP2', 'Sym:N|Hyb:SP3'], ... edge_feature=['BonTyp:SINGLE|Rot:1', 'BonTyp:SINGLE|Rot:0', ... 'BonTyp:SINGLE|Rot:1', 'BonTyp:DOUBLE|Rot:0', ... 'BonTyp:SINGLE|Rot:0', 'BonTyp:DOUBLE|Rot:0', ... 'BonTyp:SINGLE|Rot:0', 'BonTyp:SINGLE|Rot:0'], ... ) >>> node_embedding = molgraph.layers.NodeEmbeddingLookup( ... 32, mask_token='[MASK]') >>> edge_embedding = molgraph.layers.EdgeEmbeddingLookup( ... 32, mask_token='[MASK]') >>> node_embedding.adapt(graph_tensor) >>> edge_embedding.adapt(graph_tensor) >>> graph_transformer_encoder = tf.keras.Sequential([ ... node_embedding, ... edge_embedding, ... molgraph.layers.GTConv(units=32), ... molgraph.layers.GTConv(units=32), ... molgraph.layers.GTConv(units=32), ... ]) >>> pretraining_model = molgraph.models.GraphMasking( ... graph_transformer_encoder, ... node_feature_masking_rate=0.15, ... edge_feature_masking_rate=0.15 ... ) >>> pretraining_model.compile( ... optimizer=tf.keras.optimizers.Adam(1e-4), ... metrics=[ ... tf.keras.metrics.SparseCategoricalAccuracy(name='sparse_acc'), ... ] ... ) >>> _ = pretraining_model.fit(graph_tensor, epochs=1, verbose=0) >>> metric_values = pretraining_model.evaluate(graph_tensor, verbose=0) >>> graph_transformer_encoder.save( ... '/tmp/my_pretrained_encoder_model' ... ) >>> loaded_encoder = tf.saved_model.load( ... '/tmp/my_pretrained_encoder_model' ... ) ``` -------------------------------- ### Import libraries and set up environment Source: https://molgraph.readthedocs.io/en/latest/examples/tutorials/07_benchmark-MPNN-Tox21.html Imports required Python packages including TensorFlow, Keras, pandas, numpy, matplotlib, and molgraph modules. Also appends the parent directory to sys.path for module resolution. ```python import sys sys.path.append('../../../../') import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from molgraph.chemistry.benchmark import configs from molgraph.chemistry.benchmark import tf_records from molgraph.chemistry import datasets from molgraph.losses import MaskedBinaryCrossentropy ``` -------------------------------- ### NodeReadout usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to use NodeReadout in a Keras Sequential model to aggregate edge states produced by EdgeConv layers. The example creates a GraphTensor with node and edge features, builds a model with two EdgeConv layers followed by NodeReadout, and prints the resulting node feature shape. ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_feature=[[1., 0.], [0., 1.], [0., 1.], [0., 1.], ... [1., 0.], [0., 1.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> gnn_model = tf.keras.Sequential([ ... molgraph.layers.EdgeConv(16), # will produce 'edge_state' component ... molgraph.layers.EdgeConv(16), # will produce 'edge_state' component ... molgraph.layers.NodeReadout(target='edge_state'), # target='edge_state' is default ... ]) >>> gnn_model(graph_tensor).node_feature.shape TensorShape([5, 16]) ``` -------------------------------- ### GraphTensor.update Source: https://molgraph.readthedocs.io/en/latest/api/tensors.html Updates existing data fields or adds new data fields to the GraphTensor instance. When adding new fields, names starting with 'node' or 'edge' must match the number of nodes or edges, and static fields should start with an underscore. Updating with values of a different type (e.g., tf.Tensor vs tf.RaggedTensor) requires caution to avoid silent errors. ```APIDOC ## GraphTensor.update ### Description Updates data field(s) of the GraphTensor instance. This method either updates existing data fields or adds new data fields to the GraphTensor instance. ### Method update ### Parameters - **data** (optional) - Data to update. - **data_as_kwargs** (optional) - Additional data fields as keyword arguments. ### Cautions - If name of data field starts with 'node' or 'edge' it is assumed that the size of the corresponding values match with that of node_feature or edge_src respectively. In other words, the new data need to encode the same number of nodes or edges respectively. - If new data should not be associated with the nodes or edges of the GraphTensor instance, then the name of the data field should start with an underscore ('_'). The underscore indicates that the corresponding values are static and should not be tampered with. - A GraphTensor instance should only be updated with values originating from the existing values, or corresponding to the existing values. Reason: although very rare, tf.Tensor values coming from another graph structure may have the same size (namely, the same node or edge dimension), but different row lengths (namely, different sized subgraphs). This will result in a silent error, where the GraphTensor instance is updated without error, but with wrongly partitioned values. ### Example Usage (No explicit example provided in the source.) ``` -------------------------------- ### TransformerEncoderReadout usage example Source: https://molgraph.readthedocs.io/en/latest/api/layers.html Shows how to create a GraphTensor and use TransformerEncoderReadout in a tf.keras.Sequential model. The output shape is TensorShape([2, 2]). ```python >>> graph_tensor = molgraph.GraphTensor( ... sizes=[2, 3], ... node_feature=[[1., 0.], [1., 0.], [1., 0.], [1., 0.], [0., 1.]], ... edge_src=[1, 0, 3, 4, 2, 4, 3, 2], ... edge_dst=[0, 1, 2, 2, 3, 3, 4, 4], ... ) >>> model = tf.keras.Sequential([ ... # molgraph.layers.GCNConv(4), ... molgraph.layers.TransformerEncoderReadout() ... ]) >>> model(graph_tensor).shape TensorShape([2, 2]) ``` -------------------------------- ### from_config(config) Source: https://molgraph.readthedocs.io/en/latest/api/models.html Creates a layer from its config dictionary. This is the reverse of get_config and does not handle connectivity or weights. ```APIDOC ## from_config(config) ### Description Creates a layer from its config dictionary. This is the reverse of get_config and does not handle connectivity or weights. ### Parameters - **config** (Python dictionary) - Required - Typically the output of get_config. ### Returns - A layer instance. ``` -------------------------------- ### Import molgraph chemistry and dependencies Source: https://molgraph.readthedocs.io/en/latest/examples/walk_through/02_molecules.html Imports the molgraph chemistry module, TensorFlow, and matplotlib for the walkthrough. ```python from molgraph import chemistry import tensorflow as tf import matplotlib.pyplot as plt ```