topobench.transforms.liftings.graph2simplicial.neighborhood_complex_lifting module#

This module implements the NeighborhoodComplexLifting class, which lifts graphs to simplicial complexes.

class Any(*args, **kwargs)#

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class Data(x=None, edge_index=None, edge_attr=None, y=None, pos=None, time=None, **kwargs)#

Bases: BaseData, FeatureStore, GraphStore

A data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general, Data tries to mimic the behavior of a regular :python:`Python` dictionary. In addition, it provides useful functionality for analyzing graph structures, and provides basic PyTorch tensor functionalities. See here for the accompanying tutorial.

from torch_geometric.data import Data

data = Data(x=x, edge_index=edge_index, ...)

# Add additional arguments to `data`:
data.train_idx = torch.tensor([...], dtype=torch.long)
data.test_mask = torch.tensor([...], dtype=torch.bool)

# Analyzing the graph structure:
data.num_nodes
>>> 23

data.is_directed()
>>> False

# PyTorch tensor functionality:
data = data.pin_memory()
data = data.to('cuda:0', non_blocking=True)
Parameters:
  • x (torch.Tensor, optional) – Node feature matrix with shape [num_nodes, num_node_features]. (default: None)

  • edge_index (LongTensor, optional) – Graph connectivity in COO format with shape [2, num_edges]. (default: None)

  • edge_attr (torch.Tensor, optional) – Edge feature matrix with shape [num_edges, num_edge_features]. (default: None)

  • y (torch.Tensor, optional) – Graph-level or node-level ground-truth labels with arbitrary shape. (default: None)

  • pos (torch.Tensor, optional) – Node position matrix with shape [num_nodes, num_dimensions]. (default: None)

  • time (torch.Tensor, optional) – The timestamps for each event with shape [num_edges] or [num_nodes]. (default: None)

  • **kwargs (optional) – Additional attributes.

__init__(x=None, edge_index=None, edge_attr=None, y=None, pos=None, time=None, **kwargs)#
connected_components()#

Extracts connected components of the graph using a union-find algorithm. The components are returned as a list of Data objects, where each object represents a connected component of the graph.

data = Data()
data.x = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
data.y = torch.tensor([[1.1], [2.1], [3.1], [4.1]])
data.edge_index = torch.tensor(
    [[0, 1, 2, 3], [1, 0, 3, 2]], dtype=torch.long
)

components = data.connected_components()
print(len(components))
>>> 2

print(components[0].x)
>>> Data(x=[2, 1], y=[2, 1], edge_index=[2, 2])
Returns:

A list of disconnected components.

Return type:

List[Data]

debug()#
edge_subgraph(subset)#

Returns the induced subgraph given by the edge indices subset. Will currently preserve all the nodes in the graph, even if they are isolated after subgraph computation.

Parameters:

subset (LongTensor or BoolTensor) – The edges to keep.

classmethod from_dict(mapping)#

Creates a Data object from a dictionary.

get_all_edge_attrs()#

Returns all registered edge attributes.

get_all_tensor_attrs()#

Obtains all feature attributes stored in Data.

is_edge_attr(key)#

Returns True if the object at key key denotes an edge-level tensor attribute.

is_node_attr(key)#

Returns True if the object at key key denotes a node-level tensor attribute.

stores_as(data)#
subgraph(subset)#

Returns the induced subgraph given by the node indices subset.

Parameters:

subset (LongTensor or BoolTensor) – The nodes to keep.

to_dict()#

Returns a dictionary of stored key/value pairs.

to_heterogeneous(node_type=None, edge_type=None, node_type_names=None, edge_type_names=None)#

Converts a Data object to a heterogeneous HeteroData object. For this, node and edge attributes are splitted according to the node-level and edge-level vectors node_type and edge_type, respectively. node_type_names and edge_type_names can be used to give meaningful node and edge type names, respectively. That is, the node_type 0 is given by node_type_names[0]. If the Data object was constructed via to_homogeneous(), the object can be reconstructed without any need to pass in additional arguments.

Parameters:
  • node_type (torch.Tensor, optional) – A node-level vector denoting the type of each node. (default: None)

  • edge_type (torch.Tensor, optional) – An edge-level vector denoting the type of each edge. (default: None)

  • node_type_names (List[str], optional) – The names of node types. (default: None)

  • edge_type_names (List[Tuple[str, str, str]], optional) – The names of edge types. (default: None)

to_namedtuple()#

Returns a NamedTuple of stored key/value pairs.

update(data)#

Updates the data object with the elements from another data object. Added elements will override existing ones (in case of duplicates).

validate(raise_on_error=True)#

Validates the correctness of the data.

property batch: Tensor | None#

!! processed by numpydoc !!

property edge_attr: Tensor | None#

!! processed by numpydoc !!

property edge_index: Tensor | None#

!! processed by numpydoc !!

property edge_stores: List[EdgeStorage]#

!! processed by numpydoc !!

property edge_weight: Tensor | None#

!! processed by numpydoc !!

property face: Tensor | None#

!! processed by numpydoc !!

property node_stores: List[NodeStorage]#

!! processed by numpydoc !!

property num_edge_features: int#

Returns the number of features per edge in the graph.

property num_edge_types: int#

Returns the number of edge types in the graph.

property num_faces: int | None#

Returns the number of faces in the mesh.

property num_features: int#

Returns the number of features per node in the graph. Alias for num_node_features.

property num_node_features: int#

Returns the number of features per node in the graph.

property num_node_types: int#

Returns the number of node types in the graph.

property num_nodes: int | None#

Returns the number of nodes in the graph.

Note

