### Install torch_topological from source with poetry Source: https://github.com/aidos-lab/pytorch-topological/blob/main/docs/source/usage.rst Clone the repository and install the package from source using poetry. Requires a virtual environment manager capable of parsing pyproject.toml files. ```console $ git clone git@github.com:aidos-lab/pytorch-topological.git $ cd pytorch-topological $ poetry install ``` -------------------------------- ### Install with Poetry Source: https://github.com/aidos-lab/pytorch-topological/blob/main/README.md Recommended installation method using the Poetry dependency manager. Requires Python 3.9 for the smoothest experience. ```bash poetry add torch-topological ``` -------------------------------- ### Install with pip Source: https://github.com/aidos-lab/pytorch-topological/blob/main/README.md Alternative installation method using pip. Upgrades to the latest version of the package. ```bash pip install -U torch-topological ``` -------------------------------- ### Install torch_topological via pip Source: https://github.com/aidos-lab/pytorch-topological/blob/main/docs/source/usage.rst Install the latest release version of torch_topological using pip. It is recommended to use a virtual environment manager such as poetry for handling project dependencies. ```console $ pip install torch_topological ``` -------------------------------- ### sample_from_disk usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/data-shapes.md Example of sampling 200 points from an annulus with inner radius 0.5 and outer radius 0.7 using a fixed seed. Returns a torch.Tensor of shape (n, 2). ```python from torch_topological.data import sample_from_disk X = sample_from_disk(n=200, r=0.5, R=0.7, seed=42) assert X.shape == (200, 2) ``` -------------------------------- ### VietorisRipsComplex usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Example usage of VietorisRipsComplex. Computes dim 0 and dim 1 homology for a batch of two point clouds, and demonstrates using pre-computed distance matrices with treat_as_distances=True. ```python from torch_topological.nn import VietorisRipsComplex # Batch of two point clouds; compute dim 0 and dim 1 homology. vr = VietorisRipsComplex(dim=1) pers_infos = vr(torch.rand(2, 50, 3)) # Use pre-computed distance matrices instead: dists = torch.cdist(torch.rand(50, 3), torch.rand(50, 3)) pi = vr(dists, treat_as_distances=True) ``` -------------------------------- ### MultiScaleKernel usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Example of using MultiScaleKernel with VietorisRipsComplex. Samples two disks, computes the kernel value, and shows the maximum-norm variant with `p=float('inf')`. Norms other than 2 are not guaranteed positive-definite. ```python from torch_topological.data import sample_from_disk from torch_topological.nn import MultiScaleKernel, VietorisRipsComplex x = sample_from_disk(r=0.5, R=0.6, n=100) y = sample_from_disk(r=0.9, R=1.0, n=100) vr = VietorisRipsComplex(dim=1) msk = MultiScaleKernel(1.) value = msk(vr(x), vr(y)) # scalar tensor # Maximum-norm variant: value_inf = msk(vr(x), vr(y), p=float('inf')) ``` -------------------------------- ### sample_from_unit_cube usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/data-shapes.md Example of sampling 100 points from a 5-dimensional unit cube. Returns a torch.Tensor of shape (n, d). ```python from torch_topological.data import sample_from_unit_cube X = sample_from_unit_cube(100, d=5) # (100, 5) ``` -------------------------------- ### General PyTorch training loop structure Source: https://github.com/aidos-lab/pytorch-topological/blob/main/docs/source/examples/summary_statistics.rst Shows the typical structure of a PyTorch training loop: set up an optimizer, iterate, compute loss, zero gradients, backpropagate, and step. This is a generic pattern referenced in the example. ```default # Set up your favourite optimiser opt = optim.SGD(...) for i in range(100): # Do some calculations and obtain a loss term. In our specific # example, we have to get persistence information from data and # evaluate the loss based on that. loss = ... # This is what you will see in many such examples: we set all # gradients to zero and do a backwards pass. opt.zero_grad() loss.backward() opt.step() ``` -------------------------------- ### p_norm usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils-summary-statistics.md Example of computing the p-norm with p=2. p_norm is only importable from torch_topological.utils.summary_statistics, not from the top-level package. ```python from torch_topological.utils.summary_statistics import p_norm # not in top-level __all__ D = torch.tensor([[0.0, 1.0], [0.5, 0.9]]) print(p_norm(D, p=2)) ``` -------------------------------- ### make_tensor usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-data.md Shows how to use make_tensor with a VietorisRipsComplex to convert a batch of point clouds into a dense tensor of shape (8, N, 3). ```python from torch_topological.nn import VietorisRipsComplex from torch_topological.nn.data import make_tensor vr = VietorisRipsComplex(dim=1) X = torch.rand(8, 32, 2) # batch of 8 point clouds dense = make_tensor(vr(X)) # shape (8, N, 3) ``` -------------------------------- ### create_sphere_dataset usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/datasets.md Generates a SPHERES dataset with 100 samples per sphere, 5 spheres, dimension 50, radius 5, and seed 3, then prints the shape and unique labels. ```python import numpy as np from torch_topological.datasets.spheres import create_sphere_dataset X, y = create_sphere_dataset(n_samples=100, n_spheres=5, d=50, r=5, seed=3) print(X.shape, np.unique(y)) # (1400, 51), labels 0..4 ``` -------------------------------- ### SlicedWassersteinKernel usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Example showing how to instantiate SlicedWassersteinKernel with 20 directions and sigma=2.0, then apply it to VietorisRipsComplex diagrams of random 2D points (dim=1). Returns a scalar tensor representing the kernel value. ```python from torch_topological.nn import SlicedWassersteinKernel, VietorisRipsComplex swk = SlicedWassersteinKernel(num_directions=20, sigma=2.0) vr = VietorisRipsComplex(dim=1) k = swk(vr(torch.rand(30, 2)), vr(torch.rand(30, 2))) ``` -------------------------------- ### sample_from_torus usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/data-shapes.md Imports and calls sample_from_torus to generate 300 points on a torus with tube radius 1.0 and torus radius 2.0, producing a tensor of shape (300, 3). ```python from torch_topological.data import sample_from_torus T = sample_from_torus(300, r=1.0, R=2.0, seed=1) # (300, 3) ``` -------------------------------- ### batch_handler usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-data.md Shows how to use batch_handler with a custom handler function that sums each point cloud. It processes a single point cloud and a batch of point clouds. ```python from torch_topological.nn.data import batch_handler def handle_point_cloud(x): return x.sum(dim=0) single = batch_handler(torch.rand(10, 3), handle_point_cloud) batch = batch_handler(torch.rand(4, 10, 3), handle_point_cloud) ``` -------------------------------- ### batch_iter usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-data.md Demonstrates iterating over batches of persistence information, filtering by dimension and printing dimensions. ```python from torch_topological.nn import VietorisRipsComplex from torch_topological.nn.data import batch_iter vr = VietorisRipsComplex(dim=1) pi_batch = vr(torch.rand(4, 64, 2)) for batch in batch_iter(pi_batch, dim=1): for pi in batch: assert pi.dimension == 1 # Or iterate all dimensions: for batch in batch_iter(pi_batch): for pi in batch: print(pi.dimension) ``` -------------------------------- ### Topological classifier example using StructureElementLayer Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-layers.md Example from torch_topological/examples/classification.py showing a topological classifier over dense persistence tensors. Uses StructureElementLayer, VietorisRipsComplex, and make_tensor to produce logits. ```python import torch from torch_topological.nn import VietorisRipsComplex from torch_topological.nn.layers import StructureElementLayer from torch_topological.nn.data import make_tensor class TopologicalModel(torch.nn.Module): def __init__(self, n_elements, latent_dim=64, output_dim=2): super().__init__() self.model = torch.nn.Sequential( StructureElementLayer(n_elements), torch.nn.Linear(n_elements, latent_dim), torch.nn.ReLU(), torch.nn.Linear(latent_dim, output_dim), ) self.vr = VietorisRipsComplex(dim=0) def forward(self, x): pers_info = self.vr(x) pers_info = make_tensor(pers_info) # (B, N, 3) return self.model(pers_info) model = TopologicalModel(n_elements=10) out = model(torch.rand(8, 32, 2)) # (8, 2) logits ``` -------------------------------- ### CubicalComplex usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Example of creating a CubicalComplex and computing persistence diagrams for a single image and volume data. For single images, dim is not set; for volumes, dim=3 handles batch and channel dimensions explicitly. ```python from torch_topological.nn import CubicalComplex image = torch.rand(32, 32) # single image cc = CubicalComplex() pi = cc(image) # list over dims 0..1 pi0 = pi[0].diagram # Volume data: batches are handled explicitly via dim=3. vol_cc = CubicalComplex(dim=3) pi_vol = vol_cc(torch.rand(2, 3, 16, 16, 16)) # (batch, channel, 16,16,16) ``` -------------------------------- ### AlphaComplex usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Example of instantiating AlphaComplex with p=2 and computing persistence on a random 2D point cloud. The result is a list over dimensions 0..1, with the diagram accessible via pi[0].diagram. ```python from torch_topological.nn import AlphaComplex alpha = AlphaComplex(p=2) pi = alpha(torch.rand(100, 2)) # list over dims 0..1 pi_dim0 = pi[0].diagram ``` -------------------------------- ### SignatureLoss usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-losses.md Example of using SignatureLoss with a VietorisRipsComplex. Creates random point clouds, computes persistence information, and calculates the loss. The loss is differentiable and supports backward propagation. ```python from torch_topological.nn import SignatureLoss, VietorisRipsComplex import torch vr = VietorisRipsComplex(dim=0) x = torch.rand(30, 2, requires_grad=True) z = torch.rand(30, 2, requires_grad=True) pi_x = vr(x) pi_z = vr(z) loss_fn = SignatureLoss(p=2, dimensions=0, normalise=True) loss = loss_fn((x, pi_x), (z, pi_z)) # scalar, differentiable loss.backward() ``` -------------------------------- ### Using nesting_level Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Example usage of nesting_level to assert nesting levels for flat and nested lists, and non-list input. ```python from torch_topological.utils import nesting_level assert nesting_level([1, 2, 3]) == 1 assert nesting_level([[1, 2], [3, 4]]) == 2 assert nesting_level("x") == 0 ``` -------------------------------- ### make_tensor_from_persistence_information usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-data.md Shows how to use make_tensor_from_persistence_information with a CubicalComplex to convert persistence information into a tensor, optionally extracting generator indices. ```python from torch_topological.nn import CubicalComplex from torch_topological.nn.data import make_tensor_from_persistence_information cc = CubicalComplex() pi = cc(torch.rand(16, 16))[0] # dimension-0 persistence info t = make_tensor_from_persistence_information(pi) gens = make_tensor_from_persistence_information(pi, extract_generators=True) ``` -------------------------------- ### LowerStarPersistence simple graph usage Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Example using a simple 2-vertex graph with a lower star filtration. clip_inf=True clips essential feature destruction to the filtration maximum. ```python import torch from torch_topological.nn import LowerStarPersistence # Simple 2-vertex graph: x = (num_vertices, edge_index) x = (2, torch.tensor([[0, 1]]).T) filtration = torch.tensor([0.0, 1.0]) lsp = LowerStarPersistence(clip_inf=True) pi = lsp(x, filtration) ``` -------------------------------- ### sample_from_sphere usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/data-shapes.md Imports and calls sample_from_sphere to generate 500 points on a 2-sphere with radius 2.0 and noise 0.05, then asserts the output shape is (500, 3). ```python from torch_topological.data import sample_from_sphere S = sample_from_sphere(n=500, d=2, r=2.0, noise=0.05, seed=7) assert S.shape == (500, 3) ``` -------------------------------- ### Using SelectByDimension with loss functions Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Example usage of SelectByDimension to restrict a loss to a single dimension, here maximising 1D persistence with SummaryStatisticLoss. ```python from torch_topological.nn import AlphaComplex, SummaryStatisticLoss from torch_topological.utils import SelectByDimension selector = SelectByDimension(1) loss_fn = SummaryStatisticLoss(summary_statistic='polynomial_function', p=2, q=0) pi = AlphaComplex()(X) loss = -loss_fn(selector(pi)) # maximise 1D persistence ``` -------------------------------- ### Using pairwise Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Example usage of pairwise to iterate over consecutive pairs from a list. Outputs (1,2) (2,3) (3,4). ```python from torch_topological.utils import pairwise for a, b in pairwise([1, 2, 3, 4]): print(a, b) # (1,2) (2,3) (3,4) ``` -------------------------------- ### sample_from_annulus usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/data-shapes.md Imports sample_from_annulus from torch_topological.data and samples 250 points from an annulus with inner radius 1.0 and outer radius 2.5, using seed 0. Returns a torch.Tensor of shape (250, 2). ```python from torch_topological.data import sample_from_annulus A = sample_from_annulus(250, r=1.0, R=2.5, seed=0) # (250, 2) ``` -------------------------------- ### Minimal usage of TopoGCN with torch_geometric data Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-graphs.md Example of creating a graph data object and running the TopoGCN model. The output shape is (1, 2) for a single graph. ```python # Minimal usage with torch_geometric data. from torch_geometric.data import Data from torch_geometric.utils import erdos_renyi_graph import torch from torch_topological.nn.graphs import TopoGCN data = Data(x=torch.rand(20, 1), edge_index=erdos_renyi_graph(20, 0.2), num_nodes=20) data.batch = torch.zeros(20, dtype=torch.long) model = TopoGCN() out = model(data) # (1, 2) ``` -------------------------------- ### embed usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/data-shapes.md Imports embed from torch_topological.data.utils and embeds a random 100x3 numpy array into 10 dimensions, producing a (100, 10) randomly rotated array. ```python import numpy as np from torch_topological.data.utils import embed X = np.random.rand(100, 3) Y = embed(X, ambient=10) # (100, 10), randomly rotated ``` -------------------------------- ### Basic usage with diagrams as tensors Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-perslay.md Creates a PersLay layer that processes a batch of persistence diagrams given as tensors. The example uses a batch of 4 diagrams with 20 points each, a permutation-equivariant point transform, sum operation, and outputs a tensor of shape (4, 16). ```python import torch from torch_topological.nn import PersLay diagrams = torch.rand(4, 20, 2) # batch of 4 diagrams, 20 points each layer = PersLay(output_dim=16, point_transform="PermutationEquivariant", op="sum", dim=0) out = layer(diagrams) # (4, 16) ``` -------------------------------- ### DeepSetLayer usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-graphs.md Instantiates DeepSetLayer with mean aggregation, creates random node features and a batch vector for two graphs of 12 nodes each, then runs a forward pass producing output of shape (24, 16). ```python import torch from torch_topological.nn.graphs import DeepSetLayer layer = DeepSetLayer(16, 16, "mean") x = torch.rand(24, 16) batch = torch.cat([torch.zeros(12, dtype=torch.long), torch.ones(12, dtype=torch.long)]) out = layer(x, batch) # (24, 16) ``` -------------------------------- ### SelectByDimension.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Initializes the SelectByDimension filter with minimum and optional maximum dimension. ```APIDOC ## `SelectByDimension.__init__` ### Description Initializes the filter with minimum and optional maximum dimension. ### Parameters - **min_dim** (int) - Required - Minimum dimension; if `max_dim` is `None`, only diagrams with `dimension == min_dim` pass - **max_dim** (int) - Optional - Optional upper bound; pass diagrams with `min_dim <= dimension <= max_dim` ### Returns None ``` -------------------------------- ### polynomial_function usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils-summary-statistics.md Example of computing the polynomial function with p=2 and q=0, yielding the sum of squared persistences. ```python from torch_topological.utils import polynomial_function D = torch.tensor([[0.0, 1.0], [0.1, 0.4]]) value = polynomial_function(D, p=2, q=0) # sum of squared persistences ``` -------------------------------- ### total_persistence usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils-summary-statistics.md Example of computing total persistence with p=2. The infinite entry is skipped, so the result is 1.0 + 0.25. ```python from torch_topological.utils import total_persistence D = torch.tensor([[0.0, 1.0], [2.0, 2.5], [1.0, torch.inf]]) tp = total_persistence(D, p=2) # 1.0 + 0.25 (infinite entry skipped) ``` -------------------------------- ### persistent_entropy usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils-summary-statistics.md Example of computing persistent entropy on a diagram with an infinite death value. The infinite entry is ignored. ```python import torch from torch_topological.utils import persistent_entropy D = torch.tensor([[0.0, 1.0], [0.5, 3.0], [2.0, torch.inf]]) entropy = persistent_entropy(D) ``` -------------------------------- ### Image.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-perslay.md Initializes a persistence image layer. The layer converts each point to (birth, persistence) and evaluates a Gaussian around each grid point. ```APIDOC ## Image.__init__ ### Description Initializes a persistence image layer. The layer converts each point to (birth, persistence) and evaluates a Gaussian around each grid point. ### Method Constructor ### Signature ```python def __init__(self, image_size, image_bnds=((-0.01, 1.01), (-0.01, 1.01))): ``` ### Parameters - `image_size` (tuple) - Required - Two positive integers: `(width, height)` of the output image (source indexes `image_size[1]` × `image_size[0]` parameters) - `image_bnds` (tuple of tuple) - Optional, default `((-0.01, 1.01), (-0.01, 1.01))` - Axis bounds of the image grid ``` -------------------------------- ### PersLay.__init__ signature Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-perslay.md Constructor for the PersLay layer. Requires output_dim, point_transform, and op; optional weight_fn, dim, k, and kwargs. Raises ValueError for invalid op or unknown point_transform, and TypeError for non-integer k when op is 'topk'. ```python def __init__( self, output_dim, point_transform, op, weight_fn=None, dim=0, k=None, **kwargs ): ``` -------------------------------- ### MultiScaleKernel.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Initializes the multi-scale kernel with a given scale parameter sigma. This constructor is required to create an instance of the kernel. ```APIDOC ## MultiScaleKernel.__init__ ### Description Initializes the multi-scale kernel with a given scale parameter sigma. This constructor is required to create an instance of the kernel. ### Method Constructor ### Signature ```python def __init__(self, sigma): ``` ### Parameters - **sigma** (float) - Required - Scale parameter of the kernel (no default; must be provided) ### Returns None ``` -------------------------------- ### SummaryStatisticLoss usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-losses.md Example of using SummaryStatisticLoss with a polynomial_function statistic. It creates VietorisRipsComplex persistence diagrams from random points, then computes the loss with p=2 and q=0. The loss is differentiable and supports backward(). ```python from torch_topological.nn import SummaryStatisticLoss, VietorisRipsComplex import torch vr = VietorisRipsComplex(dim=1) pi_x = vr(torch.rand(50, 2)) pi_y = vr(torch.rand(50, 2)) loss_fn = SummaryStatisticLoss( summary_statistic='polynomial_function', p=2, q=0 ) loss = loss_fn(pi_x, pi_y) # (stat(X) - stat(Y)).abs().pow(2) loss.backward() # differentiable ``` -------------------------------- ### WassersteinDistance usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Example of computing the 2-Wasserstein distance between two persistence diagrams. Creates VietorisRipsComplex with dim=1, generates random point clouds, and computes the scalar distance. ```python import torch from torch_topological.nn import VietorisRipsComplex, WassersteinDistance vr = VietorisRipsComplex(dim=1) x = torch.rand(50, 2) y = torch.rand(50, 2) loss = WassersteinDistance(q=2) # 2-Wasserstein distance dist = loss(vr(x), vr(y)) # scalar tensor ``` -------------------------------- ### SelectByDimension __init__ method Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Defines the __init__ method of the SelectByDimension filter. Takes min_dim and optional max_dim to filter persistence diagrams by dimension. ```python def __init__(self, min_dim, max_dim=None): ``` -------------------------------- ### VietorisRipsComplex Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/configuration.md Constructor parameters for the VietorisRipsComplex persistence calculator. ```APIDOC ## VietorisRipsComplex ### Description Constructor parameters for the VietorisRipsComplex persistence calculator. ### Parameters - **dim** (int) - Optional - Default: `1` - Compute homology up to (and including) this dimension. - **p** (float) - Optional - Default: `2` - Minkowski `p`-norm for pairwise distances (ignored with `treat_as_distances`). - **threshold** (float) - Optional - Default: `numpy.inf` - Only compute features below this distance threshold. - **keep_infinite_features** (bool) - Optional - Default: `False` - Keep essential (infinite) features. - **kwargs** - Optional - Extra `ripser_parallel` parameters (e.g. `n_threads`). ``` -------------------------------- ### SlicedWassersteinDistance usage example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Example showing how to instantiate SlicedWassersteinDistance with 20 directions and apply it to VietorisRipsComplex diagrams of random 2D points (dim=0). Returns a scalar tensor representing the distance. ```python from torch_topological.nn import SlicedWassersteinDistance, VietorisRipsComplex swd = SlicedWassersteinDistance(num_directions=20) vr = VietorisRipsComplex(dim=0) d = swd(vr(torch.rand(40, 2)), vr(torch.rand(40, 2))) ``` -------------------------------- ### SignatureLoss.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-losses.md Initializes the SignatureLoss instance with configurable parameters for the p-norm, normalization, and homology dimensions. ```APIDOC ## SignatureLoss.__init__ ### Description Initializes the SignatureLoss instance with configurable parameters for the p-norm, normalization, and homology dimensions. ### Method `__init__` ### Signature ```python def __init__(self, p=2, normalise=True, dimensions=0): ``` ### Parameters - **p** (`float`) - Optional, default `2` - Exponent of the `p`-norm for distance calculations (`torch.cdist` and `torch.linalg.vector_norm`). - **normalise** (`bool`) - Optional, default `True` - Divide pairwise distance matrices by their maximum (per point cloud). - **dimensions** (`int` or `tuple` of `int`) - Optional, default `0` - Homology dimensions used in the signature calculation; wrapped in a list if not iterable. ``` -------------------------------- ### SlicedWassersteinKernel.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Initializes the SlicedWassersteinKernel module with the number of directions for the internal distance and a sigma parameter for the kernel expression. ```APIDOC ## SlicedWassersteinKernel.__init__ ### Description Initializes the SlicedWassersteinKernel module with the number of directions for the internal distance and a sigma parameter for the kernel expression. ### Method Constructor ### Parameters - `num_directions` (int) - Optional, default: `10` - Directions for the internal `SlicedWassersteinDistance` - `sigma` (int) - Optional, default: `1.0` - Variance term of the kernel expression (documented as `int` in the source, used numerically) ### Request Example ```python swk = SlicedWassersteinKernel(num_directions=20, sigma=2.0) ``` ``` -------------------------------- ### LowerStarPersistence Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/configuration.md Constructor parameters for the LowerStarPersistence persistence calculator. ```APIDOC ## LowerStarPersistence ### Description Constructor parameters for the LowerStarPersistence persistence calculator. ### Parameters - **clip_inf** (bool) - Optional - Default: `False` - Clip essential-feature deaths to the max filtration value (else `torch.inf`). - **include_max_dim** (bool) - Optional - Default: `False` - Include homology of the highest dimension. - **list_of_lists** (bool) - Optional - Default: `True` - Return per-graph lists for PyG `Batch` input (vs `pairs_batch` tuples). - **kwargs** - Optional - Extra `gudhi.SimplexTree.compute_persistence` arguments. ``` -------------------------------- ### torch_topological.nn.layers Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/index.md Layer module with StructureElementLayer, used in classification examples. ```APIDOC ## Module: torch_topological.nn.layers ### Description Provides neural network layers for topological structures. ### Classes - `StructureElementLayer` ### Usage ```python from torch_topological.nn.layers import StructureElementLayer ``` ``` -------------------------------- ### TopoGCN.__init__() Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-graphs.md Constructor for the TopoGCN model. Takes no parameters; the architecture is fixed with two GCNConv layers, a TOGL layer, and global mean pooling. ```APIDOC ## TopoGCN.__init__() ### Description Initializes the TopoGCN model with a fixed architecture: two GCNConv layers (1→8 and 8→2), a TOGL layer, and global mean pooling. ### Method Constructor ### Parameters None ### Returns None ``` -------------------------------- ### Using is_iterable Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Example usage of is_iterable to assert that lists and strings are iterable, while floats are not. ```python from torch_topological.utils import is_iterable assert is_iterable([1, 2]) and is_iterable("abc") assert not is_iterable(1.0) ``` -------------------------------- ### TOGL.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-graphs.md Initializes the TOGL layer with the specified configuration. Sets up the filtration MLP, set-function layers, and batch normalization. ```APIDOC ## TOGL.__init__ ### Description Initializes the TOGL layer with the specified configuration. Sets up the filtration MLP, set-function layers, and batch normalization. ### Method Constructor ### Signature ```python def __init__( self, n_features, n_filtrations, hidden_dim, out_dim, aggregation_fn, ): ``` ### Parameters - **n_features** (int) - Required - Input/output node feature dimension - **n_filtrations** (int) - Required - Number of learned filtrations - **hidden_dim** (int) - Required - Hidden dimension of the filtration MLP - **out_dim** (int) - Required - Hidden dimension of the set-function layers - **aggregation_fn** (str) - Required - Passed to the two `DeepSetLayer` instances ### Structure - `self.filtrations = nn.Sequential(Linear(n_features, hidden_dim), ReLU(), Linear(hidden_dim, n_filtrations))` - `self.set_fn = nn.ModuleList([Linear(n_filtrations*2, out_dim), ReLU(), DeepSetLayer(out_dim, out_dim, aggregation_fn), ReLU(), DeepSetLayer(out_dim, n_features, aggregation_fn)])` - `self.batch_norm = nn.BatchNorm1d(n_features)` ``` -------------------------------- ### MultiScaleKernel __init__ signature Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Constructor for the multi-scale kernel. Requires a scale parameter `sigma` with no default value. ```python def __init__(self, sigma): ``` -------------------------------- ### LowerStarPersistence.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Initializes the LowerStarPersistence module with configuration options for clipping infinite features, including maximum dimension homology, and output format for PyG batches. ```APIDOC ## LowerStarPersistence.__init__ ### Description Initializes the LowerStarPersistence module with configuration options for clipping infinite features, including maximum dimension homology, and output format for PyG batches. ### Method Constructor ### Signature ```python def __init__( self, clip_inf=False, include_max_dim=False, list_of_lists=True, **kwargs ): ``` ### Parameters - `clip_inf` (bool) - Optional, default `False` - Clip the destruction value of essential (infinite) features to the maximum filtration value; otherwise it is `torch.inf`. - `include_max_dim` (bool) - Optional, default `False` - Include homology of the highest dimension in the output. - `list_of_lists` (bool) - Optional, default `True` - For PyG `Batch` input: return a list of lists (per graph) instead of a flat list of `(info, pairs_batch)` tuples. - `**kwargs` - Optional - Extra arguments forwarded to `gudhi.SimplexTree.compute_persistence` (e.g. `persistence_dim_max`; see gudhi docs). ``` -------------------------------- ### Using wrap_if_not_iterable Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Example usage of wrap_if_not_iterable to wrap non-iterables in a list, while leaving iterables unchanged. Strings are iterable. ```python from torch_topological.utils import wrap_if_not_iterable assert wrap_if_not_iterable(1.0) == [1.0] assert wrap_if_not_iterable([1.0]) == [1.0] assert wrap_if_not_iterable("abc") == "abc" # strings are iterable ``` -------------------------------- ### LowerStarPersistence __init__ signature Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Constructor for LowerStarPersistence. Accepts clip_inf, include_max_dim, list_of_lists, and extra kwargs forwarded to gudhi.SimplexTree.compute_persistence. ```python def __init__( self, clip_inf=False, include_max_dim=False, list_of_lists=True, **kwargs ): ``` -------------------------------- ### Full source code for summary statistics minimisation Source: https://github.com/aidos-lab/pytorch-topological/blob/main/docs/source/examples/summary_statistics.rst Complete script demonstrating how to use topological summary statistics (persistent entropy, polynomial function, total persistence) as loss functions to adjust the shape of point clouds. Supports both two-point-cloud (source vs target) and single-point-cloud modes. Uses SummaryStatisticLoss with VietorisRipsComplex and SGD optimization. ```python """Demo for summary statistics minimisation of a point cloud. This example demonstrates how to use various topological summary statistics in order to change the shape of an input point cloud. The script can either demonstrate how to adjust the shape of two point clouds, i.e. using a summary statistic as a loss function, or how to change the shape of a *single* point cloud. By default two point clouds will be used. """ import argparse import matplotlib.pyplot as plt from torch_topological.data import sample_from_disk from torch_topological.data import sample_from_unit_cube from torch_topological.nn import SummaryStatisticLoss from torch_topological.nn import VietorisRipsComplex from tqdm import tqdm import torch import torch.optim as optim def create_data_set(args): """Create data set based on user-provided arguments.""" n = args.n_samples if args.single: X = sample_from_unit_cube(n=n, d=2) Y = X.clone() else: X = sample_from_disk(n=n, r=0.5, R=0.6) Y = sample_from_disk(n=n, r=0.9, R=1.0) # Make source point cloud adjustable by treating it as a parameter. # This enables topological loss functions to influence the shape of # `X`. X = torch.nn.Parameter(torch.as_tensor(X), requires_grad=True) return X, Y def main(args): """Run example.""" n_iterations = args.n_iterations statistic = args.statistic p = args.p q = args.q X, Y = create_data_set(args) vr = VietorisRipsComplex(dim=2) if not args.single: pi_target = vr(Y) loss_fn = SummaryStatisticLoss( summary_statistic=statistic, p=p, q=q ) opt = optim.SGD([X], lr=0.05) progress = tqdm(range(n_iterations)) for i in progress: pi_source = vr(X) if not args.single: loss = loss_fn(pi_source, pi_target) else: loss = loss_fn(pi_source) opt.zero_grad() loss.backward() opt.step() progress.set_postfix(loss=f'{loss.item():.08f}') X = X.detach().numpy() if args.single: plt.scatter(X[:, 0], X[:, 1], label='Result') plt.scatter(Y[:, 0], Y[:, 1], label='Initial') else: plt.scatter(X[:, 0], X[:, 1], label='Source') plt.scatter(Y[:, 0], Y[:, 1], label='Target') plt.legend() plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '-i', '--n-iterations', default=250, type=int, help='Number of iterations' ) parser.add_argument( '-n', '--n-samples', default=100, type=int, help='Number of samples in point clouds' ) parser.add_argument( '-s', '--statistic', choices=[ 'persistent_entropy', 'polynomial_function', 'total_persistence', ], default='polynomial_function', help='Name of summary statistic to use for the loss' ) parser.add_argument( '-S', '--single', action='store_true', help='If set, uses only a single point cloud' ) parser.add_argument( '-p', type=float, default=2.0, help='Outer exponent for summary statistic loss calculation' ) parser.add_argument( '-q', type=float, default=2.0, help='Inner exponent for summary statistic loss calculation. Will ' 'only be used for certain summary statistics.' ) args = parser.parse_args() main(args) ``` -------------------------------- ### Using SelectByDimension to filter diagrams Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/utils.md Example usage of SelectByDimension to keep only dimension-1 diagrams or a range of dimensions from a VietorisRipsComplex output. ```python from torch_topological.nn import VietorisRipsComplex from torch_topological.utils import SelectByDimension vr = VietorisRipsComplex(dim=1) pi = vr(torch.rand(50, 2)) only_loops = SelectByDimension(1)(pi) # keep dim-1 diagrams only loops_and_components = SelectByDimension(0, max_dim=1)(pi) ``` -------------------------------- ### SummaryStatisticLoss.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-losses.md Initializes a SummaryStatisticLoss instance with a specified summary statistic function and optional keyword arguments. The summary statistic is resolved from torch_topological.utils.summary_statistics via getattr. ```APIDOC ## SummaryStatisticLoss.__init__ ### Description Initializes a SummaryStatisticLoss instance with a specified summary statistic function and optional keyword arguments. The summary statistic is resolved from torch_topological.utils.summary_statistics via getattr. ### Method Constructor ### Endpoint SummaryStatisticLoss.__init__ ### Parameters - **summary_statistic** (str) - Optional, default: "total_persistence" - Name of a summary-statistic function in torch_topological.utils.summary_statistics. Valid: persistent_entropy, polynomial_function, total_persistence, p_norm - **kwargs** - Optional - Passed to the statistic function. p read out via kwargs.get("p", 1.0) for the outer loss exponent. E.g. q for polynomial_function ### Request Example ```python loss_fn = SummaryStatisticLoss( summary_statistic='polynomial_function', p=2, q=0 ) ``` ### Response #### Success Response Returns a SummaryStatisticLoss instance. #### Response Example ```python loss_fn = SummaryStatisticLoss( summary_statistic='polynomial_function', p=2, q=0 ) ``` ``` -------------------------------- ### AlphaComplex.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Initializes an AlphaComplex persistence calculator with a specified p-norm exponent for pairwise-distance filtration values. ```APIDOC ## AlphaComplex.__init__ ### Description Initializes an AlphaComplex persistence calculator with a specified p-norm exponent for pairwise-distance filtration values. ### Method Constructor ### Signature ```python def __init__(self, p=2): ``` ### Parameters - `p` (float) - Optional, default `2` - Exponent of the `p`-norm used for pairwise-distance filtration values. ### Returns None ``` -------------------------------- ### SignatureLoss Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/configuration.md Constructor parameters for the SignatureLoss loss. ```APIDOC ## SignatureLoss ### Description Constructor parameters for the SignatureLoss loss. ### Parameters - **p** (float) - Optional - Default: `2` - Norm exponent for cdist/vector_norm. - **normalise** (bool) - Optional - Default: `True` - Divide distance matrices by their maximum. - **dimensions** (int or tuple) - Optional - Default: `0` - Homology dimensions used in the signature. ``` -------------------------------- ### Optimisation loop with WeightedEulerCurve and EulerDistance Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-wect.md Example adapted from torch_topological/examples/weighted_euler_characteristic_transform.py. It optimizes a volume to match a target using WeightedEulerCurve with prod=True and EulerDistance as loss. The loop runs until the loss is below 0.05. ```python import torch import torch.optim as optim from torch_topological.nn import WeightedEulerCurve, EulerDistance torch.manual_seed(4) z = 3 arr = torch.ones([z, z, z], requires_grad=False) arr2 = torch.rand([z, z, z], requires_grad=False) arr2[arr2 > 0.5] = 1 arr2[arr2 <= 0.5] = 0 ec = WeightedEulerCurve(prod=True) # product cell values dist = EulerDistance() optimizer = optim.SGD([arr], lr=0.001, momentum=0.9) ans = 100 while ans > 0.05: optimizer.zero_grad() ans = dist(ec(arr), ec(arr2)) ans.backward() optimizer.step() ``` -------------------------------- ### WassersteinDistance.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-distances-kernels.md Initializes the WassersteinDistance module with parameters for the norm exponent and the order of the Wasserstein metric. ```APIDOC ## `WassersteinDistance.__init__` ### Description Initializes the WassersteinDistance module with parameters for the norm exponent and the order of the Wasserstein metric. ### Method Constructor ### Parameters - **p** (float or inf) - Optional, default `torch.inf` - Exponent of the norm used for point-to-point cost (maximum norm by default) - **q** (float) - Optional, default `1` - Order of the Wasserstein metric; internal matching costs are raised to `q`, the final result is the `q`-th root ### Request Example ```python WassersteinDistance(p=torch.inf, q=1) ``` ### Response #### Success Response No return value (constructor). ``` -------------------------------- ### VietorisRipsComplex.__init__ Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Initializes a VietorisRipsComplex instance for computing differentiable persistence diagrams from point clouds. Configures homology dimension, distance norm, filtration threshold, and handling of infinite features. ```APIDOC ## VietorisRipsComplex.__init__ ### Description Initializes a VietorisRipsComplex instance for computing differentiable persistence diagrams from point clouds. Configures homology dimension, distance norm, filtration threshold, and handling of infinite features. ### Method Constructor ### Signature ```python def __init__( self, dim=1, p=2, threshold=numpy.inf, keep_infinite_features=False, **kwargs ): ``` ### Parameters - **dim** (`int`) - Optional, default `1` - Compute persistent homology up to (and including) this dimension. - **p** (`float`) - Optional, default `2` - Minkowski `p`-norm for pairwise distances; ignored when `treat_as_distances=True` in `forward`. - **threshold** (`float`) - Optional, default `numpy.inf` - Only compute features with filtration value ≤ threshold. - **keep_infinite_features** (`bool`) - Optional, default `False` - Keep the infinite (essential) feature(s). Disabled by default because infinite values need deliberate handling. - **`**kwargs`** - Optional - Extra arguments forwarded to `ripser` (e.g. `n_threads`); stored in `self.ripser_params`. ### Returns None ``` -------------------------------- ### Official usage in autoencoders example Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-losses.md The official usage pattern from torch_topological/examples/autoencoders.py. The forward pass expects a tuple/list with exactly two elements: the point cloud and its persistence information, in that order. ```python topo_loss = self.loss([x, pi_x], [z, pi_z]) ``` -------------------------------- ### PLLay.__init__ signature Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-pllay.md Constructor for the PLLay layer. Parameters: output_dim, K_max, t_min, t_max, m, and optional layer (default 'Affine'). Raises ValueError for invalid layer strings. ```python def __init__(self, output_dim, K_max, t_min, t_max, m, layer="Affine"): ``` -------------------------------- ### LowerStarPersistence PyG Batch usage Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Example using a PyG Batch with list_of_lists=False to obtain pairs_batch tensors. The result is a tuple (info, pairs_batch) where pairs_batch maps pairing rows to graph index. ```python # PyG Batch usage (list_of_lists=False yields pairs_batch tensors): from torch_geometric.data import Batch, Data from torch_topological.nn import LowerStarPersistence data = [Data(x=torch.ones(4, 1), edge_index=torch.tensor([[0,1],[1,2],[2,3]]).T, num_nodes=4)] batch = Batch.from_data_list(data) lsp = LowerStarPersistence(list_of_lists=False, clip_inf=True) result = lsp(batch, torch.rand(4)) info, pairs_batch = result[0] # pairs_batch maps pairing rows to graph index ``` -------------------------------- ### VietorisRipsComplex forward signature Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Forward method for VietorisRipsComplex. Accepts point clouds or batches, or pre-computed distance matrices when treat_as_distances is True. Returns a list of PersistenceInformation per dimension, starting with dimension 0. ```python def forward(self, x, treat_as_distances=False): ``` -------------------------------- ### VietorisRipsComplex __init__ signature Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Constructor for the VietorisRipsComplex class. Parameters control homology dimension, Minkowski p-norm, filtration threshold, and handling of infinite features. Extra keyword arguments are forwarded to ripser and stored in self.ripser_params. ```python def __init__( self, dim=1, p=2, threshold=numpy.inf, keep_infinite_features=False, **kwargs ): ``` -------------------------------- ### AlphaComplex __init__ method Source: https://github.com/aidos-lab/pytorch-topological/blob/main/_autodocs/api-reference/nn-complexes.md Constructor for the AlphaComplex module. Accepts an optional exponent p for the p-norm used in pairwise-distance filtration values, defaulting to 2. ```python def __init__(self, p=2): ```