### ExampleProvider::next Source: https://gnina.github.io/libmolgrid/cpp/index.html Retrieves the next example from the provider. ```APIDOC ## void next(Example &ex) ### Description Provides the next example in the sequence by populating the provided Example object. ### Parameters - **ex** (Example&) - Required - Reference to an Example object to be populated. ``` -------------------------------- ### ExampleProvider::next_batch Source: https://gnina.github.io/libmolgrid/cpp/index.html Retrieves a batch of examples from the provider. ```APIDOC ## void next_batch(std::vector &ex, unsigned batch_size = 0) ### Description Provides a batch of examples. If batch_size is 0 or unspecified, the default batch size is used. ### Parameters - **ex** (std::vector&) - Required - Vector to store the batch of examples. - **batch_size** (unsigned) - Optional - Number of examples to retrieve. ``` -------------------------------- ### molgrid.ExampleProvider.next_batch Source: https://gnina.github.io/libmolgrid/python/index.html Retrieves the next batch of examples from the provider. ```APIDOC ## next_batch(batch_size=0) ### Description Returns a vector of the next batch of examples. ### Parameters - **batch_size** (int) - Optional - The number of examples to retrieve in the batch. Defaults to 0. ``` -------------------------------- ### ExampleProvider::populate Source: https://gnina.github.io/libmolgrid/cpp/index.html Loads example files and initializes the provider with the specified number of labels. ```APIDOC ## void populate(const std::string &fname, int num_labels = -1) ### Description Loads an example file from the given path and sets up the provider. If num_labels is not specified, it will be auto-detected from the first example. ### Parameters - **fname** (std::string) - Required - Path to the example file. - **num_labels** (int) - Optional - Number of numerical labels per example. ``` -------------------------------- ### Install libmolgrid via pip Source: https://gnina.github.io/libmolgrid/index Recommended method for installing the library using the Python package manager. ```bash pip install molgrid ``` -------------------------------- ### Install libmolgrid via conda Source: https://gnina.github.io/libmolgrid/index Alternative installation method using the conda package manager. ```bash conda install -c jsunseri molgrid ``` -------------------------------- ### Setup plotting Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Configures plotting utilities and initializes loss tracking lists. ```python #setup plotting def get_ylim(vals): min_val = 0 #min(vals) max_val = max(vals) val_range = max_val - min_val return min_val - 0.1*val_range, max_val + 0.1*val_range import seaborn as sns sns.set_style('white') sns.set_context('notebook') sns.set_palette('bright') from IPython import display grid_losses = [] oob_losses = [] ``` -------------------------------- ### static void extract_labels(const std::vector &examples, Grid &out) Source: https://gnina.github.io/libmolgrid/cpp/index.html Extracts labels from a vector of examples into a 2D grid. ```APIDOC ## static void extract_labels(const std::vector &examples, Grid &out) ### Description Extracts labels from a vector of examples, typically as returned by ExampleProvider.next_batch, into a 2D grid (NxL). ``` -------------------------------- ### GroupedExampleRefProvider Class Source: https://gnina.github.io/libmolgrid/cpp/index.html The GroupedExampleRefProvider class manages grouped example references. It provides methods for adding references, setting up the provider, and iterating through grouped examples. ```APIDOC ## GroupedExampleRefProvider ### Description A class for grouping multiple grids into a single example. It maintains frames in the order they are added and supports fixed batch and time series sizes. ### Public Methods - **GroupedExampleRefProvider()** - Default constructor. - **GroupedExampleRefProvider(const ExampleProviderSettings &parm)** - Constructor with settings. - **void addref(const ExampleRef &ex)** - Adds an example reference. - **void setup()** - Sets up the provider. - **size_t num_labels() const** - Returns the number of labels in an example. - **bool has_group() const** - Checks if the provider has a group field. - **void check_batch_size(unsigned bsize) const** - Checks the batch size. - **void nextref(ExampleRef &ex)** - Retrieves the next example reference. - **unsigned size() const** - Returns the size of the provider. - **size_t small_epoch_size() const** - Returns the number of examples in a small epoch. - **size_t large_epoch_size() const** - Returns the number of examples in a large epoch. - **void reset()** - Resets iterators to the start. - **int populate(std::istream &lines, int numlabels)** - Reads example references from an input stream. - **size_t get_small_epoch_num() const** - Returns the current small epoch number. - **size_t get_large_epoch_num() const** - Returns the current large epoch number. ``` -------------------------------- ### Define ExampleProvider input types file Source: https://gnina.github.io/libmolgrid/tutorials Format for input files where each line represents a training example containing numerical labels followed by paths to molecular structure files. ```text 1 6.05 0.162643 4kqp/4kqp_rec_0.gninatypes 4kqp/4kqp_min_0.gninatypes 1 6.05 0.216481 4kqp/4kqp_rec_0.gninatypes 4kqp/4kqp_docked_0.gninatypes 0 -6.05 4.28411 4kqp/4kqp_rec_0.gninatypes 4kqp/4kqp_docked_1.gninatypes 0 -6.05 2.50741 4kqp/4kqp_rec_0.gninatypes 4kqp/4kqp_docked_2.gninatypes 0 -6.05 2.78808 4kqp/4kqp_rec_0.gninatypes 4kqp/4kqp_docked_3.gninatypes ``` -------------------------------- ### Install build dependencies Source: https://gnina.github.io/libmolgrid/index Required Python packages for building the library from source. ```bash pip3 install numpy pytest pyquaternion ``` -------------------------------- ### static void extract_label(const std::vector &examples, unsigned labelpos, Grid &out) Source: https://gnina.github.io/libmolgrid/cpp/index.html Extracts a specific label from a vector of examples into a 1D grid. ```APIDOC ## static void extract_label(const std::vector &examples, unsigned labelpos, Grid &out) ### Description Extracts a specific label from a vector of examples into a 1D grid (N). ``` -------------------------------- ### extract Source: https://gnina.github.io/libmolgrid/cpp/index.html Extracts data from an ExampleRef into an Example object. ```APIDOC ## virtual void extract(const ExampleRef &ref, Example &ex) ### Description Converts the provided ExampleRef into the target Example object, applying atom typers and caching as configured. ### Parameters - **ref** (const ExampleRef &) - Required - The reference to the example data. - **ex** (Example &) - Required - The target example object to populate. ``` -------------------------------- ### num_types Source: https://gnina.github.io/libmolgrid/cpp/index.html Returns the number of types or channels per example. ```APIDOC ## virtual size_t num_types() const ### Description Returns the number of types (channels) each example will have. Note: this is only accurate if types are explicitly setup. ## virtual size_t num_types(const ExampleRef &ref) const ### Description Returns the number of types (channels) for a specific ExampleRef. ``` -------------------------------- ### ExampleVec Class Source: https://gnina.github.io/libmolgrid/python/index.html The ExampleVec class provides methods to manage collections of examples, including appending, extending, and extracting labels from batches. ```APIDOC ## ExampleVec ### Methods - **append(object)**: Appends an object to the vector. - **extend(object)**: Extends the vector with another object. - **extract_label(int, Grid1f/Grid1fCUDA)**: Extracts a specific label from the vector into a 1D grid. - **extract_labels(Grid2f/Grid2fCUDA)**: Extracts all labels from the vector into a 2D grid. - **sum_types(Grid2f/Grid2fCUDA, bool=True)**: Sums types from the vector into a 2D grid. ``` -------------------------------- ### Compute initial losses Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Calculates starting losses for normalization purposes using random initialization. ```python # compute starting losses for normalization purposes origcoords = torch.rand(batch_size,n_atoms,3,device='cuda')*10-5 with torch.no_grad(): for i in range(batch_size): gmaker.forward((0,0,0), origcoords[i], origtypes[i], batch_radii[i], grid_true[i]) coords, types, grid_gen = model(grid_true) start_grid_loss = F.mse_loss(grid_true, grid_gen) oob_loss = out_of_box_loss(coords, max_val=11.5) start_type_loss = F.mse_loss(type_count_true, types.sum(dim=1)) ``` ```python start_type_loss ``` ```python tensor(1., device='cuda:0') ``` ```python start_grid_loss ``` ```python tensor(0.0015, device='cuda:0') ``` -------------------------------- ### forward Source: https://gnina.github.io/libmolgrid/cpp/index.html Populates a grid with atom density values based on input coordinates or examples. ```APIDOC ## forward(...) ### Description Executes the forward mapping from atomic coordinates to grid density values. Multiple overloads exist to support different input types such as CoordinateSet, Example, or vectors of Examples, as well as CUDA-enabled grids. ``` -------------------------------- ### size_t num_types() Source: https://gnina.github.io/libmolgrid/cpp/index.html Returns the number of types or channels associated with each example. ```APIDOC ### Method `size_t num_types() const` ### Description Returns the number of types (channels) that each example will contain. ``` -------------------------------- ### get_type_names Source: https://gnina.github.io/libmolgrid/cpp/index.html Retrieves the names of the types for explicitly typed examples. ```APIDOC ## virtual std::vector get_type_names() const ### Description Returns a vector of strings representing the names of types for explicitly typed examples. Type names are prepended by the coordinate set index. ``` -------------------------------- ### Transform.forward Source: https://gnina.github.io/libmolgrid/python/index.html Applies a 3D transformation to various data structures (grids, CoordinateSet, Example) on CPU or GPU. ```APIDOC ## forward(arg1, in, out, dotranslate=True) ### Description Applies a 3D transformation to the input data and stores the result in the output. It is safe to perform this operation in-place. ### Parameters - **arg1** (Transform) - The transformation object. - **in** (Grid2f/CoordinateSet/Example) - The input data to be transformed. - **out** (Grid2f/CoordinateSet/Example) - The output container for the transformed data. - **dotranslate** (bool) - Optional. If false, only rotation around the origin is applied (used for vector quantities like gradients and normals). ``` -------------------------------- ### GridMaker.forward Source: https://gnina.github.io/libmolgrid/python/index.html Generates a grid tensor from atomic data. Multiple overloads exist to handle CPU/GPU memory, batched data, and different input formats like CoordinateSets or Examples. ```APIDOC ## GridMaker.forward ### Description Generates a grid tensor from atomic data. The grid must be properly sized before calling this method. ### Signatures - `forward(GridMaker, float3, CoordinateSet, Grid4f)` (CPU) - `forward(GridMaker, float3, CoordinateSet, Grid4fCUDA)` (GPU) - `forward(GridMaker, Example, Transform, Grid4f)` (CPU with Transform) - `forward(GridMaker, Example, Transform, Grid4fCUDA)` (GPU with Transform) - `forward(GridMaker, float3, Grid2f, Grid1f, Grid1f, Grid4f)` (CPU atomic data) - `forward(GridMaker, float3, Grid2fCUDA, Grid1fCUDA, Grid1fCUDA, Grid4fCUDA)` (GPU atomic data) - `forward(GridMaker, Grid2f, Grid3f, Grid2f, Grid2f, Grid5f)` (Batched atomic data) ### Parameters - **center/centers** (float3/Bx3) - The center(s) of the grid. - **coordinate/coordinates** (CoordinateSet/BxNx3) - The atomic coordinate data. - **example** (Example) - An example object containing atomic data. - **transformation** (Transform) - A transformation to apply to the data. - **indices** (Grid1f) - N integers stored as floats. - **radii** (Grid1f/BxN/BxT) - Radii information for the atoms. - **grid** (Grid4f/Grid5f) - The output grid tensor. ``` -------------------------------- ### Initialize ExampleProvider Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Set up the libmolgrid ExampleProvider to handle data loading. ```python # use the libmolgrid ExampleProvider to obtain shuffled, balanced, and stratified batches from a file e = molgrid.ExampleProvider(data_root=datadir+"/structs",balanced=True,shuffle=True) e.populate(fname) ``` -------------------------------- ### Initialize ExampleProvider Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_Tensorflow.html Sets up the data provider to load and shuffle structural data. ```python e = molgrid.ExampleProvider(data_root=datadir+"/structs",balanced=True,shuffle=True) e.populate(fname) ``` -------------------------------- ### molgrid.ExampleProvider.__init__ Source: https://gnina.github.io/libmolgrid/python/index.html Constructs an ExampleProvider instance. Can be initialized using an ExampleSettings object and AtomTypers, or via keyword arguments corresponding to ExampleProviderSettings properties. ```APIDOC ## __init__(args, kwds) ### Description Constructs an ExampleProvider using an ExampleSettings object and the desired AtomTypers for each molecule. Alternatively, specify individual settings using keyword arguments. ### Parameters - **args** (tuple) - Optional - Positional arguments for initialization. - **kwds** (dict) - Optional - Keyword arguments corresponding to properties of the ExampleProviderSettings class. ``` -------------------------------- ### molgrid.ExampleProvider.populate Source: https://gnina.github.io/libmolgrid/python/index.html Populates the provider with data from one or more files. ```APIDOC ## populate(file_name, num_labels=-1) ### Description Populates the ExampleProvider with examples from a file or a list of files. ### Parameters - **file_name** (str or list) - Required - A single file path or a list of file paths containing molecular data. - **num_labels** (int) - Optional - The number of numerical labels per example. Defaults to -1 (auto-detected). ``` -------------------------------- ### Initialize Model Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Sets up the CNN model and optimizer for training. ```python grid_losses = [] oob_losses = [] #recreate model model = CNN(gmaker, type_radii=batch_radii, n_types=1, n_latent=100, n_atoms=n_atoms).to('cuda') model.apply(weight_init) optimizer = optim.Adam(model.parameters(), lr=.0005) ``` -------------------------------- ### Initialize grid and tensors Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Sets up the GridMaker and initial tensors for the training process. ```python gmaker = molgrid.GridMaker(resolution=0.5, dimension=23.5, radius_type_indexed=True) dims = gmaker.grid_dimensions(1) grid_true = torch.empty(batch_size, *dims, dtype=torch.float32, device='cuda') type_count_true = torch.empty(batch_size, n_types, dtype=torch.float32, device='cuda') origtypes = torch.ones(batch_size,n_atoms,1,device='cuda') #size radii for batches batch_radii = torch.tensor(np.tile(radii, (batch_size, 1)), dtype=torch.float32, device='cuda') ``` -------------------------------- ### ExampleExtractor Constructor Source: https://gnina.github.io/libmolgrid/cpp/index.html Initializes an ExampleExtractor with specific settings, atom typers, and optional molecule caches. ```APIDOC ## ExampleExtractor(const ExampleProviderSettings &settings, const std::vector> &typrs, std::vector molcaches) ### Description Initializes the extractor with provider settings, a list of atom typers, and optional molecule cache paths. ### Parameters - **settings** (ExampleProviderSettings) - Required - Configuration settings for the provider. - **typrs** (std::vector>) - Required - List of atom typers to apply. - **molcaches** (std::vector) - Optional - List of molecule cache file paths. ``` -------------------------------- ### Transform Property Accessors Source: https://gnina.github.io/libmolgrid/python/index.html Methods to get or set transformation parameters. ```APIDOC ## Property Accessors - **get_quaternion(arg1)**: Returns the current Quaternion. - **set_quaternion(arg1, arg2)**: Sets the Quaternion. - **get_rotation_center(arg1)**: Returns the current rotation center (float3). - **set_rotation_center(arg1, arg2)**: Sets the rotation center (float3). - **get_translation(arg1)**: Returns the current translation (float3). - **set_translation(arg1, arg2)**: Sets the translation (float3). ``` -------------------------------- ### Build libmolgrid from source Source: https://gnina.github.io/libmolgrid/index Commands to clone the repository and compile the library using CMake. ```bash git clone https://github.com/gnina/libmolgrid.git cd libmolgrid mkdir build cd build cmake .. make -j8 sudo make install ``` -------------------------------- ### GridMaker.__init__ Source: https://gnina.github.io/libmolgrid/python/index.html Initializes a new GridMaker instance with specified grid settings. ```APIDOC ## __init__(resolution=0.5, dimension=23.5, binary=False, radius_type_indexed=False, radius_scale=1.0, gaussian_radius_multiple=1.0) ### Description Initializes the GridMaker with universal grid settings. ### Parameters - **resolution** (float) - Optional - Grid resolution (default: 0.5) - **dimension** (float) - Optional - Grid dimension (default: 23.5) - **binary** (bool) - Optional - Whether to use binary grid (default: False) - **radius_type_indexed** (bool) - Optional - Whether radius is type indexed (default: False) - **radius_scale** (float) - Optional - Scaling factor for radius (default: 1.0) - **gaussian_radius_multiple** (float) - Optional - Gaussian radius multiplier (default: 1.0) ``` -------------------------------- ### Initialize GridMaker and tensor Source: https://gnina.github.io/libmolgrid/tutorials/grid_single_molecule.html Set up the GridMaker and allocate a PyTorch tensor for the grid data. ```python gmaker = molgrid.GridMaker() dims = gmaker.grid_dimensions(molgrid.defaultGninaLigandTyper.num_types()) gridtensor = torch.zeros(dims,dtype=torch.float32) ``` -------------------------------- ### Initialize Model Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Move the model to GPU and apply weight initialization. ```python # initialize Net on GPU model = Net(dims).to('cuda') model.apply(weights_init) ``` -------------------------------- ### Initialize molgrid and PyTorch Source: https://gnina.github.io/libmolgrid/tutorials/grid_single_molecule.html Import the necessary libraries for molecule processing and tensor operations. ```python import torch import molgrid from molgrid.openbabel import pybel as pybel ``` -------------------------------- ### Import required libraries Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_Tensorflow.html Initializes the environment by importing molgrid, numpy, tensorflow, and matplotlib. ```python import molgrid import numpy as np import tensorflow as tf import tensorflow.keras as keras import keras.layers import os import matplotlib.pyplot as plt ``` -------------------------------- ### Prepare GridMaker and model Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_Tensorflow.html Initializes the GridMaker and creates the model based on input dimensions. ```python gmaker = molgrid.GridMaker() dims = gmaker.grid_dimensions(e.num_types()) tensor_shape = (batch_size,)+dims model = create_model(dims) ``` -------------------------------- ### initialize Source: https://gnina.github.io/libmolgrid/cpp/index.html Configures or re-initializes the grid settings for an existing GridMaker instance. ```APIDOC ## initialize(float res, float d, bool bin, float rscale, float grm) ### Description Sets the grid configuration parameters for the GridMaker instance. ### Parameters - **res** (float) - Resolution of grid in Angstroms. - **d** (float) - Dimension of cubic grid side in Angstroms. - **bin** (bool) - Indicates if binary density should be used. - **rscale** (float) - Scaling factor applied to all input radii. - **grm** (float) - Gaussian radius multiplier. ``` -------------------------------- ### ExampleProvider::reset Source: https://gnina.github.io/libmolgrid/cpp/index.html Resets the provider to the beginning of the dataset. ```APIDOC ## void reset() ### Description Resets the internal state of the provider to the beginning of the example set. ``` -------------------------------- ### Configure environment and data paths Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_Tensorflow.html Sets random seeds and defines the batch size and data directory path. ```python molgrid.set_random_seed(0) np.random.seed(0) batch_size = 50 datadir = os.getcwd() +'/../data' fname = datadir+"/small.types" ``` -------------------------------- ### Create model and optimizer Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Instantiates the CNN model and the Adam optimizer. ```python #create model model = CNN(gmaker, type_radii=batch_radii, n_types=1, n_latent=100, n_atoms=n_atoms).to('cuda') model.apply(weight_init) optimizer = optim.Adam(model.parameters(), lr=.0005) ``` -------------------------------- ### Construct Optimizer Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Initialize the SGD optimizer with model parameters. ```python # construct optimizer optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9) ``` -------------------------------- ### Define loss and initialization functions Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Defines the out-of-box loss function and weight initialization strategy. ```python def out_of_box_loss(c, max_val): '''hingey loss at box boundaries''' return (0.1*F.relu(abs(c)-max_val)).sum() ``` ```python def weight_init(m): if isinstance(m, nn.Conv3d) or isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight.data) ``` -------------------------------- ### Train with Coordinate Warm-up Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Performs training using a progressive range of coordinate values to improve convergence. ```python #size radii for batches batch_radii = torch.tensor(np.tile(radii, (batch_size, 1)), dtype=torch.float32, device='cuda') fig = plt.figure(figsize=(10,4)) ax = plt.gca() ax.plot(grid_losses, label='grid loss') ax.plot(oob_losses, label='oob loss') ax.legend(loc=1) ax.set_xlabel('iteration') scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=400, gamma=0.1) for maxcoord in [4,6,8,8,8]: for iter in range(100): try: optimizer.zero_grad() origcoords = torch.rand(batch_size,n_atoms,3,device='cuda')*2*maxcoord-maxcoord for i in range(batch_size): gmaker.forward((0,0,0), origcoords[i], origtypes[i], batch_radii[i], grid_true[i]) coords, types, grid_gen = model(grid_true) grid_loss = F.mse_loss(grid_true, grid_gen) oob_loss = out_of_box_loss(coords, max_val=11.5) grid_loss /= start_grid_loss loss = grid_loss + oob_loss loss.backward() grid_losses.append(min(float(grid_loss),100)) # for viz oob_losses.append(min(float(oob_loss),2)) #for viz optimizer.step() scheduler.step() if iter % 10 == 0: x = len(grid_losses) ax.get_lines()[0].set_data(range(x), grid_losses) ax.get_lines()[1].set_data(range(x), oob_losses) ax.set_xlim(0, x) ax.set_ylim(get_ylim(grid_losses + oob_losses )) display.display(fig) display.clear_output(wait=True) except KeyboardInterrupt: print('interrupted') break ``` -------------------------------- ### GninaIndexTyper Constructor Source: https://gnina.github.io/libmolgrid/cpp/index.html Initializes a new instance of the GninaIndexTyper class. ```APIDOC ## GninaIndexTyper(bool usec, const info *d) ### Description Creates a gnina typer instance. ### Parameters - **usec** (bool) - [in] - Whether to use the gnina determined covalent radius. ``` -------------------------------- ### FileMappedGninaTyper Constructor Source: https://gnina.github.io/libmolgrid/cpp/index.html Initializes a new instance of the FileMappedGninaTyper class using a file path or input stream. ```APIDOC ## FileMappedGninaTyper(const std::string &fname, bool usec = false) ## FileMappedGninaTyper(const GninaIndexTyper &etyper, const std::string &fname) ## FileMappedGninaTyper(std::istream &i, bool usec = false) ## FileMappedGninaTyper(const GninaIndexTyper &etyper, std::istream &i) ### Description Constructs a FileMappedGninaTyper object. It can be initialized from a file path or an input stream, optionally specifying a GninaIndexTyper and a usec flag. ``` -------------------------------- ### molgrid.ExampleProvider.reset Source: https://gnina.github.io/libmolgrid/python/index.html Resets the internal iterator of the provider to the beginning. ```APIDOC ## reset() ### Description Resets the iterator to the beginning of the dataset. ``` -------------------------------- ### Initialize GridMaker Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Configure the GridMaker to determine input tensor dimensions. ```python # initialize libmolgrid GridMaker gmaker = molgrid.GridMaker() dims = gmaker.grid_dimensions(e.num_types()) tensor_shape = (batch_size,)+dims ``` -------------------------------- ### ManagedGrid Indexing and Cloning Source: https://gnina.github.io/libmolgrid/cpp/index.html Methods for bracket indexing and cloning a ManagedGrid instance. ```cpp inline subgrid_t operator[](size_t i) const; ``` ```cpp inline ManagedGrid clone() const; ``` -------------------------------- ### Import required libraries Source: https://gnina.github.io/libmolgrid/tutorials/custom_atom_typer_example.html Imports necessary modules for molecule handling and molgrid integration. ```python import torch ``` ```python import molgrid ``` ```python from openbabel import pybel ``` -------------------------------- ### Import dependencies Source: https://gnina.github.io/libmolgrid/tutorials/train_simple_cartesian_reduction.html Imports necessary libraries for the molgrid and PyTorch environment. ```python import molgrid import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt import seaborn as sns import os ``` -------------------------------- ### Set Constants and Seeds Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Configure batch size, data paths, and random seeds for reproducibility. ```python # set some constants batch_size = 50 datadir = os.getcwd() +'/data' fname = datadir+"/small.types" molgrid.set_random_seed(0) torch.manual_seed(0) np.random.seed(0) ``` -------------------------------- ### libmolgrid::StringCache::get Source: https://gnina.github.io/libmolgrid/cpp/index.html Retrieves a string from the cache. ```APIDOC ## const char *get(const std::string &s) ### Description Retrieves a pointer to a cached string representation. ### Parameters - **s** (const std::string &) - The string to retrieve from the cache. ``` -------------------------------- ### Import Dependencies Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Required imports for libmolgrid, PyTorch, and visualization tools. ```python import molgrid import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.nn import init import os import matplotlib.pyplot as plt ``` -------------------------------- ### ManagedGrid Constructors Source: https://gnina.github.io/libmolgrid/cpp/index.html Default and variadic constructors for initializing ManagedGrid. ```cpp ManagedGrid() = default; ``` ```cpp template::type> inline ManagedGrid(I... sizes); ``` -------------------------------- ### molgrid.torch_bindings.MolDataset Source: https://gnina.github.io/libmolgrid/python/index.html A PyTorch mappable dataset for molgrid training files. ```APIDOC ## class molgrid.torch_bindings.MolDataset(*args, **kwargs) ### Description A PyTorch mappable dataset for molgrid training files. It supports various initialization parameters like typers, cache_structs, and data_root. ### Static Methods - **collateMolDataset(batch)**: A collate_fn for use in torch.utils.data.Dataloader. Returns lengths, centers, coords, types, radii, and labels padded to fit the maximum size of the batch. ``` -------------------------------- ### clone() Source: https://gnina.github.io/libmolgrid/cpp/index.html Creates and returns a copy of the current ManagedGrid. ```APIDOC ## clone() ### Description Returns a deep copy of the current ManagedGrid object. ### Returns - **ManagedGrid** - A new instance containing the same data as the original. ``` -------------------------------- ### Model Summary Output Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html The printed representation of the initialized model. ```text Net( (pool0): MaxPool3d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv1): Conv3d(28, 32, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) (pool1): MaxPool3d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv2): Conv3d(32, 64, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) (pool2): MaxPool3d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv3): Conv3d(64, 128, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) (fc1): Linear(in_features=27648, out_features=2, bias=True) ) ``` -------------------------------- ### molgrid.read_dx(arg1) Source: https://gnina.github.io/libmolgrid/python/index.html Reads a DX formatted grid file and returns an initialized grid object. ```APIDOC ## molgrid.read_dx(arg1) ### Description Read in dx formatted grid and return initialized grid. ### Parameters - **arg1** (str) - The filename of the DX grid. ``` -------------------------------- ### Create CoordinateSet Source: https://gnina.github.io/libmolgrid/tutorials/grid_single_molecule.html Convert the Pybel molecule into a molgrid CoordinateSet. ```python mol = pybel.readstring('sdf',sdf) c = molgrid.CoordinateSet(mol) ``` -------------------------------- ### Construct Input Tensors Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Pre-allocate GPU tensors for input data and labels. ```python # construct input tensors input_tensor = torch.zeros(tensor_shape, dtype=torch.float32, device='cuda') float_labels = torch.zeros(batch_size, dtype=torch.float32) ``` -------------------------------- ### Define Weight Initialization Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_PyTorch.html Helper function to apply Xavier uniform initialization to convolutional and linear layers. ```python # define weight initialization def weights_init(m): if isinstance(m, nn.Conv3d) or isinstance(m, nn.Linear): init.xavier_uniform_(m.weight.data) ``` -------------------------------- ### tonumpy Source: https://gnina.github.io/libmolgrid/python/index.html Returns a numpy array copy of the grid. ```APIDOC ## tonumpy() ### Description Return a numpy array copy of grid g. ``` -------------------------------- ### Execute training loop Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_Tensorflow.html Iterates through batches, performs forward passes, and updates the model weights. ```python losses = [] # train for 500 iterations for iteration in range(500): # load data batch = e.next_batch(batch_size) gmaker.forward(batch, input_tensor, 0, random_rotation=True) batch.extract_label(0, labels) loss = model.train_on_batch(input_tensor.tonumpy(), labels.tonumpy()) losses.append(float(loss)) ``` -------------------------------- ### CoordCache(std::shared_ptr t, const ExampleProviderSettings &settings, const std::string &mc) Source: https://gnina.github.io/libmolgrid/cpp/index.html Constructs a new CoordCache instance with the specified atom typer, settings, and optional cache file path. ```APIDOC ### Constructor `CoordCache(std::shared_ptr t, const ExampleProviderSettings &settings, const std::string &mc = "")` ### Description Initializes the coordinate cache with an atom typer and configuration settings. Optionally accepts a path to a precalculated molcache2 file for memory mapping. ``` -------------------------------- ### Create molecule Source: https://gnina.github.io/libmolgrid/tutorials/custom_atom_typer_example.html Initializes a simple molecule from a SMILES string and adds hydrogens. ```python # create simple molecule m = pybel.readstring('smi','C') m.addh() ``` -------------------------------- ### Forward pass methods for GridMaker Source: https://gnina.github.io/libmolgrid/cpp/index.html Methods to compute the forward pass for grid generation, supporting different input configurations and device types. ```cpp template void forward(float3 grid_center, const Grid &coords, const Grid &type_vector, const Grid &radii, Grid &out) const ``` ```cpp template inline void forward(const Grid ¢ers, const Grid &coords, const Grid &types, const Grid &radii, Grid &out) const ``` -------------------------------- ### make_ndarray Source: https://gnina.github.io/libmolgrid/python/index.html Creates an appropriately sized numpy array of grid densities. ```APIDOC ## make_ndarray(center, c) ### Description Create appropriately sized numpy array of grid densities. ``` -------------------------------- ### ManagedGrid(I... sizes) Source: https://gnina.github.io/libmolgrid/cpp/index.html Constructs a new ManagedGrid with the specified dimensions. ```APIDOC ## ManagedGrid(I... sizes) ### Description Constructs a dense grid with the specified dimensions. Memory is allocated as unified memory for CPU/GPU access. ### Parameters - **sizes** (variadic) - Required - The dimensions of the grid. ``` -------------------------------- ### molgrid.set_gpu_enabled(arg1) Source: https://gnina.github.io/libmolgrid/python/index.html Configures whether generated grids should be on the GPU by default. ```APIDOC ## molgrid.set_gpu_enabled(arg1) ### Description Set if generated grids should be on GPU by default. ### Parameters - **arg1** (bool) - Enable or disable GPU usage. ``` -------------------------------- ### SubsettedGninaTyper Constructor Source: https://gnina.github.io/libmolgrid/cpp/index.html Initializes a new instance of the SubsettedGninaTyper class. ```APIDOC ## SubsettedGninaTyper(const std::vector &map, bool include_catchall = true, bool usec = false) ### Description Initializes the typer with a mapping vector. ### Parameters - **map** (const std::vector &) - Required - Mapping vector. - **include_catchall** (bool) - Optional - Whether to include a catchall type. - **usec** (bool) - Optional - Use C flag. ``` -------------------------------- ### molgrid.set_gpu_device(arg1) Source: https://gnina.github.io/libmolgrid/python/index.html Sets the current GPU device to be used. ```APIDOC ## molgrid.set_gpu_device(arg1) ### Description Set current GPU device. ### Parameters - **arg1** (int) - The GPU device index. ``` -------------------------------- ### molgrid.get_gpu_device() Source: https://gnina.github.io/libmolgrid/python/index.html Returns the index of the current GPU device. ```APIDOC ## molgrid.get_gpu_device() ### Description Get the current GPU device index. ### Returns - **int** - The index of the current GPU device. ``` -------------------------------- ### tocpu / togpu Source: https://gnina.github.io/libmolgrid/python/index.html Sets memory affinity for a CoordinateSet to CPU or GPU. ```APIDOC ## tocpu(arg1, arg2) ## togpu(arg1, arg2) ### Description Sets the memory affinity of the CoordinateSet to either CPU or GPU. ### Parameters - **arg1** (CoordinateSet) - Required - The coordinate set. - **arg2** (bool) - Required - Affinity flag. ``` -------------------------------- ### libmolgrid::FileMappedElementTyper Source: https://gnina.github.io/libmolgrid/cpp/index.html A class for file-mapped element types, providing convenient initialization for atom typing. ```APIDOC ## FileMappedElementTyper ### Constructors - `FileMappedElementTyper(const std::string &fname, unsigned maxe = 84)` - `FileMappedElementTyper(const ElementIndexTyper &etyper, const std::string &fname)` - `FileMappedElementTyper(std::istream &i, unsigned maxe = 84)` - `FileMappedElementTyper(const ElementIndexTyper &etyper, std::istream &i)` ### Methods - `unsigned num_types() const`: Returns the number of types. - `std::pair get_atom_type_index(OpenBabel::OBAtom *a) const`: Returns the type index of a given OpenBabel atom. - `std::pair get_int_type(int t) const`: Returns the type and radius given a precomputed type. - `std::vector get_type_names() const`: Returns a vector of string representations of types. - `std::vector get_type_radii() const`: Returns the standard atomic radius of each type. - `bool is_vector_typer() const`: Checks if the typer is a vector typer. ``` -------------------------------- ### molgrid.torch_bindings.tensor_as_grid Source: https://gnina.github.io/libmolgrid/python/index.html Returns a Grid view of a tensor. ```APIDOC ## molgrid.torch_bindings.tensor_as_grid(t) ### Description Return a Grid view of the provided tensor t. ``` -------------------------------- ### operator[](size_t i) Source: https://gnina.github.io/libmolgrid/cpp/index.html Provides bracket indexing for the grid, returning a subgrid. ```APIDOC ## operator[](size_t i) ### Description Accesses the grid using bracket indexing. This method performs index checking for safety. ### Parameters - **i** (size_t) - Required - The index to access. ### Returns - **subgrid_t** - A subgrid corresponding to the index. ``` -------------------------------- ### void set_coords(const char *fname, CoordinateSet &coord) Source: https://gnina.github.io/libmolgrid/cpp/index.html Populates a CoordinateSet object with data from the specified molecular file. ```APIDOC ### Method `void set_coords(const char *fname, CoordinateSet &coord)` ### Description Loads molecular data from the specified file name into the provided CoordinateSet object. ### Parameters - **fname** (const char*) - [in] The file name of the molecular data, excluding the root directory prefix. - **coord** (CoordinateSet&) - [out] The CoordinateSet object to be populated. ``` -------------------------------- ### molgrid.torch_bindings.make_grid_tensor Source: https://gnina.github.io/libmolgrid/python/index.html Creates a PyTorch tensor of grid densities. ```APIDOC ## molgrid.torch_bindings.make_grid_tensor(gridmaker, center, c) ### Description Create an appropriately sized PyTorch tensor of grid densities. The result location (CPU or GPU) can be controlled via set_gpu_enabled. ``` -------------------------------- ### Plot training loss Source: https://gnina.github.io/libmolgrid/tutorials/train_basic_CNN_with_Tensorflow.html Visualizes the training loss history. ```python plt.plot(losses) ``` -------------------------------- ### molgrid.torch_bindings.Coords2Grid Source: https://gnina.github.io/libmolgrid/python/index.html A PyTorch Module that converts coordinates, types, and radii into a grid using a provided GridMaker. ```APIDOC ## class molgrid.torch_bindings.Coords2Grid(gmaker, center=(0, 0, 0)) ### Description Converts coordinates, types, and radii to a grid using the provided GridMaker and grid center. ### Methods - **forward(coords, types, radii)**: Defines the computation performed at every call. ``` -------------------------------- ### molgrid.get_gpu_enabled() Source: https://gnina.github.io/libmolgrid/python/index.html Checks if generated grids are placed on the GPU by default. ```APIDOC ## molgrid.get_gpu_enabled() ### Description Get if generated grids are on GPU by default. ### Returns - **bool** - True if GPU is enabled, False otherwise. ``` -------------------------------- ### forward Source: https://gnina.github.io/libmolgrid/python/index.html Generates grid tensors from batched atomic data. The grid must be properly sized before calling this method. ```APIDOC ## forward(centers, coordinates, type, radii, a) ### Description Generates grid tensors from batched atomic data. The grid must be properly sized. ### Parameters - **centers** (Bx3) - Grid centers - **coordinates** (BxNx3) - Atomic coordinates - **type** (BxNxT or BxN) - Vectors or type indices - **radii** (BxN or BxT) - Atomic radii - **a** (5D grid) - Output grid tensor ``` -------------------------------- ### Backward pass methods for GridMaker Source: https://gnina.github.io/libmolgrid/cpp/index.html Methods to compute the backward pass, calculating atomic and type gradients based on input coordinates and grid differences. ```cpp template inline void backward(float3 grid_center, const CoordinateSet &in, const Grid &diff, Grid &atomic_gradients, Grid &type_gradients) const ``` ```cpp template inline void backward(float3 grid_center, const CoordinateSet &in, const Grid &diff, Grid &atomic_gradients) const ``` ```cpp template inline void backward(float3 grid_center, const CoordinateSet &in, const Grid &diff, Grid &atomic_gradients, Grid &type_gradients) const ``` ```cpp template inline void backward(float3 grid_center, const CoordinateSet &in, const Grid &diff, Grid &atomic_gradients) const ``` ```cpp template void backward(float3 grid_center, const Grid &coords, const Grid &type_index, const Grid &radii, const Grid &diff, Grid &atom_gradients) const ``` ```cpp template void backward(float3 grid_center, const Grid &coords, const Grid &type_index, const Grid &radii, const Grid &grid, Grid &atom_gradients) const ``` ```cpp template void backward(float3 grid_center, const Grid &coords, const Grid &type_vectors, const Grid &radii, const Grid &diff, Grid &atom_gradients, Grid &type_gradients) const ``` ```cpp template void backward(float3 grid_center, const Grid &coords, const Grid &type_vectors, const Grid &radii, const Grid &grid, Grid &atom_gradients, Grid &type_gradients) const ``` -------------------------------- ### Transform::forward Source: https://gnina.github.io/libmolgrid/cpp/index.html Applies the stored transformation to the input data and writes the result to the output. ```APIDOC ## void forward(const Grid &in, Grid &out, bool dotranslate = true) const ### Description Applies the transformation to a 2D grid. The transformation can be applied with or without translation. ### Parameters - **in** (const Grid &) - The input grid. - **out** (Grid &) - The output grid. - **dotranslate** (bool) - Whether to include translation in the transformation (default: true). ``` -------------------------------- ### Generate grid Source: https://gnina.github.io/libmolgrid/tutorials/grid_single_molecule.html Populate the grid tensor using the CoordinateSet. ```python gmaker.forward(c.center(),c,gridtensor) ``` -------------------------------- ### CallbackIndexTyper Constructor Source: https://gnina.github.io/libmolgrid/cpp/index.html Initializes a new instance of the CallbackIndexTyper class with a custom typing function and optional type names. ```APIDOC ## CallbackIndexTyper(AtomIndexTyperFunc f, unsigned ntypes, const std::vector &names) ### Description Initializes the callback typer. If names are not provided, numerical names will be generated. ### Parameters - **f** (AtomIndexTyperFunc) - Required - A function that takes an OpenBabel::OBAtom and returns a pair of (int, float). - **ntypes** (unsigned) - Required - The number of types. - **names** (const std::vector&) - Optional - A vector of strings representing the names of the types. ``` -------------------------------- ### GridMaker.backward Source: https://gnina.github.io/libmolgrid/python/index.html Generates atom and type gradients from grid gradients. Multiple overloads exist for CPU/GPU and different input types. ```APIDOC ## backward(...) ### Description Calculates atomic gradients from grid gradients. Requires the original coordinates or grid state used in the forward pass. ### Parameters - **center** (float3) - Required - Center of the grid - **coordinate_set** (CoordinateSet) - Required - Original coordinate set - **grid_gradients** (Grid4f/Grid4fCUDA) - Required - 4D grid of gradients - **atomic_gradients** (Grid2f/Grid2fCUDA) - Required - Vector quantities for each atom - **type_gradients** (Grid2f/Grid2fCUDA) - Optional - Type gradients (only if input has type vectors) ``` -------------------------------- ### backward Source: https://gnina.github.io/libmolgrid/python/index.html Generates atom and type gradients from grid gradients. Requires atom coordinates, types, and radii that defined the original grid in the forward pass. ```APIDOC ## backward(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) ### Description Generate atom and type gradients from grid gradients. This method is available for both CPU and GPU (via Grid2fCUDA/Grid1fCUDA/Grid4fCUDA types). ### Parameters - **arg1** (GridMaker) - The GridMaker instance. - **arg2** (float3) - Center of the grid. - **arg3** (Grid2f) - Coordinates (Nx3). - **arg4** (Grid2f) - Type vectors (NxT). - **arg5** (Grid1f) - Radii. - **arg6** (Grid4f) - 4D grid of gradients. - **arg7** (Grid2f) - Atomic gradients (vector quantities for each atom). - **arg8** (Grid2f) - Type gradients (vector quantities for each atom). ``` -------------------------------- ### make_tensor Source: https://gnina.github.io/libmolgrid/python/index.html Creates an appropriately sized pytorch tensor of grid densities. ```APIDOC ## make_tensor(center, c) ### Description Create appropriately sized pytorch tensor of grid densities. set_gpu_enabled can be used to control if result is located on the cpu or gpu. ```