The number of nodes in the data object is automatically inferred in case node-level attributes are present, e.g., data.x. In some cases, however, a graph may only be given without any node-level attributes. :pyg:`PyG` then guesses the number of nodes according to edge_index.max().item() + 1. However, in case there exists isolated nodes, this number does not have to be correct which can result in unexpected behavior. Thus, we recommend to set the number of nodes in your data object explicitly via data.num_nodes = .... You will be given a warning that requests you to do so.

property pos: Tensor | None#

!! processed by numpydoc !!

property stores: List[BaseStorage]#

!! processed by numpydoc !!

property time: Tensor | None#

!! processed by numpydoc !!

property x: Tensor | None#

!! processed by numpydoc !!

property y: Tensor | int | float | None#

!! processed by numpydoc !!

class Graph2SimplicialLifting(complex_dim=2, **kwargs)#

Bases: GraphLifting

Abstract class for lifting graphs to simplicial complexes.

Parameters:
complex_dimint, optional

The maximum dimension of the simplicial complex to be generated. Default is 2.

**kwargsoptional

Additional arguments for the class.

__init__(complex_dim=2, **kwargs)#
class NeighborhoodComplexLifting(max_simplices=10, **kwargs)#

Bases: Graph2SimplicialLifting

Lifts graphs to a simplicial complex domain by identifying the neighborhood complex as k-simplices.

Parameters:
max_simplicesint, optional

The maximum number of simplices to be added to the simplicial complex for each node. Default is 50.

**kwargsoptional

Additional arguments for the class.

__init__(max_simplices=10, **kwargs)#
lift_topology(data)#

Lift the topology of a graph to a simplicial complex.

Parameters:
datatorch_geometric.data.Data

The input data to be lifted.

Returns:
dict

The lifted topology.

class SimplicialComplex(simplices=None, **kwargs)#

Bases: Complex, Generic[ElementType]

Class representing a simplicial complex.

Class for construction boundary operators, Hodge Laplacians, higher order (co)adjacency operators from a collection of simplices.

A simplicial complex is a topological space of a specific kind, constructed by “gluing together” points, line segments, triangles, and their higher-dimensional counterparts. It is a generalization of the notion of a triangle in a triangulated surface, or a tetrahedron in a tetrahedralized 3-dimensional manifold. Simplicial complexes are the basic objects of study in combinatorial topology.

For example, a triangle is a simplicial complex because it is a collection of three points that are connected to each other in a specific way. Similarly, a tetrahedron is a simplicial complex because it is a collection of four points that are connected to each other in a specific way. These simplices can be thought of as the “building blocks” of a simplicial complex, and the complex itself is constructed by combining these building blocks in a specific way. For example, a 2-dimensional simplicial complex could be a collection of triangles that are connected to each other to form a surface, while a 3-dimensional simplicial complex could be a collection of tetrahedra that are connected to each other to form a solid object.

The SimplicialComplex class is a class for representing simplicial complexes, which are a type of topological space constructed by “gluing together” points, line segments, triangles, and higher-dimensional counterparts. The class provides methods for computing boundary operators, Hodge Laplacians, and higher-order adjacency operators on the simplicial complex. It also allows for compatibility with NetworkX and the GUDHI library.

Features:

  1. The SimplicialComplex class allows for the dynamic construction of simplicial complexes,

    enabling users to add or remove simplices from the complex after its initial creation.

  2. The class provides methods for computing boundary operators, Hodge Laplacians,

    and higher-order adjacency operators on the simplicial complex.

  3. The class is compatible with the gudhi library, allowing users to leverage the powerful

    algorithms and data structures provided by this package.

  4. The class supports the attachment of arbitrary attributes and data to simplices,

    enabling users to store and manipulate additional information about these objects.

  5. The class has robust error handling and input validation, ensuring reliable and easy use of the class.

Parameters:
simplicesiterable, optional

Iterable of maximal simplices that define the simplicial complex.

**kwargskeyword arguments, optional

Attributes to add to the complex as key=value pairs.

Attributes:
complexdict

A dictionary that can be used to store additional information about the complex.

Notes

A simplicial complex is determined by its maximal simplices, simplices that are not contained in any other simplices. If a maximal simplex is inserted, all faces of this simplex will be inserted automatically.

Examples

Define a simplicial complex using a set of maximal simplices:

>>> SC = tnx.SimplicialComplex([[1, 2, 3], [2, 3, 5], [0, 1]])

TopoNetX is also compatible with NetworkX, allowing users to create a simplicial complex from a NetworkX graph. Existing node and edge attributes are copied to the simplicial complex:

>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=4)
>>> G.add_edges_from([(0, 3), (0, 4), (1, 4)])
>>> SC = tnx.SimplicialComplex(simplices=G)
>>> SC.add_simplex([1, 2, 3])
>>> SC.simplices
SimplexView([(0,), (1,), (3,), (4,), (2,), (0, 1), (0, 3), (0, 4), (1, 4), (1, 2), (1, 3), (2, 3), (1, 2, 3)])
>>> SC[(0, 1)]["weight"]
4
__init__(simplices=None, **kwargs)#

Initialize a new instance of the Complex class.

Parameters:
**kwargskeyword arguments, optional

Attributes to add to the complex as key=value pairs.

add_elements_from_nx_graph(G)#

Add elements from a networkx graph to this simplicial complex.

Parameters:
Gnetworkx.Graph

A networkx graph instance.

add_node(node, **kwargs)#

Add node to simplicial complex.

Parameters:
nodeHashable or Simplex

The node to be added to the simplicial complex.

**kwargskeyword arguments, optional

Additional attributes to be associated with the node.

add_simplex(simplex, **kwargs)#

Add simplex to simplicial complex.

In case sub-simplices are missing, they are added without attributes to the simplicial complex to fulfill the simplex requirements.

