topobench.transforms.liftings.simplicial2combinatorial.coface_cc_lifting module#
The CofaceCCLifting lifting.
- class CofaceCCLifting(**kwargs)#
Bases:
Simplicial2CombinatorialLiftingThe CofaceCCLifting class.
This class lifts a simplicial complex to a combinatorial complex by using the coface relation between the simplicial cells.
- Parameters:
- **kwargsdict
The keyword arguments.
- __init__(**kwargs)#
- forward(data)#
Forward pass.
- Parameters:
- datatorch_geometric.data.Data
The input data.
- Returns:
- torch_geometric.data.Data
The updated lifted data.
- get_lower_cells(data)#
Get the lower cells of the complex.
- Parameters:
- datatorch_geometric.data.Data
The input data.
- Returns:
- list
The list of lower cells.
- lift_topology(data)#
Lift the simplicial topology to a combinatorial complex.
- Parameters:
- datatorch_geometric.data.Data
The input data.
- Returns:
- dict
The lifted connectivity dict.
- class CombinatorialComplex(cells=None, ranks=None, graph_based=False, **kwargs)#
Bases:
ColoredHyperGraphClass for Combinatorial Complex.
A Combinatorial Complex (CCC) is a triple $CCC = (S, X, rk)$ where: - $S$ is an abstract set of entities, - $X$ a subset of the power set of $S$, and - $rk$ is the a rank function that associates for every set x in X a rank, a positive integer.
The rank function $rk$ must satisfy $x subseteq y$ then $rk(x) leq rk(y)$. We call this condition the CCC condition.
A CCC is a generalization of graphs, hypergraphs, cellular and simplicial complexes.
Mathematical Example:
Let $S = {1, 2, 3, 4}$ be a set of abstract entities. Let $X = {{1, 2}, {1, 2, 3}, {1, 3}, {1, 4}}$ be a subset of the power set of $S$. Let rk be the ranking function that assigns the length of a set as its rank, i.e. $rk({1, 2}) = 2$, $rk({1, 2, 3}) = 3$, etc.
Then, $(S, X, rk)$ is a combinatorial complex.
- Parameters:
- cellsCollection, optional
A collection of cells to add to the combinatorial complex.
- ranksCollection, optional
When cells is an iterable or dictionary, ranks cannot be None and it must be iterable/dict of the same size as cells.
- graph_basedbool, default=False
When true rank 1 edges must have cardinality equals to 1.
- **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.
- Raises:
- TypeError
If cells is not given as an Iterable.
- ValueError
If input cells is not an instance of HyperEdge when rank is None. If input HyperEdge has None rank when rank is specified. If cells and ranks do not have an equal number of elements.
Examples
Define an empty combinatorial complex:
>>> CCC = tnx.CombinatorialComplex()
Add cells to the combinatorial complex:
>>> CCC = tnx.CombinatorialComplex() >>> CCC.add_cell([1, 2], rank=1) >>> CCC.add_cell([3, 4], rank=1) >>> CCC.add_cell([1, 2, 3, 4], rank=2) >>> CCC.add_cell([1, 2, 4], rank=2) >>> CCC.add_cell([1, 2, 3, 4, 5, 6, 7], rank=3)
- __init__(cells=None, ranks=None, graph_based=False, **kwargs)#
Initialize a new instance of the Complex class.
- Parameters:
- **kwargskeyword arguments, optional
Attributes to add to the complex as key=value pairs.
- add_cell(cell, rank=None, **attr)#
Add a single cells to combinatorial complex.
- Parameters:
- cellhashable, iterable or HyperEdge
If hashable the cell returned will be empty.
- rankint
Rank of the cell.
- **attrkeyword arguments, optional
Attributes to add to the cell as key=value pairs.
- add_cells_from(cells, ranks=None)#
Add cells to combinatorial complex.
- Parameters:
- cellsiterable of hashables
For hashables the cells returned will be empty.
- ranksiterable or int, optional
When iterable, len(ranks) == len(cells).
- add_node(node, **attr)#
Add a node to a CCC.
- Parameters:
- nodeHashable
The node to add to this combinatorial complex.
- **attrkeyword arguments, optional
Attributes to add to the node as key=value pairs.
- adjacency_matrix(rank, via_rank, s=1, index=False)#
Sparse weighted s-adjacency matrix.
- Parameters:
- rank, via_rankint
Two ranks for skeletons in the input combinatorial complex.
- sint, default=1
Minimum number of edges shared by neighbors with node.
- indexbool, default=False
Whether to return the indices of the rows and columns of the adjacency matrix.
- Returns:
- indiceslist
List identifying the rows and columns of the adjacency matrix with the cells of the combinatorial complex. Only returned if index is True.
- adjacency_matrixscipy.sparse.csr.csr_matrix
The adjacency matrix of this combinatorial complex.
Examples
>>> CCC = tnx.CombinatorialComplex() >>> CCC.add_cell([1, 2], rank=1) >>> CCC.add_cell([3, 4], rank=1) >>> CCC.add_cell([1, 2, 3, 4], rank=2) >>> CCC.add_cell([1, 2, 4], rank=2) >>> CCC.add_cell([1, 2, 3, 4, 5, 6, 7], rank=3) >>> CCC.adjacency_matrix(0, 1)
- clone()#
Return a copy of the simplex.
The clone method by default returns an independent shallow copy of the simplex and attributes. That is, if an attribute is a container, that container is shared by the original and the copy. Use Python’s copy.deepcopy for new containers.
- Returns:
- CombinatorialComplex
A copy of this combinatorial complex.
- coadjacency_matrix(rank, via_rank, s=1, index=False)#
Compute the coadjacency matrix of self.
- Parameters:
- rank, via_rankint
Two ranks for skeletons in the input combinatorial complex , such that r>k.
- sint, default=1
Minimum number of edges shared by neighbors with node.
- 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 cells of the combinatorial complex. Only returned if index is True.
- coadjacency_matrixscipy.sparse.csr.csr_matrix
The coadjacency matrix of this combinatorial complex.
- dirac_operator_matrix(weight=None, index=False)#
Compute dirac operator matrix of self.
- Parameters:
- weightstr, optional
The name of the cell attribute to use as weights for the dirac operator matrix. If None, the matrix is binary.
- indexbool, default=False
If True, return will include a dictionary of all cells in the complex uid.
- Returns:
- scipy.sparse.csr.csc_matrix | tuple[dict, dict, scipy.sparse.csc_matrix]
The dirac operator matrix, if index is False; otherwise, row_indices, col_indices : dict List identifying rows and columns of the dirac operator matrix. Only returned if index is True. dirac_matrix : scipy.sparse.csr.csc_matrix The dirac operator matrix of this combinatorial complex.
Examples
>>> CCC = tnx.CombinatorialComplex() >>> CCC.add_cell([1, 2, 3, 4], rank=2) >>> CCC.add_cell([1, 2], rank=1) >>> CCC.add_cell([2, 3], rank=1) >>> CCC.add_cell([1, 4], rank=1) >>> CCC.add_cell([3, 4, 8], rank=2) >>> CCC.dirac_operator_matrix()
- get_cell_attributes(name, rank=None)#
Get node attributes from graph.
- Parameters:
- namestr
Attribute name.
- rankint
Restrict the returned attribute values to cells of a specific rank.
- Returns:
- dict
Dictionary of attributes keyed by cell or k-cells if k is not None.
Examples
>>> G = nx.path_graph(3) >>> CCC = tnx.CombinatorialComplex(G) >>> d = { ... (1, 2): {"color": "red", "attr2": 1}, ... (0, 1): {"color": "blue", "attr2": 3}, ... } >>> CCC.set_cell_attributes(d) >>> cell_color = CCC.get_cell_attributes("color") >>> cell_color[frozenset({0, 1})] 'blue'
- get_node_attributes(name)#
Get node attributes.
- Parameters:
- namestr
Attribute name.
- Returns:
- dict[Hashable, Any]
Dictionary mapping each node to the value of the given attribute name.
Examples
>>> G = nx.path_graph(3) >>> CCC = tnx.CombinatorialComplex(G) >>> d = {0: {"color": "red", "attr2": 1}, 1: {"color": "blue", "attr2": 3}} >>> CCC.set_node_attributes(d) >>> CCC.get_node_attributes("color") {0: 'red', 1: 'blue'}
>>> G = nx.Graph() >>> G.add_nodes_from([1, 2, 3], color="blue") >>> CCC = tnx.CombinatorialComplex(G) >>> nodes_color = CCC.get_node_attributes("color") >>> nodes_color[1] 'blue'
- incidence_matrix(rank, to_rank=None, incidence_type='up', weight=None, sparse=True, index=False)#
Compute incidence matrix for the CCC between rank and to_rank skeleti.
- Parameters:
- rank, to_rankint
For which rank of cells to compute the incidence matrix.
- incidence_type{“up”, “down”}, default=”up”
Whether to compute the up or down incidence matrix.
- weightbool, default=False
The name of the cell attribute to use as weights for the incidence matrix. If None, all cell weights are considered to be one.
- sparsebool, default=True
Whether to return a sparse or dense incidence matrix.
- 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 cell.
- incidence_matrixscipy.sparse.csr.csr_matrix
The incidence matrix.
- number_of_cells(cell_set=None)#
Compute the number of cells in cell_set belonging to the CCC.
- Parameters:
- cell_setiterable of HyperEdge, optional
If None, then return the number of cells.
- Returns:
- int
The number of cells in cell_set belonging to this combinatorial complex.
- number_of_nodes(node_set=None)#
Compute the number of nodes in node_set belonging to the CCC.
- Parameters:
- node_setiterable of Entities, optional
If None, then return the number of nodes in the CCC.
- Returns:
- int
The number of nodes in node_set belonging to this combinatorial complex.
- order()#
Compute the number of nodes in the CCC.
- Returns:
- int
The number of nodes in this combinatorial complex.
- remove_cell(cell)#
Remove a single cell from CCC.
- Parameters:
- cellhashable or RankedEntity
The cell to remove from this combinatorial complex.
Notes
Deletes reference to cell from all of its nodes. If any of its nodes do not belong to any other cells the node is dropped from self.
- remove_cells(cell_set)#
Remove cells from CCC.
- Parameters:
- cell_setiterable of hashables
The cells to remove from this combinatorial complex.
- remove_node(node)#
Remove node from cells.
This also deletes any reference in the nodes of the CCC. This also deletes cell references in higher ranks for the particular node.
- Parameters:
- nodehashable or HyperEdge
The node to remove from this combinatorial complex.
- remove_nodes(node_set)#
Remove nodes from cells.
This also deletes references in combinatorial complex nodes.
- Parameters:
- node_setan iterable of hashables
The nodes to remove from this combinatorial complex.
- remove_singletons()#
Construct new CCC with singleton cells removed.
- Returns:
- CombinatorialComplex
A copy of this combinatorial complex with singleton cells removed.
- set_cell_attributes(values, name=None)#
Set cell attributes.
- Parameters:
- valuesdict
Dictionary of cell attributes to set keyed by cell name.
- namestr, optional
Attribute name.
Examples
After computing some property of the cell of a combinatorial complex, you may want to assign a cell attribute to store the value of that property for each cell:
>>> CCC = tnx.CombinatorialComplex() >>> CCC.add_cell([1, 2, 3, 4], rank=2) >>> CCC.add_cell([1, 2, 4], rank=2) >>> CCC.add_cell([3, 4], rank=2) >>> d = {(1, 2, 3, 4): "red", (1, 2, 3): "blue", (3, 4): "green"} >>> CCC.set_cell_attributes(d, name="color") >>> CCC.cells[(3, 4)]["color"] 'green'
If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update edge attributes:
>>> G = nx.path_graph(3) >>> CCC = tnx.CombinatorialComplex(G) >>> d = { ... (1, 2): {"color": "red", "attr2": 1}, ... (0, 1): {"color": "blue", "attr2": 3}, ... } >>> CCC.set_cell_attributes(d) >>> CCC.cells[(0, 1)]["color"] 'blue' 3
Note that if the dict contains cells that are not in self.cells, they are silently ignored.
- singletons()#
Return a list of singleton cell.
A singleton cell is a node of degree 0.
- Returns:
- list
A list of cells uids.
Examples
>>> CCC = tnx.CombinatorialComplex() >>> CCC.add_cell([1, 2], rank=1) >>> CCC.add_cell([3, 4], rank=1) >>> CCC.add_cell([9], rank=0) >>> CCC.singletons() [frozenset({9})]
- skeleton(rank, level='equal')#
Skeleton of the CCC.
- Parameters:
- rankint
The rank of the skeleton.
- levelstr, default=”equal”
Level of the skeleton.
- Returns:
- list of HyperEdge
The skeleton of the CCC.
- property cells#
Object associated with self._cells.
- Returns:
- HyperEdgeView
Returns all the present cells in the combinatorial complex along with their rank.
- property nodes#
Object associated with self.elements.
- Returns:
- NodeView
Returns all the nodes of the combinatorial complex.
- property shape#
Return shape.
This is: (number of cells[i], for i in range(0,dim(CCC)) )
- Returns:
- tuple of ints
Shape of the CC object.
- class Data(x=None, edge_index=None, edge_attr=None, y=None, pos=None, time=None, **kwargs)#
Bases:
BaseData,FeatureStore,GraphStoreA data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general,
Datatries 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
Dataobjects, 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
Dataobject from a dictionary.
- get_all_edge_attrs()#
Returns all registered edge attributes.
- get_all_tensor_attrs()#
Obtains all feature attributes stored in Data.
- 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
Dataobject to a heterogeneousHeteroDataobject. For this, node and edge attributes are splitted according to the node-level and edge-level vectorsnode_typeandedge_type, respectively.node_type_namesandedge_type_namescan be used to give meaningful node and edge type names, respectively. That is, the node_type0is given bynode_type_names[0]. If theDataobject was constructed viato_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
NamedTupleof 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 num_features: int#
Returns the number of features per node in the graph. Alias for
num_node_features.
- 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 toedge_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 viadata.num_nodes = .... You will be given a warning that requests you to do so.
- class HyperEdge(elements, rank=None, **kwargs)#
Bases:
Atom[frozenset[Hashable]]Class for a hyperedge (or a set-type cell).
This class represents a set-type cell in a combinatorial complex, which is a set of nodes with optional attributes and a rank. The nodes in a hyperedge must be hashable and unique, and the hyperedge itself is immutable.
- Parameters:
- elementsiterable of hashables
The nodes in the hyperedge.
- rankint, optional
The rank of the hyperedge. Default is None.
- **kwargsadditional attributes
Additional attributes of the hyperedge, as keyword arguments.
Examples
>>> ac1 = tnx.HyperEdge((1, 2, 3)) >>> ac2 = tnx.HyperEdge((1, 2, 4, 5)) >>> ac3 = tnx.HyperEdge(("a", "b", "c")) >>> ac3 = tnx.HyperEdge(("a", "b", "c"), rank=10)
- __init__(elements, rank=None, **kwargs)#
- property rank#
Rank of the HyperEdge.
- Returns:
- int or None
The rank of the HyperEdge if it is not None, None otherwise.
- class Simplicial2CombinatorialLifting(**kwargs)#
Bases:
SimplicialLiftingAbstract class for lifting graphs to combinatorial complexes.
- Parameters:
- **kwargsoptiona””l
Additional arguments for the class.
- __init__(**kwargs)#
- get_combinatorial_complex_connectivity(complex, max_rank, neighborhoods=None)#
Get the connectivity matrices for the Combinatorial Complex.
- Parameters:
- complextopnetx.CombinatorialComplex
Cell complex.
- max_rankint
Maximum rank of the complex.
- neighborhoodslist, optional
List of neighborhoods of interest.
- Returns:
- dict
Dictionary containing the connectivity matrices.