If the given simplex is already part of the simplicial complex, its attributes will be updated by the provided ones.

Parameters:
simplexCollection

The simplex to be added to the simplicial complex.

If a Simplex object is given, its attributes will be copied to the simplicial complex. kwargs take precedence over the attributes of the Simplex object.

**kwargskeyword arguments, optional

Additional attributes to be associated with the simplex.

add_simplices_from(simplices)#

Add simplices from iterable to simplicial complex.

Parameters:
simplicesiterable

Iterable of simplices to be added to the simplicial complex.

adjacency_matrix(rank, signed=False, weight=None, index=False)#

Compute the adjacency matrix of the simplicial complex.

Parameters:
rankint

Rank of the adjacency matrix.

signedbool

Whether to return the signed or unsigned adjacency matrix.

weightstr, optional

The name of the simplex attribute to use as weights for the hodge laplacian matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the adjacency matrix.

Returns:
indicesdict

Dictionary mapping each row and column of the coadjacency matrix to a simplex. Only returned if index is True.

adjacency_matrixscipy.sparse.csr.csr_matrix

The adjacency matrix of rank rank of this simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> adj1 = SC.adjacency_matrix(1)
clone()#

Return a copy of the simplicial complex.

The clone method by default returns an independent shallow copy of the simplicial complex. Use Python’s copy.deepcopy for new containers.

Returns:
SimplicialComplex

A shallow copy of this simplicial complex.

coadjacency_matrix(rank, signed=False, weight=None, index=False)#

Compute the coadjacency matrix of the simplicial complex.

Parameters:
rankint

Rank of the coadjacency matrix.

signedbool

Whether to return the signed or unsigned coadjacency matrix.

weightstr, optional

The name of the simplex attribute to use as weights for the hodge laplacian matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the coadjacency matrix.

Returns:
indiceslist

List identifying the rows and columns of the coadjacency matrix with the simplices of the simplicial complex. Only returned if index is True.

coadjacency_matrixscipy.sparse.csr.csr_matrix

The coadjacency matrix of this simplicial complex.

coincidence_matrix(rank, signed=True, weight=None, index=False)#

Compute coincidence matrix of the simplicial complex.

This is also called the coboundary matrix.

Parameters:
rankint

For which rank of simplices to compute the coincidence matrix.

signedbool, default=True

Whether to return the signed or unsigned coincidence matrix.

weightstr, optional

The name of the simplex attribute to use as weights for the coincidence matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the coincidence matrix.

Returns:
row_indices, col_indicesdict

Dictionary assigning each row and column of the coincidence matrix to a simplex. Only returned if index is True.

coincidence_matrixscipy.sparse.csr.csr_matrix

The coincidence matrix.

dirac_operator_matrix(signed=True, weight=None, index=False)#

Compute dirac operator matrix matrix.

Parameters:
signedbool, default=False

Whether the returned dirac matrix should be signed (i.e., respect orientations) or unsigned.

weightstr, optional

The name of the simplex attribute to use as weights for the dirac operator matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the dirac operator matrix.

Returns:
row_indices, col_indicesdict

List identifying rows and columns of the dirac operator matrix. Only returned if index is True.

scipy.sparse.csr.csc_matrix

The dirac operator matrix of this simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> SC.dirac_operator_matrix()
down_laplacian_matrix(rank, signed=True, weight=None, index=False)#

Compute the down Laplacian matrix of the simplicial complex.

Parameters:
rankint

Rank of the down Laplacian matrix.

signedbool

Whether to return the signed or unsigned down laplacian.

weightstr, optional

The name of the simplex attribute to use as weights for the hodge laplacian matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the laplacian.

Returns:
indicesdict

Dictionary assigning each row and column of the laplacian matrix to a simplex. Only returned if index is True.

down_laplacianscipy.sparse.csr.csr_matrix

The down laplacian matrix of this simplicial complex.

classmethod from_gudhi(tree)#

Import from gudhi.

Parameters:
treegudhi.SimplexTree

The input gudhi simplex tree.

Returns:
SimplicialComplex

The resulting SimplicialComplex.

Examples

>>> from gudhi import SimplexTree
>>> tree = SimplexTree()
>>> _ = tree.insert([1, 2, 3, 5])
>>> SC = tnx.SimplicialComplex.from_gudhi(tree)
classmethod from_nx(G)#

Convert from netwrokx graph.

Parameters:
Gnx.Graph

The graph to convert to a simplicial complex.

Returns:
SimplicialComplex

The simplicial complex.

Examples

>>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge(1, 2, weight=2)
>>> G.add_edge(3, 4, weight=4)
>>> SC = tnx.SimplicialComplex.from_nx(G)
>>> SC[(1, 2)]["weight"]
2
classmethod from_spharapy(mesh)#

Import from sharpy.

Parameters:
meshspharapy.trimesh.TriMesh

The input spharapy object.

Returns:
SimplicialComplex

The resulting SimplicialComplex.

Examples

>>> import spharapy.trimesh as tm
>>> import spharapy.spharabasis as sb
>>> import spharapy.datasets as sd
>>> mesh = tm.TriMesh(
...     [[0, 1, 2]], [[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]]
... )
>>> SC = tnx.SimplicialComplex.from_spharapy(mesh)
classmethod from_spharpy(mesh)#

Import from sharpy.

Parameters:
meshspharapy.trimesh.TriMesh

The input spharapy object.

Returns:
SimplicialComplex

The resulting SimplicialComplex.

classmethod from_trimesh(mesh)#

Import from trimesh.

Parameters:
meshtrimesh.Trimesh

The input trimesh object.

Returns:
SimplicialComplex

The resulting SimplicialComplex.

Examples

>>> import trimesh
>>> mesh = trimesh.Trimesh(
...     vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]],
...     faces=[[0, 1, 2]],
...     process=False,
... )
>>> SC = tnx.SimplicialComplex.from_trimesh(mesh)
>>> print(SC.nodes)
>>> print(SC.simplices)
>>> SC[(0)]["position"]
get_all_maximal_simplices()#

Get all maximal simplices of this simplicial complex.

A simplex is maximal if it is not a face of any other simplex in the complex.

Returns:
list of tuples

List of maximal simplices in this simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex([(1, 2), (1, 2, 3), (1, 2, 4), (2, 5)])
>>> SC.get_all_maximal_simplices()
[(2, 5), (1, 2, 3), (1, 2, 4)]
static get_boundaries(simplices, min_dim=None, max_dim=None)#

Get boundaries of the given simplices.

Parameters:
simplicesIterable

Iterable of simplices for which to compute the boundaries.

min_dimint, optional

Constrain the max dimension of faces.

max_dimint, optional

Constrain the max dimension of faces.

Returns:
set of frozensets

Set of simplices that are boundaries of the given simplices. If min_dim or max_dim are given, only simplices with dimension in the given range are returned.

get_cofaces(simplex, codimension)#

Get cofaces of simplex.

Parameters:
simplexIterable of AtomType

The simplex for which to compute the cofaces.

codimensionint

The codimension of the returned cofaces. If zero, all cofaces are returned.

Returns:
list of tuples

The cofaces of the given simplex.

static get_edges_from_matrix(matrix)#

Get edges from matrix.

Parameters:
matrixnumpy or scipy array

The matrix to get the edges from.

Returns:
list of int

List of indices where the operator is not zero.

Notes

Most operaters (e.g. adjacencies/(co)boundary maps) that describe connectivity of the simplicial complex can be described as a G whose nodes are the simplices used to construct the operator and whose edges correspond to the entries in the matrix where the operator is not zero.

This property implies that many computations on simplicial complexes can be reduced to G computations.

get_maximal_simplices_of_simplex(simplex)#

Get maximal simplices of simplex.

Parameters:
simplexIterable

The simplex for which to compute the maximal simplices.

Returns:
set of Simplex

Set of maximal simplices of the given simplex.

get_node_attributes(name)#

Get node attributes from simplicial complex.

Parameters:
namestr

Attribute name.

Returns:
dict

Dictionary mapping each node to the value of the given attribute name.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> SC.set_simplex_attributes({1: "red", 2: "blue", 3: "black"}, name="color")
>>> SC.get_node_attributes("color")
{1: 'red', 2: 'blue', 3: 'black'}
get_simplex_attributes(name, rank=None)#

Get node attributes from simplical complex.

Parameters:
namestr

Attribute name.

rankint, optional

Restrict the returned attribute values to simplices of a specific rank.

Returns:
dict[tuple[Hashable, …], Any]

Dictionary mapping each simplex to the value of the given attribute name.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> d = {(1, 2): "red", (2, 3): "blue", (3, 4): "black"}
>>> SC.set_simplex_attributes(d, name="color")
>>> SC.get_simplex_attributes("color")
{(1, 2): 'red', (2, 3): 'blue', (3, 4): 'black'}
get_star(simplex)#

Get star.

Parameters:
simplexIterable of AtomType

The simplex for which to compute the star.

Returns:
list of tuples

The star of the given simplex.

Notes

This function is equivalent to calling get_cofaces(simplex, 0).

graph_skeleton()#

Return the graph-skeleton of this simplicial complex.

The graph-skeleton consists of the 0 and 1-simplices (i.e., nodes and edges) of the simplicial complex.

Returns:
nx.Graph

The graph-skeleton of this simplicial complex.

hodge_laplacian_matrix(rank, signed=True, weight=None, index=False)#

Compute hodge-laplacian matrix for the simplicial complex.

Parameters:
rankint

Dimension of the Laplacian matrix.

signedbool, default=True

Whether to return the signed or unsigned hodge laplacian.

weightstr, optional

The name of the simplex attribute to use as weights for the hodge laplacian matrix. If None, the matrix is binary.

indexbool, default=False

Indicates whether to return the indices that define the hodge laplacian matrix.

Returns:
indexlist

List assigning each row and column of the laplacian matrix to a simplex. Only available when index is True.

laplacianscipy.sparse.csr.csr_matrix

The hodge laplacian matrix of rank rank.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> L1 = SC.hodge_laplacian_matrix(1)
incidence_matrix(rank, signed=True, weight=None, index=False)#

Compute incidence matrix of the simplicial complex.

Getting the matrix that correpodnds to the boundary matrix of the input SC.

Parameters:
rankint

For which rank of simplices to compute the incidence matrix.

signedbool, default=True

Whether to return the signed or unsigned incidence matrix.

weightstr, optional

The name of the simplex attribute to use as weights for the incidence matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the incidence matrix.

Returns:
row_indices, col_indicesdict

Dictionary assigning each row and column of the incidence matrix to a simplex. Only returned if index is True.

incidence_matrixscipy.sparse.csr.csr_matrix

The incidence matrix.

Raises:
ValueError

If rank is negative or larger than the dimension of the simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> B1 = SC.incidence_matrix(1)
>>> B2 = SC.incidence_matrix(2)
is_connected()#

Check if the simplicial complex is connected.

Returns:
bool

True if the simplicial complex is connected, False otherwise.

Notes

A simplicial complex is connected iff its 1-skeleton is connected.

is_maximal(simplex)#

Check if simplex is maximal, i.e., not a face of any other simplex in the complex.

Parameters:
simplexIterable

The Simplex to check.

Returns:
bool

True if the given simplex is maximal in this simplicial complex, False otherwise.

Raises:
ValueError

If simplex is not in the simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex([[1, 2, 3]])
>>> SC.is_maximal([1, 2, 3])
True
>>> SC.is_maximal([1, 2])
False
is_triangular_mesh()#

Check if the simplicial complex is a triangular mesh.

Returns:
bool

True if the simplicial complex can be converted to a triangular mesh, False otherwise.

laplace_beltrami_operator(mode='inv_euclidean')#

Compute a laplacian matrix for a triangular mesh.

The method creates a laplacian matrix for a triangular mesh using different weighting function.

Parameters:
mode{‘unit’, ‘inv_euclidean’, ‘half_cotangent’}, optional

The methods for determining the edge weights. Using the option ‘unit’ all edges of the mesh are weighted by unit weighting function, the result is an adjacency matrix. The option ‘inv_euclidean’ results in edge weights corresponding to the inverse Euclidean distance of the edge lengths. The option ‘half_cotangent’ uses the half of the cotangent of the two angles opposed to an edge as weighting function. the default weighting function is ‘inv_euclidean’.

Returns:
numpy.ndarray, shape (n_vertices, n_vertices)

Matrix, which contains the discrete laplace operator for data defined at the vertices of a triangular mesh. The number of vertices of the triangular mesh is n_points.

classmethod load_mesh(file_path, process=False)#

Load a mesh.

Parameters:
file_pathstr or pathlib.Path

The source of the data to be loaded.

processbool

Whether trimesh should try to process the mesh before loading it.

Returns:
SimplicialComplex

The output simplicial complex stores the same structure stored in the mesh input file.

Notes

mesh files supported : obj, off, glb

Examples

>>> SC = tnx.SimplicialComplex.load_mesh("C:/temp/stanford-bunny.obj")
>>> SC.nodes
normalized_laplacian_matrix(rank, weight=None)#

Return the normalized hodge Laplacian matrix of simplicial complex .

The normalized hodge Laplacian is the matrix

\[N_d = D^{-1/2} L_d D^{-1/2}\]

where L is the simplicial complex Laplacian and D is the diagonal matrix of simplices of rank d.

Parameters:
rankint

Rank of the hodge laplacian matrix.

weightstr, optional

The name of the simplex attribute to use as weights for the hodge laplacian matrix. If None, the matrix is binary.

Returns:
Scipy sparse matrix

The normalized hodge Laplacian matrix.

Examples

>>> SC = tnx.SimplicialComplex([[1, 2, 3], [2, 3, 5], [0, 1]])
>>> SC.normalized_laplacian_matrix(1)
remove_maximal_simplex(simplex)#

Remove maximal simplex from simplicial complex.

Parameters:
simplexCollection

The simplex to be removed from the simplicial complex.

Raises:
KeyError

If simplex is not in simplicial complex.

ValueError

If simplex is not maximal.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex((1, 2, 3, 4), weight=1)
>>> SC.add_simplex((1, 2, 3, 4, 5))
>>> SC.remove_maximal_simplex((1, 2, 3, 4, 5))
remove_nodes(node_set)#

Remove the given nodes from the simplicial complex.

Any simplices that become invalid due to the removal of nodes are also removed.

Parameters:
node_setIterable

The nodes to be removed from the simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex([(1, 2), (2, 3), (3, 4)])
>>> SC.remove_nodes([1])
>>> SC.simplices
SimplexView([(2,), (3,), (4,), (2, 3), (3, 4)])
restrict_to_nodes(node_set)#

Construct a new simplicial complex by restricting the simplices.

The simplices are restricted to the nodes referenced by node_set.

Parameters:
node_setiterable of hashables

A subset of nodes of the simplicial complex to restrict to.

Returns:
SimplicialComplex

A new simplicial complex restricted to the nodes in node_set.

Examples

>>> SC = tnx.SimplicialComplex([(1, 2, 3), (1, 2, 4), (1, 2, 5)])
>>> new_complex = SC.restrict_to_nodes([1, 2, 3, 4])
>>> new_complex.simplices
SimplexView([(1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (1, 2, 3), (1, 2, 4)])
restrict_to_simplices(cell_set)#

Construct a simplicial complex using a subset of the simplices.

Parameters:
cell_setiterable of hashables or simplices

A subset of elements of the simplicial complex that should be in the new simplicial complex.

Returns:
SimplicialComplex

New simplicial complex restricted to the simplices in cell_set.

Examples

>>> c1 = tnx.Simplex((1, 2, 3))
>>> c2 = tnx.Simplex((1, 2, 4))
>>> c3 = tnx.Simplex((1, 2, 5))
>>> SC = tnx.SimplicialComplex([c1, c2, c3])
>>> SC1 = SC.restrict_to_simplices([c1, (2, 4)])
>>> SC1.simplices
SimplexView([(1,), (2,), (3,), (4,), (1, 2), (1, 3), (2, 3), (2, 4), (1, 2, 3)])
set_simplex_attributes(values, name=None)#

Set simplex attributes.

Parameters:
valuesdict

Either provide a mapping from simplices to values or a dict of dicts. In the former case, the attribute name for each simplex is set to the corresponding value. In the latter case, the entire dictionary is used to update the attributes of the simplices.

namestr, optional

The name of the attribute to set.

Notes

If the dict contains simplices that are not in self.simplices, they are silently ignored.

Examples

After computing some property of the simplex of a simplicial complex, you may want to assign a simplex attribute to store the value of that property for each simplex:

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 2, 3, 4])
>>> SC.add_simplex([1, 2, 4])
>>> SC.add_simplex([3, 4, 8])
>>> d = {(1, 2, 3): "red", (1, 2, 4): "blue"}
>>> SC.set_simplex_attributes(d, name="color")
>>> SC[(1, 2, 3)]["color"]
'red'

If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update simplex attributes:

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([1, 3, 4])
>>> SC.add_simplex([1, 2, 3])
>>> SC.add_simplex([1, 2, 4])
>>> d = {
...     (1, 3, 4): {"color": "red", "attr2": 1},
...     (1, 2, 4): {"color": "blue", "attr2": 3},
... }
>>> SC.set_simplex_attributes(d)
>>> SC[(1, 3, 4)]["color"]
'red'
classmethod simplicial_closure_of_hypergraph(H)#

Compute the simplicial complex closure of a hypergraph.

Parameters:
Hhyernetx hypergraph

The hypergraph to compute the simplicial complex closure of.

Returns:
SimplicialComplex

Simplicial complex closure of the hypergraph.

Examples

>>> import hypernetx as hnx
>>> hg = hnx.Hypergraph([[1, 2, 3, 4], [1, 2, 3]], static=True)
>>> sc = tnx.SimplicialComplex.simplicial_closure_of_hypergraph(hg)
>>> sc.simplices
SimplexView([(1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)])
skeleton(rank)#

Compute the rank-skeleton of the simplicial complex containing simplices of given rank.

Parameters:
rankint

The rank of the skeleton to compute.

Returns:
list of Simplex

Simplices of rank rank in the simplicial complex.

to_cell_complex()#

Convert a simplicial complex to a cell complex.

Returns:
toponetx.classes.CellComplex

The cell complex corresponding to this simplicial complex.

Examples

>>> c1 = tnx.Simplex((1, 2, 3))
>>> c2 = tnx.Simplex((1, 2, 4))
>>> c3 = tnx.Simplex((2, 5))
>>> SC = tnx.SimplicialComplex([c1, c2, c3])
>>> SC.to_cell_complex()
to_combinatorial_complex()#

Convert a simplicial complex to a combinatorial complex.

Returns:
toponetx.classes.CombinatorialComplex

The combinatorial complex equivalent to this simplicial complex.

Examples

>>> c1 = tnx.Simplex((1, 2, 3))
>>> c2 = tnx.Simplex((1, 2, 3))
>>> c3 = tnx.Simplex((1, 2, 4))
>>> SC = tnx.SimplicialComplex([c1, c2, c3])
>>> CCC = SC.to_combinatorial_complex()
to_hasse_graph()#

Create the hasse graph corresponding to this simplicial complex.

Returns:
nx.DiGraph

A NetworkX Digraph representing the Hasse graph of the Simplicial Complex.

Examples

>>> SC = tnx.SimplicialComplex()
>>> SC.add_simplex([0, 1, 2])
>>> G = SC.to_hasse_graph()
to_hypergraph()#

Convert a simplicial complex to a hypernetx hypergraph.

Returns:
Hypergraph

The hypergraph corresponding to this simplicial complex.

Raises:
RuntimeError

If hypernetx is not installed

Examples

>>> c1 = tnx.Simplex((1, 2, 3))
>>> c2 = tnx.Simplex((1, 2, 4))
>>> c3 = tnx.Simplex((2, 5))
>>> SC = tnx.SimplicialComplex([c1, c2, c3])
>>> SC.to_hypergraph()
Hypergraph({'e0': [1, 2], 'e1': [1, 3], 'e2': [1, 4], 'e3': [2, 3], 'e4': [2, 4], 'e5': [2, 5], 'e6': [1, 2, 3], 'e7': [1, 2, 4]},name=)
to_spharapy(vertex_position_name='position')#

Convert to spharapy.

Parameters:
vertex_position_namestr, default=”position”

The simplex attribute name that contains the vertex positions.

Returns:
spharapy.trimesh.TriMesh

The spharapy object corresponding to this simplicial complex.

Raises:
RuntimeError

If package spharapy is not installed.

Examples

>>> import spharapy.trimesh as tm
>>> import spharapy.spharabasis as sb
>>> import spharapy.datasets as sd
>>> mesh = tm.TriMesh([[0, 1, 2]], [[0, 0, 0], [0, 0, 1], [0, 1, 0]])
>>> SC = tnx.SimplicialComplex.from_spharapy(mesh)
>>> mesh2 = SC.to_spharapy()
>>> mesh2.vertlist == mesh.vertlist
>>> mesh2.trilist == mesh.trilist
to_trimesh(vertex_position_name='position')#

Convert simplicial complex to trimesh object.

Parameters:
vertex_position_namestr, default=”position”

The simplex attribute name that contains the vertex positions.

Returns:
trimesh.Trimesh

The trimesh object corresponding to this simplicial complex.

up_laplacian_matrix(rank, signed=True, weight=None, index=False)#

Compute the up Laplacian matrix of the simplicial complex.

Parameters:
rankint

Rank of the up Laplacian matrix.

signedbool

Whether to return the signed or unsigned up laplacian.

weightstr, optional

The name of the simplex attribute to use as weights for the hodge laplacian matrix. If None, the matrix is binary.

indexbool, default=False

Whether to return the indices of the rows and columns of the laplacian.

Returns:
row_indices, col_indiceslist

List identifying the rows and columns of the laplacian matrix with the simplices of this complex. Only returned if index is True.

up_laplacianscipy.sparse.csr.csr_matrix

The upper laplacian matrix of this simplicial complex.

Examples

>>> SC = tnx.SimplicialComplex([[1, 2, 3], [2, 3, 5], [0, 1]])
>>> SC.up_laplacian_matrix(1)
property dim: int#

Maximal dimension of the simplices in this complex.

Returns:
int

The dimension of the simplicial complex.

Examples

>>> SC = SimplicialComplex([[0, 1], [1, 2, 3], [2, 3, 4]])
>>> SC.dim
2
property maxdim: int#

Maximum dimension of the simplicial complex.

This is the highest dimension of any simplex in the complex.

Returns:
int

The maximum dimension of the simplicial complex.

property nodes: NodeView#

Return the list of nodes in the simplicial complex.

Returns:
NodeView

A NodeView object representing the nodes of the simplicial complex.

property shape: tuple[int, ...]#

Shape of simplicial complex, i.e., the number of simplices for each dimension.

Returns:
tuple of ints

This gives the number of cells in each rank.

Examples

>>> SC = SimplicialComplex([[0, 1], [1, 2, 3], [2, 3, 4]])
>>> SC.shape
(5, 5, 2)
property simplices: SimplexView#

Set of all simplices in the simplicial complex.

Returns:
SimplexView

A SimplexView object representing the set of all simplices in the simplicial complex.

class combinations(iterable, r)#

Bases: object

Return successive r-length combinations of elements in the iterable.

combinations(range(4), 3) –> (0,1,2), (0,1,3), (0,2,3), (1,2,3)

class tqdm(*_, **__)#

Bases: Comparable

Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested.

Parameters:
iterableiterable, optional

Iterable to decorate with a progressbar. Leave blank to manually manage the updates.

descstr, optional

Prefix for the progressbar.

totalint or float, optional

The number of expected iterations. If unspecified, len(iterable) is used if possible. If float(“inf”) or as a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If gui is True and this parameter needs subsequent updating, specify an initial arbitrary large positive number, e.g. 9e9.

leavebool, optional

If [default: True], keeps all traces of the progressbar upon termination of iteration. If None, will leave only if position is 0.

fileio.TextIOWrapper or io.StringIO, optional

Specifies where to output the progress messages (default: sys.stderr). Uses file.write(str) and file.flush() methods. For encoding, see write_bytes.

ncolsint, optional

The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).

minintervalfloat, optional

Minimum progress display update interval [default: 0.1] seconds.

maxintervalfloat, optional

Maximum progress display update interval [default: 10] seconds. Automatically adjusts miniters to correspond to mininterval after long display update lag. Only works if dynamic_miniters or monitor thread is enabled.

minitersint or float, optional

Minimum progress display update interval, in iterations. If 0 and dynamic_miniters, will automatically adjust to equal mininterval (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and mininterval to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1.

asciibool or str, optional

If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters “ 123456789#”.

disablebool, optional

Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY.

unitstr, optional

String that will be used to define the unit of each iteration [default: it].

unit_scalebool or int or float, optional

If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale total and n.

dynamic_ncolsbool, optional

If set, constantly alters ncols and nrows to the environment (allowing for window resizes) [default: False].

smoothingfloat, optional

Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].

bar_formatstr, optional

Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘

‘{rate_fmt}{postfix}]’

Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

Note that a trailing “: “ is automatically removed after {desc} if the latter is empty.

initialint or float, optional

The initial counter value. Useful when restarting a progress bar [default: 0]. If using float, consider specifying {n:.3f} or similar in bar_format, or specifying unit_scale.

positionint, optional

Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).

postfixdict or *, optional

Specify additional stats to display at the end of the bar. Calls set_postfix(**postfix) if possible (dict).

unit_divisorfloat, optional

[default: 1000], ignored unless unit_scale is True.

write_bytesbool, optional

Whether to write bytes. If (default: False) will write unicode.

lock_argstuple, optional

Passed to refresh for intermediate output (initialisation, iterating, and updating).

nrowsint, optional

The screen height. If specified, hides nested bars outside this bound. If unspecified, attempts to use environment height. The fallback is 20.

colourstr, optional

Bar colour (e.g. ‘green’, ‘#00ff00’).

delayfloat, optional

Don’t display until [default: 0] seconds have elapsed.

guibool, optional

WARNING: internal parameter - do not use. Use tqdm.gui.tqdm(…) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False].

Returns:
outdecorated iterator.
__init__(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0.0, gui=False, **kwargs)#
clear(nolock=False)#

Clear current bar display.

close()#

Cleanup and (if leave=False) close the progressbar.

display(msg=None, pos=None)#

Use self.sp to display msg in the specified pos.

Consider overloading this function when inheriting to use e.g.: self.some_frontend(**self.format_dict) instead of self.sp.

Parameters:
msgstr, optional. What to display (default: repr(self)).
posint, optional. Position to moveto

(default: abs(self.pos)).

classmethod external_write_mode(file=None, nolock=False)#

Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream

static format_interval(t)#

Formats a number of seconds as a clock time, [H:]MM:SS

Parameters:
tint

Number of seconds.

Returns:
outstr

[H:]MM:SS

static format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs)#

Return a string-based progress bar given some parameters

Parameters:
nint or float

Number of finished iterations.

totalint or float

The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA).

elapsedfloat

Number of seconds passed since start.

ncolsint, optional

The width of the entire output message. If specified, dynamically resizes {bar} to stay within this bound [default: None]. If 0, will not print any bar (only stats). The fallback is {bar:10}.

prefixstr, optional

Prefix message (included in total width) [default: ‘’]. Use as {desc} in bar_format string.

asciibool, optional or str, optional

If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters “ 123456789#”.

unitstr, optional

The iteration unit [default: ‘it’].

unit_scalebool or int or float, optional

If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale total and n.

ratefloat, optional

Manual override for iteration rate. If [default: None], uses n/elapsed.

bar_formatstr, optional

Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘

‘{rate_fmt}{postfix}]’

Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

Note that a trailing “: “ is automatically removed after {desc} if the latter is empty.

postfix*, optional

Similar to prefix, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ‘, ‘ + postfix. However other types are supported (#382).

unit_divisorfloat, optional

[default: 1000], ignored unless unit_scale is True.

initialint or float, optional

The initial counter value [default: 0].

colourstr, optional

Bar colour (e.g. ‘green’, ‘#00ff00’).

Returns:
outFormatted meter and stats, ready to display.
static format_num(n)#

Intelligent scientific notation (.3g).

Parameters:
nint or float or Numeric

A Number.

Returns:
outstr

Formatted number.

static format_sizeof(num, suffix='', divisor=1000)#

Formats a number (greater than unity) with SI Order of Magnitude prefixes.

Parameters:
numfloat

Number ( >= 1) to format.

suffixstr, optional

Post-postfix [default: ‘’].

divisorfloat, optional

Divisor between prefixes [default: 1000].

Returns:
outstr

Number with Order of Magnitude SI unit postfix.

classmethod get_lock()#

Get the global lock. Construct it if it does not exist.

moveto(n)#
classmethod pandas(**tqdm_kwargs)#
Registers the current tqdm class with

pandas.core. ( frame.DataFrame | series.Series | groupby.(generic.)DataFrameGroupBy | groupby.(generic.)SeriesGroupBy ).progress_apply

A new instance will be created every time progress_apply is called, and each instance will automatically close() upon completion.

Parameters:
tqdm_kwargsarguments for the tqdm instance

References

<https://stackoverflow.com/questions/18603270/ progress-indicator-during-pandas-operations-python>

Examples

>>> import pandas as pd
>>> import numpy as np
>>> from tqdm import tqdm
>>> from tqdm.gui import tqdm as tqdm_gui
>>>
>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
>>> tqdm.pandas(ncols=50)  # can use tqdm_gui, optional kwargs, etc
>>> # Now you can use `progress_apply` instead of `apply`
>>> df.groupby(0).progress_apply(lambda x: x**2)
refresh(nolock=False, lock_args=None)#

Force refresh the display of this bar.

Parameters:
nolockbool, optional

If True, does not lock. If [default: False]: calls acquire() on internal lock.

lock_argstuple, optional

Passed to internal lock’s acquire(). If specified, will only display() if acquire() returns True.

reset(total=None)#

Resets to 0 iterations for repeated use.

Consider combining with leave=True.

Parameters:
totalint or float, optional. Total to use for the new bar.
set_description(desc=None, refresh=True)#

Set/modify description of the progress bar.

Parameters:
descstr, optional
refreshbool, optional

Forces refresh [default: True].

set_description_str(desc=None, refresh=True)#

Set/modify description without ‘: ‘ appended.

classmethod set_lock(lock)#

Set the global lock.

set_postfix(ordered_dict=None, refresh=True, **kwargs)#

Set/modify postfix (additional stats) with automatic formatting based on datatype.

Parameters:
ordered_dictdict or OrderedDict, optional
refreshbool, optional

Forces refresh [default: True].

kwargsdict, optional
set_postfix_str(s='', refresh=True)#

Postfix without dictionary expansion, similar to prefix handling.

static status_printer(file)#

Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh).

unpause()#

Restart tqdm timer from last print time.

update(n=1)#

Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: … … … t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if t.update() will be called in such a way that filesize will be exactly reached and printed.

Parameters:
nint or float, optional

Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying {n:.3f} or similar in bar_format, or specifying unit_scale.

Returns:
outbool or None

True if a display() was triggered.

classmethod wrapattr(stream, method, total=None, bytes=True, **tqdm_kwargs)#

stream : file-like object. method : str, “read” or “write”. The result of read() and

the first argument of write() should have a len().

>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
...     while True:
...         chunk = fobj.read(chunk_size)
...         if not chunk:
...             break
classmethod write(s, file=None, end='\n', nolock=False)#

Print a message via tqdm (without overlap with bars).

property format_dict#

Public API for read-only member access.

monitor = None#
monitor_interval = 10#
to_undirected(edge_index, edge_attr='???', num_nodes=None, reduce='add')#

Converts the graph given by edge_index to an undirected graph such that \((j,i) \in \mathcal{E}\) for every edge \((i,j) \in \mathcal{E}\).

Parameters:
  • edge_index (LongTensor) – The edge indices.

  • edge_attr (Tensor or List[Tensor], optional) – Edge weights or multi- dimensional edge features. If given as a list, will remove duplicates for all its entries. (default: None)

  • num_nodes (int, optional) – The number of nodes, i.e. max(edge_index) + 1. (default: None)

  • reduce (str, optional) – The reduce operation to use for merging edge features ("add", "mean", "min", "max", "mul"). (default: "add")

Return type:

LongTensor if edge_attr is not passed, else (LongTensor, Optional[Tensor] or List[Tensor]])

Warning

From :pyg:`PyG >= 2.3.0` onwards, this function will always return a tuple whenever edge_attr is passed as an argument (even in case it is set to None).

Examples

>>> edge_index = torch.tensor([[0, 1, 1],
...                            [1, 0, 2]])
>>> to_undirected(edge_index)
tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]])
>>> edge_index = torch.tensor([[0, 1, 1],
...                            [1, 0, 2]])
>>> edge_weight = torch.tensor([1., 1., 1.])
>>> to_undirected(edge_index, edge_weight)
(tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]]),
tensor([2., 2., 1., 1.]))
>>> # Use 'mean' operation to merge edge features
>>>  to_undirected(edge_index, edge_weight, reduce='mean')
(tensor([[0, 1, 1, 2],
        [1, 0, 2, 1]]),
tensor([1., 1., 1., 1.]))