diff --git a/docs/build/.buildinfo b/docs/build/.buildinfo index d47e0bb6..15de628c 100644 --- a/docs/build/.buildinfo +++ b/docs/build/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: bbecb70f0b1dbbfd5f5e21c3f3cc3da1 +config: 61749d9a3b09dd54ea31a725ed375529 tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/.doctrees/algorithms/algorithms.doctree b/docs/build/.doctrees/algorithms/algorithms.doctree index 03a511d1..aab674b2 100644 Binary files a/docs/build/.doctrees/algorithms/algorithms.doctree and b/docs/build/.doctrees/algorithms/algorithms.doctree differ diff --git a/docs/build/.doctrees/classes/classes.doctree b/docs/build/.doctrees/classes/classes.doctree index bf061d41..ae309cc8 100644 Binary files a/docs/build/.doctrees/classes/classes.doctree and b/docs/build/.doctrees/classes/classes.doctree differ diff --git a/docs/build/.doctrees/drawing/drawing.doctree b/docs/build/.doctrees/drawing/drawing.doctree index 77265ab8..a9d74851 100644 Binary files a/docs/build/.doctrees/drawing/drawing.doctree and b/docs/build/.doctrees/drawing/drawing.doctree differ diff --git a/docs/build/.doctrees/environment.pickle b/docs/build/.doctrees/environment.pickle index ca6be2e3..58acddd9 100644 Binary files a/docs/build/.doctrees/environment.pickle and b/docs/build/.doctrees/environment.pickle differ diff --git a/docs/build/.doctrees/reports/reports.doctree b/docs/build/.doctrees/reports/reports.doctree index dd0af8e0..686572f7 100644 Binary files a/docs/build/.doctrees/reports/reports.doctree and b/docs/build/.doctrees/reports/reports.doctree differ diff --git a/docs/build/_modules/algorithms/homology_mod2.html b/docs/build/_modules/algorithms/homology_mod2.html deleted file mode 100644 index ffc33828..00000000 --- a/docs/build/_modules/algorithms/homology_mod2.html +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - - - - - - algorithms.homology_mod2 — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • algorithms.homology_mod2
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for algorithms.homology_mod2

-"""
-Homology and Smith Normal Form
-==============================
-The purpose of computing the Homology groups for data generated
-hypergraphs is to identify data sources that correspond to interesting
-features in the topology of the hypergraph.
-
-The elements of one of these Homology groups are generated by $k$
-dimensional cycles of relationships in the original data that are not
-bound together by higher order relationships. Ideally, we want the
-briefest description of these cycles; we want a minimal set of
-relationships exhibiting interesting cyclic behavior. This minimal set
-will be a bases for the Homology group.
-
-The cyclic relationships in the data are discovered using a **boundary
-map** represented as a matrix. To discover the bases we compute the
-**Smith Normal Form** of the boundary map.
-
-Homology Mod2
--------------
-This module computes the homology groups for data represented as an
-abstract simplicial complex with chain groups $\{C_k\}$ and $Z_2$ additions.
-The boundary matrices are represented as rectangular matrices over $Z_2$.
-These matrices are diagonalized and represented in Smith
-Normal Form. The kernel and image bases are computed and the Betti
-numbers and homology bases are returned.
-
-Methods for obtaining SNF for Z/2Z are based on Ferrario's work:
-http://www.dlfer.xyz/post/2016-10-27-smith-normal-form/
-
-"""
-
-import numpy as np
-import hypernetx as hnx
-import warnings
-import copy
-from hypernetx import HyperNetXError
-from collections import defaultdict
-import itertools as it
-import pickle
-from scipy.sparse import csr_matrix
-
-__all__ = [
-    "kchainbasis",
-    "bkMatrix",
-    "swap_rows",
-    "swap_columns",
-    "add_to_row",
-    "add_to_column",
-    "logical_dot",
-    "logical_matmul",
-    "matmulreduce",
-    "logical_matadd",
-    "smith_normal_form_mod2",
-    "reduced_row_echelon_form_mod2",
-    "boundary_group",
-    "chain_complex",
-    "betti",
-    "betti_numbers",
-    "homology_basis",
-    "hypergraph_homology_basis",
-    "interpret",
-]
-
-
-
[docs]def kchainbasis(h, k): - """ - Compute the set of k dimensional cells in the abstract simplicial - complex associated with the hypergraph. - - Parameters - ---------- - h : hnx.Hypergraph - k : int - dimension of cell - - Returns - ------- - : list - an ordered list of kchains represented as tuples of length k+1 - - See also - -------- - hnx.hypergraph.toplexes - - Notes - ----- - - Method works best if h is simple [Berge], i.e. no edge contains another and there are no duplicate edges (toplexes). - - Hypergraph node uids must be sortable. - - """ - - import itertools as it - - kchains = set() - for e in h.edges(): - en = sorted(h.edges[e]) - if len(en) == k + 1: - kchains.add(tuple(en)) - elif len(en) > k + 1: - kchains.update(set(it.combinations(en, k + 1))) - return sorted(list(kchains))
- - -
[docs]def bkMatrix(km1basis, kbasis): - """ - Compute the boundary map from $C_{k-1}$-basis to $C_k$ basis with - respect to $Z_2$ - - Parameters - ---------- - km1basis : indexable iterable - Ordered list of $k-1$ dimensional cell - kbasis : indexable iterable - Ordered list of $k$ dimensional cells - - Returns - ------- - bk : np.array - boundary matrix in $Z_2$ stored as boolean - - """ - bk = np.zeros((len(km1basis), len(kbasis)), dtype=int) - for cell in kbasis: - for idx in range(len(cell)): - face = cell[:idx] + cell[idx + 1 :] - row = km1basis.index(face) - col = kbasis.index(cell) - bk[row, col] = 1 - return bk
- - -def _rswap(i, j, S): - """ - Swaps ith and jth row of copy of S - - Parameters - ---------- - i : int - j : int - S : np.array - - Returns - ------- - N : np.array - """ - N = copy.deepcopy(S) - row = copy.deepcopy(N[i]) - N[i] = copy.deepcopy(N[j]) - N[j] = row - return N - - -def _cswap(i, j, S): - """ - Swaps ith and jth column of copy of S - - Parameters - ---------- - i : int - j : int - S : np.array - matrix - - Returns - ------- - N : np.array - """ - N = _rswap(i, j, S.transpose()).transpose() - return N - - -
[docs]def swap_rows(i, j, *args): - """ - Swaps ith and jth row of each matrix in args - Returns a list of new matrices - - Parameters - ---------- - i : int - j : int - args : np.arrays - - Returns - ------- - list - list of copies of args with ith and jth row swapped - """ - output = list() - for M in args: - output.append(_rswap(i, j, M)) - return output
- - -
[docs]def swap_columns(i, j, *args): - """ - Swaps ith and jth column of each matrix in args - Returns a list of new matrices - - Parameters - ---------- - i : int - j : int - args : np.arrays - - Returns - ------- - list - list of copies of args with ith and jth row swapped - """ - output = list() - for M in args: - output.append(_cswap(i, j, M)) - return output
- - -
[docs]def add_to_row(M, i, j): - """ - Replaces row i with logical xor between row i and j - - Parameters - ---------- - M : np.array - i : int - index of row being altered - j : int - index of row being added to altered - - Returns - ------- - N : np.array - """ - N = copy.deepcopy(M) - N[i] = 1 * np.logical_xor(N[i], N[j]) - return N
- - -
[docs]def add_to_column(M, i, j): - """ - Replaces column i (of M) with logical xor between column i and j - - Parameters - ---------- - M : np.array - matrix - i : int - index of column being altered - j : int - index of column being added to altered - - Returns - ------- - N : np.array - """ - N = M.transpose() - return add_to_row(N, i, j).transpose()
- - -
[docs]def logical_dot(ar1, ar2): - """ - Returns the boolean equivalent of the dot product mod 2 on two 1-d arrays of - the same length. - - Parameters - ---------- - ar1 : numpy.ndarray - 1-d array - ar2 : numpy.ndarray - 1-d array - - Returns - ------- - : bool - boolean value associated with dot product mod 2 - - Raises - ------ - HyperNetXError - If arrays are not of the same length an error will be raised. - """ - if len(ar1) != len(ar2): - raise HyperNetXError("logical_dot requires two 1-d arrays of the same length") - else: - return 1 * np.logical_xor.reduce(np.logical_and(ar1, ar2))
- - -
[docs]def logical_matmul(mat1, mat2): - """ - Returns the boolean equivalent of matrix multiplication mod 2 on two - binary arrays stored as type boolean - - Parameters - ---------- - mat1 : np.ndarray - 2-d array of boolean values - mat2 : np.ndarray - 2-d array of boolean values - - Returns - ------- - mat : np.ndarray - boolean matrix equivalent to the mod 2 matrix multiplication of the - matrices as matrices over Z/2Z - - Raises - ------ - HyperNetXError - If inner dimensions are not equal an error will be raised. - - """ - L1, R1 = mat1.shape - L2, R2 = mat2.shape - if R1 != L2: - raise HyperNetXError( - "logical_matmul called for matrices with inner dimensions mismatched" - ) - - mat = np.zeros((L1, R2), dtype=int) - mat2T = mat2.transpose() - for i in range(L1): - if np.any(mat1[i]): - for j in range(R2): - mat[i, j] = logical_dot(mat1[i], mat2T[j]) - else: - mat[i] = np.zeros((1, R2), dtype=int) - return mat
- - -
[docs]def matmulreduce(arr, reverse=False): - """ - Recursively applies a 'logical multiplication' to a list of boolean arrays. - - For arr = [arr[0],arr[1],arr[2]...arr[n]] returns product arr[0]arr[1]...arr[n] - If reverse = True, returns product arr[n]arr[n-1]...arr[0] - - Parameters - ---------- - arr : list of np.array - list of nxm matrices represented as np.array - reverse : bool, optional - order to multiply the matrices - - Returns - ------- - P : np.array - Product of matrices in the list - """ - if reverse: - items = range(len(arr) - 1, -1, -1) - else: - items = range(len(arr)) - P = arr[items[0]] - for i in items[1:]: - P = logical_matmul(P, arr[i]) * 1 - return P
- - -
[docs]def logical_matadd(mat1, mat2): - """ - Returns the boolean equivalent of matrix addition mod 2 on two - binary arrays stored as type boolean - - Parameters - ---------- - mat1 : np.ndarray - 2-d array of boolean values - mat2 : np.ndarray - 2-d array of boolean values - - Returns - ------- - mat : np.ndarray - boolean matrix equivalent to the mod 2 matrix addition of the - matrices as matrices over Z/2Z - - Raises - ------ - HyperNetXError - If dimensions are not equal an error will be raised. - - """ - S1 = mat1.shape - S2 = mat2.shape - mat = np.zeros(S1, dtype=int) - if S1 != S2: - raise HyperNetXError( - "logical_matadd called for matrices with different dimensions" - ) - if len(S1) == 1: - for idx in range(S1[0]): - mat[idx] = 1 * np.logical_xor(mat1[idx], mat2[idx]) - else: - for idx in range(S1[0]): - for jdx in range(S1[1]): - mat[idx, jdx] = 1 * np.logical_xor(mat1[idx, jdx], mat2[idx, jdx]) - return mat
- - -# Convenience methods for computing Smith Normal Form -# All of these operations have themselves as inverses - - -def _sr(i, j, M, L): - return swap_rows(i, j, M, L) - - -def _sc(i, j, M, R): - return swap_columns(i, j, M, R) - - -def _ar(i, j, M, L): - return add_to_row(M, i, j), add_to_row(L, i, j) - - -def _ac(i, j, M, R): - return add_to_column(M, i, j), add_to_column(R, i, j) - - -def _get_next_pivot(M, s1, s2=None): - """ - Determines the first r,c indices in the submatrix of M starting - with row s1 and column s2 index (row,col) that is nonzero, - if it exists. - - Search starts with the s2th column and looks for the first nonzero - s1 row. If none is found, search continues to the next column and so - on. - - Parameters - ---------- - M : np.array - matrix represented as np.array - s1 : int - index of row position to start submatrix of M - s2 : int, optional, default = s1 - index of column position to start submatrix of M - - Returns - ------- - (r,c) : tuple of int or None - - """ - # find the next nonzero pivot to put in s,s spot for Smith Normal Form - m, n = M.shape - if not s2: - s2 = s1 - for c in range(s2, n): - for r in range(s1, m): - if M[r, c]: - return (r, c) - return None - - -
[docs]def smith_normal_form_mod2(M): - """ - Computes the invertible transformation matrices needed to compute the - Smith Normal Form of M modulo 2 - - Parameters - ---------- - M : np.array - a rectangular matrix with data type bool - track : bool - if track=True will print out the transformation as Z/2Z matrix as it - discovers L[i] and R[j] - - Returns - ------- - L, R, S, Linv : np.arrays - LMR = S is the Smith Normal Form of the matrix M. - - Note - ---- - Given a mxn matrix $M$ with - entries in $Z_2$ we start with the equation: $L M R = S$, where - $L = I_m$, and $R=I_n$ are identity matrices and $S = M$. We - repeatedly apply actions to the left and right side of the equation - to transform S into a diagonal matrix. - For each action applied to the left side we apply its inverse - action to the right side of I_m to generate $L^{-1}$. - Finally we verify: - $L M R = S$ and $LLinv = I_m$. - """ - - S = copy.copy(M) - dimL, dimR = M.shape - - # initialize left and right transformations with identity matrices - L = np.eye(dimL, dtype=int) - R = np.eye(dimR, dtype=int) - Linv = np.eye(dimL, dtype=int) - for s in range(min(dimL, dimR)): - # Find index pair (rdx,cdx) with value 1 in submatrix M[s:,s:] - pivot = _get_next_pivot(S, s) - if not pivot: - break - else: - rdx, cdx = pivot - # Swap rows and columns as needed so that 1 is in the s,s position - if rdx > s: - S, L = _sr(s, rdx, S, L) - Linv = swap_columns(rdx, s, Linv)[0] - if cdx > s: - S, R = _sc(s, cdx, S, R) - # add sth row to every row with 1 in sth column & sth column to every column with 1 in sth row - row_indices = [idx for idx in range(s + 1, dimL) if S[idx, s] == 1] - for rdx in row_indices: - S, L = _ar(rdx, s, S, L) - Linv = add_to_column(Linv, s, rdx) - column_indices = [jdx for jdx in range(s + 1, dimR) if S[s, jdx] == 1] - for cdx in column_indices: - S, R = _ac(cdx, s, S, R) - return L, R, S, Linv
- - -
[docs]def reduced_row_echelon_form_mod2(M): - """ - Computes the invertible transformation matrices needed to compute - the reduced row echelon form of M modulo 2 - - Parameters - ---------- - M : np.array - a rectangular matrix with elements in $Z_2$ - - Returns - ------- - L, S, Linv : np.arrays - LM = S where S is the reduced echelon form of M - and M = LinvS - """ - S = copy.deepcopy(M) - dimL, dimR = M.shape - - # method with numpy - Linv = np.eye(dimL, dtype=int) - L = np.eye(dimL, dtype=int) - - s2 = 0 - s1 = 0 - while s2 <= dimR and s1 <= dimL: - # Find index pair (rdx,cdx) with value 1 in submatrix M[s1:,s2:] - # look for the first 1 in the s2 column - pivot = _get_next_pivot(S, s1, s2) - - if not pivot: - return L, S, Linv - else: - rdx, cdx = pivot - if rdx > s1: - # Swap rows as needed so that 1 leads the row - S, L = _sr(s1, rdx, S, L) - Linv = swap_columns(rdx, s1, Linv)[0] - # add s1th row to every nonzero row - row_indices = [ - idx for idx in range(0, dimL) if idx != s1 and S[idx, cdx] == 1 - ] - for idx in row_indices: - S, L = _ar(idx, s1, S, L) - Linv = add_to_column(Linv, s1, idx) - s1, s2 = s1 + 1, cdx + 1 - - return L, S, Linv
- - -
[docs]def boundary_group(image_basis): - """ - Returns a csr_matrix with rows corresponding to the elements of the - group generated by image basis over $\mathbb{Z}_2$ - - Parameters - ---------- - image_basis : numpy.ndarray or scipy.sparse.csr_matrix - 2d-array of basis elements - - Returns - ------- - : scipy.sparse.csr_matrix - """ - if len(image_basis) > 10: - msg = """ - This method is inefficient for large image bases. - """ - warnings.warn(msg, stacklevel=2) - if np.sum(image_basis) == 0: - return None - dim = image_basis.shape[0] - itm = csr_matrix(list(it.product([0, 1], repeat=dim))) - return csr_matrix(np.mod(itm * image_basis, 2))
- - -def _compute_matrices_for_snf(bd): - """ - Helper method for smith normal form decomposition for boundary maps - associated to chain complex - - Parameters - ---------- - bd : dict - dict of k-boundary matrices keyed on dimension of domain - - Returns - ------- - L,R,S,Linv : dict - dict of matrices ranging over krange - - """ - L, R, S, Linv = [dict() for i in range(4)] - - for kdx in bd: - L[kdx], R[kdx], S[kdx], Linv[kdx] = smith_normal_form_mod2(bd[kdx]) - return L, R, S, Linv - - -def _get_krange(max_dim, k=None): - """ - Helper method to compute range of appropriate k dimensions for homology - computations given k and the max dimension of a simplicial complex - """ - if k is None: - krange = [1, max_dim] - elif isinstance(k, int): - if k == 0: - msg = ( - "Only kth simplicial homology groups for k>0 may be computed." - "If you are interested in k=0, compute the number connected components." - ) - print(msg) - return - if k > max_dim: - msg = f"No simplices of dim {k} exist. k adjusted to max dim." - print(msg) - krange = [min([k, max_dim])] * 2 - elif not len(k) == 2: - msg = f"Please enter krange as a positive integer or list of integers: [<min k>,<max k>] inclusive." - print(msg) - return None - elif not k[0] <= k[1]: - msg = f"k must be an integer or a list of two integers [min,max] with min <=max" - print(msg) - return None - else: - krange = k - - if krange[1] > max_dim: - msg = f"No simplices of dim {krange[1]} exist. Range adjusted to max dim." - print(msg) - krange[1] = max_dim - if krange[0] < 1: - msg = ( - "Only kth simplicial homology groups for k>0 may be computed." - "If you are interested in k=0, compute the number of connected components." - ) - print(msg) - krange[0] = 1 - return krange - - -
[docs]def chain_complex(h, k=None): - """ - Compute the k-chains and k-boundary maps required to compute homology - for all values in k - - Parameters - ---------- - h : hnx.Hypergraph - k : int or list of length 2, optional, default=None - k must be an integer greater than 0 or a list of - length 2 indicating min and max dimensions to be - computed. eg. if k = [1,2] then 0,1,2,3-chains - and boundary maps for k=1,2,3 will be returned, - if None than k = [1,max dimension of edge in h] - - Returns - ------- - C, bd : dict - C is a dictionary of lists - bd is a dictionary of numpy arrays - """ - max_dim = np.max([len(h.edges[e]) for e in h.edges()]) - 1 - krange = _get_krange(max_dim, k) - if not krange: - return - # Compute chain complex - - C = defaultdict(list) - C[krange[0] - 1] = kchainbasis(h, krange[0] - 1) - bd = dict() - for kdx in range(krange[0], krange[1] + 2): - C[kdx] = kchainbasis(h, kdx) - bd[kdx] = bkMatrix(C[kdx - 1], C[kdx]) - return C, bd
- - -
[docs]def betti(bd, k=None): - """ - Generate the kth-betti numbers for a chain complex with boundary - matrices given by bd - - Parameters - ---------- - bd: dict of k-boundary matrices keyed on dimension of domain - k : int, list or tuple, optional, default=None - list must be min value and max value of k values inclusive - if None, then all betti numbers for dimensions of existing cells will be - computed. - - Returns - ------- - betti : dict - Description - """ - rank = defaultdict(int) - if k: - max_dim = max(bd.keys()) - krange = _get_krange(max_dim, k) - if not krange: - return - kvals = sorted(set(range(krange[0], krange[1] + 2)).intersection(bd.keys())) - else: - kvals = bd.keys() - for kdx in kvals: - _, S, _ = hnx.reduced_row_echelon_form_mod2(bd[kdx]) - rank[kdx] = np.sum(np.sum(S, axis=1).astype(bool)) - - betti = dict() - for kdx in kvals: - if kdx + 1 in kvals: - betti[kdx] = bd[kdx].shape[1] - rank[kdx] - rank[kdx + 1] - else: - continue - - return betti
- - -
[docs]def betti_numbers(h, k=None): - """ - Return the kth betti numbers for the simplicial homology of the ASC - associated to h - - Parameters - ---------- - h : hnx.Hypergraph - Hypergraph to compute the betti numbers from - k : int or list, optional, default=None - list must be min value and max value of k values inclusive - if None, then all betti numbers for dimensions of existing cells will be - computed. - - Returns - ------- - betti : dict - A dictionary of betti numbers keyed by dimension - """ - _, bd = chain_complex(h, k) - return betti(bd)
- - -
[docs]def homology_basis(bd, k=None, boundary=False, **kwargs): - """ - Compute a basis for the kth-simplicial homology group, $H_k$, defined by a - chain complex $C$ with boundary maps given by bd $= \{k:\partial_k$\}$ - - Parameters - ---------- - bd : dict - dict of boundary matrices on k-chains to k-1 chains keyed on k - if krange is a tuple then all boundary matrices k \in [krange[0],..,krange[1]] - inclusive must be in the dictionary - k : int or list of ints, optional, default=None - k must be a positive integer or a list of - 2 integers indicating min and max dimensions to be - computed, if none given all homology groups will be computed from - available boundary matrices in bd - boundary : bool - option to return a basis for the boundary group from each dimension. - Needed to compute the shortest generators in the homology group. - - Returns - ------- - basis : dict - dict of generators as 0-1 tuples keyed by dim - basis for dimension k will be returned only if bd[k] and bd[k+1] have - been provided. - im : dict - dict of boundary group generators keyed by dim - """ - max_dim = max(bd.keys()) - if k: - krange = _get_krange(max_dim, k) - kvals = sorted( - set(bd.keys()).intersection(range(krange[0], krange[1] + 2)) - ) # to get kth dim need k+1 bdry matrix - else: - kvals = bd.keys() - - L, R, S, Linv = _compute_matrices_for_snf( - {k: v for k, v in bd.items() if k in kvals} - ) - - rank = dict() - for kdx in kvals: - rank[kdx] = np.sum(S[kdx]) - - basis = dict() - im = dict() - for kdx in kvals: - if kdx + 1 not in kvals: - continue - rank1 = rank[kdx] - rank2 = rank[kdx + 1] - ker1 = R[kdx][:, rank1:] - im2 = Linv[kdx + 1][:, :rank2] - cokernel2 = Linv[kdx + 1][:, rank2:] - cokproj2 = L[kdx + 1][rank2:, :] - - proj = matmulreduce([cokernel2, cokproj2, ker1]).transpose() - _, proj, _ = reduced_row_echelon_form_mod2(proj) - # proj = np.array(proj) - basis[kdx] = np.array([row for row in proj if np.any(row)]) - if boundary: - im[kdx] = im2.transpose() - if boundary: - return basis, im - else: - return basis
- - -
[docs]def hypergraph_homology_basis(h, k=None, shortest=False, interpreted=True): - """ - Computes the kth-homology groups mod 2 for the ASC - associated with the hypergraph h for k in krange inclusive - - Parameters - ---------- - h : hnx.Hypergraph - k : int or list of length 2, optional, default = None - k must be an integer greater than 0 or a list of - length 2 indicating min and max dimensions to be - computed - shortest : bool, optional, default=False - option to look for shortest representative for each coset in the - homology group, only good for relatively small examples - interpreted : bool, optional, default = True - if True will return an explicit basis in terms of the k-chains - - Returns - ------- - basis : list - list of generators as k-chains as boolean vectors - interpreted_basis : - lists of kchains in basis - - """ - C, bd = chain_complex(h, k) - if shortest: - basis = defaultdict(list) - tbasis, im = homology_basis(bd, boundary=True) - for kdx in tbasis: - imgrp = boundary_group(im[kdx]) - if imgrp is None: - basis[kdx] = tbasis[kdx] - else: - for b in tbasis[kdx]: - coset = np.array( - np.mod(imgrp + b, 2) - ) # dimensions appear to be wrong. See tests2 cell 5 - idx = np.argmin(np.sum(coset, axis=1)) - basis[kdx].append(coset[idx]) - basis = dict(basis) - - else: - basis = homology_basis(bd) - - if interpreted: - interpreted_basis = dict() - for kdx in basis: - interpreted_basis[kdx] = interpret(C[kdx], basis[kdx], labels=None) - return basis, interpreted_basis - else: - return basis
- - -
[docs]def interpret(Ck, arr, labels=None): - """ - Returns the data as represented in Ck associated with the arr - - Parameters - ---------- - Ck : list - a list of k-cells being referenced by arr - arr : np.array - array of 0-1 vectors - labels : dict, optional - dictionary of labels to associate to the nodes in the cells - - Returns - ---- - : list - list of k-cells referenced by data in Ck - - """ - - def translate(cell, labels=labels): - if not labels: - return cell - else: - temp = list() - for node in cell: - temp.append(labels[node]) - return tuple(temp) - - output = list() - for vec in arr: - if len(Ck) != len(vec): - raise HyperNetXError("elements of arr must have the same length as Ck") - output.append([translate(Ck[idx]) for idx in range(len(vec)) if vec[idx] == 1]) - return output
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/algorithms/s_centrality_measures.html b/docs/build/_modules/algorithms/s_centrality_measures.html deleted file mode 100644 index b3b67d10..00000000 --- a/docs/build/_modules/algorithms/s_centrality_measures.html +++ /dev/null @@ -1,586 +0,0 @@ - - - - - - - - - - algorithms.s_centrality_measures — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • algorithms.s_centrality_measures
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for algorithms.s_centrality_measures

-# Copyright © 2018 Battelle Memorial Institute
-# All rights reserved.
-
-"""
-
-S-Centrality Measures
-=====================
-We generalize graph metrics to s-metrics for a hypergraph by using its s-connected
-components. This is accomplished by computing the s edge-adjacency matrix and
-constructing the corresponding graph of the matrix. We then use existing graph metrics
-on this representation of the hypergraph. In essence we construct an *s*-line graph
-corresponding to the hypergraph on which to apply our methods.
-
-S-Metrics for hypergraphs are discussed in depth in:        
-*Aksoy, S.G., Joslyn, C., Ortiz Marrero, C. et al. Hypernetwork science via high-order hypergraph walks.
-EPJ Data Sci. 9, 16 (2020). https://doi.org/10.1140/epjds/s13688-020-00231-0*
-
-"""
-
-import numpy as np
-from collections import defaultdict
-import networkx as nx
-import warnings
-import sys
-from functools import partial
-
-try:
-    import nwhy
-
-    nwhy_available = True
-except:
-    nwhy_available = False
-
-sys.setrecursionlimit(10000)
-
-__all__ = [
-    "s_betweenness_centrality",
-    "s_harmonic_closeness_centrality",
-    "s_harmonic_centrality",
-    "s_closeness_centrality",
-    "s_eccentricity",
-]
-
-
-def _s_centrality(
-    func, H, s=1, edges=True, f=None, return_singletons=True, use_nwhy=True, **kwargs
-):
-    """
-    Wrapper for computing s-centrality either in NetworkX or in NWHy
-
-    Parameters
-    ----------
-    func : function
-        Function or partial function from NetworkX or NWHy
-    H : hnx.Hypergraph
-
-    s : int, optional
-        s-width for computation
-    edges : bool, optional
-        If True, an edge linegraph will be used, otherwise a node linegraph will be used
-    f : str, optional
-        Identifier of node or edge of interest for computing centrality
-    return_singletons : bool, optional
-        If True will return 0 value for each singleton in the s-linegraph
-    use_nwhy : bool, optional
-        If True will attempt to use nwhy centrality methods if availaable
-    **kwargs
-        Centrality metric specific keyword arguments to be passed to func
-
-    Returns
-    : dict
-        dictionary of centrality scores keyed by names
-    """
-    comps = H.s_component_subgraphs(
-        s=s, edges=edges, return_singletons=return_singletons
-    )
-    if f is not None:
-        for cps in comps:
-            if (edges and f in cps.edges) or (not edges and f in cps.nodes):
-                comps = [cps]
-                break
-        else:
-            return {f: 0}
-
-    stats = dict()
-    if H.isstatic:
-        for h in comps:
-            if edges:
-                vertices = h.edges
-            else:
-                vertices = h.nodes
-
-            if h.shape[edges * 1] == 1:
-                stats.update({v: 0 for v in vertices})
-            elif use_nwhy and nwhy_available and h.nwhy:
-                g = h.get_linegraph(s=s, edges=edges, use_nwhy=True)
-                stats.update(dict(zip(vertices, func(g, **kwargs))))
-            else:
-                g = h.get_linegraph(s=s, edges=edges, use_nwhy=False)
-                stats.update(
-                    {
-                        h.get_name(k, edges=edges): v
-                        for k, v in func(g, **kwargs).items()
-                    }
-                )
-            if f:
-                return {f: stats[f]}
-    else:
-        for h in comps:
-            if edges:
-                A, Adict = h.edge_adjacency_matrix(s=s, index=True)
-            else:
-                A, Adict = h.adjacency_matrix(s=s, index=True)
-            A = (A >= s) * 1
-            g = nx.from_scipy_sparse_matrix(A)
-            stats.update({Adict[k]: v for k, v in func(g, **kwargs).items()})
-            if f:
-                return {f: stats[f]}
-
-    return stats
-
-
-
[docs]def s_betweenness_centrality( - H, s=1, edges=True, normalized=True, return_singletons=True, use_nwhy=True -): - """ - A centrality measure for an s-edge(node) subgraph of H based on shortest paths. - Equals the betweenness centrality of vertices in the edge(node) s-linegraph. - - In a graph (2-uniform hypergraph) the betweenness centrality of a vertex $v$ - is the ratio of the number of non-trivial shortest paths between any pair of - vertices in the graph that pass through $v$ divided by the total number of - non-trivial shortest paths in the graph. - - The centrality of edge to all shortest s-edge paths - $V$ = the set of vertices in the linegraph. - $\sigma(s,t)$ = the number of shortest paths between vertices $s$ and $t$. - $\sigma(s, t|v)$ = the number of those paths that pass through vertex $v$ - $$c_B(v) =\sum_{s \neq t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}$$ - - Parameters - ---------- - H : hnx.Hypergraph - s : int - s connectedness requirement - edges : bool, optional - determines if edge or node linegraph - normalized - bool, default=False, - If true the betweenness values are normalized by `2/((n-1)(n-2))`, - where n is the number of edges in H - return_singletons : bool, optional - if False will ignore singleton components of linegraph - - - Returns - ------- - : dict - A dictionary of s-betweenness centrality value of the edges. - - """ - if use_nwhy and nwhy_available and H.nwhy: - func = partial(nwhy.Slinegraph.s_betweenness_centrality, normalized=False) - else: - use_nwhy = False - func = partial(nx.betweenness_centrality, normalized=False) - result = _s_centrality( - func, - H, - s=s, - edges=edges, - return_singletons=return_singletons, - use_nwhy=use_nwhy, - ) - - if normalized and H.shape[edges * 1] > 2: - n = H.shape[edges * 1] - return {k: v * 2 / ((n - 1) * (n - 2)) for k, v in result.items()} - else: - return result
- - -
[docs]def s_closeness_centrality( - H, s=1, edges=True, return_singletons=True, source=None, use_nwhy=True -): - """ - In a connected component the reciprocal of the sum of the distance between an - edge(node) and all other edges(nodes) in the component times the number of edges(nodes) - in the component minus 1. - - $V$ = the set of vertices in the linegraph. - $n = |V|$ - $d$ = shortest path distance - $$C(u) = \frac{n - 1}{\sum_{v \neq u \in V} d(v, u)}$$ - - - Parameters - ---------- - H : hnx.Hypergraph - - s : int, optional - - edges : bool, optional - Indicates if method should compute edge linegraph (default) or node linegraph. - return_singletons : bool, optional - Indicates if method should return values for singleton components. - source : str, optional - Identifier of node or edge of interest for computing centrality - use_nwhy : bool, optional - If true will use the :ref:`NWHy library <nwhy>` if available. - - Returns - ------- - : dict or float - returns the s-closeness centrality value of the edges(nodes). - If source=None a dictionary of values for each s-edge in H is returned. - If source then a single value is returned. - """ - if use_nwhy and nwhy_available and H.nwhy: - func = partial(nwhy.Slinegraph.s_closeness_centrality) - else: - use_nwhy = False - func = partial(nx.closeness_centrality) - return _s_centrality( - func, - H, - s=s, - edges=edges, - return_singletons=return_singletons, - f=source, - use_nwhy=use_nwhy, - )
- - -
[docs]def s_harmonic_closeness_centrality(H, s=1, edge=None, use_nwhy=True): - msg = """ - s_harmonic_closeness_centrality is being replaced with s_harmonic_centrality - and will not be available in future releases. - """ - warnings.warn(msg) - return s_harmonic_centrality(H, s=s, edges=True, normalized=True, source=edge)
- - -
[docs]def s_harmonic_centrality( - H, - s=1, - edges=True, - source=None, - normalized=False, - return_singletons=True, - use_nwhy=True, -): - """ - A centrality measure for an s-edge subgraph of H. A value equal to 1 means the s-edge - intersects every other s-edge in H. All values range between 0 and 1. - Edges of size less than s return 0. If H contains only one s-edge a 0 is returned. - - The denormalized reciprocal of the harmonic mean of all distances from $u$ to all other vertices. - $V$ = the set of vertices in the linegraph. - $d$ = shortest path distance - $$C(u) = \sum_{v \neq u \in V} \frac{1}{d(v, u)}$$ - - Normalized this becomes: - $$C(u) = \sum_{v \neq u \in V} \frac{1}{d(v, u)}\cdot\frac{2}{(n-1)(n-2)}$$ - where $n$ is the number vertices. - - Parameters - ---------- - H : hnx.Hypergraph - - s : int, optional - - edges : bool, optional - Indicates if method should compute edge linegraph (default) or node linegraph. - return_singletons : bool, optional - Indicates if method should return values for singleton components. - source : str, optional - Identifier of node or edge of interest for computing centrality - use_nwhy : bool, optional - If true will use the :ref:`NWHy library <nwhy>` if available. - - Returns - ------- - : dict or float - returns the s-harmonic closeness centrality value of the edges, a number between 0 and 1 inclusive. - If source=None a dictionary of values for each s-edge in H is returned. - If source then a single value is returned. - - """ - - if use_nwhy and nwhy_available and H.nwhy: - func = partial(nwhy.Slinegraph.s_harmonic_closeness_centrality) - else: - use_nwhy = False - func = partial(nx.harmonic_centrality) - result = _s_centrality( - func, - H, - s=s, - edges=edges, - return_singletons=return_singletons, - f=source, - use_nwhy=use_nwhy, - ) - - if normalized and H.shape[edges * 1] > 2: - n = H.shape[edges * 1] - return {k: v * 2 / ((n - 1) * (n - 2)) for k, v in result.items()} - else: - return result
- - -
[docs]def s_eccentricity( - H, s=1, edges=True, source=None, return_singletons=True, use_nwhy=True -): - """ - The length of the longest shortest path from a vertex $u$ to every other vertex in the linegraph. - $V$ = set of vertices in the linegraph - $d$ = shortest path distance - $$ \text{s-ecc}(u) = \text{max}\{d(u,v): v \in V\} $$ - - Parameters - ---------- - H : hnx.Hypergraph - - s : int, optional - - edges : bool, optional - Indicates if method should compute edge linegraph (default) or node linegraph. - return_singletons : bool, optional - Indicates if method should return values for singleton components. - source : str, optional - Identifier of node or edge of interest for computing centrality - use_nwhy : bool, optional - If true will use the :ref:`NWHy library <nwhy>` if available. - - Returns - ------- - : dict or float - returns the s-eccentricity value of the edges(nodes). - If source=None a dictionary of values for each s-edge in H is returned. - If source then a single value is returned. - - """ - if use_nwhy and nwhy_available and H.nwhy: - func = nwhy.Slinegraph.s_eccentricity - else: - use_nwhy = False - func = nx.eccentricity - - if source is not None: - return _s_centrality( - func, - H, - s=s, - edges=edges, - f=source, - return_singletons=return_singletons, - use_nwhy=use_nwhy, - ) - else: - return _s_centrality( - func, - H, - s=s, - edges=edges, - return_singletons=return_singletons, - use_nwhy=use_nwhy, - )
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/classes/entity.html b/docs/build/_modules/classes/entity.html deleted file mode 100644 index c240bd16..00000000 --- a/docs/build/_modules/classes/entity.html +++ /dev/null @@ -1,1259 +0,0 @@ - - - - - - - - - - classes.entity — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • classes.entity
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for classes.entity

-# Copyright © 2018 Battelle Memorial Institute
-# All rights reserved.
-
-from collections import defaultdict
-import warnings
-from copy import copy
-import numpy as np
-import networkx as nx
-from hypernetx import HyperNetXError
-
-__all__ = ["Entity", "EntitySet"]
-
-
-
[docs]class Entity(object): - """ - Base class for objects used in building network-like objects including - Hypergraphs, Posets, Cell Complexes. - - Parameters - ---------- - uid : hashable - a unique identifier - - elements : list or dict, optional, default: None - a list of entities with identifiers different than uid and/or - hashables different than uid, see `Honor System`_ - - entity : Entity - an Entity object to be cloned into a new Entity with uid. If the uid is the same as - Entity.uid then the entities will not be distinguishable and error will be raised. - The `elements` in the signature will be added to the cloned entity. - - props : keyword arguments, optional, default: {} - properties belonging to the entity added as key=value pairs. - Both key and value must be hashable. - - Notes - ----- - - An Entity is a container-like object, which has a unique identifier and - may contain elements and have properties. - The Entity class was created as a generic object providing structure for - Hypergraph nodes and edges. - - - An Entity is distinguished by its identifier (sortable,hashable) :func:`Entity.uid` - - An Entity is a container for other entities but may not contain itself, :func:`Entity.elements` - - An Entity has properties :func:`Entity.properties` - - An Entity has memberships to other entities, :func:`Entity.memberships`. - - An Entity has children, :func:`Entity.children`, which are the elements of its elements. - - :func:`Entity.children` are registered in the :func:`Entity.registry`. - - All descendents of Entity are registered in :func:`Entity.fullregistry()`. - - .. _Honor System: - - **Honor System** - - HyperNetX has an Honor System that applies to Entity uid values. - Two entities are equal if their __dict__ objects match. - For performance reasons many methods distinguish entities by their uids. - It is, therefore, up to the user to ensure entities with the same uids are indeed the same. - Not doing so may cause undesirable side effects. - In particular, the methods in the Hypergraph class assume distinct nodes and edges - have distinct uids. - - Examples - -------- - - >>> x = Entity('x') - >>> y = Entity('y',[x]) - >>> z = Entity('z',[x,y],weight=1) - >>> z - Entity(z,['y', 'x'],{'weight': 1}) - >>> z.uid - 'z' - >>> z.elements - {'x': Entity(x,[],{}), 'y': Entity(y,['x'],{})} - >>> z.properties - {'weight': 1} - >>> z.children - {'x'} - >>> x.memberships - {'y': Entity(y,['x'],{}), 'z': Entity(z,['y', 'x'],{'weight': 1})} - >>> z.fullregistry() - {'x': Entity(x,[],{}), 'y': Entity(y,['x'],{})} - - - See Also - -------- - EntitySet - - """ - - def __init__(self, uid, elements=[], entity=None, **props): - super().__init__() - - self._uid = uid - - if entity is not None: - if isinstance(entity, Entity): - if uid == entity.uid: - raise HyperNetXError( - "The new entity will be indistinguishable from the original with the same uid. Use a differen uid." - ) - self._elements = entity.elements - self._memberships = entity.memberships - self.__dict__.update(entity.properties) - else: - self._elements = dict() - self._memberships = dict() - self._registry = dict() - - self.__dict__.update(props) - self._registry = self.registry - - if isinstance(elements, dict): - for k, v in elements.items(): - if isinstance(v, Entity): - self.add_element(v) - else: - self.add_element(Entity(k, v)) - elif elements is not None: - self.add(*elements) - - @property - def properties(self): - """Dictionary of properties of entity""" - temp = self.__dict__.copy() - del temp["_elements"] - del temp["_memberships"] - del temp["_registry"] - del temp["_uid"] - return temp - - @property - def uid(self): - """String identifier for entity""" - return self._uid - - @property - def elements(self): - """ - Dictionary of elements belonging to entity. - """ - return dict(self._elements) - - @property - def memberships(self): - """ - Dictionary of elements to which entity belongs. - - This assignment is done on construction and controlled by - :func:`Entity.add_element()` - and :func:`Entity.remove_element()` methods. - """ - - return { - k: self._memberships[k] - for k in self._memberships - if not isinstance(self._memberships[k], EntitySet) - } - - @property - def children(self): - """ - Set of uids of the elements of elements of entity. - - To return set of ids for deeper level use: - :code:`Entity.levelset(level).keys()` - see: :func:`Entity.levelset` - """ - return set(self.levelset(2).keys()) - - @property - def registry(self): - """ - Dictionary of uid:Entity pairs for children entity. - - To return a dictionary of all entities at all depths - :func:`Entity.complete_registry()` - """ - return self.levelset(2) - - @property - def uidset(self): - """ - Set of uids of elements of entity. - """ - return frozenset(self._elements.keys()) - - @property - def incidence_dict(self): - """ - Dictionary of element.uid:element.uidset for each element in entity - - To return an incidence dictionary of all nested entities in entity - use nested_incidence_dict - """ - temp = dict() - for ent in self.elements.values(): - temp[ent.uid] = {item for item in ent.elements} - return temp - - @property - def is_empty(self): - """Boolean indicating if entity.elements is empty""" - return len(self) == 0 - - @property - def is_bipartite(self): - """ - Returns boolean indicating if the entity satisfies the `Bipartite Condition`_ - """ - if self.uidset.isdisjoint(self.children): - return True - else: - return False - - def __eq__(self, other): - """ - Defines equality for Entities based on equivalence of their __dict__ objects. - - Checks all levels of self and other to verify they are - referencing the same uids and that they have the same set of properties. - If at any point we get duplicate addresses we stop checking that branch - because we are guaranteed equality from there on. - - May cause a recursion error if depth is too great. - """ - seen = set() - # Define a compare method to call recursively on each level of self and other - - def _comp(a, b, seen): - # Compare top level properties: same class? same ids? same children? same parents? same attributes? - if ( - (a.__class__ != b.__class__) - or (a.uid != b.uid) - or (a.uidset != b.uidset) - or (a.properties != b.properties) - or (a.memberships != b.memberships) - ): - return False - # If all agree then look at the next level down since a and b share uidsets. - for uid, elt in a.elements.items(): - if isinstance(elt, Entity): - if uid in seen: - continue - seen.add(uid) - if not _comp(elt, b[uid], seen): - return False - # if not an Entity then elt is hashable so we usual equality - elif elt != b[uid]: - return False - return True - - return _comp(self, other, seen) - - def __len__(self): - """Returns the number of elements in entity""" - return len(self._elements) - - def __str__(self): - """Return the entity uid.""" - return f"{self.uid}" - - def __repr__(self): - """Returns a string resembling the constructor for entity without any - children""" - return f"Entity({self._uid},{list(self.uidset)},{self.properties})" - - def __contains__(self, item): - """ - Defines containment for Entities. - - Parameters - ---------- - item : hashable or Entity - - Returns - ------- - Boolean - - Depends on the `Honor System`_ . Allows for uids to be used as shorthand for their entity. - This is done for performance reasons, but will fail if uids are - not unique to their entities. - Is not transitive. - """ - if isinstance(item, Entity): - return item.uid in self._elements - else: - return item in self._elements - - def __getitem__(self, item): - """ - Returns Entity element by uid. Use :func:`E[uid]`. - - Parameters - ---------- - item : hashable or Entity - - Returns - ------- - Entity or None - - If item not in entity, returns None. - """ - if isinstance(item, Entity): - return self._elements.get(item.uid, "") - else: - return self._elements.get(item) - - def __iter__(self): - """Returns iterator on element ids.""" - return iter(self.elements) - - def __call__(self): - """Returns an iterator on elements""" - for e in self.elements.values(): - yield e - - def __setattr__(self, k, v): - """Sets entity property. - - Parameters - ---------- - k : hashable, property key - v : hashable, property value - Will not set uid or change elements or memberships. - - Returns - ------- - None - - """ - if k == "uid": - raise HyperNetXError( - "Cannot reassign uid to Entity once it" - " has been created. Create a clone instead." - ) - elif k == "elements": - raise HyperNetXError("To add elements to Entity use self.add().") - elif k == "memberships": - raise HyperNetXError( - "Can't choose your own memberships, " "they are like parents!" - ) - else: - self.__dict__[k] = v - - def _depth_finder(self, entset=None): - """ - Helper method when working with levels. - - Parameters - ---------- - entset : dict, optional - a dictionary of entities keyed by uid - - Returns - ------- - Dictionary extending entset - """ - temp = dict() - for uid, item in entset.items(): - temp.update(item.elements) - return temp - -
[docs] def level(self, item, max_depth=10): - """ - The first level where item appears in self. - - Parameters - ---------- - item : hashable - uid for an entity - - max_depth : int, default: 10 - last level to check for entity - - Returns - ------- - level : int - - Note - ---- - Item must be the uid of an entity listed - in :func:`fullregistry()` - """ - d = 1 - currentlevel = self.levelset(1) - while d <= max_depth + 1: - if item in currentlevel: - return d - else: - d += 1 - currentlevel = self._depth_finder(currentlevel) - return None
- -
[docs] def levelset(self, k=1): - """ - A dictionary of level k of self. - - Parameters - ---------- - k : int, optional, default: 1 - - Returns - ------- - levelset : dict - - Note - ---- - An Entity contains other entities, hence the relationships between entities - and their elements may be represented in a directed graph with entity as root. - The levelsets are sets of entities which make up the elements appearing at - a certain level. - """ - if k <= 0: - return None - currentlevel = self.elements - if k > 1: - for idx in range(k - 1): - currentlevel = self._depth_finder(currentlevel) - return currentlevel
- -
[docs] def depth(self, max_depth=10): - """ - Returns the number of nonempty level sets of level <= max_depth - - Parameters - ---------- - max_depth : int, optional, default: 10 - If full depth is desired set max_depth to number of entities in - system + 1. - - Returns - ------- - depth : int - If max_depth is exceeded output will be numpy infinity. - If there is a cycle output will be numpy infinity. - - """ - if max_depth < 0: - return 0 - currentlevel = self.elements - if not currentlevel: - return 0 - else: - depth = 1 - while depth < max_depth + 1: - currentlevel = self._depth_finder(currentlevel) - if not currentlevel: - return depth - depth += 1 - return np.inf
- -
[docs] def fullregistry(self, lastlevel=10, firstlevel=1): - """ - A dictionary of all entities appearing in levels firstlevel - to lastlevel. - - Parameters - ---------- - lastlevel : int, optional, default: 10 - - firstlevel : int, optional, default: 1 - - Returns - ------- - fullregistry : dict - - """ - currentlevel = self.levelset(firstlevel) - accumulater = dict(currentlevel) - for idx in range(firstlevel, lastlevel): - currentlevel = self._depth_finder(currentlevel) - accumulater.update(currentlevel) - return accumulater
- -
[docs] def complete_registry(self): - """ - A dictionary of all entities appearing in any level of - entity - - Returns - ------- - complete_registry : dict - """ - results = dict() - Entity._complete_registry(self, results) - return results
- - @staticmethod - def _complete_registry(entity, results): - """ - Helper method for complete_registry - """ - for uid, e in entity.elements.items(): - if uid not in results: - results[uid] = e - Entity._complete_registry(e, results) - -
[docs] def nested_incidence_dict(self, level=10): - """ - Returns a nested dictionary with keys up to level - - Parameters - ---------- - level : int, optional, default: 10 - If level<=1, returns the incidence_dict. - - Returns - ------- - nested_incidence_dict : dict - - """ - if level > 1: - return {ent.uid: ent.nested_incidence_dict(level - 1) for ent in self()} - else: - return self.incidence_dict
- -
[docs] def size(self): - """ - Returns the number of elements in entity - """ - return len(self)
- -
[docs] def clone(self, newuid): - """ - Returns shallow copy of entity with newuid. Entity's elements will - belong to two distinct Entities. - - Parameters - ---------- - newuid : hashable - Name of the new entity - - Returns - ------- - clone : Entity - - """ - return Entity(newuid, entity=self)
- -
[docs] def intersection(self, other): - """ - A dictionary of elements belonging to entity and other. - - Parameters - ---------- - other : Entity - - Returns - ------- - Dictionary of elements : dict - - """ - return {e: self[e] for e in self if e in other}
- -
[docs] def restrict_to(self, element_subset, name=None): - """ - Shallow copy of entity removing elements not in element_subset. - - Parameters - ---------- - element_subset : iterable - A subset of entities elements - - name: hashable, optional - If not given, a name is generated to reflect entity uid - - Returns - ------- - New Entity : Entity - Could be empty. - - """ - newelements = [self[e] for e in element_subset if e in self] - name = name or f"{self.uid}_r" - return Entity(name, newelements, **self.properties)
- -
[docs] def add(self, *args): - """ - Adds unpacked args to entity elements. Depends on add_element() - - Parameters - ---------- - args : One or more entities or hashables - - Returns - ------- - self : Entity - - Note - ---- - Adding an element to an object in a hypergraph will not add the - element to the hypergraph and will cause an error. Use :func:`Hypergraph.add_edge <classes.hypergraph.Hypergraph.add_edge>` - or :func:`Hypergraph.add_node_to_edge <classes.hypergraph.Hypergraph.add_node_to_edge>` instead. - - """ - for item in args: - self.add_element(item) - - return self
- -
[docs] def add_elements_from(self, arg_set): - """ - Similar to :func:`add()` it allows for adding from an interable. - - Parameters - ---------- - arg_set : Iterable of hashables or entities - - Returns - ------- - self : Entity - - """ - for item in arg_set: - self.add_element(item) - - return self
- -
[docs] def add_element(self, item): - """ - Adds item to entity elements and adds entity to item.memberships. - - Parameters - ---------- - item : hashable or Entity - If hashable, will be replaced with empty Entity using hashable as uid - - Returns - ------- - self : Entity - - Notes - ----- - If item is in entity elements, no new element is added but properties - will be updated. - If item is in complete_registry(), only the item already known to self will be added. - This method employs the `Honor System`_ since membership in complete_registry is checked - using the item's uid. It is assumed that the user will only use the same uid - for identical instances within the entities registry. - - """ - checkelts = self.complete_registry() - if isinstance(item, Entity): - # if item is an Entity, descendents will be compared to avoid collisions - if item.uid == self.uid: - raise HyperNetXError( - f"Error: Self reference in submitted elements." - f" Entity {self.uid} may not contain itself. " - ) - elif item in self: - # item is already an element so only the properties will be updated - checkelts[item.uid].__dict__.update(item.properties) - elif item.uid in checkelts: - # if item belongs to an element or a descendent of an element - # then the existing descendent becomes an element - # and properties are updated. - checkelts[item.uid]._memberships[self.uid] = self - checkelts[item.uid].__dict__.update(item.properties) - self._elements[item.uid] = checkelts[item.uid] - else: - # if item's uid doesn't appear in complete_registry - # then it is added as something new - item._memberships[self.uid] = self - self._elements[item.uid] = item - else: - # item must be a hashable. - # if it appears as a uid in checkelts then - # the corresponding Entity will become an element of entity. - # Otherwise, at most it will be added as an empty Entity. - if self.uid == item: - raise HyperNetXError( - f"Error: Self reference in submitted elements." - f" Entity {self.uid} may not contain itself." - ) - elif item not in self._elements: - if item in checkelts: - self._elements[item] = checkelts[item] - checkelts[item]._memberships[self.uid] = self - else: - self._elements[item] = Entity(item, _memberships={self.uid: self}) - - return self
- -
[docs] def remove(self, *args): - """ - Removes args from entitie's elements if they belong. - Does nothing with args not in entity. - - Parameters - ---------- - args : One or more hashables or entities - - Returns - ------- - self : Entity - - - """ - for item in args: - Entity.remove_element(self, item) - return self
- -
[docs] def remove_elements_from(self, arg_set): - """ - Similar to :func:`remove()`. Removes elements in arg_set. - - Parameters - ---------- - arg_set : Iterable of hashables or entities - - Returns - ------- - self : Entity - - """ - for item in arg_set: - Entity.remove_element(self, item) - return self
- -
[docs] def remove_element(self, item): - """ - Removes item from entity and reference to entity from - item.memberships - - Parameters - ---------- - item : Hashable or Entity - - Returns - ------- - self : Entity - - - """ - if isinstance(item, Entity): - del item._memberships[self.uid] - del self._elements[item.uid] - else: - del self[item]._memberships[self.uid] - del self._elements[item] - - return self
- -
[docs] @staticmethod - def merge_entities(name, ent1, ent2): - """ - Merge two entities making sure they do not conflict. - - Parameters - ---------- - name : hashable - - ent1 : Entity - First entity to have elements and properties added to new - entity - - ent2 : Entity - elements of ent2 will be checked against ent1.complete_registry() - and only nonexisting elements will be added using add() method. - Properties of ent2 will update properties of ent1 in new entity. - - Returns - ------- - a new entity : Entity - - """ - newent = ent1.clone(name) - newent.add_elements_from(ent2.elements.values()) - for k, v in ent2.properties.items(): - newent.__setattr__(k, v) - return newent
- - -
[docs]class EntitySet(Entity): - """ - .. _entityset: - - Parameters - ---------- - uid : hashable - a unique identifier - - elements : list or dict, optional, default: None - a list of entities with identifiers different than uid and/or - hashables different than uid, see `Honor System`_ - - props : keyword arguments, optional, default: {} - properties belonging to the entity added as key=value pairs. - Both key and value must be hashable. - - Notes - ----- - The EntitySet class was created to distinguish Entities satifying the Bipartite Condition. - - .. _Bipartite Condition: - - **Bipartite Condition** - - *Entities that are elements of the same EntitySet, may not contain each other as elements.* - The elements and children of an EntitySet generate a specific partition for a bipartite graph. - The partition is isomorphic to a Hypergraph where the elements correspond to hyperedges and - the children correspond to the nodes. EntitySets are the basic objects used to construct hypergraphs - in HNX. - - Example: :: - - >>> y = Entity('y') - >>> x = Entity('x') - >>> x.add(y) - >>> y.add(x) - >>> w = EntitySet('w',[x,y]) - HyperNetXError: Error: Fails the Bipartite Condition for EntitySet. - y references a child of an existing Entity in the EntitySet. - - """ - - def __init__(self, uid, elements=[], **props): - super().__init__(uid, elements, **props) - if not self.is_bipartite: - raise HyperNetXError( - "Entity does not satisfy the Bipartite Condition, elements and children are not disjoint." - ) - - def __str__(self): - """Return the entityset uid.""" - return f"{self.uid}" - - def __repr__(self): - """Returns a string resembling the constructor for entityset without any - children""" - return f"EntitySet({self._uid},{list(self.uidset)},{self.properties})" - -
[docs] def add(self, *args): - """ - Adds args to entityset's elements, checking to make sure no self references are - made to element ids. - Ensures Bipartite Condition of EntitySet. - - Parameters - ---------- - args : One or more entities or hashables - - Returns - ------- - self : EntitySet - - """ - for item in args: - if isinstance(item, Entity): - if item.uid in self.children: - raise HyperNetXError( - f"Error: Fails the Bipartite Condition for EntitySet. {item.uid} references a child of an existing Entity in the EntitySet." - ) - elif not self.uidset.isdisjoint(item.uidset): - raise HyperNetXError( - f"Error: Fails the bipartite condition for EntitySet." - ) - else: - Entity.add_element(self, item) - else: - if not item in self.children: - Entity.add_element(self, item) - else: - raise HyperNetXError( - f"Error: {item} references a child of an existing Entity in the EntitySet." - ) - return self
- -
[docs] def clone(self, newuid): - """ - Returns shallow copy of entityset with newuid. Entityset's - elements will belong to two distinct entitysets. - - - Parameters - ---------- - newuid : hashable - Name of the new entityset - - Returns - ------- - clone : EntitySet - - """ - return EntitySet(newuid, elements=self.elements.values(), **self.properties)
- -
[docs] def collapse_identical_elements(self, newuid, return_equivalence_classes=False): - """ - Returns a deduped copy of the entityset, using representatives of equivalence classes as element keys. - Two elements of an EntitySet are collapsed if they share the same children. - - Parameters - ---------- - newuid : hashable - - return_equivalence_classes : boolean, default=False - If True, return a dictionary of equivalence classes keyed by new edge names - - Returns - ------- - : EntitySet - eq_classes : dict - if return_equivalence_classes = True - - Notes - ----- - Treats elements of the entityset as equal if they have the same uidsets. Using this - as an equivalence relation, the entityset's uidset is partitioned into equivalence classes. - The equivalent elements are identified using a single entity by using the - frozenset of uids associated to these elements as the uid for the new element - and dropping the properties. - If use_reps is set to True a representative element of the equivalence class is - used as identifier instead of the frozenset. - - Example: :: - - >>> E = EntitySet('E',elements=[Entity('E1', ['a','b']),Entity('E2',['a','b'])]) - >>> E.incidence_dict - {'E1': {'a', 'b'}, 'E2': {'a', 'b'}} - >>> E.collapse_identical_elements('_',).incidence_dict - {'E2': {'a', 'b'}} - - """ - - shared_children = defaultdict(set) - for e in self.__call__(): - shared_children[frozenset(e.uidset)].add(e.uid) - new_entity_dict = { - f"{next(iter(v))}:{len(v)}": set(k) for k, v in shared_children.items() - } - if return_equivalence_classes: - eq_classes = { - f"{next(iter(v))}:{len(v)}": v for k, v in shared_children.items() - } - return EntitySet(newuid, new_entity_dict), dict(eq_classes) - else: - return EntitySet(newuid, new_entity_dict)
- -
[docs] def incidence_matrix(self, sparse=True, index=False): - """ - An incidence matrix for the EntitySet indexed by children x uidset. - - Parameters - ---------- - sparse : boolean, optional, default: True - - index : boolean, optional, default False - If True return will include a dictionary of children uid : row number - and element uid : column number - - Returns - ------- - incidence_matrix : scipy.sparse.csr.csr_matrix or np.ndarray - - row dictionary : dict - Dictionary identifying row with item in entityset's children - - column dictionary : dict - Dictionary identifying column with item in entityset's uidset - - Notes - ----- - - Example: :: - - >>> E = EntitySet('E',{'a':{1,2,3},'b':{2,3},'c':{1,4}}) - >>> E.incidence_matrix(sparse=False, index=True) - (array([[0, 1, 1], - [1, 1, 0], - [1, 1, 0], - [0, 0, 1]]), {0: 1, 1: 2, 2: 3, 3: 4}, {0: 'b', 1: 'a', 2: 'c'}) - """ - if sparse: - from scipy.sparse import csr_matrix - - nchildren = len(self.children) - nuidset = len(self.uidset) - - ndict = dict(zip(self.children, range(nchildren))) - edict = dict(zip(self.uidset, range(nuidset))) - - if len(ndict) != 0: - - if index: - rowdict = {v: k for k, v in ndict.items()} - coldict = {v: k for k, v in edict.items()} - - if sparse: - # Create csr sparse matrix - rows = list() - cols = list() - data = list() - for e in self: - for n in self[e].elements: - data.append(1) - rows.append(ndict[n]) - cols.append(edict[e]) - MP = csr_matrix((data, (rows, cols))) - else: - # Create an np.matrix - MP = np.zeros((nchildren, nuidset), dtype=int) - for e in self: - for n in self[e].elements: - MP[ndict[n], edict[e]] = 1 - if index: - return MP, rowdict, coldict - else: - return MP - else: - if index: - return np.zeros(1), {}, {} - else: - return np.zeros(1)
- -
[docs] def restrict_to(self, element_subset, name=None): - """ - Shallow copy of entityset removing elements not in element_subset. - - Parameters - ---------- - element_subset : iterable - A subset of the entityset's elements - - name: hashable, optional - If not given, a name is generated to reflect entity uid - - Returns - ------- - new entityset : EntitySet - Could be empty. - - See also - -------- - Entity.restrict_to - - """ - newelements = [self[e] for e in element_subset if e in self] - name = name or f"{self.uid}_r" - return EntitySet(name, newelements, **self.properties)
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/classes/hypergraph.html b/docs/build/_modules/classes/hypergraph.html deleted file mode 100644 index 29e149a6..00000000 --- a/docs/build/_modules/classes/hypergraph.html +++ /dev/null @@ -1,2798 +0,0 @@ - - - - - - - - - - classes.hypergraph — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • classes.hypergraph
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for classes.hypergraph

-# Copyright © 2018 Battelle Memorial Institute
-# All rights reserved.
-
-import warnings
-import pickle
-import networkx as nx
-from networkx.algorithms import bipartite
-import numpy as np
-import pandas as pd
-from scipy.sparse import issparse, coo_matrix, dok_matrix, csr_matrix
-from collections import OrderedDict, defaultdict
-from hypernetx.classes.entity import Entity, EntitySet
-from hypernetx.classes.staticentity import StaticEntity, StaticEntitySet
-from hypernetx.exception import HyperNetXError
-from hypernetx.utils.decorators import not_implemented_for
-
-
-__all__ = ["Hypergraph"]
-
-
-
[docs]class Hypergraph: - """ - Hypergraph H = (V,E) references a pair of disjoint sets: - V = nodes (vertices) and E = (hyper)edges. - - An HNX Hypergraph is either dynamic or static. - Dynamic hypergraphs can change by adding or subtracting objects - from them. Static hypergraphs require that all of the nodes and edges - be known at creation. A hypergraph is dynamic by default. - - *Dynamic hypergraphs* require the user to keep track of its objects, - by using a unique names for each node and edge. This allows for multi-edge graphs and - inseperable nodes. - - For example: Let V = {1,2,3} and E = {e1,e2,e3}, - where e1 = {1,2}, e2 = {1,2}, and e3 = {1,2,3}. - The edges e1 and e2 contain the same set of nodes and yet - are distinct and must be distinguishable within H. - - In a dynamic hypergraph each node and edge is - instantiated as an Entity and given an identifier or uid. Entities - keep track of inclusion relationships and can be nested. Since - hypergraphs can be quite large, only the entity identifiers will be used - for computation intensive methods, this means the user must take care - to keep a one to one correspondence between their set of uids and - the objects in their hypergraph. See `Honor System`_ - Dynamic hypergraphs are most practical for small to modestly sized - hypergraphs (<1000 objects). - - *Static hypergraphs* store node and edge information in numpy arrays and - are immutable. Each node and edge receives a class generated internal - identifier used for computations so do not require the user to create - different ids for nodes and edges. To create a static hypergraph set - `static = True` in the signature. - - We will create hypergraphs in multiple ways: - - 1. As an empty instance: :: - - >>> H = hnx.Hypergraph() - >>> H.nodes, H.edges - ({}, {}) - - 2. From a dictionary of iterables (elements of iterables must be of type hypernetx.Entity or hashable): :: - - >>> H = Hypergraph({'a':[1,2,3],'b':[4,5,6]}) - >>> H.nodes, H.edges - # output: (EntitySet(_:Nodes,[1, 2, 3, 4, 5, 6],{}), EntitySet(_:Edges,['b', 'a'],{})) - - 3. From an iterable of iterables: (elements of iterables must be of type hypernetx.Entity or hashable): :: - - >>> H = Hypergraph([{'a','b'},{'b','c'},{'a','c','d'}]) - >>> H.nodes, H.edges - # output: (EntitySet(_:Nodes,['d', 'b', 'c', 'a'],{}), EntitySet(_:Edges,['_1', '_2', '_0'],{})) - - 4. From a hypernetx.EntitySet or StaticEntitySet: :: - - >>> a = Entity('a',{1,2}); b = Entity('b',{2,3}) - >>> E = EntitySet('sample',elements=[a,b]) - >>> H = Hypergraph(E) - >>> H.nodes, H.edges. - # output: (EntitySet(_:Nodes,[1, 2, 3],{}), EntitySet(_:Edges,['b', 'a'],{})) - - All of these constructions apply for both dynamic and static hypergraphs. To - create a static hypergraph set the parameter `static=True`. In addition a static - hypergraph is automatically created if a StaticEntity, StaticEntitySet, or pandas.DataFrame object - is passed to the Hypergraph constructor. - - 5. | From a pandas.DataFrame. The dataframe must have at least two columns with headers and there can be no nans. - | By default the first column corresponds to the edge names and the second column to the node names. - | You can specify the columns by restricting the dataframe to the columns of interest in the order: - | :code:`hnx.Hypergraph(df[[edge_column_name,node_column_name]])` - | See :ref:`Colab Tutorials <colab>` Tutorial 6 - Static Hypergraphs and Entities for additional information. - - - Parameters - ---------- - setsystem : (optional) EntitySet, StaticEntitySet, dict, iterable, pandas.dataframe, default: None - See notes above for setsystem requirements. - - name : hashable, optional, default: None - If None then a placeholder '_' will be inserted as name - - static : boolean, optional, default: False - If True the hypergraph will be immutable, edges and nodes may not be changed. - - use_nwhy : boolean, optional, default = False - If True hypergraph will be static and computations will be done using - C++ backend offered by NWHypergraph. This requires installation of the - NWHypergraph C++ library. Please see the :ref:`NWHy documentation <nwhy>` for more information. - - - """ - - # TODO: remove lambda functions from constructor in H and E. - - def __init__( - self, setsystem=None, name=None, static=False, use_nwhy=False, filepath=None - ): - self.filepath = filepath - if use_nwhy: - static = True - try: - import nwhy - - self.nwhy = True - - except: - self.nwhy = False - print("NWHypergraph is not available. Will continue with static=True.") - use_nwhy = False - else: - self.nwhy = False - if not name: - self.name = "" - else: - self.name = name - - if static == True or ( - isinstance(setsystem, StaticEntitySet) or - isinstance(setsystem, StaticEntity) or - isinstance(setsystem, pd.DataFrame) ) : - self._static=True - if setsystem is None: - self._edges=StaticEntitySet() - self._nodes=StaticEntitySet() - else: - E=StaticEntitySet(entity = setsystem) - self._edges=E - self._nodes=E.restrict_to_levels([1]) - else: - self._static=False - if setsystem is None: - setsystem=EntitySet("_", elements = []) - elif isinstance(setsystem, Entity): - setsystem=EntitySet("_", setsystem.incidence_dict) - elif isinstance(setsystem, dict): - # Must be a dictionary with values equal to iterables of Entities and hashables. - # Keys will be uids for new edges and values of the dictionary will generate the nodes. - setsystem=EntitySet("_", setsystem) - elif not isinstance(setsystem, EntitySet): - # If no ids are given, return default ids indexed by position in iterator - # This should be an iterable of sets - edge_labels=[self.name + str(x) for x in range(len(setsystem))] - setsystem=EntitySet("_", dict(zip(edge_labels, setsystem))) - - _reg=setsystem.registry - _nodes={k: Entity(k, **_reg[k].properties) for k in _reg} - _elements={j: {k: _nodes[k] for k in setsystem[j]} for j in setsystem} - _edges={ - j: Entity(j, elements=_elements[j].values(), **setsystem[j].properties) - for j in setsystem - } - - self._edges = EntitySet( - f"{self.name}:Edges", elements=_edges.values(), **setsystem.properties - ) - self._nodes = EntitySet(f"{self.name}:Nodes", elements=_nodes.values()) - if self._static: - temprows, tempcols = self.edges.data.T - tempdata = np.ones(len(temprows), dtype=int) - self.state_dict = { - "data": (temprows, tempcols, tempdata) - } # how can we incorporate the counts into the nwhy hypergraph? - if self.nwhy: - self.g = nwhy.NWHypergraph(*self.state_dict["data"]) - self.nwhy_dict = {"snodelg": dict(), "sedgelg": dict()} - self.state_dict["snodelg"] = dict() - self.state_dict["sedgelg"] = dict() - if self.filepath is not None: - self.save_state(fpath=self.filepath) - - @property - def edges(self): - """ - Object associated with self._edges. - - Returns - ------- - StaticEntitySet or EntitySet - If self.isstatic the StaticEntitySet, otherwise EntitySet. - """ - return self._edges - - @property - def nodes(self): - """ - Object associated with self._nodes. - - Returns - ------- - StaticEntitySet or EntitySet - If self.isstatic the StaticEntitySet, otherwise EntitySet. - - """ - return self._nodes - - @property - def isstatic(self): - """ - Checks whether nodes and edges are immutable - - Returns - ------- - Boolean - - """ - return self._static - - @property - def incidence_dict(self): - """ - Dictionary keyed by edge uids with values the uids of nodes in each edge - - Returns - ------- - dict - - """ - return self._edges.incidence_dict - - @property - def shape(self): - """ - (number of nodes, number of edges) - - Returns - ------- - tuple - - """ - if self.nwhy: - return (self.g.number_of_nodes(), self.g.number_of_edges()) - else: - return (len(self._nodes.elements), len(self._edges.elements)) - - def __str__(self): - """ - String representation of hypergraph - - Returns - ------- - str - - """ - return f"Hypergraph({self.edges.elements},name={self.name})" - - def __repr__(self): - """ - String representation of hypergraph - - Returns - ------- - str - - """ - return f"Hypergraph({self.edges.elements},name={self.name})" - - def __len__(self): - """ - Number of nodes - - Returns - ------- - int - - """ - if self.nwhy: - return self.g.number_of_nodes() - else: - return len(self._nodes) - - def __iter__(self): - """ - Iterate over the nodes of the hypergraph - - Returns - ------- - dict_keyiterator - - """ - return iter(self.nodes) - - def __contains__(self, item): - """ - Returns boolean indicating if item is in self.nodes - - Parameters - ---------- - item : hashable or Entity - - """ - if isinstance(item, Entity): - return item.uid in self.nodes - else: - return item in self.nodes - - def __getitem__(self, node): - """ - Returns the neighbors of node - - Parameters - ---------- - node : Entity or hashable - If hashable, then must be uid of node in hypergraph - - Returns - ------- - neighbors(node) : iterator - - """ - return self.neighbors(node) - -
[docs] @not_implemented_for("dynamic") - def get_id(self, uid, edges=False): - """ - Return the internally assigned id associated with a label. - - Parameters - ---------- - uid : string - User provided name/id/label for hypergraph object - edges : bool, optional - Determines if uid is an edge or node name - - Returns - ------- - : int - internal id assigned at construction - """ - kdx = (edges + 1) % 2 - return int(np.argwhere(self.edges.labs(kdx) == uid)[0])
- -
[docs] @not_implemented_for("dynamic") - def get_name(self, id, edges=False): - """ - Return the user defined name/id/label associated to an - internally assigned id. - - Parameters - ---------- - id : int - Internally assigned id - edges : bool, optional - Determines if id references an edge or node - - Returns - ------- - str - User provided name/id/label for hypergraph object - """ - kdx = (edges + 1) % 2 - return self.edges.labs(kdx)[id]
- -
[docs] @not_implemented_for("dynamic") - def get_linegraph(self, s, edges=True, use_nwhy=True): - """ - Creates an ::term::s-linegraph for the Hypergraph. - If edges=True (default)then the edges will be the vertices of the line graph. - Two vertices are connected by an s-line-graph edge if the corresponding - hypergraphedges intersect in at least s hypergraph nodes. - If edges=False, the hypergraph nodes will be the vertices of the line graph. - Two vertices are connected if the nodes they correspond to share at least s - incident hyper edges. - - Parameters - ---------- - s : int - The width of the connections. - edges : bool, optional - Determine if edges or nodes will be the vertices in the linegraph. - use_nwhy : bool, optional - Requests that nwhy be used to construct the linegraph. If NWHy is not available this is ignored. - - Returns - ------- - nx.Graph - A NetworkX graph. - """ - if use_nwhy and self.nwhy: - d = self.nwhy_dict - else: - d = self.state_dict - key = "sedgelg" if edges else "snodelg" - if s in d[key]: - return d[key][s] - else: - if use_nwhy and self.nwhy: - d[key][s] = self.g.s_linegraph(s=s, edges=edges) - else: - if edges: - A = self.edge_adjacency_matrix(s=s) - else: - A = self.adjacency_matrix(s=s) - d[key][s] = nx.from_scipy_sparse_matrix(A) - if self.filepath is not None: - self.save_state(fpath=self.filepath) - return d[key][s]
- -
[docs] @not_implemented_for("dynamic") - def set_state(self, **kwargs): - """ - Allow state_dict updates from outside of class. Use with caution. - - Parameters - ---------- - **kwargs - key=value pairs to save in state dictionary - """ - self.state_dict.update(kwargs) - if self.filepath is not None: - self.save_state(fpath=self.filepath)
- -
[docs] @not_implemented_for("dynamic") - def save_state(self, fpath=None): - """ - Save the hypergraph as an ordered pair: [state_dict,labels] - The hypergraph can be recovered using the command: - - >>> H = hnx.Hypergraph.recover_from_state(fpath) - - Parameters - ---------- - fpath : str, optional - """ - if fpath is None: - fpath = self.filepath or "current_state.p" - pickle.dump([self.state_dict, self.edges.labels], open(fpath, "wb"))
- -
[docs] @classmethod - def recover_from_state(cls, fpath="current_state.p", newfpath=None, use_nwhy=True): - """ - Recover a static hypergraph pickled using save_state. - - Parameters - ---------- - fpath : str - Full path to pickle file containing state_dict and labels - of hypergraph - - Returns - ------- - H : Hypergraph - static hypergraph with state dictionary prefilled - """ - temp, labels = pickle.load(open(fpath, "rb")) - recovered_data = np.array(temp["data"])[[0, 1]].T # need to save counts as well - recovered_counts = np.array(temp["data"])[ - [2] - ] # ammend this to store cell weights - E = StaticEntitySet(data=recovered_data, labels=labels) - E.properties["counts"] = recovered_counts - H = Hypergraph(E, use_nwhy=use_nwhy) - H.state_dict.update(temp) - if newfpath == "same": - newfpath = fpath - if newfpath is not None: - H.filepath = newfpath - H.save_state() - return H
- -
[docs] @classmethod - def add_nwhy(cls, h, fpath=None): - """ - Add nwhy functionality to a hypergraph. - - Parameters - ---------- - h : hnx.Hypergraph - fpath : file path for storage of hypergraph state dictionary - - Returns - ------- - hnx.Hypergraph - Returns a copy of h with static set to true and nwhy set to True - if it is available. - - """ - - if h.isstatic: - sd = h.state_dict - H = Hypergraph(h.edges, use_nwhy=True, filepath=fpath) - H.state_dict.update(sd) - return H - else: - return Hypergraph(StaticEntitySet(h.edges), use_nwhy=True, filepath=fpath)
- -
[docs] def edge_size_dist(self): - """ - Returns the size for each edge - - Returns - ------- - np.array - - """ - if self.isstatic: - dist = self.state_dict.get("edge_size_dist", None) - if dist: - return dist - else: - if self.nwhy: - dist = self.g.edge_size_dist() - else: - dist = list(np.array(np.sum(self.incidence_matrix(), axis=0))[0]) - - self.set_state(edge_size_dist=dist) - return dist - else: - return list(np.array(np.sum(self.incidence_matrix(), axis=0))[0])
- -
[docs] def convert_to_static( - self, - name=None, - nodes_name="nodes", - edges_name="edges", - use_nwhy=False, - filepath=None, - ): - """ - Returns new static hypergraph with the same dictionary as original hypergraph - - Parameters - ---------- - name : None, optional - Name - nodes_name : str, optional - name for list of node labels - edges_name : str, optional - name for list of edge labels - - Returns - ------- - hnx.Hypergraph - Will have attribute static = True - - Note - ---- - Static hypergraphs store the user defined node and edge names in - a dictionary of labeled lists. The order of the lists provides an - index, which the hypergraph uses in place of the node and edge names - for fast processing. - """ - arr, cdict, rdict = self.edges.incidence_matrix(index=True) - labels = OrderedDict( - [ - (edges_name, [cdict[k] for k in range(len(cdict))]), - (nodes_name, [rdict[k] for k in range(len(rdict))]), - ] - ) - E = StaticEntity(arr=arr.T, labels=labels) - return Hypergraph(setsystem=E, name=name)
- -
[docs] def remove_static(self, name=None): - """ - Returns dynamic hypergraph - - Parameters - ---------- - name : None, optional - User defined namae of hypergraph - - Returns - ------- - hnx.Hypergraph - A new hypergraph with the same dictionary as self but allowing dynamic - changes to nodes and edges. - If hypergraph is not static, returns self. - """ - if not self.isstatic: - return self - else: - return Hypergraph(self.edges.incidence_dict, name=name)
- -
[docs] def translate(self, idx, edges=False): - """ - Returns the translation of numeric values associated with hypergraph. - Only needed if exposing the static identifiers assigned by the class. - If not static then the idx is returned. - - Parameters - ---------- - idx : int - class assigned integer for internal manipulation of Hypergraph data - edges : bool, optional, default: True - If True then translates from edge index. Otherwise will translate from - node index, default=False - - Returns - ------- - : int or string - User assigned identifier corresponding to idx - """ - if self.isstatic: - return self.get_name(idx, edges=edges) - else: - return idx
- -
[docs] def s_degree(self, node, s=1): # deprecate this to degree - """ - Same as `degree` - - Parameters - ---------- - node : Entity or hashable - If hashable, then must be uid of node in hypergraph - - s : positive integer, optional, default: 1 - - Returns - ------- - s_degree : int - The degree of a node in the subgraph induced by edges - of size s - - Note - ---- - The :term:`s-degree` of a node is the number of edges of size - at least s that contain the node. - - """ - msg = ( - "s-degree is deprecated and will be removed in" - " release 1.0.0. Use degree(node,s=int) instead." - ) - - warnings.warn(msg, DeprecationWarning) - return self.degree(node, s)
- -
[docs] def degree(self, node, s=1, max_size=None): - """ - The number of edges of size s that contain node. - - Parameters - ---------- - node : hashable - identifier for the node. - s : positive integer, optional, default: 1 - smallest size of edge to consider in degree - max_size : positive integer or None, optional, default: None - largest size of edge to consider in degree - - Returns - ------- - : int - - """ - if self.isstatic: - ndx = self.get_id(node) - # if s == 1: - # return np.sum(self.edges.data.T[1] == ndx) - if self.nwhy: - return self.g.degree(ndx, min_size=s, max_size=None) - - else: - if max_size is not None: - ids = np.where( - np.array(self.edge_size_dist()) in range(s, max_size + 1) - )[0] - else: - ids = np.where(np.array(self.edge_size_dist()) >= s)[0] - imat = self.incidence_matrix() - return np.sum(imat[ndx, ids]) - else: - memberships = set(self.nodes[node].memberships) - if max_size is not None: - return len( - set( - e - for e in memberships - if len(self.edges[e]) in range(s, max_size + 1) - ) - ) - elif s > 1: - return len(set(e for e in memberships if len(self.edges[e]) >= s)) - else: - return len(memberships)
- -
[docs] def size(self, edge): - """ - The number of nodes that belong to edge. - - Parameters - ---------- - edge : hashable - The uid of an edge in the hypergraph - - Returns - ------- - size : int - - """ - if self.isstatic: - edx = self.get_id(edge, edges=True) - esd = self.state_dict.get("edge_size_dist", None) - if esd is not None: - return esd[edx] - else: - if self.nwhy: - return self.g.size(edx) - else: - return np.sum(self.edges.data.T[0] == edx) - else: - return len(self.edges[edge])
- -
[docs] def number_of_nodes(self, nodeset=None): - """ - The number of nodes in nodeset belonging to hypergraph. - - Parameters - ---------- - nodeset : an interable of Entities, optional, default: None - If None, then return the number of nodes in hypergraph. - - Returns - ------- - number_of_nodes : int - - """ - if nodeset: - return len([n for n in self.nodes if n in nodeset]) - else: - if self.nwhy == True: - return self.g.number_of_nodes() - else: - return len(self.nodes)
- -
[docs] def number_of_edges(self, edgeset=None): - """ - The number of edges in edgeset belonging to hypergraph. - - Parameters - ---------- - edgeset : an interable of Entities, optional, default: None - If None, then return the number of edges in hypergraph. - - Returns - ------- - number_of_edges : int - """ - if edgeset: - return len([e for e in self.edges if e in edgeset]) - else: - if self.nwhy == True: - return self.g.number_of_edges() - else: - return len(self.edges)
- -
[docs] def order(self): - """ - The number of nodes in hypergraph. - - Returns - ------- - order : int - """ - if self.nwhy: - return self.g.number_of_nodes() - else: - return len(self.nodes)
- -
[docs] def dim(self, edge): - """ - Same as size(edge)-1. - """ - return self.size(edge) - 1
- -
[docs] def neighbors(self, node, s=1): - """ - The nodes in hypergraph which share s edge(s) with node. - - Parameters - ---------- - node : hashable or Entity - uid for a node in hypergraph or the node Entity - - s : int, list, optional, default : 1 - Minimum number of edges shared by neighbors with node. - - Returns - ------- - : list - List of neighbors - - """ - if not node in self.nodes: - print(f"Node is not in hypergraph {self.name}.") - return - - if self.isstatic: - g = self.get_linegraph(s=s, edges=False) - ndx = self.get_id(node) - if self.nwhy == True: - nbrs = g.s_neighbors(ndx) - else: - nbrs = list(g.neighbors(ndx)) - return [self.translate(nb, edges=False) for nb in nbrs] - - else: - node = self.nodes[ - node - ].uid # this allows node to be an Entity instead of a string - memberships = set(self.nodes[node].memberships).intersection( - self.edges.uidset - ) - edgeset = {e for e in memberships if len(self.edges[e]) >= s} - - neighborlist = set() - for e in edgeset: - neighborlist.update(self.edges[e].uidset) - neighborlist.discard(node) - return list(neighborlist)
- -
[docs] def edge_neighbors(self, edge, s=1): - """ - The edges in hypergraph which share s nodes(s) with edge. - - Parameters - ---------- - edge : hashable or Entity - uid for a edge in hypergraph or the edge Entity - - s : int, list, optional, default : 1 - Minimum number of nodes shared by neighbors edge node. - - Returns - ------- - : list - List of edge neighbors - - """ - if not edge in self.edges: - print(f"Edge is not in hypergraph {self.name}.") - return - - if self.isstatic: - g = self.get_linegraph(s=s, edges=True) - edx = self.get_id(edge, edges=True) - if self.nwhy == True: - nbrs = g.s_neighbors(edx) - else: - nbrs = list(g.neighbors(edx)) - return [self.translate(nb, edges=True) for nb in nbrs] - - else: - node = self.edges[edge].uid - return self.dual().neighbors(node, s=s)
- -
[docs] @not_implemented_for("static") - def remove_node(self, node): - """ - Removes node from edges and deletes reference in hypergraph nodes - - Parameters - ---------- - node : hashable or Entity - a node in hypergraph - - Returns - ------- - hypergraph : Hypergraph - - """ - if not node in self._nodes: - return self - else: - if not isinstance(node, Entity): - node = self._nodes[node] - for edge in node.memberships: - self._edges[edge].remove(node) - self._nodes.remove(node) - return self
- -
[docs] @not_implemented_for("static") - def remove_nodes(self, node_set): - """ - Removes nodes from edges and deletes references in hypergraph nodes - - Parameters - ---------- - node_set : an iterable of hashables or Entities - Nodes in hypergraph - - Returns - ------- - hypergraph : Hypergraph - - """ - for node in node_set: - self.remove_node(node) - return self
- - @not_implemented_for("static") - def _add_nodes_from(self, nodes): - """ - Private helper method instantiates new nodes when edges added to hypergraph. - - Parameters - ---------- - nodes : iterable of hashables or Entities - - """ - for node in nodes: - if node in self._edges: - raise HyperNetXError("Node already an edge.") - elif node in self._nodes and isinstance(node, Entity): - self._nodes[node].__dict__.update(node.properties) - elif node not in self._nodes: - if isinstance(node, Entity): - self._nodes.add(Entity(node.uid, **node.properties)) - else: - self._nodes.add(Entity(node)) - -
[docs] @not_implemented_for("static") - def add_edge(self, edge): - """ - - Adds a single edge to hypergraph. - - Parameters - ---------- - edge : hashable or Entity - If hashable the edge returned will be empty. - - Returns - ------- - hypergraph : Hypergraph - - Notes - ----- - When adding an edge to a hypergraph children must be removed - so that nodes do not have elements. - Each node (element of edge) must be instantiated as a node, - making sure its uid isn't already present in the self. - If an added edge contains nodes that cannot be added to hypergraph - then an error will be raised. - - """ - if edge in self._edges: - warnings.warn("Cannot add edge. Edge already in hypergraph") - elif edge in self._nodes: - warnings.warn("Cannot add edge. Edge is already a Node") - elif isinstance(edge, Entity): - if len(edge) > 0: - self._add_nodes_from(edge.elements.values()) - self._edges.add( - Entity( - edge.uid, - elements=[self._nodes[k] for k in edge], - **edge.properties, - ) - ) - for n in edge.elements: - self._nodes[n].memberships[edge.uid] = self._edges[edge.uid] - else: - self._edges.add(Entity(edge.uid, **edge.properties)) - else: - self._edges.add(Entity(edge)) # this generates an empty edge - return self
- -
[docs] @not_implemented_for("static") - def add_edges_from(self, edge_set): - """ - Add edges to hypergraph. - - Parameters - ---------- - edge_set : iterable of hashables or Entities - For hashables the edges returned will be empty. - - Returns - ------- - hypergraph : Hypergraph - - """ - for edge in edge_set: - self.add_edge(edge) - return self
- -
[docs] @not_implemented_for("static") - def add_node_to_edge(self, node, edge): - """ - - Adds node to an edge in hypergraph edges - - Parameters - ---------- - node: hashable or Entity - If Entity, only uid and properties will be used. - If uid is already in nodes then the known node will - be used - - edge: uid of edge or edge, must belong to self.edges - - Returns - ------- - hypergraph : Hypergraph - - """ - if edge in self._edges: - if not isinstance(edge, Entity): - edge = self._edges[edge] - if node in self._nodes: - self._edges[edge].add(self._nodes[node]) - else: - if not isinstance(node, Entity): - node = Entity(node) - else: - node = Entity(node.uid, **node.properties) - self._edges[edge].add(node) - self._nodes.add(node) - - return self
- -
[docs] @not_implemented_for("static") - def remove_edge(self, edge): - """ - Removes a single edge from hypergraph. - - Parameters - ---------- - edge : hashable or Entity - - Returns - ------- - hypergraph : Hypergraph - - Notes - ----- - - Deletes reference to edge from all of its nodes. - If any of its nodes do not belong to any other edges - the node is dropped from self. - - """ - if edge in self._edges: - if not isinstance(edge, Entity): - edge = self._edges[edge] - for node in edge.uidset: - edge.remove(node) - if len(self._nodes[node]._memberships) == 1: - self._nodes.remove(node) - self._edges.remove(edge) - return self
- -
[docs] @not_implemented_for("static") - def remove_edges(self, edge_set): - """ - Removes edges from hypergraph. - - Parameters - ---------- - edge_set : iterable of hashables or Entities - - Returns - ------- - hypergraph : Hypergraph - - """ - for edge in edge_set: - self.remove_edge(edge) - return self
- -
[docs] def incidence_matrix(self, index=False): - """ - An incidence matrix for the hypergraph indexed by nodes x edges. - - Parameters - ---------- - index : boolean, optional, default False - If True return will include a dictionary of node uid : row number - and edge uid : column number - - Returns - ------- - incidence_matrix : scipy.sparse.csr.csr_matrix or np.ndarray - - row dictionary : dict - Dictionary identifying rows with nodes - - column dictionary : dict - Dictionary identifying columns with edges - - """ - if self.isstatic: - mat = self.state_dict.get("incidence_matrix", None) - if mat is None: - mat = self.edges.incidence_matrix() - self.state_dict["incidence_matrix"] = mat - if index: - rdict = dict(enumerate(self.edges.labs(1))) - cdict = dict(enumerate(self.edges.labs(0))) - return mat, rdict, cdict - else: - return mat - - else: - return self.edges.incidence_matrix(index=index)
- -
[docs] @staticmethod - def incidence_to_adjacency(M, s=1, weighted=True): - """ - Helper method to obtain adjacency matrix from incidence matrix. - - Parameters - ---------- - M : scipy.sparse.csr.csr_matrix - - s : int, optional, default: 1 - - weighted : boolean, optional, default: True - - Returns - ------- - a matrix : scipy.sparse.csr.csr_matrix - - """ - A = M.dot(M.transpose()) - if issparse(A): - A.setdiag(0) - B = (A >= s) * 1 - A = A.multiply(B) - else: - np.fill_diagonal(A, 0) - B = (A >= s) * 1 - A = np.multiply(A, B) - - if not weighted: - A = (A > 0) * 1 - return csr_matrix(A)
- -
[docs] def adjacency_matrix(self, index=False, s=1, weighted=True): - """ - The sparse weighted :term:`s-adjacency matrix` - - Parameters - ---------- - s : int, optional, default: 1 - - index: boolean, optional, default: False - if True, will return a rowdict of row to node uid - - weighted: boolean, optional, default: True - - - Returns - ------- - adjacency_matrix : scipy.sparse.csr.csr_matrix - - row dictionary : dict - - Notes - ----- - If weighted is True each off diagonal cell will equal the number - of edges shared by the nodes indexing the row and column if that number is - greater than s, otherwise the cell will equal 0. If weighted is False, the off - diagonal cell will equal 1 if the nodes indexed by the row and column share at - least s edges and 0 otherwise. - - """ - M = self.incidence_matrix(index=index) - if index: - return Hypergraph.incidence_to_adjacency(M[0], s=s, weighted=weighted), M[1] - else: - return Hypergraph.incidence_to_adjacency(M, s=s, weighted=weighted)
- -
[docs] def edge_adjacency_matrix(self, index=False, s=1, weighted=True): - """ - The weighted :term:`s-adjacency matrix` for the dual hypergraph. - - Parameters - ---------- - s : int, optional, default: 1 - - index: boolean, optional, default: False - if True, will return a coldict of column to edge uid - - sparse: boolean, optional, default: True - - weighted: boolean, optional, default: True - - Returns - ------- - edge_adjacency_matrix : scipy.sparse.csr.csr_matrix or numpy.ndarray - - column dictionary : dict - - Notes - ----- - This is also the adjacency matrix for the line graph. - Two edges are s-adjacent if they share at least s nodes. - If index=True, returns a dictionary column_index:edge_uid - - """ - M = self.incidence_matrix(index=index) - if index: - return ( - Hypergraph.incidence_to_adjacency( - M[0].transpose(), s=s, weighted=weighted - ), - M[2], - ) - else: - return Hypergraph.incidence_to_adjacency( - M.transpose(), s=s, weighted=weighted - )
- -
[docs] def auxiliary_matrix(self, s=1, index=False): - """ - The unweighted :term:`s-auxiliary matrix` for hypergraph - - Parameters - ---------- - s : int - index : bool, optional, default: False - return a dictionary of labels for the rows of the matrix - - - Returns - ------- - auxiliary_matrix : scipy.sparse.csr.csr_matrix or numpy.ndarray - Will return the same type of matrix as self.arr - - Notes - ----- - Creates subgraph by restricting to edges of cardinality at least s. - Returns the unweighted s-edge adjacency matrix for the subgraph. - - """ - - edges = [e for e in self.edges if len(self.edges[e]) >= s] - H = self.restrict_to_edges(edges) - return H.edge_adjacency_matrix(s=s, index=index, weighted=False)
- -
[docs] def bipartite(self): - """ - Constructs the networkX bipartite graph associated to hypergraph. - - Returns - ------- - bipartite : nx.Graph() - - Notes - ----- - Creates a bipartite networkx graph from hypergraph. - The nodes and (hyper)edges of hypergraph become the nodes of bipartite graph. - For every (hyper)edge e in the hypergraph and node n in e there is an edge (n,e) - in the graph. - - """ - B = nx.Graph() - E = self.edges - V = self.nodes - B.add_nodes_from(E, bipartite=1) - B.add_nodes_from(V, bipartite=0) - B.add_edges_from([(v, e) for e in E for v in self.edges[e]]) - return B
- -
[docs] def dual(self, name=None): - """ - Constructs a new hypergraph with roles of edges and nodes of hypergraph reversed. - - Parameters - ---------- - name : hashable - - Returns - ------- - dual : hypergraph - """ - if self.isstatic: - E = self.edges.restrict_to_levels((1, 0)) - return Hypergraph(E, name=name, use_nwhy=self.nwhy) - else: - E = defaultdict(list) - for k, v in self.edges.incidence_dict.items(): - for n in v: - E[n].append(k) - return Hypergraph(E, name=name)
- - def _collapse_nwhy(self, edges, rec): - """ - Helper method for collapsing nodes and edges when hypergraph - is static and using nwhy - - Parameters - ---------- - edges : bool - Collapse the edges if True, otherwise the nodes - rec : bool - return the equivalence classes - """ - - if edges: - d = self.g.collapse_edges(return_equivalence_class=rec) - else: - d = self.g.collapse_nodes(return_equivalence_class=rec) - - if rec: - en = { - self.get_name( - k, edges=edges - ): f"{self.get_name(k,edges=edges)}:{len(v)}" - for k, v in d.items() - } - ec = { - f"{self.get_name(k,edges=edges)}:{len(v)}": { - self.get_name(vd, edges=edges) for vd in v - } - for k, v in d.items() - } - else: - en = { - self.get_name( - k, edges=edges - ): f"{self.get_name(k,edges=edges)}:{v.pop()}" - for k, v in d.items() - } - ec = {} - lev = self.edges.keys[1-1*edges] - E = self.edges.restrict_to_indices(sorted(d.keys()), level=1-1*edges) - E.labels[str(lev)] = np.array([en[k] for k in E.labels[lev]]) - if rec: - return E, ec - else: - return E - -
[docs] def collapse_edges( - self, - name=None, - use_reps=None, - return_counts=None, - return_equivalence_classes=False, - ): - """ - Constructs a new hypergraph gotten by identifying edges containing the same nodes - - Parameters - ---------- - name : hashable, optional, default: None - - return_equivalence_classes: boolean, optional, default: False - Returns a dictionary of edge equivalence classes keyed by frozen sets of nodes - - Returns - ------- - new hypergraph : Hypergraph - Equivalent edges are collapsed to a single edge named by a representative of the equivalent - edges followed by a colon and the number of edges it represents. - - equivalence_classes : dict - A dictionary keyed by representative edge names with values equal to the edges in - its equivalence class - - Notes - ----- - Two edges are identified if their respective elements are the same. - Using this as an equivalence relation, the uids of the edges are partitioned into - equivalence classes. - - A single edge from the collapsed edges followed by a colon and the number of elements - in its equivalence class as uid for the new edge - - - """ - if use_reps is not None or return_counts is not None: - msg = """ - use_reps ane return_counts are no longer supported keyword arguments and will throw - an error in the next release. - collapsed hypergraph automatically names collapsed objects by a string "rep:count" - """ - warnings.warn(msg, DeprecationWarning) - - if self.nwhy: - temp = self._collapse_nwhy(True, return_equivalence_classes) - else: - temp = self.edges.collapse_identical_elements( - "_", return_equivalence_classes=return_equivalence_classes - ) - if return_equivalence_classes: - return Hypergraph(temp[0], name, use_nwhy=self.nwhy), temp[1] - else: - return Hypergraph(temp, name, use_nwhy=self.nwhy)
- -
[docs] def collapse_nodes( - self, - name=None, - use_reps=True, - return_counts=True, - return_equivalence_classes=False, - ): - """ - Constructs a new hypergraph gotten by identifying nodes contained by the same edges - - Parameters - ---------- - name: str, optional, default: None - - return_equivalence_classes: boolean, optional, default: False - Returns a dictionary of node equivalence classes keyed by frozen sets of edges - - use_reps : boolean, optional, default: False - Deprecated, this no longer works and will be removed - Choose a single element from the collapsed nodes as uid for the new node, otherwise uses - a frozen set of the uids of nodes in the equivalence class - - return_counts: boolean, - Deprecated, this no longer works and will be removed - if use_reps is True the new nodes have uids given by a tuple of the rep - and the count - - Returns - ------- - new hypergraph : Hypergraph - - Notes - ----- - Two nodes are identified if their respective memberships are the same. - Using this as an equivalence relation, the uids of the nodes are partitioned into - equivalence classes. A single member of the equivalence class is chosen to represent - the class followed by the number of members of the class. - - Example - ------- - - >>> h = Hypergraph(EntitySet('example',elements=[Entity('E1', ['a','b']),Entity('E2',['a','b'])])) - >>> h.incidence_dict - {'E1': {'a', 'b'}, 'E2': {'a', 'b'}} - >>> h.collapse_nodes().incidence_dict - {'E1': {frozenset({'a', 'b'})}, 'E2': {frozenset({'a', 'b'})}} ### Fix this - >>> h.collapse_nodes(use_reps=True).incidence_dict - {'E1': {('a', 2)}, 'E2': {('a', 2)}} - - """ - if use_reps is not None or return_counts is not None: - msg = """ - use_reps ane return_counts are no longer supported keyword arguments and will throw - an error in the next release. - collapsed hypergraph automatically names collapsed objects by a string "rep:count" - """ - warnings.warn(msg, DeprecationWarning) - - if self.nwhy: - temp = self._collapse_nwhy(False, return_equivalence_classes) - if return_equivalence_classes: - return Hypergraph(temp[0], name, use_nwhy=self.nwhy), temp[1] - else: - return Hypergraph(temp, name, use_nwhy=self.nwhy) - else: - temp = self.dual().edges.collapse_identical_elements( - "_", return_equivalence_classes=return_equivalence_classes - ) - - if return_equivalence_classes: - return Hypergraph(temp[0], name, use_nwhy=self.nwhy).dual(), temp[1] - else: - return Hypergraph(temp, name, use_nwhy=self.nwhy).dual()
- -
[docs] def collapse_nodes_and_edges( - self, - name=None, - use_reps=True, - return_counts=True, - return_equivalence_classes=False, - ): - """ - Returns a new hypergraph by collapsing nodes and edges. - - Parameters - ---------- - - name: str, optional, default: None - - use_reps: boolean, optional, default: False - Choose a single element from the collapsed elements as a representative - - return_counts: boolean, optional, default: True - if use_reps is True the new elements are keyed by a tuple of the rep - and the count - - return_equivalence_classes: boolean, optional, default: False - Returns a dictionary of edge equivalence classes keyed by frozen sets of nodes - - Returns - ------- - new hypergraph : Hypergraph - - Notes - ----- - Collapses the Nodes and Edges EntitySets. Two nodes(edges) are duplicates - if their respective memberships(elements) are the same. Using this as an - equivalence relation, the uids of the nodes(edges) are partitioned into - equivalence classes. A single member of the equivalence class is chosen to represent - the class followed by the number of members of the class. - - Example - ------- - - >>> h = Hypergraph(EntitySet('example',elements=[Entity('E1', ['a','b']),Entity('E2',['a','b'])])) - >>> h.incidence_dict - {'E1': {'a', 'b'}, 'E2': {'a', 'b'}} - >>> h.collapse_nodes_and_edges().incidence_dict ### Fix this - {('E1', 2): {('a', 2)}} - - """ - if use_reps is not None or return_counts is not None: - msg = """ - use_reps ane return_counts are no longer supported keyword arguments and will throw - an error in the next release. - collapsed hypergraph automatically names collapsed objects by a string "rep:count" - """ - warnings.warn(msg, DeprecationWarning) - - if return_equivalence_classes: - temp, neq = self.collapse_nodes( - name="temp", return_equivalence_classes=True - ) - ntemp, eeq = temp.collapse_edges(name=name, return_equivalence_classes=True) - return ntemp, neq, eeq - else: - temp = self.collapse_nodes(name="temp") - return temp.collapse_edges(name=name)
- -
[docs] def restrict_to_edges(self, edgeset, name=None): - """ - Constructs a hypergraph using a subset of the edges in hypergraph - - Parameters - ---------- - edgeset: iterable of hashables or Entities - A subset of elements of the hypergraph edges - - name: str, optional - - Returns - ------- - new hypergraph : Hypergraph - """ - if self._static: - E = self._edges - setsystem = E.restrict_to(sorted(E.indices(E.keys[0], list(edgeset)))) - return Hypergraph(setsystem, name=name, use_nwhy=self.nwhy) - else: - inneredges = set() - for e in edgeset: - if isinstance(e, Entity): - inneredges.add(e.uid) - else: - inneredges.add(e) - return Hypergraph({e: self.edges[e] for e in inneredges}, name=name)
- -
[docs] def restrict_to_nodes(self, nodeset, name=None): - """ - Constructs a new hypergraph by restricting the edges in the hypergraph to - the nodes referenced by nodeset. - - Parameters - ---------- - nodeset: iterable of hashables - References a subset of elements of self.nodes - - name: string, optional, default: None - - Returns - ------- - new hypergraph : Hypergraph - """ - if self.isstatic: - E = self.edges.restrict_to_levels((1, 0)) - setsystem = E.restrict_to(sorted(E.indices(E.keys[0], list(nodeset)))) - return Hypergraph( - setsystem.restrict_to_levels((1, 0)), name=name, use_nwhy=self.nwhy - ) - else: - memberships = set() - innernodes = set() - for node in nodeset: - innernodes.add(node) - if node in self.nodes: - memberships.update(set(self.nodes[node].memberships)) - newedgeset = dict() - for e in memberships: - if e in self.edges: - temp = self.edges[e].uidset.intersection(innernodes) - if temp: - newedgeset[e] = Entity(e, temp, **self.edges[e].properties) - return Hypergraph(newedgeset, name=name)
- -
[docs] def toplexes(self, name=None, collapse=False, use_reps=False, return_counts=True): - """ - Returns a :term:`simple hypergraph` corresponding to self. - - Warning - ------- - Collapsing is no longer supported inside the toplexes method. Instead generate a new - collapsed hypergraph and compute the toplexes of the new hypergraph. - - Parameters - ---------- - name: str, optional, default: None - - # collapse: boolean, optional, default: False - # Should the hypergraph be collapsed? This would preserve a link between duplicate maximal sets. - # If False then only one of these sets will be used and uniqueness will be up to sets of equal size. - - # use_reps: boolean, optional, default: False - # If collapse=True then each toplex will be named by a representative of the set of - # equivalent edges, default is False (see collapse_edges). - - return_counts: boolean, optional, default: True - # If collapse=True then each toplex will be named by a tuple of the representative - # of the set of equivalent edges and their count - - """ - # TODO: There is a better way to do this....need to refactor - if collapse: - if len(self.edges) > 20: # TODO: Determine how big is too big. - warnings.warn( - "Collapsing a hypergraph can take a long time. It may be preferable to collapse the graph first and pickle it then apply the toplex method separately." - ) - temp = self.collapse_edges() - else: - temp = self - - if collapse: - msg = """ - collapse, return_counts, and use_reps are no longer supported keyword arguments - and will throw an error in the next release. - """ - warnings.warn(msg, DeprecationWarning) - - thdict = dict() - if self.nwhy: - tops = self.g.toplexes() - E = self.edges.restrict_to(tops) - return hnx.Hypergraph(E, use_nwhy=True) - else: - if self.isstatic: - for e in temp.edges: - thdict[e] = temp.edges[e] - else: - for e in temp.edges: - thdict[e] = temp.edges[e].uidset - tops = list() - for e in temp.edges: - flag = True - old_tops = list(tops) - for top in old_tops: - if set(thdict[e]).issubset(thdict[top]): - flag = False - break - elif set(thdict[top]).issubset(thdict[e]): - tops.remove(top) - if flag: - tops += [e] - return self.restrict_to_edges(tops, name=name)
- -
[docs] def is_connected(self, s=1, edges=False): - """ - Determines if hypergraph is :term:`s-connected <s-connected, s-node-connected>`. - - Parameters - ---------- - s: int, optional, default: 1 - - edges: boolean, optional, default: False - If True, will determine if s-edge-connected. - For s=1 s-edge-connected is the same as s-connected. - - Returns - ------- - is_connected : boolean - - Notes - ----- - - A hypergraph is s node connected if for any two nodes v0,vn - there exists a sequence of nodes v0,v1,v2,...,v(n-1),vn - such that every consecutive pair of nodes v(i),v(i+1) - share at least s edges. - - A hypergraph is s edge connected if for any two edges e0,en - there exists a sequence of edges e0,e1,e2,...,e(n-1),en - such that every consecutive pair of edges e(i),e(i+1) - share at least s nodes. - - """ - - if self.isstatic: - g = self.get_linegraph(s=s, edges=edges) - if self.nwhy: - return g.is_s_connected() - else: - return g.is_connected() - return result - else: - if edges: - A = self.edge_adjacency_matrix(s=s) - else: - A = self.adjacency_matrix(s=s) - G = nx.from_scipy_sparse_matrix(A) - return nx.is_connected(G)
- -
[docs] def singletons(self): - """ - Returns a list of singleton edges. A singleton edge is an edge of - size 1 with a node of degree 1. - - Returns - ------- - singles : list - A list of edge uids. - """ - if self.nwhy: - return self.edges.translate(0, self.g.singletons()) - else: - M, rdict, cdict = self.incidence_matrix(index=True) - idx = np.argmax(M.shape) # which axis has fewest members? if 1 then columns - cols = M.sum(idx) # we add down the row index if there are fewer columns - singles = list() - for c in range(cols.shape[(idx + 1) % 2]): # index along opposite axis - if cols[idx * c, c * ((idx + 1) % 2)] == 1: - # then see if the singleton entry in that column is also singleton in its row - # find the entry - if idx == 0: - r = np.argmax(M.getcol(c)) - # and get its sum - s = np.sum(M.getrow(r)) - # if this is also 1 then the entry in r,c represents a singleton - # so we want to change that entry to 0 and remove the row. - # this means we want to remove the edge corresponding to c - if s == 1: - singles.append(cdict[c]) - else: # switch the role of r and c - r = np.argmax(M.getrow(c)) - s = np.sum(M.getcol(r)) - if s == 1: - singles.append(cdict[r]) - return singles
- -
[docs] def remove_singletons(self, name=None): - """XX - Constructs clone of hypergraph with singleton edges removed. - - Parameters - ---------- - name: str, optional, default: None - - Returns - ------- - new hypergraph : Hypergraph - - """ - E = [e for e in self.edges if e not in self.singletons()] - return self.restrict_to_edges(E)
- -
[docs] def s_connected_components(self, s=1, edges=True, return_singletons=False): - """ - Returns a generator for the :term:`s-edge-connected components <s-edge-connected component>` - or the :term:`s-node-connected components <s-connected component, s-node-connected component>` - of the hypergraph. - - Parameters - ---------- - s : int, optional, default: 1 - - edges : boolean, optional, default: True - If True will return edge components, if False will return node components - return_singletons : bool, optional, default : False - - Notes - ----- - If edges=True, this method returns the s-edge-connected components as - lists of lists of edge uids. - An s-edge-component has the property that for any two edges e1 and e2 - there is a sequence of edges starting with e1 and ending with e2 - such that pairwise adjacent edges in the sequence intersect in at least - s nodes. If s=1 these are the path components of the hypergraph. - - If edges=False this method returns s-node-connected components. - A list of sets of uids of the nodes which are s-walk connected. - Two nodes v1 and v2 are s-walk-connected if there is a - sequence of nodes starting with v1 and ending with v2 such that pairwise - adjacent nodes in the sequence share s edges. If s=1 these are the - path components of the hypergraph. - - Example - ------- - >>> S = {'A':{1,2,3},'B':{2,3,4},'C':{5,6},'D':{6}} - >>> H = Hypergraph(S) - - >>> list(H.s_components(edges=True)) - [{'C', 'D'}, {'A', 'B'}] - >>> list(H.s_components(edges=False)) - [{1, 2, 3, 4}, {5, 6}] - - Yields - ------ - s_connected_components : iterator - Iterator returns sets of uids of the edges (or nodes) in the s-edge(node) - components of hypergraph. - - """ - components = list() - - if self.nwhy: - g = self.get_linegraph(s, edges=edges) - if return_singletons: - allobjects = set(self.edges) if edges == True else set(self.nodes) - for c in g.s_connected_components(): - comp = {self.get_name(nd, edges=edges) for nd in c} - allobjects.difference_update(comp) - for c in g.s_connected_components(): - yield {self.get_name(nd, edges=edges) for nd in c} - for obj in allobjects: - yield {obj} - else: - for c in g.s_connected_components(): - comp = {self.get_name(nd, edges=edges) for nd in c} - yield comp - - elif self.isstatic: - g = self.get_linegraph(s, edges=edges) - for c in nx.connected_components(g): - if not return_singletons and len(c) == 1: - continue - yield {self.get_name(n, edges=edges) for n in c} - else: - if edges: - A, coldict = self.edge_adjacency_matrix(s=s, index=True) - G = nx.from_scipy_sparse_matrix(A) - # if not return_singletons: - # temp = [c for c in nx.connected_components(G) if len(c) > 1] - # else: - # temp = nx.connected_components(G) - for c in nx.connected_components(G): - if not return_singletons and len(c) == 1: - continue - yield {coldict[n] for n in c} - else: - A, rowdict = self.adjacency_matrix(s=s, index=True) - G = nx.from_scipy_sparse_matrix(A) - for c in nx.connected_components(G): - if not return_singletons: - if len(c) == 1: - continue - yield {rowdict[n] for n in c}
- -
[docs] def s_component_subgraphs(self, s=1, edges=True, return_singletons=False): - """ - - Returns a generator for the induced subgraphs of s_connected components. - Removes singletons unless return_singletons is set to True. Computed using - s-linegraph generated either by the hypergraph (edges=True) or its dual - (edges = False) - - Parameters - ---------- - s : int, optional, default: 1 - - edges : boolean, optional, edges=False - Determines if edge or node components are desired. Returns - subgraphs equal to the hypergraph restricted to each set of nodes(edges) in the - s-connected components or s-edge-connected components - return_singletons : bool, optional - - Yields - ------ - s_component_subgraphs : iterator - Iterator returns subgraphs generated by the edges (or nodes) in the - s-edge(node) components of hypergraph. - - """ - for idx, c in enumerate( - self.s_components(s=s, edges=edges, return_singletons=return_singletons) - ): - if edges: - yield self.restrict_to_edges(c, name=f"{self.name}:{idx}") - else: - yield self.restrict_to_nodes(c, name=f"{self.name}:{idx}")
- -
[docs] def s_components(self, s=1, edges=True, return_singletons=True): - """ - Same as s_connected_components - - See Also - -------- - s_connected_components - """ - return self.s_connected_components( - s=s, edges=edges, return_singletons=return_singletons - )
- -
[docs] def connected_components(self, edges=False, return_singletons=True): - """ - Same as :meth:`s_connected_components` with s=1, but nodes are returned - by default. Return iterator. - - See Also - -------- - s_connected_components - """ - return self.s_connected_components(edges=edges, return_singletons=True)
- -
[docs] def connected_component_subgraphs(self, return_singletons=True): - """ - Same as :meth:`s_component_subgraphs` with s=1. Returns iterator - - See Also - -------- - s_component_subgraphs - """ - return self.s_component_subgraphs(return_singletons=return_singletons)
- -
[docs] def components(self, edges=False, return_singletons=True): - """ - Same as :meth:`s_connected_components` with s=1, but nodes are returned - by default. Return iterator. - - See Also - -------- - s_connected_components - """ - return self.s_connected_components(s=1, edges=edges)
- -
[docs] def component_subgraphs(self, return_singletons=False): - """ - Same as :meth:`s_components_subgraphs` with s=1. Returns iterator. - - See Also - -------- - s_component_subgraphs - """ - return self.s_component_subgraphs(return_singletons=return_singletons)
- -
[docs] def node_diameters(self, s=1): - """ - Returns the node diameters of the connected components in hypergraph. - - Parameters - ---------- - list of the diameters of the s-components and - list of the s-component nodes - """ - if self.nwhy: - g = self.get_linegraph(s, edges=False) - if g.is_s_connected(): - return g.s_diameter() - else: - diameters = list() - nodelists = list() - for c in g.s_connected_components(): - tc = self.edges.labs(1)[c] - nodelists.append(tc) - diameters.append(self.restrict_to_nodes(tc).node_diameters(s=s)) - else: - A, coldict = self.adjacency_matrix(s=s, index=True) - G = nx.from_scipy_sparse_matrix(A) - diams = [] - comps = [] - for c in nx.connected_components(G): - diamc = nx.diameter(G.subgraph(c)) - temp = set() - for e in c: - temp.add(coldict[e]) - comps.append(temp) - diams.append(diamc) - loc = np.argmax(diams) - return diams[loc], diams, comps
- -
[docs] def edge_diameters(self, s=1): - """ - Returns the edge diameters of the s_edge_connected component subgraphs - in hypergraph. - - Parameters - ---------- - s : int, optional, default: 1 - - Returns - ------- - maximum diameter : int - - list of diameters : list - List of edge_diameters for s-edge component subgraphs in hypergraph - - list of component : list - List of the edge uids in the s-edge component subgraphs. - - """ - if self.nwhy: - g = self.get_linegraph(s, edges=True) - if g.is_s_connected(): - return g.s_diameter() - else: - diameters = list() - edgelists = list() - for c in g.s_connected_components(): - tc = self.edges.labs(0)[c] - edgelists.append(tc) - diameters.append(self.restrict_to_edges(tc).edge_diameters(s=s)) - else: - A, coldict = self.edge_adjacency_matrix(s=s, index=True) - G = nx.from_scipy_sparse_matrix(A) - diams = [] - comps = [] - for c in nx.connected_components(G): - diamc = nx.diameter(G.subgraph(c)) - temp = set() - for e in c: - temp.add(coldict[e]) - comps.append(temp) - diams.append(diamc) - loc = np.argmax(diams) - return diams[loc], diams, comps
- -
[docs] def diameter(self, s=1): - """ - Returns the length of the longest shortest s-walk between nodes in hypergraph - - Parameters - ---------- - s : int, optional, default: 1 - - Returns - ------- - diameter : int - - Raises - ------ - HyperNetXError - If hypergraph is not s-edge-connected - - Notes - ----- - Two nodes are s-adjacent if they share s edges. - Two nodes v_start and v_end are s-walk connected if there is a sequence of - nodes v_start, v_1, v_2, ... v_n-1, v_end such that consecutive nodes - are s-adjacent. If the graph is not connected, an error will be raised. - - """ - if self.nwhy: - g = self.get_linegraph(s, edges=False) - if g.is_s_connected(): - return g.s_diameter() - else: - raise HyperNetXError(f"Hypergraph is not s-connected. s={s}") - else: - A = self.adjacency_matrix(s=s) - G = nx.from_scipy_sparse_matrix(A) - if nx.is_connected(G): - return nx.diameter(G) - else: - raise HyperNetXError(f"Hypergraph is not s-connected. s={s}")
- -
[docs] def edge_diameter(self, s=1): - """ - Returns the length of the longest shortest s-walk between edges in hypergraph - - Parameters - ---------- - s : int, optional, default: 1 - - Return - ------ - edge_diameter : int - - Raises - ------ - HyperNetXError - If hypergraph is not s-edge-connected - - Notes - ----- - Two edges are s-adjacent if they share s nodes. - Two nodes e_start and e_end are s-walk connected if there is a sequence of - edges e_start, e_1, e_2, ... e_n-1, e_end such that consecutive edges - are s-adjacent. If the graph is not connected, an error will be raised. - - """ - if self.nwhy: - g = self.get_linegraph(s, edges=True) - if g.is_s_connected(): - return g.s_diameter() - else: - raise HyperNetXError(f"Hypergraph is not s-connected. s={s}") - else: - A = self.edge_adjacency_matrix(s=s) - G = nx.from_scipy_sparse_matrix(A) - if nx.is_connected(G): - return nx.diameter(G) - else: - raise HyperNetXError(f"Hypergraph is not s-connected. s={s}")
- -
[docs] def distance(self, source, target, s=1): - """ - Returns the shortest s-walk distance between two nodes in the hypergraph. - - Parameters - ---------- - source : node.uid or node - a node in the hypergraph - - target : node.uid or node - a node in the hypergraph - - s : positive integer - the number of edges - - Returns - ------- - s-walk distance : int - - See Also - -------- - edge_distance - - Notes - ----- - The s-distance is the shortest s-walk length between the nodes. - An s-walk between nodes is a sequence of nodes that pairwise share - at least s edges. The length of the shortest s-walk is 1 less than - the number of nodes in the path sequence. - - Uses the networkx shortest_path_length method on the graph - generated by the s-adjacency matrix. - - """ - if self.isstatic: - g = self.get_linegraph(s=s, edges=False) - src = self.get_id(source, edges=False) - tgt = self.get_id(target, edges=False) - try: - if self.nwhy: - d = g.s_distance(src, tgt) - if d == -1: - warnings.warn(f"No {s}-path between {source} and {target}") - return np.inf - else: - return d - else: - return nx.shortest_path(g, src, tgt) - except: - warnings.warn(f"No {s}-path between {source} and {target}") - return np.inf - else: - if isinstance(source, Entity): - source = source.uid - if isinstance(target, Entity): - target = target.uid - A, rowdict = self.adjacency_matrix(s=s, index=True) - g = nx.from_scipy_sparse_matrix(A) - rkey = {v: k for k, v in rowdict.items()} - try: - path = nx.shortest_path_length(g, rkey[source], rkey[target]) - return path - except: - warnings.warn(f"No {s}-path between {source} and {target}") - return np.inf
- -
[docs] def edge_distance(self, source, target, s=1): - """XX TODO: still need to return path and translate into user defined nodes and edges - Returns the shortest s-walk distance between two edges in the hypergraph. - - Parameters - ---------- - source : edge.uid or edge - an edge in the hypergraph - - target : edge.uid or edge - an edge in the hypergraph - - s : positive integer - the number of intersections between pairwise consecutive edges - - TODO: add edge weights - weight : None or string, optional, default: None - if None then all edges have weight 1. If string then edge attribute - string is used if available. - - - Returns - ------- - s- walk distance : the shortest s-walk edge distance - A shortest s-walk is computed as a sequence of edges, - the s-walk distance is the number of edges in the sequence - minus 1. If no such path exists returns np.inf. - - See Also - -------- - distance - - Notes - ----- - The s-distance is the shortest s-walk length between the edges. - An s-walk between edges is a sequence of edges such that consecutive pairwise - edges intersect in at least s nodes. The length of the shortest s-walk is 1 less than - the number of edges in the path sequence. - - Uses the networkx shortest_path_length method on the graph - generated by the s-edge_adjacency matrix. - - """ - if self.isstatic: - g = self.get_linegraph(s=s, edges=True) - src = self.get_id(source, edges=True) - tgt = self.get_id(target, edges=True) - try: - if self.nwhy: - d = g.s_distance(src, tgt) - if d == -1: - warnings.warn(f"No {s}-path between {source} and {target}") - return np.inf - else: - return d - else: - return nx.shortest_path(g, src, tgt) - except: - warnings.warn(f"No {s}-path between {source} and {target}") - return np.inf - else: - if isinstance(source, Entity): - source = source.uid - if isinstance(target, Entity): - target = target.uid - A, coldict = self.edge_adjacency_matrix(s=s, index=True) - g = nx.from_scipy_sparse_matrix(A) - ckey = {v: k for k, v in coldict.items()} - try: - path = nx.shortest_path_length(g, ckey[source], ckey[target]) - return path - except: - warnings.warn(f"No {s}-path between {source} and {target}") - return np.inf
- -
[docs] def dataframe(self, sort_rows=False, sort_columns=False): - """ - Returns a pandas dataframe for hypergraph indexed by the nodes and - with column headers given by the edge names. - - Parameters - ---------- - sort_rows : bool, optional, default=True - sort rows based on hashable node names - sort_columns : bool, optional, default=True - sort columns based on hashable edge names - - """ - - mat, rdx, cdx = self.edges.incidence_matrix(index=True) - index = [rdx[i] for i in rdx] - columns = [cdx[j] for j in cdx] - df = pd.DataFrame(mat.todense(), index=index, columns=columns) - if sort_rows: - df = df.sort_index() - if sort_columns: - df = df[sorted(columns)] - return df
- -
[docs] @classmethod - def from_bipartite( - cls, B, set_names=("nodes", "edges"), name=None, static=False, use_nwhy=False - ): - """ - Static method creates a Hypergraph from a bipartite graph. - - Parameters - ---------- - - B: nx.Graph() - A networkx bipartite graph. Each node in the graph has a property - 'bipartite' taking the value of 0 or 1 indicating a 2-coloring of the graph. - - set_names: iterable of length 2, optional, default = ['nodes','edges'] - Category names assigned to the graph nodes associated to each bipartite set - - name: hashable - - static: bool - - Returns - ------- - : Hypergraph - - Notes - ----- - A partition for the nodes in a bipartite graph generates a hypergraph. - - >>> import networkx as nx - >>> B = nx.Graph() - >>> B.add_nodes_from([1, 2, 3, 4], bipartite=0) - >>> B.add_nodes_from(['a', 'b', 'c'], bipartite=1) - >>> B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'b'), (2, 'c'), (3, 'c'), (4, 'a')]) - >>> H = Hypergraph.from_bipartite(B) - >>> H.nodes, H.edges - # output: (EntitySet(_:Nodes,[1, 2, 3, 4],{}), EntitySet(_:Edges,['b', 'c', 'a'],{})) - - """ - # TODO: Add filepath keyword to signatures here and with dataframe and numpy array - edges = [] - nodes = [] - for n, d in B.nodes(data=True): - if d["bipartite"] == 0: - nodes.append(n) - else: - edges.append(n) - - if not bipartite.is_bipartite_node_set(B, nodes): - raise HyperNetXError( - "Error: Method requires a 2-coloring of a bipartite graph." - ) - - if static: - elist = [] - for e in list(B.edges): - if e[0] in nodes: - elist.append([e[0], e[1]]) - else: - elist.append([e[1], e[0]]) - df = pd.DataFrame(elist, columns=set_names) - E = StaticEntitySet(entity=df) - name = name or "_" - return Hypergraph(E, name=name, use_nwhy=use_nwhy) - else: - node_entities = { - n: Entity(n, [], properties=B.nodes(data=True)[n]) for n in nodes - } - edge_dict = { - e: [node_entities[n] for n in list(B.neighbors(e))] for e in edges - } - name = name or "_" - return Hypergraph(setsystem=edge_dict, name=name)
- -
[docs] @classmethod - def from_numpy_array( - cls, - M, - node_names=None, - edge_names=None, - node_label="nodes", - edge_label="edges", - name=None, - key=None, - static=False, - use_nwhy=False, - ): - """ - Create a hypergraph from a real valued matrix represented as a 2 dimensionsl numpy array. - The matrix is converted to a matrix of 0's and 1's so that any truthy cells are converted to 1's and - all others to 0's. - - Parameters - ---------- - M : real valued array-like object, 2 dimensions - representing a real valued matrix with rows corresponding to nodes and columns to edges - - node_names : object, array-like, default=None - List of node names must be the same length as M.shape[0]. - If None then the node names correspond to row indices with 'v' prepended. - - edge_names : object, array-like, default=None - List of edge names must have the same length as M.shape[1]. - If None then the edge names correspond to column indices with 'e' prepended. - - name : hashable - - key : (optional) function - boolean function to be evaluated on each cell of the array, - must be applicable to numpy.array - - Returns - ------- - : Hypergraph - - Note - ---- - The constructor does not generate empty edges. - All zero columns in M are removed and the names corresponding to these - edges are discarded. - - - """ - # Create names for nodes and edges - # Validate the size of the node and edge arrays - - M = np.array(M) - if len(M.shape) != (2): - raise HyperNetXError("Input requires a 2 dimensional numpy array") - # apply boolean key if available - if key: - M = key(M) - - if node_names is not None: - nodenames = np.array(node_names) - if len(nodenames) != M.shape[0]: - raise HyperNetXError( - "Number of node names does not match number of rows." - ) - else: - nodenames = np.array([f"v{idx}" for idx in range(M.shape[0])]) - - if edge_names is not None: - edgenames = np.array(edge_names) - if len(edgenames) != M.shape[1]: - raise HyperNetXError( - "Number of edge_names does not match number of columns." - ) - else: - edgenames = np.array([f"e{jdx}" for jdx in range(M.shape[1])]) - - if static or use_nwhy: - arr = np.array(M) - if key: - arr = key(arr) * 1 - arr = arr.transpose() - labels = OrderedDict([(edge_label, edgenames), (node_label, nodenames)]) - E = StaticEntitySet(arr=arr, labels=labels) - return Hypergraph(E, name=name, use_nwhy=use_nwhy) - - else: - # Remove empty column indices from M columns and edgenames - colidx = np.array([jdx for jdx in range(M.shape[1]) if any(M[:, jdx])]) - colidxsum = np.sum(colidx) - if not colidxsum: - return Hypergraph() - else: - M = M[:, colidx] - edgenames = edgenames[colidx] - edict = dict() - # Create an EntitySet of edges from M - for jdx, e in enumerate(edgenames): - edict[e] = nodenames[ - [idx for idx in range(M.shape[0]) if M[idx, jdx]] - ] - return Hypergraph(edict, name=name)
- -
[docs] @classmethod - def from_dataframe( - cls, - df, - columns=None, - rows=None, - name=None, - fillna=0, - transpose=False, - transforms=[], - key=None, - node_label="nodes", - edge_label="edges", - static=False, - use_nwhy=False, - ): - """ - Create a hypergraph from a Pandas Dataframe object using index to label vertices - and Columns to label edges. The values of the dataframe are transformed into an - incidence matrix. - Note this is different than passing a dataframe directly - into the Hypergraph constructor. The latter automatically generates a static hypergraph - with edge and node labels given by the cell values. - - Parameters - ---------- - df : Pandas.Dataframe - a real valued dataframe with a single index - - columns : (optional) list, default = None - restricts df to the columns with headers in this list. - - rows : (optional) list, default = None - restricts df to the rows indexed by the elements in this list. - - name : (optional) string, default = None - - fillna : float, default = 0 - a real value to place in empty cell, all-zero columns will not generate - an edge. - - transpose : (optional) bool, default = False - option to transpose the dataframe, in this case df.Index will label the edges - and df.columns will label the nodes, transpose is applied before transforms and - key - - transforms : (optional) list, default = [] - optional list of transformations to apply to each column, - of the dataframe using pd.DataFrame.apply(). - Transformations are applied in the order they are - given (ex. abs). To apply transforms to rows or for additional - functionality, consider transforming df using pandas.DataFrame methods - prior to generating the hypergraph. - - key : (optional) function, default = None - boolean function to be applied to dataframe. Must be defined on numpy - arrays. - - See also - -------- - from_numpy_array()) - - - Returns - ------- - : Hypergraph - - Notes - ----- - The `from_dataframe` constructor does not generate empty edges. - All-zero columns in df are removed and the names corresponding to these - edges are discarded. - Restrictions and data processing will occur in this order: - - 1. column and row restrictions - 2. fillna replace NaNs in dataframe - 3. transpose the dataframe - 4. transforms in the order listed - 5. boolean key - - This method offers the above options for wrangling a dataframe into an incidence - matrix for a hypergraph. For more flexibility we recommend you use the Pandas - library to format the values of your dataframe before submitting it to this - constructor. - - """ - - if type(df) != pd.core.frame.DataFrame: - raise HyperNetXError("Error: Input object must be a pandas dataframe.") - - if columns: - df = df[columns] - if rows: - df = df.loc[rows] - - df = df.fillna(fillna) - if transpose: - df = df.transpose() - - # node_names = np.array(df.index) - # edge_names = np.array(df.columns) - - for t in transforms: - df = df.apply(t) - if key: - mat = key(df.values) * 1 - else: - mat = df.values * 1 - - params = { - "node_names": np.array(df.index), - "edge_names": np.array(df.columns), - "name": name, - "node_label": node_label, - "edge_label": edge_label, - "static": static, - "use_nwhy": use_nwhy, - } - return cls.from_numpy_array(mat, **params)
- - -# end of Hypergraph class - - -def _make_3_arrays(mat): - arr = coo_matrix(mat) - return arr.row, arr.col, arr.data -
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/classes/staticentity.html b/docs/build/_modules/classes/staticentity.html deleted file mode 100644 index 091c7421..00000000 --- a/docs/build/_modules/classes/staticentity.html +++ /dev/null @@ -1,1294 +0,0 @@ - - - - - - - - - - classes.staticentity — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • classes.staticentity
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for classes.staticentity

-from collections import OrderedDict, defaultdict
-from collections.abc import Iterable
-import warnings
-from copy import copy
-import numpy as np
-import networkx as nx
-from hypernetx import *
-from hypernetx.exception import HyperNetXError
-from hypernetx.classes.entity import Entity, EntitySet
-from hypernetx.utils import HNXCount, DefaultOrderedDict, remove_row_duplicates
-from scipy.sparse import coo_matrix, csr_matrix, issparse
-import itertools as it
-import pandas as pd
-
-__all__ = ["StaticEntity", "StaticEntitySet"]
-
-
-
[docs]class StaticEntity(object): - - """ - .. _staticentity: - - Parameters - ---------- - entity : StaticEntity, StaticEntitySet, Entity, EntitySet, pandas.DataFrame, dict, or list of lists - If a pandas.DataFrame, an error will be raised if there are nans. - data : array or array-like - Two dimensional array of integers. Provides sparse tensor indices for incidence - tensor. - arr : numpy.ndarray or scip.sparse.matrix, optional, default=None - Incidence tensor of data. - labels : OrderedDict of lists, optional, default=None - User defined labels corresponding to integers in data. - uid : hashable, optional, default=None - - props : user defined keyword arguments to be added to a properties dictionary, optional - - Attributes - ---------- - properties : dict - Description - - """ - - def __init__( - self, entity=None, data=None, arr=None, labels=None, uid=None, **props - ): - - self._uid = uid - self.properties = {} - if entity is not None: - if isinstance(entity, StaticEntity) or isinstance(entity, StaticEntitySet): - self.properties.update(entity.properties) - self.properties.update(props) - self.__dict__.update(self.properties) - self.__dict__.update(props) - self._data = entity.data.copy() - self._dimensions = entity.dimensions - self._dimsize = entity.dimsize - self._labels = OrderedDict( - (category, np.array(values)) - for category, values in entity.labels.items() - ) - self._keys = np.array(list(self._labels.keys())) - self._keyindex = lambda category: int( - np.where(np.array(list(self._labels.keys())) == category)[0] - ) - self._index = ( - lambda category, value: int( - np.where(self._labels[category] == value)[0] - ) - if np.where(self._labels[category] == value)[0].size > 0 - else None - ) - self._arr = None - elif isinstance(entity, pd.DataFrame): - self.properties.update(props) - data, labels, counts = _turn_dataframe_into_entity( - entity, return_counts=True - ) - self.properties.update({"counts": counts}) - self.__dict__.update(self.properties) - self._data = data - self._labels = labels - self._arr = None - self._dimensions = tuple([max(x) + 1 for x in self._data.transpose()]) - self._dimsize = len(self._dimensions) - self._keys = np.array(list(self._labels.keys())) - self._keyindex = lambda category: int( - np.where(np.array(list(self._labels.keys())) == category)[0] - ) - self._index = ( - lambda category, value: int( - np.where(self._labels[category] == value)[0] - ) - if np.where(self._labels[category] == value)[0].size > 0 - else None - ) - else: - if isinstance(entity, Entity) or isinstance(entity, EntitySet): - d = entity.incidence_dict - self._data, self._labels = _turn_dict_to_staticentity( - d - ) # For now duplicate entries will be removed. - elif isinstance(entity, dict): # returns only 2 levels - self._data, self._labels = _turn_dict_to_staticentity( - entity - ) # For now duplicate entries will be removed. - else: # returns only 2 levels - self._data, self._labels = _turn_iterable_to_staticentity(entity) - self._dimensions = tuple([len(self._labels[k]) for k in self._labels]) - self._dimsize = len(self._dimensions) - self._keys = np.array(list(self._labels.keys())) - self._keyindex = lambda category: int( - np.where(np.array(list(self._labels.keys())) == category)[0] - ) - self._index = ( - lambda category, value: int( - np.where(self._labels[category] == value)[0] - ) - if np.where(self._labels[category] == value)[0].size > 0 - else None - ) - self.properties.update(props) - self.__dict__.update( - self.properties - ) # Add function to set attributes ###########!!!!!!!!!!!!! - self._arr = None - elif data is not None: - self._arr = None - self._data, counts = remove_row_duplicates( - data, return_counts=True - ) # TODO Incorporate counts into data for distance - self.properties["counts"] = counts - self._dimensions = tuple([max(x) + 1 for x in self._data.transpose()]) - self._dimsize = len(self._dimensions) - self.properties.update(props) - self.__dict__.update(props) - if ( - labels is not None - ): # determine if hashmaps might be better than lambda expressions to recover indices - self._labels = OrderedDict( - (category, np.array(values)) for category, values in labels.items() - ) # OrderedDict(category,np.array([categorical values ....])) is aligned to arr - self._keyindex = lambda category: int( - np.where(np.array(list(self._labels.keys())) == category)[0] - ) - self._keys = np.array(list(labels.keys())) - self._index = ( - lambda category, value: int( - np.where(self._labels[category] == value)[0] - ) - if np.where(self._labels[category] == value)[0].size > 0 - else None - ) - else: - self._labels = OrderedDict( - [ - (int(dim), np.arange(ct)) - for dim, ct in enumerate(self.dimensions) - ] - ) - self._keyindex = lambda category: int(category) - self._keys = np.arange(self._dimsize) - self._index = ( - lambda category, value: value - if value in self._labels[category] - else None - ) - # self._index = lambda category, value: int(np.where(self._labels[category] == value)[0]) if np.where(self._labels[category] == value)[0].size > 0 else None - elif arr is not None: - self._arr = arr - self.properties.update(props) - self.__dict__.update(props) - self._state_dict = {"arr": arr * 1} - self._dimensions = arr.shape - self._dimsize = len(arr.shape) - self._data = _turn_tensor_to_data(arr * 1) - if ( - labels is not None - ): # determine if hashmaps might be better than lambda expressions to recover indices - self._labels = OrderedDict( - (category, np.array(values)) for category, values in labels.items() - ) - self._keyindex = lambda category: int( - np.where(np.array(list(self._labels.keys())) == category)[0] - ) - self._keys = np.array(list(labels.keys())) - self._index = ( - lambda category, value: int( - np.where(self._labels[category] == value)[0] - ) - if np.where(self._labels[category] == value)[0].size > 0 - else None - ) - else: - self._labels = OrderedDict( - [ - (int(dim), np.arange(ct)) - for dim, ct in enumerate(self.dimensions) - ] - ) - self._keyindex = lambda category: int(category) - self._keys = np.arange(self._dimsize) - self._index = ( - lambda category, value: value - if value in self._labels[category] - else None - ) - else: # no entity, data or arr is given - - if labels is not None: - self._labels = OrderedDict( - (category, np.array(values)) for category, values in labels.items() - ) - self._dimensions = tuple([len(labels[k]) for k in labels]) - self._data = np.zeros((0, len(labels)), dtype=int) - self._arr = np.empty(self._dimensions, dtype=int) - self._state_dict = {"arr": np.empty(self.dimensions, dtype=int)} - self._dimsize = len(self._dimensions) - self._keyindex = lambda category: int( - np.where(np.array(list(self._labels.keys())) == category)[0] - ) - self._keys = np.array(list(labels.keys())) - self._index = ( - lambda category, value: int( - np.where(self._labels[category] == value)[0] - ) - if np.where(self._labels[category] == value)[0].size > 0 - else None - ) - else: - self._data = np.zeros((0, 0), dtype=int) - self._arr = np.array([], dtype=int) - self._labels = OrderedDict([]) - self._dimensions = tuple([]) - self._dimsize = 0 - self._keyindex = lambda category: None - self._keys = np.array([]) - self._index = lambda category, value: None - - # if labels is a list of categorical values, then change it into an - # ordered dictionary? - self.properties = props - self.__dict__.update(props) # keyed by the method name and signature - - if len(self._labels) > 0: - self._labs = lambda kdx: self._labels.get(self._keys[kdx], {}) - else: - self._labs = lambda kdx: {} - - @property - def arr(self): - if self._arr is not None: - if type(self._arr) == int and self._arr == 0: - print("arr cannot be computed") - else: - try: - imat = np.zeros(self.dimensions, dtype=int) - for d in self._data: - imat[tuple(d)] = 1 - self._arr = imat - except Exception as ex: - print(ex) - print("arr cannot be computed") - self._arr = 0 - return self._arr # Do we need to return anything here - - # @property - # def array_with_counts(self): - # """ - # This method will be included in future release. - # It allows duplicate rows in the data table - # Returns - # ------- - # np.ndarray - # """ - # if self._arr is not None: - # if type(self._arr) == int and self._arr == 0: - # print("arr cannot be computed") - # else: - # try: - # imat = np.zeros(self.dimensions, dtype=int) - # for d in self._data: - # imat[tuple(d)] += 1 - # self._arr = imat - # except Exception as ex: - # print(ex) - # print("arr cannot be computed") - # self._arr = 0 - # return self._arr - - @property - def data(self): - """ - Data array or tensor array of Static Entity - - Returns - ------- - np.ndarray - """ - - return self._data - - @property - def labels(self): - """ - Ordered dictionary of labels - - Returns - ------- - collections.OrderedDict - """ - return self._labels - - @property - def dimensions(self): - """ - Dimension of Static Entity data - - Returns - ------- - tuple - """ - return self._dimensions - - @property - def dimsize(self): - """ - Number of categories in the data - - Returns - ------- - int - """ - return self._dimsize - - @property - def keys(self): - """ - Array of keys of labels - - Returns - ------- - np.ndarray - """ - return self._keys - - @property - def keyindex(self): - """ - Returns the index of a category in keys array - - Returns - ------- - int - """ - return self._keyindex - - @property - def uid(self): - return self._uid - - @property - def uidset(self): - """ - Returns a set of the string identifiers for Static Entity - - Returns - ------- - frozenset - """ - return self.uidset_by_level(0) - - @property - def elements(self): - """ - Keys and values in the order of insertion - - Returns - ------- - collections.OrderedDict - - level1 = elements, level2 = children - """ - if len(self._keys) == 1: - return {k: {} for k in self._labels[self._keys[0]]} - else: - return self.elements_by_level(0, translate=True) - - @property - def children(self): - """ - Labels of keys of first index - - Returns - ------- - set - """ - return set(self._labs(1)) - - @property - def incidence_dict(self): - """ - Dictionary using index 0 as nodes and index 1 as edges - - Returns - ------- - collections.OrderedDict - """ - return self.elements_by_level(0, 1, translate=True) - - @property - def dataframe(self): - """ - Returns the entity data in DataFrame format - - Returns - ------- - pandas.core.frame.DataFrame - """ - return self.turn_entity_data_into_dataframe(self.data) - - def __len__(self): - """ - Returns the number of elements in Static Entity - - Returns - ------- - int - """ - return self._dimensions[0] - - def __str__(self): - """ - Return the Static Entity uid - - Returns - ------- - string - """ - return f"{self.uid}" - - def __repr__(self): - """ - Returns a string resembling the constructor for staticentity without any - children - - Returns - ------- - string - """ - return f"StaticEntity({self._uid},{list(self.uidset)},{self.properties})" - - def __contains__(self, item): - """ - Defines containment for StaticEntity based on labels/categories. - - Parameters - ---------- - item : string - - Returns - ------- - bool - """ - return item in np.concatenate(list(self._labels.values())) - - def __getitem__(self, item): - """ - Get value of key in E.elements - - Parameters - ---------- - item : string - - Returns - ------- - list - """ - # return self.elements_by_level(0, 1)[item] - return self.elements[item] - - def __iter__(self): - """ - Create iterator from E.elements - - Returns - ------- - odict_iterator - """ - return iter(self.elements) - - def __call__(self, label_index=0): - return iter(self._labs(label_index)) - -
[docs] def size(self): - """ - The number of elements in E, the size of dimension 0 in the E.arr - - Returns - ------- - int - """ - return len(self)
- -
[docs] def labs(self, kdx): - """ - Retrieve labels by index in keys - - Parameters - ---------- - kdx : int - index of key in E.keys - - Returns - ------- - np.ndarray - """ - return self._labs(kdx)
- -
[docs] def is_empty(self, level=0): - """ - Boolean indicating if entity.elements is empty - - Parameters - ---------- - level : int, optional - - Returns - ------- - bool - """ - return len(self._labs(level)) == 0
- -
[docs] def uidset_by_level(self, level=0): - """ - The labels found in columns = level - - Parameters - ---------- - level : int, optional - - Returns - ------- - frozenset - """ - return frozenset(self._labs(level)) # should be update this to tuples?
- -
[docs] def elements_by_level(self, level1=0, level2=None, translate=False): - """ - Elements of staticentity by specified column - - Parameters - ---------- - level1 : int, optional - edges - level2 : int, optional - nodes - translate : bool, optional - whether to replace indices with labels - - Returns - ------- - collections.defaultdict - - think: level1 = edges, level2 = nodes - """ - # Is there a better way to view a slice of self._arr? - if level1 > self.dimsize - 1 or level1 < 0: - print(f"This StaticEntity has no level {level1}.") - return - if level2 is None: - level2 = level1 + 1 - - if level2 > self.dimsize - 1 or level2 < 0: - print(f"This StaticEntity has no level {level2}.") - elts = OrderedDict([[k, np.array([])] for k in self._labs(level1)]) - elif level1 == level2: - print(f"level1 equals level2") - elts = OrderedDict([[k, np.array([])] for k in self._labs(level1)]) - - temp = remove_row_duplicates(self.data[:, [level1, level2]]) - elts = defaultdict(list) - for row in temp: - elts[row[0]].append(row[1]) - - if translate: - telts = OrderedDict() - for kdx, vec in elts.items(): - k = self._labs(level1)[kdx] - telts[k] = list() - for vdx in vec: - telts[k].append(self._labs(level2)[vdx]) - return telts - else: - return elts
- -
[docs] def incidence_matrix(self, level1=0, level2=1, weighted=False, index=False): - """ - Convenience method to navigate large tensor - - Parameters - ---------- - level1 : int, optional - indexes columns - level2 : int, optional - indexes rows - weighted : bool, optional - index : bool, optional - - Returns - ------- - scipy.sparse.csr.csr_matrix - - think level1 = edges, level2 = nodes - """ - if not weighted: - temp = remove_row_duplicates(self.data[:, [level2, level1]]) - else: - temp = self.data[:, [level2, level1]] - result = csr_matrix((np.ones(len(temp)), temp.transpose()), dtype=int) - - if index: # give index of rows then columns - return ( - result, - {k: v for k, v in enumerate(self._labs(level2))}, - {k: v for k, v in enumerate(self._labs(level1))}, - ) - else: - return result
- -
[docs] def restrict_to_levels(self, levels, uid=None): - """ - Limit Static Entity data to specific labels - - Parameters - ---------- - levels : array - index of labels in data - uid : None, optional - - Returns - ------- - Static Entity class - hnx.classes.staticentity.StaticEntity - """ - - if len(levels) == 1: - if levels[0] >= self.dimsize: - return self.__class__() - else: - newlabels = OrderedDict( - [(self.keys[lev], self._labs(lev)) for lev in levels] - ) - return self.__class__(labels=newlabels) - temp = remove_row_duplicates(self.data[:, levels]) - newlabels = OrderedDict([(self.keys[lev], self._labs(lev)) for lev in levels]) - return self.__class__(data=temp, labels=newlabels, uid=uid)
- -
[docs] def turn_entity_data_into_dataframe( - self, data_subset - ): # add option to include multiplicities stored in properties - """ - Convert rows of original data in StaticEntity to dataframe - - Parameters - ---------- - data : numpy.ndarray - Subset of the rows in the original data held in the StaticEntity - - Returns - ------- - pandas.core.frame.DataFrame - Columns and cell entries are derived from data and self.labels - """ - df = pd.DataFrame(data=data_subset, columns=self.keys) - width = data_subset.shape[1] - for ddx, row in enumerate(data_subset): - nrow = [self.labs(idx)[row[idx]] for idx in range(width)] - df.iloc[ddx] = nrow - return df
- -
[docs] def restrict_to_indices( - self, indices, level=0, uid=None - ): # restricting to indices requires renumbering the labels. - """ - Limit Static Entity data to specific indices of keys - - Parameters - ---------- - indices : array - array of category indices - level : int, optional - index of label - uid : None, optional - - Returns - ------- - Static Entity class - hnx.classes.staticentity.StaticEntity - """ - indices = list(indices) - idx = np.concatenate( - [np.argwhere(self.data[:, level] == k) for k in indices], axis=0 - ).transpose()[0] - temp = self.data[idx] - df = self.turn_entity_data_into_dataframe(temp) - return self.__class__(entity=df, uid=uid)
- -
[docs] def translate(self, level, index): - """ - Replaces a category index and value index with label - - Parameters - ---------- - level : int - category index of label - index : int - value index of label - - Returns - ------- - : numpy.array(str) - """ - if isinstance(index, int): - return self._labs(level)[index] - else: - return [self._labs(level)[idx] for idx in index]
- -
[docs] def translate_arr(self, coords): - """ - Translates a single cell in the entity array - - Parameters - ---------- - coords : tuple of ints - - Returns - ------- - list - """ - assert len(coords) == self.dimsize - translation = list() - for idx in range(self.dimsize): - translation.append(self.translate(idx, coords[idx])) - return translation
- -
[docs] def index(self, category, value=None): - """ - Returns dimension of category and index of value - - Parameters - ---------- - category : string - value : string, optional - - Returns - ------- - int or tuple of ints - """ - if value is not None: - return self._keyindex(category), self._index(category, value) - else: - return self._keyindex(category)
- -
[docs] def indices(self, category, values): - """ - Returns dimension of category and index of values (array) - - Parameters - ---------- - category : string - values : single string or array of strings - - Returns - ------- - list - """ - return [self._index(category, value) for value in values]
- -
[docs] def level(self, item, min_level=0, max_level=None, return_index=True): - """ - Returns first level item appears by order of keys from minlevel to maxlevel - inclusive - - Parameters - ---------- - item : string - min_level : int, optional - max_level : int, optional - - return_index : bool, optional - - Returns - ------- - tuple - """ - n = len(self.dimensions) - if max_level is not None: - n = min([max_level + 1, n]) - for lev in range(min_level, n): - if item in self._labs(lev): - if return_index: - return lev, self._index(self._keys[lev], item) - else: - return lev - else: - print(f'"{item}" not found') - return None
- - # note the depth and registry methods may or may not be useful. We can add these later. - - -
[docs]class StaticEntitySet(StaticEntity): - - """ - .. _staticentityset: - """ - - def __init__( - self, - entity=None, - data=None, - arr=None, - labels=None, - uid=None, - level1=0, - level2=1, - **props, - ): - - if entity is None: - if data is not None: - data = data[:, [level1, level2]] - arr = None - elif arr is not None: - data = _turn_tensor_to_data(arr) - data = data[:, [level1, level2]] - arr = None - if labels is not None: - keys = np.array(list(labels.keys())) - temp = OrderedDict() - for lev in [level1, level2]: - if lev < len(keys): - temp[keys[lev]] = labels[keys[lev]] - labels = temp - super().__init__(data=data, arr=arr, labels=labels, uid=uid, **props) - else: - E = StaticEntity(entity=entity) - E = E.restrict_to_levels([level1, level2]) - super().__init__(entity=E, uid=uid, **props) - - def __repr__(self): - """ - Returns a string resembling the constructor for entityset without any - children - - Returns - ------- - string - """ - return f"StaticEntitySet({self._uid},{list(self.uidset)},{self.properties})" - -
[docs] def incidence_matrix(self, sparse=True, weighted=False, index=False): - """ - Incidence matrix of StaticEntitySet indexed by uidset - - Parameters - ---------- - sparse : bool, optional - weighted : bool, optional - index : bool, optional - give index of rows then columns - - Returns - ------- - matrix - scipy.sparse.csr.csr_matrix - """ - if not weighted: - temp = remove_row_duplicates(self.data[:, [1, 0]]) - else: - temp = self.data[:, [1, 0]] - result = csr_matrix((np.ones(len(temp)), temp.transpose()), dtype=int) - - if index: - return ( - result, - {k: v for k, v in enumerate(self._labs(1))}, - {k: v for k, v in enumerate(self._labs(0))}, - ) - else: - return result
- -
[docs] def restrict_to(self, indices, uid=None): - """ - Limit Static Entityset data to specific indices of keys - - Parameters - ---------- - indices : array - array of indices in keys - uid : None, optional - - Returns - ------- - StaticEntitySet - hnx.classes.staticentity.StaticEntitySet - - """ - return self.restrict_to_indices(indices, level=0, uid=uid)
- -
[docs] def convert_to_entityset(self, uid): - """ - Convert given uid of Static EntitySet into EntitySet - - Parameters - ---------- - uid : string - - Returns - ------- - EntitySet - hnx.classes.entity.EntitySet - """ - return EntitySet(uid, self.incidence_dict)
- -
[docs] def collapse_identical_elements( - self, - uid=None, - return_equivalence_classes=False, - ): - """ - Returns StaticEntitySet after collapsing elements if they have same children - If no elements share same children, a copy of the original StaticEntitySet is returned - Parameters - ---------- - uid : None, optional - return_equivalence_classes : bool, optional - If True, return a dictionary of equivalence classes keyed by new edge names - - - Returns - ------- - StaticEntitySet - hnx.classes.staticentity.StaticEntitySet - """ - shared_children = DefaultOrderedDict(list) - for k, v in self.elements.items(): - shared_children[frozenset(v)].append(k) - new_entity_dict = OrderedDict( - [ - ( - f"{next(iter(v))}:{len(v)}", - sorted(set(k), key=lambda x: list(self.labs(1)).index(x)), - ) - for k, v in shared_children.items() - ] - ) - if return_equivalence_classes: - eq_classes = OrderedDict( - [ - ( - f"{next(iter(v))}:{len(v)}", - sorted(v, key=lambda x: list(self.labs(0)).index(x)), - ) - for k, v in shared_children.items() - ] - ) - return StaticEntitySet(uid=uid, entity=new_entity_dict), eq_classes - else: - return StaticEntitySet(uid=uid, entity=new_entity_dict)
- - -def _turn_tensor_to_data(arr, remove_duplicates=True): - """ - Return list of nonzero coordinates in arr. - - Parameters - ---------- - arr : numpy.ndarray - Tensor corresponding to incidence of co-occurring labels. - """ - return np.array(arr.nonzero()).transpose() - - -def _turn_dict_to_staticentity(dict_object, remove_duplicates=True): - """Create a static entity directly from a dictionary of hashables""" - d = OrderedDict(dict_object) - level2ctr = HNXCount() - level1ctr = HNXCount() - level2 = DefaultOrderedDict(level2ctr) - level1 = DefaultOrderedDict(level1ctr) - coords = list() - for k, val in d.items(): - level1[k] - for v in val: - level2[v] - coords.append((level1[k], level2[v])) - if remove_duplicates: - coords = remove_row_duplicates(coords) - level1 = list(level1) - level2 = list(level2) - data = np.array(coords, dtype=int) - labels = OrderedDict({"0": level1, "1": level2}) - return data, labels - - -def _turn_iterable_to_staticentity(iter_object, remove_duplicates=True): - for s in iter_object: - if not isinstance(s, Iterable): - raise HyperNetXError( - "StaticEntity constructor requires an iterable of iterables." - ) - else: - labels = [f"e{str(x)}" for x in range(len(iter_object))] - dict_object = dict(zip(labels, iter_object)) - return _turn_dict_to_staticentity(dict_object, remove_duplicates=remove_duplicates) - - -def _turn_dataframe_into_entity(df, return_counts=False, include_unknowns=False): - """ - Convenience method to reformat dataframe object into data,labels format - for construction of a static entity - - Parameters - ---------- - df : pandas.DataFrame - May not contain nans - return_counts : bool, optional, default : False - Used for keeping weights - include_unknowns : bool, optional, default : False - If Unknown <column name> was used to fill in nans - - Returns - ------- - outputdata : numpy.ndarray - counts : numpy.array of ints - slabels : numpy.array of strings - - """ - columns = df.columns - ctr = [HNXCount() for c in range(len(columns))] - ldict = OrderedDict() - rdict = OrderedDict() - for idx, c in enumerate(columns): - ldict[c] = defaultdict(ctr[idx]) # TODO make this an Ordered default dict - rdict[c] = OrderedDict() - if include_unknowns: - ldict[c][ - f"Unknown {c}" - ] # TODO: update this to take a dict assign for each column - rdict[c][0] = f"Unknown {c}" - for k in df[c]: - ldict[c][k] - rdict[c][ldict[c][k]] = k - ldict[c] = dict(ldict[c]) - dims = tuple([len(ldict[c]) for c in columns]) - - m = len(df) - n = len(columns) - data = np.zeros((m, n), dtype=int) - for rid in range(m): - for cid in range(n): - c = columns[cid] - data[rid, cid] = ldict[c][df.iloc[rid][c]] - - output_data = remove_row_duplicates(data, return_counts=return_counts) - - slabels = OrderedDict() - for cdx, c in enumerate(columns): - slabels.update({c: np.array(list(ldict[c].keys()))}) - if return_counts: - return output_data[0], slabels, output_data[1] - else: - return output_data, slabels -
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/drawing/rubber_band.html b/docs/build/_modules/drawing/rubber_band.html deleted file mode 100644 index 7f56ef56..00000000 --- a/docs/build/_modules/drawing/rubber_band.html +++ /dev/null @@ -1,715 +0,0 @@ - - - - - - - - - - drawing.rubber_band — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • drawing.rubber_band
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for drawing.rubber_band

-# Copyright © 2018 Battelle Memorial Institute
-# All rights reserved.
-
-from hypernetx import Hypergraph
-from .util import (
-    get_frozenset_label,
-    get_set_layering,
-    inflate_kwargs,
-    transpose_inflated_kwargs,
-)
-
-import matplotlib.pyplot as plt
-from matplotlib.collections import PolyCollection, LineCollection, CircleCollection
-
-import networkx as nx
-
-from itertools import combinations
-from collections import defaultdict
-
-import numpy as np
-from scipy.spatial.distance import pdist
-from scipy.spatial import ConvexHull
-from scipy.spatial import Voronoi
-
-# increases the default figure size to 8in square.
-plt.rcParams["figure.figsize"] = (8, 8)
-
-N_CONTROL_POINTS = 24
-
-theta = np.linspace(0, 2 * np.pi, N_CONTROL_POINTS + 1)[:-1]
-
-cp = np.vstack((np.cos(theta), np.sin(theta))).T
-
-
-
-
-
-
[docs]def get_default_radius(H, pos): - """ - Calculate a reasonable default node radius - - This function iterates over the hyper edges and finds the most distant - pair of points given the positions provided. Then, the node radius is a fraction - of the median of this distance take across all hyper-edges. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - - Returns - ------- - float - the recommended radius - - """ - if len(H) > 1: - return 0.0125 * np.median( - [pdist(np.vstack(list(map(pos.get, H.nodes)))).max() for nodes in H.edges()] - ) - return 1
- - -
[docs]def draw_hyper_edge_labels(H, polys, labels={}, ax=None, **kwargs): - """ - Draws a label on the hyper edge boundary. - - Should be passed Matplotlib PolyCollection representing the hyper-edges, see - the return value of draw_hyper_edges. - - The label will be draw on the least curvy part of the polygon, and will be - aligned parallel to the orientation of the polygon where it is drawn. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - polys: PolyCollection - collection of polygons returned by draw_hyper_edges - labels: dict - mapping of node id to string label - ax: Axis - matplotlib axis on which the plot is rendered - kwargs: dict - Keyword arguments are passed through to Matplotlib's annotate function. - - """ - ax = ax or plt.gca() - - params = transpose_inflated_kwargs(inflate_kwargs(H.edges, kwargs)) - - for edge, path, params in zip(H.edges, polys.get_paths(), params): - s = labels.get(edge, edge) - - # calculate the xy location of the annotation - # this is the midpoint of the pair of adjacent points the most distant - d = ((path.vertices[:-1] - path.vertices[1:]) ** 2).sum(axis=1) - i = d.argmax() - - x1, x2 = path.vertices[i : i + 2] - x, y = x2 - x1 - theta = 360 * np.arctan2(y, x) / (2 * np.pi) - theta = (theta + 360) % 360 - - while theta > 90: - theta -= 180 - - # the string is a comma separated list of the edge uid - ax.annotate( - s, (x1 + x2) / 2, rotation=theta, ha="center", va="center", **params - )
- - -
[docs]def layout_hyper_edges(H, pos, node_radius={}, dr=None): - """ - Draws a convex hull for each edge in H. - - Position of the nodes in the graph is specified by the position dictionary, - pos. Convex hulls are spaced out such that if one set contains another, the - convex hull will surround the contained set. The amount of spacing added - between hulls is specified by the parameter, dr. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - node_radius: dict - mapping of node to R^1 (radius of each node) - dr: float - the spacing between concentric rings - ax: Axis - matplotlib axis on which the plot is rendered - - Returns - ------- - dict - A mapping from hyper edge ids to paths (Nx2 numpy matrices) - """ - - if len(node_radius): - r0 = min(node_radius.values()) - else: - r0 = get_default_radius(H, pos) - - dr = dr or r0 - - levels = get_set_layering(H) - - radii = { - v: {v: i for i, v in enumerate(sorted(e, key=levels.get))} - for v, e in H.dual().edges.elements.items() - } - - def get_padded_hull(uid, edge): - # make sure the edge contains at least one node - if len(edge): - points = np.vstack( - [ - cp * (node_radius.get(v, r0) + dr * (2 + radii[v][uid])) + pos[v] - for v in edge - ] - ) - # if not, draw an empty edge centered around the location of the edge node (in the bipartite graph) - else: - points = 4 * r0 * cp + pos[uid] - - hull = ConvexHull(points) - - return hull.points[hull.vertices] - - return [get_padded_hull(uid, list(H.edges[uid])) for uid in H.edges]
- - -
[docs]def draw_hyper_edges(H, pos, ax=None, node_radius={}, dr=None, **kwargs): - """ - Draws a convex hull around the nodes contained within each edge in H - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - node_radius: dict - mapping of node to R^1 (radius of each node) - dr: float - the spacing between concentric rings - ax: Axis - matplotlib axis on which the plot is rendered - kwargs: dict - keyword arguments, e.g., linewidth, facecolors, are passed through to the PolyCollection constructor - - Returns - ------- - PolyCollection - a Matplotlib PolyCollection that can be further styled - """ - points = layout_hyper_edges(H, pos, node_radius=node_radius, dr=dr) - - polys = PolyCollection(points, **inflate_kwargs(H.edges, kwargs)) - - (ax or plt.gca()).add_collection(polys) - - return polys
- - -
[docs]def draw_hyper_nodes(H, pos, node_radius={}, r0=None, ax=None, **kwargs): - """ - Draws a circle for each node in H. - - The position of each node is specified by the a dictionary/list-like, pos, - where pos[v] is the xy-coordinate for the vertex. The radius of each node - can be specified as a dictionary where node_radius[v] is the radius. If a - node is missing from this dictionary, or the node_radius is not specified at - all, a sensible default radius is chosen based on distances between nodes - given by pos. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - node_radius: dict - mapping of node to R^1 (radius of each node) - r0: float - minimum distance that concentric rings start from the node position - ax: Axis - matplotlib axis on which the plot is rendered - kwargs: dict - keyword arguments, e.g., linewidth, facecolors, are passed through to the PolyCollection constructor - - Returns - ------- - PolyCollection - a Matplotlib PolyCollection that can be further styled - """ - - ax = ax or plt.gca() - - r0 = r0 or get_default_radius(H, pos) - - points = [node_radius.get(v, r0) * cp + pos[v] for v in H.nodes] - - kwargs.setdefault("facecolors", "black") - - circles = PolyCollection(points, **inflate_kwargs(H, kwargs)) - - ax.add_collection(circles) - - return circles
- - -
[docs]def draw_hyper_labels(H, pos, node_radius={}, ax=None, labels={}, **kwargs): - """ - Draws text labels for the hypergraph nodes. - - The label is drawn to the right of the node. The node radius is needed (see - draw_hyper_nodes) so the text can be offset appropriately as the node size - changes. - - The text label can be customized by passing in a dictionary, labels, mapping - a node to its custom label. By default, the label is the string - representation of the node. - - Keyword arguments are passed through to Matplotlib's annotate function. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - node_radius: dict - mapping of node to R^1 (radius of each node) - ax: Axis - matplotlib axis on which the plot is rendered - labels: dict - mapping of node to text label - kwargs: dict - keyword arguments passed to matplotlib.annotate - - """ - ax = ax or plt.gca() - - params = transpose_inflated_kwargs(inflate_kwargs(H.nodes, kwargs)) - - for v, v_kwargs in zip(H.nodes, params): - xy = np.array([node_radius.get(v, 0), 0]) + pos[v] - ax.annotate( - labels.get(v, v), - xy, - **{ - k: ( - d[v] - if hasattr(d, "__getitem__") and type(d) not in {str, tuple} - else d - ) - for k, d in kwargs.items() - } - )
- - -
[docs]def draw( - H, - pos=None, - with_color=True, - with_node_counts=False, - with_edge_counts=False, - layout=nx.spring_layout, - layout_kwargs={}, - ax=None, - node_radius=None, - edges_kwargs={}, - nodes_kwargs={}, - edge_labels={}, - edge_labels_kwargs={}, - node_labels={}, - node_labels_kwargs={}, - with_edge_labels=True, - with_node_labels=True, - label_alpha=0.35, - return_pos=False, -): - """ - Draw a hypergraph as a Matplotlib figure - - By default this will draw a colorful "rubber band" like hypergraph, where - convex hulls represent edges and are drawn around the nodes they contain. - - This is a convenience function that wraps calls with sensible parameters to - the following lower-level drawing functions: - - * draw_hyper_edges, - * draw_hyper_edge_labels, - * draw_hyper_labels, and - * draw_hyper_nodes - - The default layout algorithm is nx.spring_layout, but other layouts can be - passed in. The Hypergraph is converted to a bipartite graph, and the layout - algorithm is passed the bipartite graph. - - If you have a pre-determined layout, you can pass in a "pos" dictionary. - This is a dictionary mapping from node id's to x-y coordinates. For example: - - >>> pos = { - >>> 'A': (0, 0), - >>> 'B': (1, 2), - >>> 'C': (5, -3) - >>> } - - will position the nodes {A, B, C} manually at the locations specified. The - coordinate system is in Matplotlib "data coordinates", and the figure will - be centered within the figure. - - By default, this will draw in a new figure, but the axis to render in can be - specified using :code:`ax`. - - This approach works well for small hypergraphs, and does not guarantee - a rigorously "correct" drawing. Overlapping of sets in the drawing generally - implies that the sets intersect, but sometimes sets overlap if there is no - intersection. It is not possible, in general, to draw a "correct" hypergraph - this way for an arbitrary hypergraph, in the same way that not all graphs - have planar drawings. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - with_color: bool - set to False to disable color cycling of edges - with_node_counts: bool - set to True to label collapsed nodes with number of elements - with_edge_counts: bool - set to True to label collapsed edges with number of elements - layout: function - layout algorithm to compute - layout_kwargs: dict - keyword arguments passed to layout function - ax: Axis - matplotlib axis on which the plot is rendered - edges_kwargs: dict - keyword arguments passed to matplotlib.collections.PolyCollection for edges - node_radius: None, int, float, or dict - radius of all nodes, or dictionary of node:value; the default (None) calculates radius based on number of collapsed nodes; reasonable values range between 1 and 3 - nodes_kwargs: dict - keyword arguments passed to matplotlib.collections.PolyCollection for nodes - edge_labels_kwargs: dict - keyword arguments passed to matplotlib.annotate for edge labels - node_labels_kwargs: dict - keyword argumetns passed to matplotlib.annotate for node labels - with_edge_labels: bool - set to False to make edge labels invisible - with_node_labels: bool - set to False to make node labels invisible - label_alpha: float - the transparency (alpha) of the box behind text drawn in the figure - """ - - ax = ax or plt.gca() - - if pos is None: - pos = layout_node_link(H, layout=layout, **layout_kwargs) - - r0 = get_default_radius(H, pos) - a0 = np.pi * r0 ** 2 - - def get_node_radius(v): - if node_radius is None: - return np.sqrt(a0 * (len(v) if type(v) == frozenset else 1) / np.pi) - elif hasattr(node_radius, "get"): - return node_radius.get(v, 1) * r0 - return node_radius * r0 - - # guarantee that node radius is a dictionary mapping nodes to values - node_radius = {v: get_node_radius(v) for v in H.nodes} - - # for convenience, we are using setdefault to mutate the argument - # however, we need to copy this to prevent side-effects - edges_kwargs = edges_kwargs.copy() - edges_kwargs.setdefault("edgecolors", plt.cm.tab10(np.arange(len(H.edges)) % 10)) - edges_kwargs.setdefault("facecolors", "none") - - polys = draw_hyper_edges(H, pos, node_radius=node_radius, ax=ax, **edges_kwargs) - - if with_edge_labels: - labels = get_frozenset_label( - H.edges, count=with_edge_counts, override=edge_labels - ) - - draw_hyper_edge_labels( - H, - polys, - color=edges_kwargs["edgecolors"], - backgroundcolor=(1, 1, 1, label_alpha), - labels=labels, - ax=ax, - **edge_labels_kwargs - ) - - if with_node_labels: - labels = get_frozenset_label( - H.nodes, count=with_node_counts, override=node_labels - ) - - draw_hyper_labels( - H, - pos, - node_radius=node_radius, - labels=labels, - ax=ax, - va="center", - xytext=(5, 0), - textcoords="offset points", - backgroundcolor=(1, 1, 1, label_alpha), - **node_labels_kwargs - ) - - draw_hyper_nodes(H, pos, node_radius=node_radius, ax=ax, **nodes_kwargs) - - if len(H.nodes) == 1: - x, y = pos[list(H.nodes)[0]] - s = 20 - - ax.axis([x - s, x + s, y - s, y + s]) - else: - ax.axis("equal") - - ax.axis("off") - if return_pos: - return pos
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/drawing/two_column.html b/docs/build/_modules/drawing/two_column.html deleted file mode 100644 index cbc4eaf2..00000000 --- a/docs/build/_modules/drawing/two_column.html +++ /dev/null @@ -1,426 +0,0 @@ - - - - - - - - - - drawing.two_column — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • drawing.two_column
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for drawing.two_column

-# Copyright © 2018 Battelle Memorial Institute
-# All rights reserved.
-
-import matplotlib.pyplot as plt
-from matplotlib.collections import LineCollection
-
-import networkx as nx
-
-from .util import get_frozenset_label
-
-
-
[docs]def layout_two_column(H, spacing=2): - """ - Two column (bipartite) layout algorithm. - - This algorithm first converts the hypergraph into a bipartite graph and - then computes connected components. Disonneccted components are handled - independently and then stacked together. - - Within a connected component, the spectral ordering of the bipartite graph - provides a quick and dirty ordering that minimizes edge crossings in the - diagram. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - spacing: float - amount of whitespace between disconnected components - """ - offset = 0 - pos = {} - - def stack(vertices, x, height): - for i, v in enumerate(vertices): - pos[v] = (x, i + offset + (height - len(vertices)) / 2) - - G = H.bipartite() - for ci in nx.connected_components(G): - Gi = G.subgraph(ci) - key = {v: i for i, v in enumerate(nx.spectral_ordering(Gi))}.get - ci_vertices, ci_edges = [ - sorted([v for v, d in Gi.nodes(data=True) if d["bipartite"] == j], key=key) - for j in [0, 1] - ] - - height = max(len(ci_vertices), len(ci_edges)) - - stack(ci_vertices, 0, height) - stack(ci_edges, 1, height) - - offset += height + spacing - - return pos
- - -
[docs]def draw_hyper_edges(H, pos, ax=None, **kwargs): - """ - Renders hyper edges for the two column layout. - - Each node-hyper edge membership is rendered as a line connecting the node - in the left column to the edge in the right column. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - ax: Axis - matplotlib axis on which the plot is rendered - kwargs: dict - keyword arguments passed to matplotlib.LineCollection - - Returns - ------- - LineCollection - the hyper edges - """ - ax = ax or plt.gca() - - pairs = [(v, e.uid) for e in H.edges() for v in e] - - kwargs = { - k: v if type(v) != dict else [v.get(e) for _, e in pairs] - for k, v in kwargs.items() - } - - lines = LineCollection([(pos[u], pos[v]) for u, v in pairs], **kwargs) - - ax.add_collection(lines) - - return lines
- - -
[docs]def draw_hyper_labels( - H, pos, labels={}, with_node_labels=True, with_edge_labels=True, ax=None -): - """ - Renders hyper labels (nodes and edges) for the two column layout. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - pos: dict - mapping of node and edge positions to R^2 - labels: dict - custom labels for nodes and edges can be supplied - with_node_labels: bool - False to disable node labels - with_edge_labels: bool - False to disable edge labels - ax: Axis - matplotlib axis on which the plot is rendered - kwargs: dict - keyword arguments passed to matplotlib.LineCollection - - """ - - ax = ax or plt.gca() - - edges = [e.uid for e in H.edges()] - - to_draw = [] - if with_node_labels: - to_draw.append((H.nodes(), "right")) - - if with_edge_labels: - to_draw.append((H.edges(), "left")) - - for points, ha in to_draw: - for p in points: - ax.annotate(labels.get(p.uid, p.uid), pos[p.uid], ha=ha, va="center")
- - -
[docs]def draw( - H, - with_node_labels=True, - with_edge_labels=True, - with_node_counts=False, - with_edge_counts=False, - with_color=True, - edge_kwargs=None, - ax=None, -): - """ - Draw a hypergraph using a two-collumn layout. - - This is intended reproduce an illustrative technique for bipartite graphs - and hypergraphs that is typically used in papers and textbooks. - - The left column is reserved for nodes and the right column is reserved for - edges. A line is drawn between a node an an edge - - The order of nodes and edges is optimized to reduce line crossings between - the two columns. Spacing between disconnected components is adjusted to make - the diagram easier to read, by reducing the angle of the lines. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - with_node_labels: bool - False to disable node labels - with_edge_labels: bool - False to disable edge labels - with_node_counts: bool - set to True to label collapsed nodes with number of elements - with_edge_counts: bool - set to True to label collapsed edges with number of elements - with_color: bool - set to False to disable color cycling of hyper edges - edge_kwargs: dict - keyword arguments to pass to matplotlib.LineCollection - ax: Axis - matplotlib axis on which the plot is rendered - """ - - edge_kwargs = edge_kwargs or {} - - ax = ax or plt.gca() - - pos = layout_two_column(H) - - V = [v.uid for v in H.nodes()] - E = [e.uid for e in H.edges()] - - labels = {} - labels.update(get_frozenset_label(V, count=with_node_counts)) - labels.update(get_frozenset_label(E, count=with_edge_counts)) - - if with_color: - edge_kwargs["color"] = { - e.uid: plt.cm.tab10(i % 10) for i, e in enumerate(H.edges()) - } - - draw_hyper_edges(H, pos, ax=ax, **edge_kwargs) - draw_hyper_labels( - H, - pos, - labels, - ax=ax, - with_node_labels=with_node_labels, - with_edge_labels=with_edge_labels, - ) - ax.autoscale_view() - - ax.axis("off")
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/drawing/util.html b/docs/build/_modules/drawing/util.html deleted file mode 100644 index 31a5dcab..00000000 --- a/docs/build/_modules/drawing/util.html +++ /dev/null @@ -1,353 +0,0 @@ - - - - - - - - - - drawing.util — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • drawing.util
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for drawing.util

-# Copyright © 2018 Battelle Memorial Institute
-# All rights reserved.
-
-from itertools import combinations
-
-import numpy as np
-
-import networkx as nx
-
-
-
[docs]def inflate(items, v): - if type(v) in {str, tuple, int, float}: - return [v] * len(items) - elif callable(v): - return [v(i) for i in items] - elif type(v) not in {list, np.ndarray} and hasattr(v, "__getitem__"): - return [v[i] for i in items] - return v
- - -
[docs]def inflate_kwargs(items, kwargs): - """ - Helper function to expand keyword arguments. - - Parameters - ---------- - n: int - length of resulting list if argument is expanded - kwargs: dict - keyword arguments to be expanded - - Returns - ------- - dict - dictionary with same keys as kwargs and whose values are lists of length n - """ - - return {k: inflate(items, v) for k, v in kwargs.items()}
- - -
[docs]def transpose_inflated_kwargs(inflated): - return [dict(zip(inflated, v)) for v in zip(*inflated.values())]
- - -
[docs]def get_frozenset_label(S, count=False, override={}): - """ - Helper function for rendering the labels of possibly collapsed nodes and edges - - Parameters - ---------- - S: iterable - list of entities to be labeled - count: bool - True if labels should be counts of entities instead of list - - Returns - ------- - dict - mapping of entity to its string representation - """ - - def helper(v): - if type(v) == frozenset: - if count and len(v) > 1: - return f"x {len(v)}" - elif count: - return "" - else: - return ", ".join([str(override.get(s, s)) for s in v]) - return str(v) - - return {v: override.get(v, helper(v)) for v in S}
- - -
[docs]def get_line_graph(H, collapse=True): - """ - Computes the line graph, a directed graph, where a directed edge (u, v) - exists if the edge u is a subset of the edge v in the hypergraph. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - collapse: bool - True if edges should be added if hyper edges are identical - - Returns - ------- - networkx.DiGraph - A directed graph - """ - D = nx.DiGraph() - - V = {edge: set(nodes) for edge, nodes in H.edges.elements.items()} - - D.add_nodes_from(V) - - for u, v in combinations(V, 2): - if V[u] != V[v] or not collapse: - if V[u].issubset(V[v]): - D.add_edge(u, v) - elif V[v].issubset(V[u]): - D.add_edge(v, u) - - return D
- - -
[docs]def get_set_layering(H, collapse=True): - """ - Computes a layering of the edges in the hyper graph. - - In this layering, each edge is assigned a level. An edge u will be above - (e.g., have a smaller level value) another edge v if v is a subset of u. - - Parameters - ---------- - H: Hypergraph - the entity to be drawn - collapse: bool - True if edges should be added if hyper edges are identical - - Returns - ------- - dict - a mapping of vertices in H to integer levels - """ - - D = get_line_graph(H, collapse=collapse) - - levels = {} - - for v in nx.topological_sort(D): - parent_levels = [levels[u] for u, _ in D.in_edges(v)] - levels[v] = max(parent_levels) + 1 if len(parent_levels) else 0 - - return levels
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/index.html b/docs/build/_modules/index.html deleted file mode 100644 index 63f60b69..00000000 --- a/docs/build/_modules/index.html +++ /dev/null @@ -1,224 +0,0 @@ - - - - - - - - - - Overview: module code — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Overview: module code
  • - - -
  • - -
  • - -
- - -
-
- - -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_modules/reports/descriptive_stats.html b/docs/build/_modules/reports/descriptive_stats.html deleted file mode 100644 index 66ea9889..00000000 --- a/docs/build/_modules/reports/descriptive_stats.html +++ /dev/null @@ -1,629 +0,0 @@ - - - - - - - - - - reports.descriptive_stats — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - -
- -
- - - - - - - - - - - - - - - - - - - -
- -
    - -
  • »
  • - -
  • Module code »
  • - -
  • reports.descriptive_stats
  • - - -
  • - -
  • - -
- - -
-
-
-
- -

Source code for reports.descriptive_stats

-"""
-This module contains methods which compute various distributions for hypergraphs:
-    * Edge size distribution
-    * Node degree distribution
-    * Component size distribution
-    * Toplex size distribution
-    * Diameter
-
-Also computes general hypergraph information: number of nodes, edges, cells, aspect ratio, incidence matrix density
-"""
-from collections import Counter
-import numpy as np
-import networkx as nx
-from hypernetx import *
-from hypernetx.utils.decorators import not_implemented_for
-
-__all__ = [
-    "centrality_stats",
-    "edge_size_dist",
-    "degree_dist",
-    "comp_dist",
-    "s_comp_dist",
-    "toplex_dist",
-    "s_node_diameter_dist",
-    "s_edge_diameter_dist",
-    "info",
-    "info_dict",
-    "dist_stats",
-]
-
-
-
[docs]def centrality_stats(X): - """ - Computes basic centrality statistics for X - - Parameters - ---------- - X : - an iterable of numbers - - Returns - ------- - [min, max, mean, median, standard deviation] : list - List of centrality statistics for X - """ - return [min(X), max(X), np.mean(X), np.median(X), np.std(X)]
- - -
[docs]def edge_size_dist(H, aggregated=False): - """ - Computes edge sizes of a hypergraph. - - Parameters - ---------- - H : Hypergraph - aggregated : - If aggregated is True, returns a dictionary of - edge sizes and counts. If aggregated is False, returns a - list of edge sizes in H. - - Returns - ------- - edge_size_dist : list or dict - List of edge sizes or dictionary of edge size distribution. - - """ - if aggregated: - return Counter(H.edge_size_dist()) - else: - return H.edge_size_dist()
- - -
[docs]def degree_dist(H, aggregated=False): - """ - Computes degrees of nodes of a hypergraph. - - Parameters - ---------- - H : Hypergraph - aggregated : - If aggregated is True, returns a dictionary of - degrees and counts. If aggregated is False, returns a - list of degrees in H. - - Returns - ------- - degree_dist : list or dict - List of degrees or dictionary of degree distribution - """ - if H.nwhy: - distr = H.g.node_size_dist() - else: - distr = [H.degree(n) for n in H.nodes] - if aggregated: - return Counter(distr) - else: - return distr
- - -
[docs]def comp_dist(H, aggregated=False): - """ - Computes component sizes, number of nodes. - - Parameters - ---------- - H : Hypergraph - aggregated : - If aggregated is True, returns a dictionary of - component sizes (number of nodes) and counts. If aggregated - is False, returns a list of components sizes in H. - - Returns - ------- - comp_dist : list or dictionary - List of component sizes or dictionary of component size distribution - - See Also - -------- - s_comp_dist - - """ - - distr = [len(c) for c in H.components()] - if aggregated: - return Counter(distr) - else: - return distr
- - -
[docs]def s_comp_dist(H, s=1, aggregated=False, edges=True, return_singletons=True): - """ - Computes s-component sizes, counting nodes or edges. - - Parameters - ---------- - H : Hypergraph - s : positive integer, default is 1 - aggregated : - If aggregated is True, returns a dictionary of - s-component sizes and counts in H. If aggregated is - False, returns a list of s-component sizes in H. - edges : - If edges is True, the component size is number of edges. - If edges is False, the component size is number of nodes. - return_singletons : bool, optional, default=True - - Returns - ------- - s_comp_dist : list or dictionary - List of component sizes or dictionary of component size distribution in H - - See Also - -------- - comp_dist - - """ - distr = list() - comps = H.s_connected_components( - s=s, edges=edges, return_singletons=return_singletons - ) - - distr = [len(c) for c in comps] - - if aggregated: - return Counter(distr) - else: - return distr
- - -
[docs]@not_implemented_for("static") -def toplex_dist(H, aggregated=False): - """ - - Computes toplex sizes for hypergraph H. - - Parameters - ---------- - H : Hypergraph - aggregated : - If aggregated is True, returns a dictionary of - toplex sizes and counts in H. If aggregated - is False, returns a list of toplex sizes in H. - - Returns - ------- - toplex_dist : list or dictionary - List of toplex sizes or dictionary of toplex size distribution in H - """ - distr = [H.size(e) for e in H.toplexes().edges] - if aggregated: - return Counter(distr) - else: - return distr
- - -
[docs]def s_node_diameter_dist(H): - """ - Parameters - ---------- - H : Hypergraph - - Returns - ------- - s_node_diameter_dist : list - List of s-node-diameters for hypergraph H starting with s=1 - and going up as long as the hypergraph is s-node-connected - """ - i = 1 - diams = [] - while H.is_connected(s=i): - diams.append(H.diameter(s=i)) - i += 1 - return diams
- - -
[docs]def s_edge_diameter_dist(H): - """ - Parameters - ---------- - H : Hypergraph - - Returns - ------- - s_edge_diameter_dist : list - List of s-edge-diameters for hypergraph H starting with s=1 - and going up as long as the hypergraph is s-edge-connected - """ - i = 1 - diams = [] - while H.is_connected(s=i, edges=True): - diams.append(H.edge_diameter(s=i)) - i += 1 - return diams
- - -
[docs]def info(H, node=None, edge=None): - """ - Print a summary of simple statistics for H - - Parameters - ---------- - H : Hypergraph - obj : optional - either a node or edge uid from the hypergraph - dictionary : optional - If True then returns the info as a dictionary rather - than a string - If False (default) returns the info as a string - - Returns - ------- - info : string - Returns a string of statistics of the size, - aspect ratio, and density of the hypergraph. - Print the string to see it formatted. - - """ - if not H.edges.elements: - return f"Hypergraph {H.name} is empty." - report = info_dict(H, node=node, edge=edge) - info = "" - if node: - info += f"Node '{node}' has the following properties:\n" - info += f"Degree: {report['degree']}\n" - info += f"Contained in: {report['membs']}\n" - info += f"Neighbors: {report['neighbors']}" - elif edge: - info += f"Edge '{edge}' has the following properties:\n" - info += f"Size: {report['size']}\n" - info += f"Elements: {report['elements']}" - else: - info += f"Number of Rows: {report['nrows']}\n" - info += f"Number of Columns: {report['ncols']}\n" - info += f"Aspect Ratio: {report['aspect ratio']}\n" - info += f"Number of non-empty Cells: {report['ncells']}\n" - info += f"Density: {report['density']}" - return info
- - -
[docs]def info_dict(H, node=None, edge=None): - """ - Create a summary of simple statistics for H - - Parameters - ---------- - H : Hypergraph - obj : optional - either a node or edge uid from the hypergraph - - Returns - ------- - info_dict : dict - Returns a dictionary of statistics of the size, - aspect ratio, and density of the hypergraph. - - """ - report = dict() - if len(H.edges.elements) == 0: - return {} - - if node: - report["membs"] = list(H.dual().edges[node]) - report["degree"] = len(report["membs"]) - report["neighbors"] = H.neighbors(node) - return report - if edge: - report["size"] = H.size(edge) - report["elements"] = list(H.edges[edge]) - return report - else: - lnodes, ledges = H.shape - M = H.incidence_matrix(index=False) - ncells = M.nnz - - report["nrows"] = lnodes - report["ncols"] = ledges - report["aspect ratio"] = lnodes / ledges - report["ncells"] = ncells - report["density"] = ncells / (lnodes * ledges) - return report
- - -
[docs]def dist_stats(H): - """ - Computes many basic hypergraph stats and puts them all into a single dictionary object - - * nrows = number of nodes (rows in the incidence matrix) - * ncols = number of edges (columns in the incidence matrix) - * aspect ratio = nrows/ncols - * ncells = number of filled cells in incidence matrix - * density = ncells/(nrows*ncols) - * node degree list = degree_dist(H) - * node degree dist = centrality_stats(degree_dist(H)) - * node degree hist = Counter(degree_dist(H)) - * max node degree = max(degree_dist(H)) - * edge size list = edge_size_dist(H) - * edge size dist = centrality_stats(edge_size_dist(H)) - * edge size hist = Counter(edge_size_dist(H)) - * max edge size = max(edge_size_dist(H)) - * comp nodes list = s_comp_dist(H, s=1, edges=False) - * comp nodes dist = centrality_stats(s_comp_dist(H, s=1, edges=False)) - * comp nodes hist = Counter(s_comp_dist(H, s=1, edges=False)) - * comp edges list = s_comp_dist(H, s=1, edges=True) - * comp edges dist = centrality_stats(s_comp_dist(H, s=1, edges=True)) - * comp edges hist = Counter(s_comp_dist(H, s=1, edges=True)) - * num comps = len(s_comp_dist(H)) - - Parameters - ---------- - H : Hypergraph - - Returns - ------- - dist_stats : dict - Dictionary which keeps track of each of the above items (e.g., basic['nrows'] = the number of nodes in H) - """ - stats = H.state_dict.get("dist_stats", None) - if stats is not None: - return H.state_dict["dist_stats"] - else: - cstats = ["min", "max", "mean", "median", "std"] - basic = dict() - - # Number of rows (nodes), columns (edges), and aspect ratio - basic["nrows"] = len(H.nodes) - basic["ncols"] = len(H.edges) - basic["aspect ratio"] = basic["nrows"] / basic["ncols"] - - # Number of cells and density - M = H.incidence_matrix(index=False) - basic["ncells"] = M.nnz - basic["density"] = basic["ncells"] / (basic["nrows"] * basic["ncols"]) - - # Node degree distribution - basic["node degree list"] = sorted(degree_dist(H), reverse=True) - basic["node degree centrality stats"] = dict( - zip(cstats, centrality_stats(basic["node degree list"])) - ) - basic["node degree hist"] = Counter(basic["node degree list"]) - basic["max node degree"] = max(basic["node degree list"]) - - # Edge size distribution - basic["edge size list"] = sorted(H.edge_size_dist(), reverse=True) - basic["edge size centrality stats"] = dict( - zip(cstats, centrality_stats(basic["edge size list"])) - ) - basic["edge size hist"] = Counter(basic["edge size list"]) - basic["max edge size"] = max(basic["edge size hist"]) - - # Component size distribution (nodes) - basic["comp nodes list"] = sorted(s_comp_dist(H, edges=False), reverse=True) - basic["comp nodes hist"] = Counter(basic["comp nodes list"]) - basic["comp nodes centrality stats"] = dict( - zip(cstats, centrality_stats(basic["comp nodes list"])) - ) - - # Component size distribution (edges) - basic["comp edges list"] = sorted(s_comp_dist(H, edges=True), reverse=True) - basic["comp edges hist"] = Counter(basic["comp edges list"]) - basic["comp edges centrality stats"] = dict( - zip(cstats, centrality_stats(basic["comp edges list"])) - ) - - # Number of components - basic["num comps"] = len(basic["comp nodes list"]) - - # # Diameters - # basic['s edge diam list'] = s_edge_diameter_dist(H) - # basic['s node diam list'] = s_node_diameter_dist(H) - if H.isstatic: - H.set_state(dist_stats=basic) - return basic
-
- -
- -
- -
-
- -
- -
- - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/_static/documentation_options.js b/docs/build/_static/documentation_options.js index 2f08d25f..9fd31e43 100644 --- a/docs/build/_static/documentation_options.js +++ b/docs/build/_static/documentation_options.js @@ -1,6 +1,6 @@ var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), - VERSION: '1.0.0', + VERSION: '1.0.1', LANGUAGE: 'None', COLLAPSE_INDEX: false, BUILDER: 'html', diff --git a/docs/build/algorithms/algorithms.html b/docs/build/algorithms/algorithms.html index 5a70cab4..4549a2f7 100644 --- a/docs/build/algorithms/algorithms.html +++ b/docs/build/algorithms/algorithms.html @@ -7,7 +7,7 @@ - algorithms package — HyperNetX 1.0.0 documentation + algorithms package — HyperNetX 1.0.1 documentation @@ -36,7 +36,6 @@ - @@ -106,9 +105,9 @@
  • Algorithms @@ -197,667 +196,14 @@

    algorithms package

    Submodules

    -
    -

    algorithms.homology_mod2 module

    -
    -

    Homology and Smith Normal Form

    -

    The purpose of computing the Homology groups for data generated -hypergraphs is to identify data sources that correspond to interesting -features in the topology of the hypergraph.

    -

    The elements of one of these Homology groups are generated by \(k\) -dimensional cycles of relationships in the original data that are not -bound together by higher order relationships. Ideally, we want the -briefest description of these cycles; we want a minimal set of -relationships exhibiting interesting cyclic behavior. This minimal set -will be a bases for the Homology group.

    -

    The cyclic relationships in the data are discovered using a boundary -map represented as a matrix. To discover the bases we compute the -Smith Normal Form of the boundary map.

    -
    -

    Homology Mod2

    -

    This module computes the homology groups for data represented as an -abstract simplicial complex with chain groups \(\{C_k\}\) and \(Z_2\) additions. -The boundary matrices are represented as rectangular matrices over \(Z_2\). -These matrices are diagonalized and represented in Smith -Normal Form. The kernel and image bases are computed and the Betti -numbers and homology bases are returned.

    -

    Methods for obtaining SNF for Z/2Z are based on Ferrario’s work: -http://www.dlfer.xyz/post/2016-10-27-smith-normal-form/

    -
    -
    -algorithms.homology_mod2.add_to_column(M, i, j)[source]
    -

    Replaces column i (of M) with logical xor between column i and j

    -
    -
    Parameters
    -
      -
    • M (np.array) – matrix

    • -
    • i (int) – index of column being altered

    • -
    • j (int) – index of column being added to altered

    • -
    -
    -
    Returns
    -

    N

    -
    -
    Return type
    -

    np.array

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.add_to_row(M, i, j)[source]
    -

    Replaces row i with logical xor between row i and j

    -
    -
    Parameters
    -
      -
    • M (np.array) –

    • -
    • i (int) – index of row being altered

    • -
    • j (int) – index of row being added to altered

    • -
    -
    -
    Returns
    -

    N

    -
    -
    Return type
    -

    np.array

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.betti(bd, k=None)[source]
    -

    Generate the kth-betti numbers for a chain complex with boundary -matrices given by bd

    -
    -
    Parameters
    -
      -
    • bd (dict of k-boundary matrices keyed on dimension of domain) –

    • -
    • k (int, list or tuple, optional, default=None) – list must be min value and max value of k values inclusive -if None, then all betti numbers for dimensions of existing cells will be -computed.

    • -
    -
    -
    Returns
    -

    betti – Description

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.betti_numbers(h, k=None)[source]
    -

    Return the kth betti numbers for the simplicial homology of the ASC -associated to h

    -
    -
    Parameters
    -
      -
    • h (hnx.Hypergraph) – Hypergraph to compute the betti numbers from

    • -
    • k (int or list, optional, default=None) – list must be min value and max value of k values inclusive -if None, then all betti numbers for dimensions of existing cells will be -computed.

    • -
    -
    -
    Returns
    -

    betti – A dictionary of betti numbers keyed by dimension

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.bkMatrix(km1basis, kbasis)[source]
    -

    Compute the boundary map from \(C_{k-1}\)-basis to \(C_k\) basis with -respect to \(Z_2\)

    -
    -
    Parameters
    -
      -
    • km1basis (indexable iterable) – Ordered list of \(k-1\) dimensional cell

    • -
    • kbasis (indexable iterable) – Ordered list of \(k\) dimensional cells

    • -
    -
    -
    Returns
    -

    bk – boundary matrix in \(Z_2\) stored as boolean

    -
    -
    Return type
    -

    np.array

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.boundary_group(image_basis)[source]
    -

    Returns a csr_matrix with rows corresponding to the elements of the -group generated by image basis over \(\mathbb{Z}_2\)

    -
    -
    Parameters
    -

    image_basis (numpy.ndarray or scipy.sparse.csr_matrix) – 2d-array of basis elements

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    scipy.sparse.csr_matrix

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.chain_complex(h, k=None)[source]
    -

    Compute the k-chains and k-boundary maps required to compute homology -for all values in k

    -
    -
    Parameters
    -
      -
    • h (hnx.Hypergraph) –

    • -
    • k (int or list of length 2, optional, default=None) – k must be an integer greater than 0 or a list of -length 2 indicating min and max dimensions to be -computed. eg. if k = [1,2] then 0,1,2,3-chains -and boundary maps for k=1,2,3 will be returned, -if None than k = [1,max dimension of edge in h]

    • -
    -
    -
    Returns
    -

    C, bd – C is a dictionary of lists -bd is a dictionary of numpy arrays

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.homology_basis(bd, k=None, boundary=False, **kwargs)[source]
    -

    Compute a basis for the kth-simplicial homology group, \(H_k\), defined by a -chain complex \(C\) with boundary maps given by bd \(= \{k:\partial_k\)}$

    -
    -
    Parameters
    -
      -
    • bd (dict) – dict of boundary matrices on k-chains to k-1 chains keyed on k -if krange is a tuple then all boundary matrices k in [krange[0],..,krange[1]] -inclusive must be in the dictionary

    • -
    • k (int or list of ints, optional, default=None) – k must be a positive integer or a list of -2 integers indicating min and max dimensions to be -computed, if none given all homology groups will be computed from -available boundary matrices in bd

    • -
    • boundary (bool) – option to return a basis for the boundary group from each dimension. -Needed to compute the shortest generators in the homology group.

    • -
    -
    -
    Returns
    -

      -
    • basis (dict) – dict of generators as 0-1 tuples keyed by dim -basis for dimension k will be returned only if bd[k] and bd[k+1] have -been provided.

    • -
    • im (dict) – dict of boundary group generators keyed by dim

    • -
    -

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.hypergraph_homology_basis(h, k=None, shortest=False, interpreted=True)[source]
    -

    Computes the kth-homology groups mod 2 for the ASC -associated with the hypergraph h for k in krange inclusive

    -
    -
    Parameters
    -
      -
    • h (hnx.Hypergraph) –

    • -
    • k (int or list of length 2, optional, default = None) – k must be an integer greater than 0 or a list of -length 2 indicating min and max dimensions to be -computed

    • -
    • shortest (bool, optional, default=False) – option to look for shortest representative for each coset in the -homology group, only good for relatively small examples

    • -
    • interpreted (bool, optional, default = True) – if True will return an explicit basis in terms of the k-chains

    • -
    -
    -
    Returns
    -

      -
    • basis (list) – list of generators as k-chains as boolean vectors

    • -
    • interpreted_basis – lists of kchains in basis

    • -
    -

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.interpret(Ck, arr, labels=None)[source]
    -

    Returns the data as represented in Ck associated with the arr

    -
    -
    Parameters
    -
      -
    • Ck (list) – a list of k-cells being referenced by arr

    • -
    • arr (np.array) – array of 0-1 vectors

    • -
    • labels (dict, optional) – dictionary of labels to associate to the nodes in the cells

    • -
    -
    -
    Returns
    -

    list of k-cells referenced by data in Ck

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.kchainbasis(h, k)[source]
    -

    Compute the set of k dimensional cells in the abstract simplicial -complex associated with the hypergraph.

    -
    -
    Parameters
    -
      -
    • h (hnx.Hypergraph) –

    • -
    • k (int) – dimension of cell

    • -
    -
    -
    Returns
    -

    an ordered list of kchains represented as tuples of length k+1

    -
    -
    Return type
    -

    list

    -
    -
    -
    -

    See also

    -

    hnx.hypergraph.toplexes

    -
    -

    Notes

    -
      -
    • Method works best if h is simple [Berge], i.e. no edge contains another and there are no duplicate edges (toplexes).

    • -
    • Hypergraph node uids must be sortable.

    • -
    -
    - -
    -
    -algorithms.homology_mod2.logical_dot(ar1, ar2)[source]
    -

    Returns the boolean equivalent of the dot product mod 2 on two 1-d arrays of -the same length.

    -
    -
    Parameters
    -
      -
    • ar1 (numpy.ndarray) – 1-d array

    • -
    • ar2 (numpy.ndarray) – 1-d array

    • -
    -
    -
    Returns
    -

    boolean value associated with dot product mod 2

    -
    -
    Return type
    -

    bool

    -
    -
    Raises
    -

    HyperNetXError – If arrays are not of the same length an error will be raised.

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.logical_matadd(mat1, mat2)[source]
    -

    Returns the boolean equivalent of matrix addition mod 2 on two -binary arrays stored as type boolean

    -
    -
    Parameters
    -
      -
    • mat1 (np.ndarray) – 2-d array of boolean values

    • -
    • mat2 (np.ndarray) – 2-d array of boolean values

    • -
    -
    -
    Returns
    -

    mat – boolean matrix equivalent to the mod 2 matrix addition of the -matrices as matrices over Z/2Z

    -
    -
    Return type
    -

    np.ndarray

    -
    -
    Raises
    -

    HyperNetXError – If dimensions are not equal an error will be raised.

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.logical_matmul(mat1, mat2)[source]
    -

    Returns the boolean equivalent of matrix multiplication mod 2 on two -binary arrays stored as type boolean

    -
    -
    Parameters
    -
      -
    • mat1 (np.ndarray) – 2-d array of boolean values

    • -
    • mat2 (np.ndarray) – 2-d array of boolean values

    • -
    -
    -
    Returns
    -

    mat – boolean matrix equivalent to the mod 2 matrix multiplication of the -matrices as matrices over Z/2Z

    -
    -
    Return type
    -

    np.ndarray

    -
    -
    Raises
    -

    HyperNetXError – If inner dimensions are not equal an error will be raised.

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.matmulreduce(arr, reverse=False)[source]
    -

    Recursively applies a ‘logical multiplication’ to a list of boolean arrays.

    -

    For arr = [arr[0],arr[1],arr[2]…arr[n]] returns product arr[0]arr[1]…arr[n] -If reverse = True, returns product arr[n]arr[n-1]…arr[0]

    -
    -
    Parameters
    -
      -
    • arr (list of np.array) – list of nxm matrices represented as np.array

    • -
    • reverse (bool, optional) – order to multiply the matrices

    • -
    -
    -
    Returns
    -

    P – Product of matrices in the list

    -
    -
    Return type
    -

    np.array

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.reduced_row_echelon_form_mod2(M)[source]
    -

    Computes the invertible transformation matrices needed to compute -the reduced row echelon form of M modulo 2

    -
    -
    Parameters
    -

    M (np.array) – a rectangular matrix with elements in \(Z_2\)

    -
    -
    Returns
    -

    L, S, Linv – LM = S where S is the reduced echelon form of M -and M = LinvS

    -
    -
    Return type
    -

    np.arrays

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.smith_normal_form_mod2(M)[source]
    -

    Computes the invertible transformation matrices needed to compute the -Smith Normal Form of M modulo 2

    -
    -
    Parameters
    -
      -
    • M (np.array) – a rectangular matrix with data type bool

    • -
    • track (bool) – if track=True will print out the transformation as Z/2Z matrix as it -discovers L[i] and R[j]

    • -
    -
    -
    Returns
    -

    L, R, S, Linv – LMR = S is the Smith Normal Form of the matrix M.

    -
    -
    Return type
    -

    np.arrays

    -
    -
    -
    -

    Note

    -

    Given a mxn matrix \(M\) with -entries in \(Z_2\) we start with the equation: \(L M R = S\), where -\(L = I_m\), and \(R=I_n\) are identity matrices and \(S = M\). We -repeatedly apply actions to the left and right side of the equation -to transform S into a diagonal matrix. -For each action applied to the left side we apply its inverse -action to the right side of I_m to generate \(L^{-1}\). -Finally we verify: -\(L M R = S\) and \(LLinv = I_m\).

    -
    -
    - -
    -
    -algorithms.homology_mod2.swap_columns(i, j, *args)[source]
    -

    Swaps ith and jth column of each matrix in args -Returns a list of new matrices

    -
    -
    Parameters
    -
      -
    • i (int) –

    • -
    • j (int) –

    • -
    • args (np.arrays) –

    • -
    -
    -
    Returns
    -

    list of copies of args with ith and jth row swapped

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -algorithms.homology_mod2.swap_rows(i, j, *args)[source]
    -

    Swaps ith and jth row of each matrix in args -Returns a list of new matrices

    -
    -
    Parameters
    -
      -
    • i (int) –

    • -
    • j (int) –

    • -
    • args (np.arrays) –

    • -
    -
    -
    Returns
    -

    list of copies of args with ith and jth row swapped

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -
    -
    -

    algorithms.s_centrality_measures module

    -
    -

    S-Centrality Measures

    -

    We generalize graph metrics to s-metrics for a hypergraph by using its s-connected -components. This is accomplished by computing the s edge-adjacency matrix and -constructing the corresponding graph of the matrix. We then use existing graph metrics -on this representation of the hypergraph. In essence we construct an s-line graph -corresponding to the hypergraph on which to apply our methods.

    -

    S-Metrics for hypergraphs are discussed in depth in: -Aksoy, S.G., Joslyn, C., Ortiz Marrero, C. et al. Hypernetwork science via high-order hypergraph walks. -EPJ Data Sci. 9, 16 (2020). https://doi.org/10.1140/epjds/s13688-020-00231-0

    -
    -
    -algorithms.s_centrality_measures.s_betweenness_centrality(H, s=1, edges=True, normalized=True, return_singletons=True, use_nwhy=True)[source]
    -
    -

    A centrality measure for an s-edge(node) subgraph of H based on shortest paths. -Equals the betweenness centrality of vertices in the edge(node) s-linegraph.

    -

    In a graph (2-uniform hypergraph) the betweenness centrality of a vertex \(v\) -is the ratio of the number of non-trivial shortest paths between any pair of -vertices in the graph that pass through \(v\) divided by the total number of -non-trivial shortest paths in the graph.

    -

    The centrality of edge to all shortest s-edge paths -\(V\) = the set of vertices in the linegraph. -\(\sigma(s,t)\) = the number of shortest paths between vertices \(s\) and \(t\). -\(\sigma(s, t|v)\) = the number of those paths that pass through vertex \(v\) -$$c_B(v) =sum_{s

    -
    -

    eq t in V} -rac{sigma(s, t|v)}{sigma(s, t)}$$

    -
    -

    H : hnx.Hypergraph -s : int

    -
    -

    s connectedness requirement

    -
    -
    -
    edgesbool, optional

    determines if edge or node linegraph

    -
    -
    normalized

    bool, default=False, -If true the betweenness values are normalized by 2/((n-1)(n-2)), -where n is the number of edges in H

    -
    -
    return_singletonsbool, optional

    if False will ignore singleton components of linegraph

    -
    -
    -
    -
    -
    : dict

    A dictionary of s-betweenness centrality value of the edges.

    -
    -
    -
    -
    -
    - -
    -
    -algorithms.s_centrality_measures.s_closeness_centrality(H, s=1, edges=True, return_singletons=True, source=None, use_nwhy=True)[source]
    -
    -

    In a connected component the reciprocal of the sum of the distance between an -edge(node) and all other edges(nodes) in the component times the number of edges(nodes) -in the component minus 1.

    -

    \(V\) = the set of vertices in the linegraph. -\(n = |V|\) -\(d\) = shortest path distance -$$C(u) =

    -
    -

    rac{n - 1}{sum_{v -eq u in V} d(v, u)}$$

    -
    -

    H : hnx.Hypergraph

    -

    s : int, optional

    -
    -
    edgesbool, optional

    Indicates if method should compute edge linegraph (default) or node linegraph.

    -
    -
    return_singletonsbool, optional

    Indicates if method should return values for singleton components.

    -
    -
    sourcestr, optional

    Identifier of node or edge of interest for computing centrality

    -
    -
    use_nwhybool, optional

    If true will use the NWHy library if available.

    -
    -
    -
    -
    -
    : dict or float

    returns the s-closeness centrality value of the edges(nodes). -If source=None a dictionary of values for each s-edge in H is returned. -If source then a single value is returned.

    -
    -
    -
    -
    -
    - -
    -
    -algorithms.s_centrality_measures.s_eccentricity(H, s=1, edges=True, source=None, return_singletons=True, use_nwhy=True)[source]
    -

    The length of the longest shortest path from a vertex \(u\) to every other vertex in the linegraph. -\(V\) = set of vertices in the linegraph -\(d\) = shortest path distance -$$ ext{s-ecc}(u) = ext{max}{d(u,v): v in V} $$

    -
    -
    Parameters
    -
      -
    • H (hnx.Hypergraph) –

    • -
    • s (int, optional) –

    • -
    • edges (bool, optional) – Indicates if method should compute edge linegraph (default) or node linegraph.

    • -
    • return_singletons (bool, optional) – Indicates if method should return values for singleton components.

    • -
    • source (str, optional) – Identifier of node or edge of interest for computing centrality

    • -
    • use_nwhy (bool, optional) – If true will use the NWHy library if available.

    • -
    -
    -
    Returns
    -

    returns the s-eccentricity value of the edges(nodes). -If source=None a dictionary of values for each s-edge in H is returned. -If source then a single value is returned.

    -
    -
    Return type
    -

    dict or float

    -
    -
    -
    - -
    -
    -algorithms.s_centrality_measures.s_harmonic_centrality(H, s=1, edges=True, source=None, normalized=False, return_singletons=True, use_nwhy=True)[source]
    -
    -

    A centrality measure for an s-edge subgraph of H. A value equal to 1 means the s-edge -intersects every other s-edge in H. All values range between 0 and 1. -Edges of size less than s return 0. If H contains only one s-edge a 0 is returned.

    -

    The denormalized reciprocal of the harmonic mean of all distances from \(u\) to all other vertices. -\(V\) = the set of vertices in the linegraph. -\(d\) = shortest path distance -$$C(u) = sum_{v

    -
    -

    eq u in V} -rac{1}{d(v, u)}$$

    -
    -

    Normalized this becomes: -$$C(u) = sum_{v

    -
    -

    eq u in V} -rac{1}{d(v, u)}cdot -rac{2}{(n-1)(n-2)}$$

    -
    -

    where \(n\) is the number vertices.

    -

    H : hnx.Hypergraph

    -

    s : int, optional

    -
    -
    edgesbool, optional

    Indicates if method should compute edge linegraph (default) or node linegraph.

    -
    -
    return_singletonsbool, optional

    Indicates if method should return values for singleton components.

    -
    -
    sourcestr, optional

    Identifier of node or edge of interest for computing centrality

    -
    -
    use_nwhybool, optional

    If true will use the NWHy library if available.

    -
    -
    -
    -
    -
    : dict or float

    returns the s-harmonic closeness centrality value of the edges, a number between 0 and 1 inclusive. -If source=None a dictionary of values for each s-edge in H is returned. -If source then a single value is returned.

    -
    -
    -
    -
    -
    - -
    -
    -algorithms.s_centrality_measures.s_harmonic_closeness_centrality(H, s=1, edge=None, use_nwhy=True)[source]
    -
    - +
    +

    algorithms.homology_mod2 module

    +
    +

    algorithms.s_centrality_measures module

    -
    -

    Module contents

    +
    +

    Module contents

    diff --git a/docs/build/algorithms/modules.html b/docs/build/algorithms/modules.html index f1aa2059..b14efc19 100644 --- a/docs/build/algorithms/modules.html +++ b/docs/build/algorithms/modules.html @@ -7,7 +7,7 @@ - algorithms — HyperNetX 1.0.0 documentation + algorithms — HyperNetX 1.0.1 documentation @@ -189,18 +189,9 @@

    algorithmsalgorithms package

  • diff --git a/docs/build/classes/classes.html b/docs/build/classes/classes.html index 973749c0..7c35d04f 100644 --- a/docs/build/classes/classes.html +++ b/docs/build/classes/classes.html @@ -7,7 +7,7 @@ - classes package — HyperNetX 1.0.0 documentation + classes package — HyperNetX 1.0.1 documentation @@ -104,10 +104,10 @@
  • Hypergraphs @@ -197,2692 +197,17 @@

    classes package

    Submodules

    -
    -

    classes.entity module

    -
    -
    -class classes.entity.Entity(uid, elements=[], entity=None, **props)[source]
    -

    Bases: object

    -

    Base class for objects used in building network-like objects including -Hypergraphs, Posets, Cell Complexes.

    -
    -
    Parameters
    -
      -
    • uid (hashable) – a unique identifier

    • -
    • elements (list or dict, optional, default: None) – a list of entities with identifiers different than uid and/or -hashables different than uid, see Honor System

    • -
    • entity (Entity) – an Entity object to be cloned into a new Entity with uid. If the uid is the same as -Entity.uid then the entities will not be distinguishable and error will be raised. -The elements in the signature will be added to the cloned entity.

    • -
    • props (keyword arguments, optional, default: {}) – properties belonging to the entity added as key=value pairs. -Both key and value must be hashable.

    • -
    -
    -
    -

    Notes

    -

    An Entity is a container-like object, which has a unique identifier and -may contain elements and have properties. -The Entity class was created as a generic object providing structure for -Hypergraph nodes and edges.

    - -

    Honor System

    -

    HyperNetX has an Honor System that applies to Entity uid values. -Two entities are equal if their __dict__ objects match. -For performance reasons many methods distinguish entities by their uids. -It is, therefore, up to the user to ensure entities with the same uids are indeed the same. -Not doing so may cause undesirable side effects. -In particular, the methods in the Hypergraph class assume distinct nodes and edges -have distinct uids.

    -

    Examples

    -
    >>> x = Entity('x')
    ->>> y = Entity('y',[x])
    ->>> z = Entity('z',[x,y],weight=1)
    ->>> z
    -Entity(z,['y', 'x'],{'weight': 1})
    ->>> z.uid
    -'z'
    ->>> z.elements
    -{'x': Entity(x,[],{}), 'y': Entity(y,['x'],{})}
    ->>> z.properties
    -{'weight': 1}
    ->>> z.children
    -{'x'}
    ->>> x.memberships
    -{'y': Entity(y,['x'],{}), 'z': Entity(z,['y', 'x'],{'weight': 1})}
    ->>> z.fullregistry()
    -{'x': Entity(x,[],{}), 'y': Entity(y,['x'],{})}
    -
    -
    -
    -

    See also

    -

    EntitySet

    -
    -
    -
    -add(*args)[source]
    -

    Adds unpacked args to entity elements. Depends on add_element()

    -
    -
    Parameters
    -

    args (One or more entities or hashables) –

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    -

    Note

    -

    Adding an element to an object in a hypergraph will not add the -element to the hypergraph and will cause an error. Use Hypergraph.add_edge -or Hypergraph.add_node_to_edge instead.

    -
    -
    - -
    -
    -add_element(item)[source]
    -

    Adds item to entity elements and adds entity to item.memberships.

    -
    -
    Parameters
    -

    item (hashable or Entity) – If hashable, will be replaced with empty Entity using hashable as uid

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    Entity

    -
    -
    -

    Notes

    -

    If item is in entity elements, no new element is added but properties -will be updated. -If item is in complete_registry(), only the item already known to self will be added. -This method employs the Honor System since membership in complete_registry is checked -using the item’s uid. It is assumed that the user will only use the same uid -for identical instances within the entities registry.

    -
    - -
    -
    -add_elements_from(arg_set)[source]
    -

    Similar to add() it allows for adding from an interable.

    -
    -
    Parameters
    -

    arg_set (Iterable of hashables or entities) –

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -property children
    -

    Set of uids of the elements of elements of entity.

    -

    To return set of ids for deeper level use: -Entity.levelset(level).keys() -see: Entity.levelset()

    -
    - -
    -
    -clone(newuid)[source]
    -

    Returns shallow copy of entity with newuid. Entity’s elements will -belong to two distinct Entities.

    -
    -
    Parameters
    -

    newuid (hashable) – Name of the new entity

    -
    -
    Returns
    -

    clone

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -complete_registry()[source]
    -

    A dictionary of all entities appearing in any level of -entity

    -
    -
    Returns
    -

    complete_registry

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -depth(max_depth=10)[source]
    -

    Returns the number of nonempty level sets of level <= max_depth

    -
    -
    Parameters
    -

    max_depth (int, optional, default: 10) – If full depth is desired set max_depth to number of entities in -system + 1.

    -
    -
    Returns
    -

    depth – If max_depth is exceeded output will be numpy infinity. -If there is a cycle output will be numpy infinity.

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -property elements
    -

    Dictionary of elements belonging to entity.

    -
    - -
    -
    -fullregistry(lastlevel=10, firstlevel=1)[source]
    -

    A dictionary of all entities appearing in levels firstlevel -to lastlevel.

    -
    -
    Parameters
    -
      -
    • lastlevel (int, optional, default: 10) –

    • -
    • firstlevel (int, optional, default: 1) –

    • -
    -
    -
    Returns
    -

    fullregistry

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -property incidence_dict
    -

    element.uidset for each element in entity

    -

    To return an incidence dictionary of all nested entities in entity -use nested_incidence_dict

    -
    -
    Type
    -

    Dictionary of element.uid

    -
    -
    -
    - -
    -
    -intersection(other)[source]
    -

    A dictionary of elements belonging to entity and other.

    -
    -
    Parameters
    -

    other (Entity) –

    -
    -
    Returns
    -

    Dictionary of elements

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -property is_bipartite
    -

    Returns boolean indicating if the entity satisfies the Bipartite Condition

    -
    - -
    -
    -property is_empty
    -

    Boolean indicating if entity.elements is empty

    -
    - -
    -
    -level(item, max_depth=10)[source]
    -

    The first level where item appears in self.

    -
    -
    Parameters
    -
      -
    • item (hashable) – uid for an entity

    • -
    • max_depth (int, default: 10) – last level to check for entity

    • -
    -
    -
    Returns
    -

    level

    -
    -
    Return type
    -

    int

    -
    -
    -
    -

    Note

    -

    Item must be the uid of an entity listed -in fullregistry()

    +
    +

    classes.entity module

    -
    - -
    -
    -levelset(k=1)[source]
    -

    A dictionary of level k of self.

    -
    -
    Parameters
    -

    k (int, optional, default: 1) –

    -
    -
    Returns
    -

    levelset

    -
    -
    Return type
    -

    dict

    -
    -
    -
    -

    Note

    -

    An Entity contains other entities, hence the relationships between entities -and their elements may be represented in a directed graph with entity as root. -The levelsets are sets of entities which make up the elements appearing at -a certain level.

    +
    +

    classes.hypergraph module

    -
    - -
    -
    -property memberships
    -

    Dictionary of elements to which entity belongs.

    -

    This assignment is done on construction and controlled by -Entity.add_element() -and Entity.remove_element() methods.

    -
    - -
    -
    -static merge_entities(name, ent1, ent2)[source]
    -

    Merge two entities making sure they do not conflict.

    -
    -
    Parameters
    -
      -
    • name (hashable) –

    • -
    • ent1 (Entity) – First entity to have elements and properties added to new -entity

    • -
    • ent2 (Entity) – elements of ent2 will be checked against ent1.complete_registry() -and only nonexisting elements will be added using add() method. -Properties of ent2 will update properties of ent1 in new entity.

    • -
    -
    -
    Returns
    -

    a new entity

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -nested_incidence_dict(level=10)[source]
    -

    Returns a nested dictionary with keys up to level

    -
    -
    Parameters
    -

    level (int, optional, default: 10) – If level<=1, returns the incidence_dict.

    -
    -
    Returns
    -

    nested_incidence_dict

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -property properties
    -

    Dictionary of properties of entity

    -
    - -
    -
    -property registry
    -

    Entity pairs for children entity.

    -

    To return a dictionary of all entities at all depths -Entity.complete_registry()

    -
    -
    Type
    -

    Dictionary of uid

    -
    -
    -
    - -
    -
    -remove(*args)[source]
    -

    Removes args from entitie’s elements if they belong. -Does nothing with args not in entity.

    -
    -
    Parameters
    -

    args (One or more hashables or entities) –

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -remove_element(item)[source]
    -

    Removes item from entity and reference to entity from -item.memberships

    -
    -
    Parameters
    -

    item (Hashable or Entity) –

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -remove_elements_from(arg_set)[source]
    -

    Similar to remove(). Removes elements in arg_set.

    -
    -
    Parameters
    -

    arg_set (Iterable of hashables or entities) –

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -restrict_to(element_subset, name=None)[source]
    -

    Shallow copy of entity removing elements not in element_subset.

    -
    -
    Parameters
    -
      -
    • element_subset (iterable) – A subset of entities elements

    • -
    • name (hashable, optional) – If not given, a name is generated to reflect entity uid

    • -
    -
    -
    Returns
    -

    New Entity – Could be empty.

    -
    -
    Return type
    -

    Entity

    -
    -
    -
    - -
    -
    -size()[source]
    -

    Returns the number of elements in entity

    -
    - -
    -
    -property uid
    -

    String identifier for entity

    -
    - -
    -
    -property uidset
    -

    Set of uids of elements of entity.

    -
    - -
    - -
    -
    -class classes.entity.EntitySet(uid, elements=[], **props)[source]
    -

    Bases: classes.entity.Entity

    -
    -
    Parameters
    -
      -
    • uid (hashable) – a unique identifier

    • -
    • elements (list or dict, optional, default: None) – a list of entities with identifiers different than uid and/or -hashables different than uid, see Honor System

    • -
    • props (keyword arguments, optional, default: {}) – properties belonging to the entity added as key=value pairs. -Both key and value must be hashable.

    • -
    -
    -
    -

    Notes

    -

    The EntitySet class was created to distinguish Entities satifying the Bipartite Condition.

    -

    Bipartite Condition

    -

    Entities that are elements of the same EntitySet, may not contain each other as elements. -The elements and children of an EntitySet generate a specific partition for a bipartite graph. -The partition is isomorphic to a Hypergraph where the elements correspond to hyperedges and -the children correspond to the nodes. EntitySets are the basic objects used to construct hypergraphs -in HNX.

    -

    Example:

    -
    >>> y = Entity('y')
    ->>> x = Entity('x')
    ->>> x.add(y)
    ->>> y.add(x)
    ->>> w = EntitySet('w',[x,y])
    -HyperNetXError: Error: Fails the Bipartite Condition for EntitySet.
    -y references a child of an existing Entity in the EntitySet.
    -
    -
    -
    -
    -add(*args)[source]
    -

    Adds args to entityset’s elements, checking to make sure no self references are -made to element ids. -Ensures Bipartite Condition of EntitySet.

    -
    -
    Parameters
    -

    args (One or more entities or hashables) –

    -
    -
    Returns
    -

    self

    -
    -
    Return type
    -

    EntitySet

    -
    -
    -
    - -
    -
    -clone(newuid)[source]
    -

    Returns shallow copy of entityset with newuid. Entityset’s -elements will belong to two distinct entitysets.

    -
    -
    Parameters
    -

    newuid (hashable) – Name of the new entityset

    -
    -
    Returns
    -

    clone

    -
    -
    Return type
    -

    EntitySet

    -
    -
    -
    - -
    -
    -collapse_identical_elements(newuid, return_equivalence_classes=False)[source]
    -

    Returns a deduped copy of the entityset, using representatives of equivalence classes as element keys. -Two elements of an EntitySet are collapsed if they share the same children.

    -
    -
    Parameters
    -
      -
    • newuid (hashable) –

    • -
    • return_equivalence_classes (boolean, default=False) – If True, return a dictionary of equivalence classes keyed by new edge names

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    EntitySet

    -
    -
    -
    -
    eq_classesdict

    if return_equivalence_classes = True

    -
    -
    -

    Notes

    -

    Treats elements of the entityset as equal if they have the same uidsets. Using this -as an equivalence relation, the entityset’s uidset is partitioned into equivalence classes. -The equivalent elements are identified using a single entity by using the -frozenset of uids associated to these elements as the uid for the new element -and dropping the properties. -If use_reps is set to True a representative element of the equivalence class is -used as identifier instead of the frozenset.

    -

    Example:

    -
    >>> E = EntitySet('E',elements=[Entity('E1', ['a','b']),Entity('E2',['a','b'])])
    ->>> E.incidence_dict
    -{'E1': {'a', 'b'}, 'E2': {'a', 'b'}}
    ->>> E.collapse_identical_elements('_',).incidence_dict
    -{'E2': {'a', 'b'}}
    -
    -
    -
    - -
    -
    -incidence_matrix(sparse=True, index=False)[source]
    -

    An incidence matrix for the EntitySet indexed by children x uidset.

    -
    -
    Parameters
    -
      -
    • sparse (boolean, optional, default: True) –

    • -
    • index (boolean, optional, default False) – If True return will include a dictionary of children uid : row number -and element uid : column number

    • -
    -
    -
    Returns
    -

      -
    • incidence_matrix (scipy.sparse.csr.csr_matrix or np.ndarray)

    • -
    • row dictionary (dict) – Dictionary identifying row with item in entityset’s children

    • -
    • column dictionary (dict) – Dictionary identifying column with item in entityset’s uidset

    • -
    -

    -
    -
    -

    Notes

    -

    Example:

    -
    >>> E = EntitySet('E',{'a':{1,2,3},'b':{2,3},'c':{1,4}})
    ->>> E.incidence_matrix(sparse=False, index=True)
    -(array([[0, 1, 1],
    -        [1, 1, 0],
    -        [1, 1, 0],
    -        [0, 0, 1]]), {0: 1, 1: 2, 2: 3, 3: 4}, {0: 'b', 1: 'a', 2: 'c'})
    -
    -
    -
    - -
    -
    -restrict_to(element_subset, name=None)[source]
    -

    Shallow copy of entityset removing elements not in element_subset.

    -
    -
    Parameters
    -
      -
    • element_subset (iterable) – A subset of the entityset’s elements

    • -
    • name (hashable, optional) – If not given, a name is generated to reflect entity uid

    • -
    -
    -
    Returns
    -

    new entityset – Could be empty.

    -
    -
    Return type
    -

    EntitySet

    -
    -
    -
    -

    See also

    -

    Entity.restrict_to

    -
    -
    - -
    - -
    -
    -

    classes.hypergraph module

    -
    -
    -class classes.hypergraph.Hypergraph(setsystem=None, name=None, static=False, use_nwhy=False, filepath=None)[source]
    -

    Bases: object

    -

    Hypergraph H = (V,E) references a pair of disjoint sets: -V = nodes (vertices) and E = (hyper)edges.

    -

    An HNX Hypergraph is either dynamic or static. -Dynamic hypergraphs can change by adding or subtracting objects -from them. Static hypergraphs require that all of the nodes and edges -be known at creation. A hypergraph is dynamic by default.

    -

    Dynamic hypergraphs require the user to keep track of its objects, -by using a unique names for each node and edge. This allows for multi-edge graphs and -inseperable nodes.

    -

    For example: Let V = {1,2,3} and E = {e1,e2,e3}, -where e1 = {1,2}, e2 = {1,2}, and e3 = {1,2,3}. -The edges e1 and e2 contain the same set of nodes and yet -are distinct and must be distinguishable within H.

    -

    In a dynamic hypergraph each node and edge is -instantiated as an Entity and given an identifier or uid. Entities -keep track of inclusion relationships and can be nested. Since -hypergraphs can be quite large, only the entity identifiers will be used -for computation intensive methods, this means the user must take care -to keep a one to one correspondence between their set of uids and -the objects in their hypergraph. See Honor System -Dynamic hypergraphs are most practical for small to modestly sized -hypergraphs (<1000 objects).

    -

    Static hypergraphs store node and edge information in numpy arrays and -are immutable. Each node and edge receives a class generated internal -identifier used for computations so do not require the user to create -different ids for nodes and edges. To create a static hypergraph set -static = True in the signature.

    -

    We will create hypergraphs in multiple ways:

    -
      -
    1. As an empty instance:

      -
      >>> H = hnx.Hypergraph()
      ->>> H.nodes, H.edges
      -({}, {})
      -
      -
      -
    2. -
    3. From a dictionary of iterables (elements of iterables must be of type hypernetx.Entity or hashable):

      -
      >>> H = Hypergraph({'a':[1,2,3],'b':[4,5,6]})
      ->>> H.nodes, H.edges
      -# output: (EntitySet(_:Nodes,[1, 2, 3, 4, 5, 6],{}), EntitySet(_:Edges,['b', 'a'],{}))
      -
      -
      -
    4. -
    5. From an iterable of iterables: (elements of iterables must be of type hypernetx.Entity or hashable):

      -
      >>> H = Hypergraph([{'a','b'},{'b','c'},{'a','c','d'}])
      ->>> H.nodes, H.edges
      -# output: (EntitySet(_:Nodes,['d', 'b', 'c', 'a'],{}), EntitySet(_:Edges,['_1', '_2', '_0'],{}))
      -
      -
      -
    6. -
    7. From a hypernetx.EntitySet or StaticEntitySet:

      -
      >>> a = Entity('a',{1,2}); b = Entity('b',{2,3})
      ->>> E = EntitySet('sample',elements=[a,b])
      ->>> H = Hypergraph(E)
      ->>> H.nodes, H.edges.
      -# output: (EntitySet(_:Nodes,[1, 2, 3],{}), EntitySet(_:Edges,['b', 'a'],{}))
      -
      -
      -
    8. -
    -

    All of these constructions apply for both dynamic and static hypergraphs. To -create a static hypergraph set the parameter static=True. In addition a static -hypergraph is automatically created if a StaticEntity, StaticEntitySet, or pandas.DataFrame object -is passed to the Hypergraph constructor.

    -
      -
    1. -
      From a pandas.DataFrame. The dataframe must have at least two columns with headers and there can be no nans.
      -
      By default the first column corresponds to the edge names and the second column to the node names.
      -
      You can specify the columns by restricting the dataframe to the columns of interest in the order:
      -
      hnx.Hypergraph(df[[edge_column_name,node_column_name]])
      -
      See Colab Tutorials Tutorial 6 - Static Hypergraphs and Entities for additional information.
      -
      -
    2. -
    -
    -
    Parameters
    -
      -
    • setsystem ((optional) EntitySet, StaticEntitySet, dict, iterable, pandas.dataframe, default: None) – See notes above for setsystem requirements.

    • -
    • name (hashable, optional, default: None) – If None then a placeholder ‘_’ will be inserted as name

    • -
    • static (boolean, optional, default: False) – If True the hypergraph will be immutable, edges and nodes may not be changed.

    • -
    • use_nwhy (boolean, optional, default = False) – If True hypergraph will be static and computations will be done using -C++ backend offered by NWHypergraph. This requires installation of the -NWHypergraph C++ library. Please see the NWHy documentation for more information.

    • -
    -
    -
    -
    -
    -add_edge(edge)[source]
    -

    Adds a single edge to hypergraph.

    -
    -
    Parameters
    -

    edge (hashable or Entity) – If hashable the edge returned will be empty.

    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -

    Notes

    -

    When adding an edge to a hypergraph children must be removed -so that nodes do not have elements. -Each node (element of edge) must be instantiated as a node, -making sure its uid isn’t already present in the self. -If an added edge contains nodes that cannot be added to hypergraph -then an error will be raised.

    -
    - -
    -
    -add_edges_from(edge_set)[source]
    -

    Add edges to hypergraph.

    -
    -
    Parameters
    -

    edge_set (iterable of hashables or Entities) – For hashables the edges returned will be empty.

    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -add_node_to_edge(node, edge)[source]
    -

    Adds node to an edge in hypergraph edges

    -
    -
    Parameters
    -
      -
    • node (hashable or Entity) – If Entity, only uid and properties will be used. -If uid is already in nodes then the known node will -be used

    • -
    • edge (uid of edge or edge, must belong to self.edges) –

    • -
    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -classmethod add_nwhy(h, fpath=None)[source]
    -

    Add nwhy functionality to a hypergraph.

    -
    -
    Parameters
    -
      -
    • h (hnx.Hypergraph) –

    • -
    • fpath (file path for storage of hypergraph state dictionary) –

    • -
    -
    -
    Returns
    -

    Returns a copy of h with static set to true and nwhy set to True -if it is available.

    -
    -
    Return type
    -

    hnx.Hypergraph

    -
    -
    -
    - -
    -
    -adjacency_matrix(index=False, s=1, weighted=True)[source]
    -

    The sparse weighted s-adjacency matrix

    -
    -
    Parameters
    -
      -
    • s (int, optional, default: 1) –

    • -
    • index (boolean, optional, default: False) – if True, will return a rowdict of row to node uid

    • -
    • weighted (boolean, optional, default: True) –

    • -
    -
    -
    Returns
    -

      -
    • adjacency_matrix (scipy.sparse.csr.csr_matrix)

    • -
    • row dictionary (dict)

    • -
    -

    -
    -
    -

    Notes

    -

    If weighted is True each off diagonal cell will equal the number -of edges shared by the nodes indexing the row and column if that number is -greater than s, otherwise the cell will equal 0. If weighted is False, the off -diagonal cell will equal 1 if the nodes indexed by the row and column share at -least s edges and 0 otherwise.

    -
    - -
    -
    -auxiliary_matrix(s=1, index=False)[source]
    -

    The unweighted s-auxiliary matrix for hypergraph

    -
    -
    Parameters
    -
      -
    • s (int) –

    • -
    • index (bool, optional, default: False) – return a dictionary of labels for the rows of the matrix

    • -
    -
    -
    Returns
    -

    auxiliary_matrix – Will return the same type of matrix as self.arr

    -
    -
    Return type
    -

    scipy.sparse.csr.csr_matrix or numpy.ndarray

    -
    -
    -

    Notes

    -

    Creates subgraph by restricting to edges of cardinality at least s. -Returns the unweighted s-edge adjacency matrix for the subgraph.

    -
    - -
    -
    -bipartite()[source]
    -

    Constructs the networkX bipartite graph associated to hypergraph.

    -
    -
    Returns
    -

    bipartite

    -
    -
    Return type
    -

    nx.Graph()

    -
    -
    -

    Notes

    -

    Creates a bipartite networkx graph from hypergraph. -The nodes and (hyper)edges of hypergraph become the nodes of bipartite graph. -For every (hyper)edge e in the hypergraph and node n in e there is an edge (n,e) -in the graph.

    -
    - -
    -
    -collapse_edges(name=None, use_reps=None, return_counts=None, return_equivalence_classes=False)[source]
    -

    Constructs a new hypergraph gotten by identifying edges containing the same nodes

    -
    -
    Parameters
    -
      -
    • name (hashable, optional, default: None) –

    • -
    • return_equivalence_classes (boolean, optional, default: False) – Returns a dictionary of edge equivalence classes keyed by frozen sets of nodes

    • -
    -
    -
    Returns
    -

      -
    • new hypergraph (Hypergraph) – Equivalent edges are collapsed to a single edge named by a representative of the equivalent -edges followed by a colon and the number of edges it represents.

    • -
    • equivalence_classes (dict) – A dictionary keyed by representative edge names with values equal to the edges in -its equivalence class

    • -
    -

    -
    -
    -

    Notes

    -

    Two edges are identified if their respective elements are the same. -Using this as an equivalence relation, the uids of the edges are partitioned into -equivalence classes.

    -

    A single edge from the collapsed edges followed by a colon and the number of elements -in its equivalence class as uid for the new edge

    -
    - -
    -
    -collapse_nodes(name=None, use_reps=True, return_counts=True, return_equivalence_classes=False)[source]
    -

    Constructs a new hypergraph gotten by identifying nodes contained by the same edges

    -
    -
    Parameters
    -
      -
    • name (str, optional, default: None) –

    • -
    • return_equivalence_classes (boolean, optional, default: False) – Returns a dictionary of node equivalence classes keyed by frozen sets of edges

    • -
    • use_reps (boolean, optional, default: False - Deprecated, this no longer works and will be removed) – Choose a single element from the collapsed nodes as uid for the new node, otherwise uses -a frozen set of the uids of nodes in the equivalence class

    • -
    • return_counts (boolean, - Deprecated, this no longer works and will be removed) – if use_reps is True the new nodes have uids given by a tuple of the rep -and the count

    • -
    -
    -
    Returns
    -

    new hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -

    Notes

    -

    Two nodes are identified if their respective memberships are the same. -Using this as an equivalence relation, the uids of the nodes are partitioned into -equivalence classes. A single member of the equivalence class is chosen to represent -the class followed by the number of members of the class.

    -

    Example

    -
    >>> h = Hypergraph(EntitySet('example',elements=[Entity('E1', ['a','b']),Entity('E2',['a','b'])]))
    ->>> h.incidence_dict
    -{'E1': {'a', 'b'}, 'E2': {'a', 'b'}}
    ->>> h.collapse_nodes().incidence_dict
    -{'E1': {frozenset({'a', 'b'})}, 'E2': {frozenset({'a', 'b'})}} ### Fix this
    ->>> h.collapse_nodes(use_reps=True).incidence_dict
    -{'E1': {('a', 2)}, 'E2': {('a', 2)}}
    -
    -
    -
    - -
    -
    -collapse_nodes_and_edges(name=None, use_reps=True, return_counts=True, return_equivalence_classes=False)[source]
    -

    Returns a new hypergraph by collapsing nodes and edges.

    -
    -
    Parameters
    -
      -
    • name (str, optional, default: None) –

    • -
    • use_reps (boolean, optional, default: False) – Choose a single element from the collapsed elements as a representative

    • -
    • return_counts (boolean, optional, default: True) – if use_reps is True the new elements are keyed by a tuple of the rep -and the count

    • -
    • return_equivalence_classes (boolean, optional, default: False) – Returns a dictionary of edge equivalence classes keyed by frozen sets of nodes

    • -
    -
    -
    Returns
    -

    new hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -

    Notes

    -

    Collapses the Nodes and Edges EntitySets. Two nodes(edges) are duplicates -if their respective memberships(elements) are the same. Using this as an -equivalence relation, the uids of the nodes(edges) are partitioned into -equivalence classes. A single member of the equivalence class is chosen to represent -the class followed by the number of members of the class.

    -

    Example

    -
    >>> h = Hypergraph(EntitySet('example',elements=[Entity('E1', ['a','b']),Entity('E2',['a','b'])]))
    ->>> h.incidence_dict
    -{'E1': {'a', 'b'}, 'E2': {'a', 'b'}}
    ->>> h.collapse_nodes_and_edges().incidence_dict   ### Fix this
    -{('E1', 2): {('a', 2)}}
    -
    -
    -
    - -
    -
    -component_subgraphs(return_singletons=False)[source]
    -

    Same as s_components_subgraphs() with s=1. Returns iterator.

    -
    -

    See also

    -

    s_component_subgraphs

    -
    -
    - -
    -
    -components(edges=False, return_singletons=True)[source]
    -

    Same as s_connected_components() with s=1, but nodes are returned -by default. Return iterator.

    - -
    - -
    -
    -connected_component_subgraphs(return_singletons=True)[source]
    -

    Same as s_component_subgraphs() with s=1. Returns iterator

    -
    -

    See also

    -

    s_component_subgraphs

    -
    -
    - -
    -
    -connected_components(edges=False, return_singletons=True)[source]
    -

    Same as s_connected_components() with s=1, but nodes are returned -by default. Return iterator.

    - -
    - -
    -
    -convert_to_static(name=None, nodes_name='nodes', edges_name='edges', use_nwhy=False, filepath=None)[source]
    -

    Returns new static hypergraph with the same dictionary as original hypergraph

    -
    -
    Parameters
    -
      -
    • name (None, optional) – Name

    • -
    • nodes_name (str, optional) – name for list of node labels

    • -
    • edges_name (str, optional) – name for list of edge labels

    • -
    -
    -
    Returns
    -

    Will have attribute static = True

    -
    -
    Return type
    -

    hnx.Hypergraph

    -
    -
    -
    -

    Note

    -

    Static hypergraphs store the user defined node and edge names in -a dictionary of labeled lists. The order of the lists provides an -index, which the hypergraph uses in place of the node and edge names -for fast processing.

    -
    -
    - -
    -
    -dataframe(sort_rows=False, sort_columns=False)[source]
    -

    Returns a pandas dataframe for hypergraph indexed by the nodes and -with column headers given by the edge names.

    -
    -
    Parameters
    -
      -
    • sort_rows (bool, optional, default=True) – sort rows based on hashable node names

    • -
    • sort_columns (bool, optional, default=True) – sort columns based on hashable edge names

    • -
    -
    -
    -
    - -
    -
    -degree(node, s=1, max_size=None)[source]
    -

    The number of edges of size s that contain node.

    -
    -
    Parameters
    -
      -
    • node (hashable) – identifier for the node.

    • -
    • s (positive integer, optional, default: 1) – smallest size of edge to consider in degree

    • -
    • max_size (positive integer or None, optional, default: None) – largest size of edge to consider in degree

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -diameter(s=1)[source]
    -

    Returns the length of the longest shortest s-walk between nodes in hypergraph

    -
    -
    Parameters
    -

    s (int, optional, default: 1) –

    -
    -
    Returns
    -

    diameter

    -
    -
    Return type
    -

    int

    -
    -
    Raises
    -

    HyperNetXError – If hypergraph is not s-edge-connected

    -
    -
    -

    Notes

    -

    Two nodes are s-adjacent if they share s edges. -Two nodes v_start and v_end are s-walk connected if there is a sequence of -nodes v_start, v_1, v_2, … v_n-1, v_end such that consecutive nodes -are s-adjacent. If the graph is not connected, an error will be raised.

    -
    - -
    -
    -dim(edge)[source]
    -

    Same as size(edge)-1.

    -
    - -
    -
    -distance(source, target, s=1)[source]
    -

    Returns the shortest s-walk distance between two nodes in the hypergraph.

    -
    -
    Parameters
    -
      -
    • source (node.uid or node) – a node in the hypergraph

    • -
    • target (node.uid or node) – a node in the hypergraph

    • -
    • s (positive integer) – the number of edges

    • -
    -
    -
    Returns
    -

    s-walk distance

    -
    -
    Return type
    -

    int

    -
    -
    -
    -

    See also

    -

    edge_distance

    -
    -

    Notes

    -

    The s-distance is the shortest s-walk length between the nodes. -An s-walk between nodes is a sequence of nodes that pairwise share -at least s edges. The length of the shortest s-walk is 1 less than -the number of nodes in the path sequence.

    -

    Uses the networkx shortest_path_length method on the graph -generated by the s-adjacency matrix.

    -
    - -
    -
    -dual(name=None)[source]
    -

    Constructs a new hypergraph with roles of edges and nodes of hypergraph reversed.

    -
    -
    Parameters
    -

    name (hashable) –

    -
    -
    Returns
    -

    dual

    -
    -
    Return type
    -

    hypergraph

    -
    -
    -
    - -
    -
    -edge_adjacency_matrix(index=False, s=1, weighted=True)[source]
    -

    The weighted s-adjacency matrix for the dual hypergraph.

    -
    -
    Parameters
    -
      -
    • s (int, optional, default: 1) –

    • -
    • index (boolean, optional, default: False) – if True, will return a coldict of column to edge uid

    • -
    • sparse (boolean, optional, default: True) –

    • -
    • weighted (boolean, optional, default: True) –

    • -
    -
    -
    Returns
    -

      -
    • edge_adjacency_matrix (scipy.sparse.csr.csr_matrix or numpy.ndarray)

    • -
    • column dictionary (dict)

    • -
    -

    -
    -
    -

    Notes

    -

    This is also the adjacency matrix for the line graph. -Two edges are s-adjacent if they share at least s nodes. -If index=True, returns a dictionary column_index:edge_uid

    -
    - -
    -
    -edge_diameter(s=1)[source]
    -

    Returns the length of the longest shortest s-walk between edges in hypergraph

    -
    -
    Parameters
    -

    s (int, optional, default: 1) –

    -
    -
    Returns
    -

    edge_diameter

    -
    -
    Return type
    -

    int

    -
    -
    Raises
    -

    HyperNetXError – If hypergraph is not s-edge-connected

    -
    -
    -

    Notes

    -

    Two edges are s-adjacent if they share s nodes. -Two nodes e_start and e_end are s-walk connected if there is a sequence of -edges e_start, e_1, e_2, … e_n-1, e_end such that consecutive edges -are s-adjacent. If the graph is not connected, an error will be raised.

    -
    - -
    -
    -edge_diameters(s=1)[source]
    -

    Returns the edge diameters of the s_edge_connected component subgraphs -in hypergraph.

    -
    -
    Parameters
    -

    s (int, optional, default: 1) –

    -
    -
    Returns
    -

      -
    • maximum diameter (int)

    • -
    • list of diameters (list) – List of edge_diameters for s-edge component subgraphs in hypergraph

    • -
    • list of component (list) – List of the edge uids in the s-edge component subgraphs.

    • -
    -

    -
    -
    -
    - -
    -
    -edge_distance(source, target, s=1)[source]
    -

    XX TODO: still need to return path and translate into user defined nodes and edges -Returns the shortest s-walk distance between two edges in the hypergraph.

    -
    -
    Parameters
    -
      -
    • source (edge.uid or edge) – an edge in the hypergraph

    • -
    • target (edge.uid or edge) – an edge in the hypergraph

    • -
    • s (positive integer) – the number of intersections between pairwise consecutive edges

    • -
    • TODO (add edge weights) –

    • -
    • weight (None or string, optional, default: None) – if None then all edges have weight 1. If string then edge attribute -string is used if available.

    • -
    -
    -
    Returns
    -

    s- walk distance – A shortest s-walk is computed as a sequence of edges, -the s-walk distance is the number of edges in the sequence -minus 1. If no such path exists returns np.inf.

    -
    -
    Return type
    -

    the shortest s-walk edge distance

    -
    -
    -
    -

    See also

    -

    distance

    -
    -

    Notes

    -

    The s-distance is the shortest s-walk length between the edges. -An s-walk between edges is a sequence of edges such that consecutive pairwise -edges intersect in at least s nodes. The length of the shortest s-walk is 1 less than -the number of edges in the path sequence.

    -

    Uses the networkx shortest_path_length method on the graph -generated by the s-edge_adjacency matrix.

    -
    - -
    -
    -edge_neighbors(edge, s=1)[source]
    -

    The edges in hypergraph which share s nodes(s) with edge.

    -
    -
    Parameters
    -
      -
    • edge (hashable or Entity) – uid for a edge in hypergraph or the edge Entity

    • -
    • s (int, list, optional, default : 1) – Minimum number of nodes shared by neighbors edge node.

    • -
    -
    -
    Returns
    -

    List of edge neighbors

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -edge_size_dist()[source]
    -

    Returns the size for each edge

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    np.array

    -
    -
    -
    - -
    -
    -property edges
    -

    Object associated with self._edges.

    -
    -
    Returns
    -

    If self.isstatic the StaticEntitySet, otherwise EntitySet.

    -
    -
    Return type
    -

    StaticEntitySet or EntitySet

    -
    -
    -
    - -
    -
    -classmethod from_bipartite(B, set_names=('nodes', 'edges'), name=None, static=False, use_nwhy=False)[source]
    -

    Static method creates a Hypergraph from a bipartite graph.

    -
    -
    Parameters
    -
      -
    • B (nx.Graph()) – A networkx bipartite graph. Each node in the graph has a property -‘bipartite’ taking the value of 0 or 1 indicating a 2-coloring of the graph.

    • -
    • set_names (iterable of length 2, optional, default = ['nodes','edges']) – Category names assigned to the graph nodes associated to each bipartite set

    • -
    • name (hashable) –

    • -
    • static (bool) –

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -

    Notes

    -

    A partition for the nodes in a bipartite graph generates a hypergraph.

    -
    >>> import networkx as nx
    ->>> B = nx.Graph()
    ->>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
    ->>> B.add_nodes_from(['a', 'b', 'c'], bipartite=1)
    ->>> B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'b'), (2, 'c'), (3, 'c'), (4, 'a')])
    ->>> H = Hypergraph.from_bipartite(B)
    ->>> H.nodes, H.edges
    -# output: (EntitySet(_:Nodes,[1, 2, 3, 4],{}), EntitySet(_:Edges,['b', 'c', 'a'],{}))
    -
    -
    -
    - -
    -
    -classmethod from_dataframe(df, columns=None, rows=None, name=None, fillna=0, transpose=False, transforms=[], key=None, node_label='nodes', edge_label='edges', static=False, use_nwhy=False)[source]
    -

    Create a hypergraph from a Pandas Dataframe object using index to label vertices -and Columns to label edges. The values of the dataframe are transformed into an -incidence matrix. -Note this is different than passing a dataframe directly -into the Hypergraph constructor. The latter automatically generates a static hypergraph -with edge and node labels given by the cell values.

    -
    -
    Parameters
    -
      -
    • df (Pandas.Dataframe) – a real valued dataframe with a single index

    • -
    • columns ((optional) list, default = None) – restricts df to the columns with headers in this list.

    • -
    • rows ((optional) list, default = None) – restricts df to the rows indexed by the elements in this list.

    • -
    • name ((optional) string, default = None) –

    • -
    • fillna (float, default = 0) – a real value to place in empty cell, all-zero columns will not generate -an edge.

    • -
    • transpose ((optional) bool, default = False) – option to transpose the dataframe, in this case df.Index will label the edges -and df.columns will label the nodes, transpose is applied before transforms and -key

    • -
    • transforms ((optional) list, default = []) – optional list of transformations to apply to each column, -of the dataframe using pd.DataFrame.apply(). -Transformations are applied in the order they are -given (ex. abs). To apply transforms to rows or for additional -functionality, consider transforming df using pandas.DataFrame methods -prior to generating the hypergraph.

    • -
    • key ((optional) function, default = None) – boolean function to be applied to dataframe. Must be defined on numpy -arrays.

    • -
    -
    -
    -
    -

    See also

    -

    from_numpy_array

    -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -

    Notes

    -

    The from_dataframe constructor does not generate empty edges. -All-zero columns in df are removed and the names corresponding to these -edges are discarded. -Restrictions and data processing will occur in this order:

    -
    -
      -
    1. column and row restrictions

    2. -
    3. fillna replace NaNs in dataframe

    4. -
    5. transpose the dataframe

    6. -
    7. transforms in the order listed

    8. -
    9. boolean key

    10. -
    -
    -

    This method offers the above options for wrangling a dataframe into an incidence -matrix for a hypergraph. For more flexibility we recommend you use the Pandas -library to format the values of your dataframe before submitting it to this -constructor.

    -
    - -
    -
    -classmethod from_numpy_array(M, node_names=None, edge_names=None, node_label='nodes', edge_label='edges', name=None, key=None, static=False, use_nwhy=False)[source]
    -

    Create a hypergraph from a real valued matrix represented as a 2 dimensionsl numpy array. -The matrix is converted to a matrix of 0’s and 1’s so that any truthy cells are converted to 1’s and -all others to 0’s.

    -
    -
    Parameters
    -
      -
    • M (real valued array-like object, 2 dimensions) – representing a real valued matrix with rows corresponding to nodes and columns to edges

    • -
    • node_names (object, array-like, default=None) – List of node names must be the same length as M.shape[0]. -If None then the node names correspond to row indices with ‘v’ prepended.

    • -
    • edge_names (object, array-like, default=None) – List of edge names must have the same length as M.shape[1]. -If None then the edge names correspond to column indices with ‘e’ prepended.

    • -
    • name (hashable) –

    • -
    • key ((optional) function) – boolean function to be evaluated on each cell of the array, -must be applicable to numpy.array

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    -

    Note

    -

    The constructor does not generate empty edges. -All zero columns in M are removed and the names corresponding to these -edges are discarded.

    -
    -
    - -
    -
    -get_id(uid, edges=False)[source]
    -

    Return the internally assigned id associated with a label.

    -
    -
    Parameters
    -
      -
    • uid (string) – User provided name/id/label for hypergraph object

    • -
    • edges (bool, optional) – Determines if uid is an edge or node name

    • -
    -
    -
    Returns
    -

    internal id assigned at construction

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -get_linegraph(s, edges=True, use_nwhy=True)[source]
    -

    Creates an ::term::s-linegraph for the Hypergraph. -If edges=True (default)then the edges will be the vertices of the line graph. -Two vertices are connected by an s-line-graph edge if the corresponding -hypergraphedges intersect in at least s hypergraph nodes. -If edges=False, the hypergraph nodes will be the vertices of the line graph. -Two vertices are connected if the nodes they correspond to share at least s -incident hyper edges.

    -
    -
    Parameters
    -
      -
    • s (int) – The width of the connections.

    • -
    • edges (bool, optional) – Determine if edges or nodes will be the vertices in the linegraph.

    • -
    • use_nwhy (bool, optional) – Requests that nwhy be used to construct the linegraph. If NWHy is not available this is ignored.

    • -
    -
    -
    Returns
    -

    A NetworkX graph.

    -
    -
    Return type
    -

    nx.Graph

    -
    -
    -
    - -
    -
    -get_name(id, edges=False)[source]
    -

    Return the user defined name/id/label associated to an -internally assigned id.

    -
    -
    Parameters
    -
      -
    • id (int) – Internally assigned id

    • -
    • edges (bool, optional) – Determines if id references an edge or node

    • -
    -
    -
    Returns
    -

    User provided name/id/label for hypergraph object

    -
    -
    Return type
    -

    str

    -
    -
    -
    - -
    -
    -property incidence_dict
    -

    Dictionary keyed by edge uids with values the uids of nodes in each edge

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -incidence_matrix(index=False)[source]
    -

    An incidence matrix for the hypergraph indexed by nodes x edges.

    -
    -
    Parameters
    -

    index (boolean, optional, default False) – If True return will include a dictionary of node uid : row number -and edge uid : column number

    -
    -
    Returns
    -

      -
    • incidence_matrix (scipy.sparse.csr.csr_matrix or np.ndarray)

    • -
    • row dictionary (dict) – Dictionary identifying rows with nodes

    • -
    • column dictionary (dict) – Dictionary identifying columns with edges

    • -
    -

    -
    -
    -
    - -
    -
    -static incidence_to_adjacency(M, s=1, weighted=True)[source]
    -

    Helper method to obtain adjacency matrix from incidence matrix.

    -
    -
    Parameters
    -
      -
    • M (scipy.sparse.csr.csr_matrix) –

    • -
    • s (int, optional, default: 1) –

    • -
    • weighted (boolean, optional, default: True) –

    • -
    -
    -
    Returns
    -

    a matrix

    -
    -
    Return type
    -

    scipy.sparse.csr.csr_matrix

    -
    -
    -
    - -
    -
    -is_connected(s=1, edges=False)[source]
    -

    Determines if hypergraph is s-connected.

    -
    -
    Parameters
    -
      -
    • s (int, optional, default: 1) –

    • -
    • edges (boolean, optional, default: False) – If True, will determine if s-edge-connected. -For s=1 s-edge-connected is the same as s-connected.

    • -
    -
    -
    Returns
    -

    is_connected

    -
    -
    Return type
    -

    boolean

    -
    -
    -

    Notes

    -

    A hypergraph is s node connected if for any two nodes v0,vn -there exists a sequence of nodes v0,v1,v2,…,v(n-1),vn -such that every consecutive pair of nodes v(i),v(i+1) -share at least s edges.

    -

    A hypergraph is s edge connected if for any two edges e0,en -there exists a sequence of edges e0,e1,e2,…,e(n-1),en -such that every consecutive pair of edges e(i),e(i+1) -share at least s nodes.

    -
    - -
    -
    -property isstatic
    -

    Checks whether nodes and edges are immutable

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    Boolean

    -
    -
    -
    - -
    -
    -neighbors(node, s=1)[source]
    -

    The nodes in hypergraph which share s edge(s) with node.

    -
    -
    Parameters
    -
      -
    • node (hashable or Entity) – uid for a node in hypergraph or the node Entity

    • -
    • s (int, list, optional, default : 1) – Minimum number of edges shared by neighbors with node.

    • -
    -
    -
    Returns
    -

    List of neighbors

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -node_diameters(s=1)[source]
    -

    Returns the node diameters of the connected components in hypergraph.

    -
    -
    Parameters
    -
      -
    • of the diameters of the s-components and (list) –

    • -
    • of the s-component nodes (list) –

    • -
    -
    -
    -
    - -
    -
    -property nodes
    -

    Object associated with self._nodes.

    -
    -
    Returns
    -

    If self.isstatic the StaticEntitySet, otherwise EntitySet.

    -
    -
    Return type
    -

    StaticEntitySet or EntitySet

    -
    -
    -
    - -
    -
    -number_of_edges(edgeset=None)[source]
    -

    The number of edges in edgeset belonging to hypergraph.

    -
    -
    Parameters
    -

    edgeset (an interable of Entities, optional, default: None) – If None, then return the number of edges in hypergraph.

    -
    -
    Returns
    -

    number_of_edges

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -number_of_nodes(nodeset=None)[source]
    -

    The number of nodes in nodeset belonging to hypergraph.

    -
    -
    Parameters
    -

    nodeset (an interable of Entities, optional, default: None) – If None, then return the number of nodes in hypergraph.

    -
    -
    Returns
    -

    number_of_nodes

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -order()[source]
    -

    The number of nodes in hypergraph.

    -
    -
    Returns
    -

    order

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -classmethod recover_from_state(fpath='current_state.p', newfpath=None, use_nwhy=True)[source]
    -

    Recover a static hypergraph pickled using save_state.

    -
    -
    Parameters
    -

    fpath (str) – Full path to pickle file containing state_dict and labels -of hypergraph

    -
    -
    Returns
    -

    H – static hypergraph with state dictionary prefilled

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -remove_edge(edge)[source]
    -

    Removes a single edge from hypergraph.

    -
    -
    Parameters
    -

    edge (hashable or Entity) –

    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -

    Notes

    -

    Deletes reference to edge from all of its nodes. -If any of its nodes do not belong to any other edges -the node is dropped from self.

    -
    - -
    -
    -remove_edges(edge_set)[source]
    -

    Removes edges from hypergraph.

    -
    -
    Parameters
    -

    edge_set (iterable of hashables or Entities) –

    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -remove_node(node)[source]
    -

    Removes node from edges and deletes reference in hypergraph nodes

    -
    -
    Parameters
    -

    node (hashable or Entity) – a node in hypergraph

    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -remove_nodes(node_set)[source]
    -

    Removes nodes from edges and deletes references in hypergraph nodes

    -
    -
    Parameters
    -

    node_set (an iterable of hashables or Entities) – Nodes in hypergraph

    -
    -
    Returns
    -

    hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -remove_singletons(name=None)[source]
    -

    XX -Constructs clone of hypergraph with singleton edges removed.

    -
    -
    Parameters
    -

    name (str, optional, default: None) –

    -
    -
    Returns
    -

    new hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -remove_static(name=None)[source]
    -

    Returns dynamic hypergraph

    -
    -
    Parameters
    -

    name (None, optional) – User defined namae of hypergraph

    -
    -
    Returns
    -

    A new hypergraph with the same dictionary as self but allowing dynamic -changes to nodes and edges. -If hypergraph is not static, returns self.

    -
    -
    Return type
    -

    hnx.Hypergraph

    -
    -
    -
    - -
    -
    -restrict_to_edges(edgeset, name=None)[source]
    -

    Constructs a hypergraph using a subset of the edges in hypergraph

    -
    -
    Parameters
    -
      -
    • edgeset (iterable of hashables or Entities) – A subset of elements of the hypergraph edges

    • -
    • name (str, optional) –

    • -
    -
    -
    Returns
    -

    new hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -restrict_to_nodes(nodeset, name=None)[source]
    -

    Constructs a new hypergraph by restricting the edges in the hypergraph to -the nodes referenced by nodeset.

    -
    -
    Parameters
    -
      -
    • nodeset (iterable of hashables) – References a subset of elements of self.nodes

    • -
    • name (string, optional, default: None) –

    • -
    -
    -
    Returns
    -

    new hypergraph

    -
    -
    Return type
    -

    Hypergraph

    -
    -
    -
    - -
    -
    -s_component_subgraphs(s=1, edges=True, return_singletons=False)[source]
    -

    Returns a generator for the induced subgraphs of s_connected components. -Removes singletons unless return_singletons is set to True. Computed using -s-linegraph generated either by the hypergraph (edges=True) or its dual -(edges = False)

    -
    -
    Parameters
    -
      -
    • s (int, optional, default: 1) –

    • -
    • edges (boolean, optional, edges=False) – Determines if edge or node components are desired. Returns -subgraphs equal to the hypergraph restricted to each set of nodes(edges) in the -s-connected components or s-edge-connected components

    • -
    • return_singletons (bool, optional) –

    • -
    -
    -
    Yields
    -

    s_component_subgraphs (iterator) – Iterator returns subgraphs generated by the edges (or nodes) in the -s-edge(node) components of hypergraph.

    -
    -
    -
    - -
    -
    -s_components(s=1, edges=True, return_singletons=True)[source]
    -

    Same as s_connected_components

    - -
    - -
    -
    -s_connected_components(s=1, edges=True, return_singletons=False)[source]
    -

    Returns a generator for the s-edge-connected components -or the s-node-connected components -of the hypergraph.

    -
    -
    Parameters
    -
      -
    • s (int, optional, default: 1) –

    • -
    • edges (boolean, optional, default: True) – If True will return edge components, if False will return node components

    • -
    • return_singletons (bool, optional, default : False) –

    • -
    -
    -
    -

    Notes

    -

    If edges=True, this method returns the s-edge-connected components as -lists of lists of edge uids. -An s-edge-component has the property that for any two edges e1 and e2 -there is a sequence of edges starting with e1 and ending with e2 -such that pairwise adjacent edges in the sequence intersect in at least -s nodes. If s=1 these are the path components of the hypergraph.

    -

    If edges=False this method returns s-node-connected components. -A list of sets of uids of the nodes which are s-walk connected. -Two nodes v1 and v2 are s-walk-connected if there is a -sequence of nodes starting with v1 and ending with v2 such that pairwise -adjacent nodes in the sequence share s edges. If s=1 these are the -path components of the hypergraph.

    -

    Example

    -
    >>> S = {'A':{1,2,3},'B':{2,3,4},'C':{5,6},'D':{6}}
    ->>> H = Hypergraph(S)
    -
    -
    -
    >>> list(H.s_components(edges=True))
    -[{'C', 'D'}, {'A', 'B'}]
    ->>> list(H.s_components(edges=False))
    -[{1, 2, 3, 4}, {5, 6}]
    -
    -
    -
    -
    Yields
    -

    s_connected_components (iterator) – Iterator returns sets of uids of the edges (or nodes) in the s-edge(node) -components of hypergraph.

    -
    -
    -
    - -
    -
    -s_degree(node, s=1)[source]
    -

    Same as degree

    -
    -
    Parameters
    -
      -
    • node (Entity or hashable) – If hashable, then must be uid of node in hypergraph

    • -
    • s (positive integer, optional, default: 1) –

    • -
    -
    -
    Returns
    -

    s_degree – The degree of a node in the subgraph induced by edges -of size s

    -
    -
    Return type
    -

    int

    -
    -
    -
    -

    Note

    -

    The s-degree of a node is the number of edges of size -at least s that contain the node.

    -
    -
    - -
    -
    -save_state(fpath=None)[source]
    -

    Save the hypergraph as an ordered pair: [state_dict,labels] -The hypergraph can be recovered using the command:

    -
    >>> H = hnx.Hypergraph.recover_from_state(fpath)
    -
    -
    -
    -
    Parameters
    -

    fpath (str, optional) –

    -
    -
    -
    - -
    -
    -set_state(**kwargs)[source]
    -

    Allow state_dict updates from outside of class. Use with caution.

    -
    -
    Parameters
    -

    **kwargs – key=value pairs to save in state dictionary

    -
    -
    -
    - -
    -
    -property shape
    -

    (number of nodes, number of edges)

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    tuple

    -
    -
    -
    - -
    -
    -singletons()[source]
    -

    Returns a list of singleton edges. A singleton edge is an edge of -size 1 with a node of degree 1.

    -
    -
    Returns
    -

    singles – A list of edge uids.

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -size(edge)[source]
    -

    The number of nodes that belong to edge.

    -
    -
    Parameters
    -

    edge (hashable) – The uid of an edge in the hypergraph

    -
    -
    Returns
    -

    size

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -toplexes(name=None, collapse=False, use_reps=False, return_counts=True)[source]
    -

    Returns a simple hypergraph corresponding to self.

    -
    -

    Warning

    -

    Collapsing is no longer supported inside the toplexes method. Instead generate a new -collapsed hypergraph and compute the toplexes of the new hypergraph.

    -
    -
    -
    Parameters
    -
      -
    • name (str, optional, default: None) –

    • -
    • collapse (#) –

    • -
    • Should the hypergraph be collapsed? This would preserve a link between duplicate maximal sets. (#) –

    • -
    • If False then only one of these sets will be used and uniqueness will be up to sets of equal size. (#) –

    • -
    • use_reps (#) –

    • -
    • If collapse=True then each toplex will be named by a representative of the set of (#) –

    • -
    • equivalent edges (#) –

    • -
    • is False (see collapse_edges) (default) –

    • -
    • return_counts (boolean, optional, default: True) – # If collapse=True then each toplex will be named by a tuple of the representative -# of the set of equivalent edges and their count

    • -
    -
    -
    -
    - -
    -
    -translate(idx, edges=False)[source]
    -

    Returns the translation of numeric values associated with hypergraph. -Only needed if exposing the static identifiers assigned by the class. -If not static then the idx is returned.

    -
    -
    Parameters
    -
      -
    • idx (int) – class assigned integer for internal manipulation of Hypergraph data

    • -
    • edges (bool, optional, default: True) – If True then translates from edge index. Otherwise will translate from -node index, default=False

    • -
    -
    -
    Returns
    -

    User assigned identifier corresponding to idx

    -
    -
    Return type
    -

    int or string

    -
    -
    -
    - -
    - -
    -
    -

    classes.staticentity module

    -
    -
    -class classes.staticentity.StaticEntity(entity=None, data=None, arr=None, labels=None, uid=None, **props)[source]
    -

    Bases: object

    -
    -
    Parameters
    -
      -
    • entity (StaticEntity, StaticEntitySet, Entity, EntitySet, pandas.DataFrame, dict, or list of lists) – If a pandas.DataFrame, an error will be raised if there are nans.

    • -
    • data (array or array-like) – Two dimensional array of integers. Provides sparse tensor indices for incidence -tensor.

    • -
    • arr (numpy.ndarray or scip.sparse.matrix, optional, default=None) – Incidence tensor of data.

    • -
    • labels (OrderedDict of lists, optional, default=None) – User defined labels corresponding to integers in data.

    • -
    • uid (hashable, optional, default=None) –

    • -
    • props (user defined keyword arguments to be added to a properties dictionary, optional) –

    • -
    -
    -
    -
    -
    -properties
    -

    Description

    -
    -
    Type
    -

    dict

    -
    -
    -
    - -
    -
    -property arr
    -
    - -
    -
    -property children
    -

    Labels of keys of first index

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    set

    -
    -
    -
    - -
    -
    -property data
    -

    Data array or tensor array of Static Entity

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    np.ndarray

    -
    -
    -
    - -
    -
    -property dataframe
    -

    Returns the entity data in DataFrame format

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    pandas.core.frame.DataFrame

    -
    -
    -
    - -
    -
    -property dimensions
    -

    Dimension of Static Entity data

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    tuple

    -
    -
    -
    - -
    -
    -property dimsize
    -

    Number of categories in the data

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -property elements
    -

    Keys and values in the order of insertion

    -
    -
    Returns
    -

      -
    • collections.OrderedDict

    • -
    • level1 = elements, level2 = children

    • -
    -

    -
    -
    -
    - -
    -
    -elements_by_level(level1=0, level2=None, translate=False)[source]
    -

    Elements of staticentity by specified column

    -
    -
    Parameters
    -
      -
    • level1 (int, optional) – edges

    • -
    • level2 (int, optional) – nodes

    • -
    • translate (bool, optional) – whether to replace indices with labels

    • -
    -
    -
    Returns
    -

      -
    • collections.defaultdict

    • -
    • think (level1 = edges, level2 = nodes)

    • -
    -

    -
    -
    -
    - -
    -
    -property incidence_dict
    -

    Dictionary using index 0 as nodes and index 1 as edges

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    collections.OrderedDict

    -
    -
    -
    - -
    -
    -incidence_matrix(level1=0, level2=1, weighted=False, index=False)[source]
    -

    Convenience method to navigate large tensor

    -
    -
    Parameters
    -
      -
    • level1 (int, optional) – indexes columns

    • -
    • level2 (int, optional) – indexes rows

    • -
    • weighted (bool, optional) –

    • -
    • index (bool, optional) –

    • -
    -
    -
    Returns
    -

      -
    • scipy.sparse.csr.csr_matrix

    • -
    • think level1 = edges, level2 = nodes

    • -
    -

    -
    -
    -
    - -
    -
    -index(category, value=None)[source]
    -

    Returns dimension of category and index of value

    -
    -
    Parameters
    -
      -
    • category (string) –

    • -
    • value (string, optional) –

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    int or tuple of ints

    -
    -
    -
    - -
    -
    -indices(category, values)[source]
    -

    Returns dimension of category and index of values (array)

    -
    -
    Parameters
    -
      -
    • category (string) –

    • -
    • values (single string or array of strings) –

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -is_empty(level=0)[source]
    -

    Boolean indicating if entity.elements is empty

    -
    -
    Parameters
    -

    level (int, optional) –

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    bool

    -
    -
    -
    - -
    -
    -property keyindex
    -

    Returns the index of a category in keys array

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -property keys
    -

    Array of keys of labels

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    np.ndarray

    -
    -
    -
    - -
    -
    -property labels
    -

    Ordered dictionary of labels

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    collections.OrderedDict

    -
    -
    -
    - -
    -
    -labs(kdx)[source]
    -

    Retrieve labels by index in keys

    -
    -
    Parameters
    -

    kdx (int) – index of key in E.keys

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    np.ndarray

    -
    -
    -
    - -
    -
    -level(item, min_level=0, max_level=None, return_index=True)[source]
    -

    Returns first level item appears by order of keys from minlevel to maxlevel -inclusive

    -
    -
    Parameters
    -
      -
    • item (string) –

    • -
    • min_level (int, optional) –

    • -
    • max_level (int, optional) –

    • -
    • return_index (bool, optional) –

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    tuple

    -
    -
    -
    - -
    -
    -restrict_to_indices(indices, level=0, uid=None)[source]
    -

    Limit Static Entity data to specific indices of keys

    -
    -
    Parameters
    -
      -
    • indices (array) – array of category indices

    • -
    • level (int, optional) – index of label

    • -
    • uid (None, optional) –

    • -
    -
    -
    Returns
    -

    hnx.classes.staticentity.StaticEntity

    -
    -
    Return type
    -

    Static Entity class

    -
    -
    -
    - -
    -
    -restrict_to_levels(levels, uid=None)[source]
    -

    Limit Static Entity data to specific labels

    -
    -
    Parameters
    -
      -
    • levels (array) – index of labels in data

    • -
    • uid (None, optional) –

    • -
    -
    -
    Returns
    -

    hnx.classes.staticentity.StaticEntity

    -
    -
    Return type
    -

    Static Entity class

    -
    -
    -
    - -
    -
    -size()[source]
    -

    The number of elements in E, the size of dimension 0 in the E.arr

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    int

    -
    -
    -
    - -
    -
    -translate(level, index)[source]
    -

    Replaces a category index and value index with label

    -
    -
    Parameters
    -
      -
    • level (int) – category index of label

    • -
    • index (int) – value index of label

    • -
    -
    -
    Returns
    -

    -
    -
    Return type
    -

    numpy.array(str)

    -
    -
    -
    - -
    -
    -translate_arr(coords)[source]
    -

    Translates a single cell in the entity array

    -
    -
    Parameters
    -

    coords (tuple of ints) –

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -turn_entity_data_into_dataframe(data_subset)[source]
    -

    Convert rows of original data in StaticEntity to dataframe

    -
    -
    Parameters
    -

    data (numpy.ndarray) – Subset of the rows in the original data held in the StaticEntity

    -
    -
    Returns
    -

    Columns and cell entries are derived from data and self.labels

    -
    -
    Return type
    -

    pandas.core.frame.DataFrame

    -
    -
    -
    - -
    -
    -property uid
    -
    - -
    -
    -property uidset
    -

    Returns a set of the string identifiers for Static Entity

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    frozenset

    -
    -
    -
    - -
    -
    -uidset_by_level(level=0)[source]
    -

    The labels found in columns = level

    -
    -
    Parameters
    -

    level (int, optional) –

    -
    -
    Returns
    -

    -
    -
    Return type
    -

    frozenset

    -
    -
    -
    - -
    - -
    -
    -class classes.staticentity.StaticEntitySet(entity=None, data=None, arr=None, labels=None, uid=None, level1=0, level2=1, **props)[source]
    -

    Bases: classes.staticentity.StaticEntity

    -
    -
    -collapse_identical_elements(uid=None, return_equivalence_classes=False)[source]
    -

    Returns StaticEntitySet after collapsing elements if they have same children -If no elements share same children, a copy of the original StaticEntitySet is returned -:param uid: -:type uid: None, optional -:param return_equivalence_classes: If True, return a dictionary of equivalence classes keyed by new edge names -:type return_equivalence_classes: bool, optional

    -
    -
    Returns
    -

    hnx.classes.staticentity.StaticEntitySet

    -
    -
    Return type
    -

    StaticEntitySet

    -
    -
    -
    - -
    -
    -convert_to_entityset(uid)[source]
    -

    Convert given uid of Static EntitySet into EntitySet

    -
    -
    Parameters
    -

    uid (string) –

    -
    -
    Returns
    -

    hnx.classes.entity.EntitySet

    -
    -
    Return type
    -

    EntitySet

    -
    -
    -
    - -
    -
    -incidence_matrix(sparse=True, weighted=False, index=False)[source]
    -

    Incidence matrix of StaticEntitySet indexed by uidset

    -
    -
    Parameters
    -
      -
    • sparse (bool, optional) –

    • -
    • weighted (bool, optional) –

    • -
    • index (bool, optional) – give index of rows then columns

    • -
    -
    -
    Returns
    -

    scipy.sparse.csr.csr_matrix

    -
    -
    Return type
    -

    matrix

    -
    -
    -
    - -
    -
    -restrict_to(indices, uid=None)[source]
    -

    Limit Static Entityset data to specific indices of keys

    -
    -
    Parameters
    -
      -
    • indices (array) – array of indices in keys

    • -
    • uid (None, optional) –

    • -
    -
    -
    Returns
    -

    hnx.classes.staticentity.StaticEntitySet

    -
    -
    Return type
    -

    StaticEntitySet

    -
    -
    -
    - -
    - +
    +

    classes.staticentity module

    -
    -

    Module contents

    +
    +

    Module contents

    diff --git a/docs/build/classes/modules.html b/docs/build/classes/modules.html index 63cbb63b..77a1e982 100644 --- a/docs/build/classes/modules.html +++ b/docs/build/classes/modules.html @@ -7,7 +7,7 @@ - classes — HyperNetX 1.0.0 documentation + classes — HyperNetX 1.0.1 documentation @@ -189,10 +189,10 @@

    classesclasses package

  • diff --git a/docs/build/core.html b/docs/build/core.html index 67b1f3ef..59a72922 100644 --- a/docs/build/core.html +++ b/docs/build/core.html @@ -7,7 +7,7 @@ - HyperNetX Packages — HyperNetX 1.0.0 documentation + HyperNetX Packages — HyperNetX 1.0.1 documentation @@ -185,10 +185,10 @@
  • Hypergraphs @@ -196,18 +196,9 @@
  • Algorithms @@ -215,10 +206,10 @@
  • Drawing @@ -226,8 +217,8 @@
  • Reports diff --git a/docs/build/drawing/drawing.html b/docs/build/drawing/drawing.html index bdf61e6e..6b70eb59 100644 --- a/docs/build/drawing/drawing.html +++ b/docs/build/drawing/drawing.html @@ -7,7 +7,7 @@ - drawing package — HyperNetX 1.0.0 documentation + drawing package — HyperNetX 1.0.1 documentation @@ -106,10 +106,10 @@
  • Drawing @@ -197,434 +197,17 @@

    drawing package

    Submodules

    -
    -

    drawing.rubber_band module

    -
    -
    -drawing.rubber_band.draw(H, pos=None, with_color=True, with_node_counts=False, with_edge_counts=False, layout=<function fruchterman_reingold_layout>, layout_kwargs={}, ax=None, node_radius=None, edges_kwargs={}, nodes_kwargs={}, edge_labels={}, edge_labels_kwargs={}, node_labels={}, node_labels_kwargs={}, with_edge_labels=True, with_node_labels=True, label_alpha=0.35, return_pos=False)[source]
    -

    Draw a hypergraph as a Matplotlib figure

    -

    By default this will draw a colorful “rubber band” like hypergraph, where -convex hulls represent edges and are drawn around the nodes they contain.

    -

    This is a convenience function that wraps calls with sensible parameters to -the following lower-level drawing functions:

    -
      -
    • draw_hyper_edges,

    • -
    • draw_hyper_edge_labels,

    • -
    • draw_hyper_labels, and

    • -
    • draw_hyper_nodes

    • -
    -

    The default layout algorithm is nx.spring_layout, but other layouts can be -passed in. The Hypergraph is converted to a bipartite graph, and the layout -algorithm is passed the bipartite graph.

    -

    If you have a pre-determined layout, you can pass in a “pos” dictionary. -This is a dictionary mapping from node id’s to x-y coordinates. For example:

    -
    >>> pos = {
    ->>> 'A': (0, 0),
    ->>> 'B': (1, 2),
    ->>> 'C': (5, -3)
    ->>> }
    -
    +
    +

    drawing.rubber_band module

    -

    will position the nodes {A, B, C} manually at the locations specified. The -coordinate system is in Matplotlib “data coordinates”, and the figure will -be centered within the figure.

    -

    By default, this will draw in a new figure, but the axis to render in can be -specified using ax.

    -

    This approach works well for small hypergraphs, and does not guarantee -a rigorously “correct” drawing. Overlapping of sets in the drawing generally -implies that the sets intersect, but sometimes sets overlap if there is no -intersection. It is not possible, in general, to draw a “correct” hypergraph -this way for an arbitrary hypergraph, in the same way that not all graphs -have planar drawings.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • with_color (bool) – set to False to disable color cycling of edges

    • -
    • with_node_counts (bool) – set to True to label collapsed nodes with number of elements

    • -
    • with_edge_counts (bool) – set to True to label collapsed edges with number of elements

    • -
    • layout (function) – layout algorithm to compute

    • -
    • layout_kwargs (dict) – keyword arguments passed to layout function

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • edges_kwargs (dict) – keyword arguments passed to matplotlib.collections.PolyCollection for edges

    • -
    • node_radius (None, int, float, or dict) – radius of all nodes, or dictionary of node:value; the default (None) calculates radius based on number of collapsed nodes; reasonable values range between 1 and 3

    • -
    • nodes_kwargs (dict) – keyword arguments passed to matplotlib.collections.PolyCollection for nodes

    • -
    • edge_labels_kwargs (dict) – keyword arguments passed to matplotlib.annotate for edge labels

    • -
    • node_labels_kwargs (dict) – keyword argumetns passed to matplotlib.annotate for node labels

    • -
    • with_edge_labels (bool) – set to False to make edge labels invisible

    • -
    • with_node_labels (bool) – set to False to make node labels invisible

    • -
    • label_alpha (float) – the transparency (alpha) of the box behind text drawn in the figure

    • -
    -
    -
    -
    - -
    -
    -drawing.rubber_band.draw_hyper_edge_labels(H, polys, labels={}, ax=None, **kwargs)[source]
    -

    Draws a label on the hyper edge boundary.

    -

    Should be passed Matplotlib PolyCollection representing the hyper-edges, see -the return value of draw_hyper_edges.

    -

    The label will be draw on the least curvy part of the polygon, and will be -aligned parallel to the orientation of the polygon where it is drawn.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • polys (PolyCollection) – collection of polygons returned by draw_hyper_edges

    • -
    • labels (dict) – mapping of node id to string label

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • kwargs (dict) – Keyword arguments are passed through to Matplotlib’s annotate function.

    • -
    -
    -
    -
    - -
    -
    -drawing.rubber_band.draw_hyper_edges(H, pos, ax=None, node_radius={}, dr=None, **kwargs)[source]
    -

    Draws a convex hull around the nodes contained within each edge in H

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • node_radius (dict) – mapping of node to R^1 (radius of each node)

    • -
    • dr (float) – the spacing between concentric rings

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • kwargs (dict) – keyword arguments, e.g., linewidth, facecolors, are passed through to the PolyCollection constructor

    • -
    -
    -
    Returns
    -

    a Matplotlib PolyCollection that can be further styled

    -
    -
    Return type
    -

    PolyCollection

    -
    -
    -
    - -
    -
    -drawing.rubber_band.draw_hyper_labels(H, pos, node_radius={}, ax=None, labels={}, **kwargs)[source]
    -

    Draws text labels for the hypergraph nodes.

    -

    The label is drawn to the right of the node. The node radius is needed (see -draw_hyper_nodes) so the text can be offset appropriately as the node size -changes.

    -

    The text label can be customized by passing in a dictionary, labels, mapping -a node to its custom label. By default, the label is the string -representation of the node.

    -

    Keyword arguments are passed through to Matplotlib’s annotate function.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • node_radius (dict) – mapping of node to R^1 (radius of each node)

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • labels (dict) – mapping of node to text label

    • -
    • kwargs (dict) – keyword arguments passed to matplotlib.annotate

    • -
    -
    -
    -
    - -
    -
    -drawing.rubber_band.draw_hyper_nodes(H, pos, node_radius={}, r0=None, ax=None, **kwargs)[source]
    -

    Draws a circle for each node in H.

    -

    The position of each node is specified by the a dictionary/list-like, pos, -where pos[v] is the xy-coordinate for the vertex. The radius of each node -can be specified as a dictionary where node_radius[v] is the radius. If a -node is missing from this dictionary, or the node_radius is not specified at -all, a sensible default radius is chosen based on distances between nodes -given by pos.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • node_radius (dict) – mapping of node to R^1 (radius of each node)

    • -
    • r0 (float) – minimum distance that concentric rings start from the node position

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • kwargs (dict) – keyword arguments, e.g., linewidth, facecolors, are passed through to the PolyCollection constructor

    • -
    -
    -
    Returns
    -

    a Matplotlib PolyCollection that can be further styled

    -
    -
    Return type
    -

    PolyCollection

    -
    -
    -
    - -
    -
    -drawing.rubber_band.get_default_radius(H, pos)[source]
    -

    Calculate a reasonable default node radius

    -

    This function iterates over the hyper edges and finds the most distant -pair of points given the positions provided. Then, the node radius is a fraction -of the median of this distance take across all hyper-edges.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    -
    -
    Returns
    -

    the recommended radius

    -
    -
    Return type
    -

    float

    -
    -
    -
    - -
    -
    -drawing.rubber_band.layout_hyper_edges(H, pos, node_radius={}, dr=None)[source]
    -

    Draws a convex hull for each edge in H.

    -

    Position of the nodes in the graph is specified by the position dictionary, -pos. Convex hulls are spaced out such that if one set contains another, the -convex hull will surround the contained set. The amount of spacing added -between hulls is specified by the parameter, dr.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • node_radius (dict) – mapping of node to R^1 (radius of each node)

    • -
    • dr (float) – the spacing between concentric rings

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    -
    -
    Returns
    -

    A mapping from hyper edge ids to paths (Nx2 numpy matrices)

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    - -

    Helper function to use a NetwrokX-like graph layout algorithm on a Hypergraph

    -

    The hypergraph is converted to a bipartite graph, allowing the usual graph layout -techniques to be applied.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • layout (function) – the layout algorithm which accepts a NetworkX graph and keyword arguments

    • -
    • kwargs (dict) – Keyword arguments are passed through to the layout algorithm

    • -
    -
    -
    Returns
    -

    mapping of node and edge positions to R^2

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - +
    +

    drawing.two_column module

    -
    -

    drawing.two_column module

    -
    -
    -drawing.two_column.draw(H, with_node_labels=True, with_edge_labels=True, with_node_counts=False, with_edge_counts=False, with_color=True, edge_kwargs=None, ax=None)[source]
    -

    Draw a hypergraph using a two-collumn layout.

    -

    This is intended reproduce an illustrative technique for bipartite graphs -and hypergraphs that is typically used in papers and textbooks.

    -

    The left column is reserved for nodes and the right column is reserved for -edges. A line is drawn between a node an an edge

    -

    The order of nodes and edges is optimized to reduce line crossings between -the two columns. Spacing between disconnected components is adjusted to make -the diagram easier to read, by reducing the angle of the lines.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • with_node_labels (bool) – False to disable node labels

    • -
    • with_edge_labels (bool) – False to disable edge labels

    • -
    • with_node_counts (bool) – set to True to label collapsed nodes with number of elements

    • -
    • with_edge_counts (bool) – set to True to label collapsed edges with number of elements

    • -
    • with_color (bool) – set to False to disable color cycling of hyper edges

    • -
    • edge_kwargs (dict) – keyword arguments to pass to matplotlib.LineCollection

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    -
    -
    -
    - -
    -
    -drawing.two_column.draw_hyper_edges(H, pos, ax=None, **kwargs)[source]
    -

    Renders hyper edges for the two column layout.

    -

    Each node-hyper edge membership is rendered as a line connecting the node -in the left column to the edge in the right column.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • kwargs (dict) – keyword arguments passed to matplotlib.LineCollection

    • -
    -
    -
    Returns
    -

    the hyper edges

    -
    -
    Return type
    -

    LineCollection

    -
    -
    -
    - -
    -
    -drawing.two_column.draw_hyper_labels(H, pos, labels={}, with_node_labels=True, with_edge_labels=True, ax=None)[source]
    -

    Renders hyper labels (nodes and edges) for the two column layout.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • pos (dict) – mapping of node and edge positions to R^2

    • -
    • labels (dict) – custom labels for nodes and edges can be supplied

    • -
    • with_node_labels (bool) – False to disable node labels

    • -
    • with_edge_labels (bool) – False to disable edge labels

    • -
    • ax (Axis) – matplotlib axis on which the plot is rendered

    • -
    • kwargs (dict) – keyword arguments passed to matplotlib.LineCollection

    • -
    -
    -
    -
    - -
    -
    -drawing.two_column.layout_two_column(H, spacing=2)[source]
    -

    Two column (bipartite) layout algorithm.

    -

    This algorithm first converts the hypergraph into a bipartite graph and -then computes connected components. Disonneccted components are handled -independently and then stacked together.

    -

    Within a connected component, the spectral ordering of the bipartite graph -provides a quick and dirty ordering that minimizes edge crossings in the -diagram.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • spacing (float) – amount of whitespace between disconnected components

    • -
    -
    -
    -
    - -
    -
    -

    drawing.util module

    -
    -
    -drawing.util.get_frozenset_label(S, count=False, override={})[source]
    -

    Helper function for rendering the labels of possibly collapsed nodes and edges

    -
    -
    Parameters
    -
      -
    • S (iterable) – list of entities to be labeled

    • -
    • count (bool) – True if labels should be counts of entities instead of list

    • -
    -
    -
    Returns
    -

    mapping of entity to its string representation

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -drawing.util.get_line_graph(H, collapse=True)[source]
    -

    Computes the line graph, a directed graph, where a directed edge (u, v) -exists if the edge u is a subset of the edge v in the hypergraph.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • collapse (bool) – True if edges should be added if hyper edges are identical

    • -
    -
    -
    Returns
    -

    A directed graph

    -
    -
    Return type
    -

    networkx.DiGraph

    -
    -
    -
    - -
    -
    -drawing.util.get_set_layering(H, collapse=True)[source]
    -

    Computes a layering of the edges in the hyper graph.

    -

    In this layering, each edge is assigned a level. An edge u will be above -(e.g., have a smaller level value) another edge v if v is a subset of u.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) – the entity to be drawn

    • -
    • collapse (bool) – True if edges should be added if hyper edges are identical

    • -
    -
    -
    Returns
    -

    a mapping of vertices in H to integer levels

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -drawing.util.inflate(items, v)[source]
    -
    - -
    -
    -drawing.util.inflate_kwargs(items, kwargs)[source]
    -

    Helper function to expand keyword arguments.

    -
    -
    Parameters
    -
      -
    • n (int) – length of resulting list if argument is expanded

    • -
    • kwargs (dict) – keyword arguments to be expanded

    • -
    -
    -
    Returns
    -

    dictionary with same keys as kwargs and whose values are lists of length n

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -drawing.util.transpose_inflated_kwargs(inflated)[source]
    -
    - +
    +

    drawing.util module

    -
    -

    Module contents

    +
    +

    Module contents

    diff --git a/docs/build/drawing/modules.html b/docs/build/drawing/modules.html index 6e693e5b..68658da8 100644 --- a/docs/build/drawing/modules.html +++ b/docs/build/drawing/modules.html @@ -7,7 +7,7 @@ - drawing — HyperNetX 1.0.0 documentation + drawing — HyperNetX 1.0.1 documentation @@ -189,10 +189,10 @@

    drawingdrawing package

  • diff --git a/docs/build/genindex.html b/docs/build/genindex.html index ebd20a43..1986b9ff 100644 --- a/docs/build/genindex.html +++ b/docs/build/genindex.html @@ -7,7 +7,7 @@ - Index — HyperNetX 1.0.0 documentation + Index — HyperNetX 1.0.1 documentation @@ -172,180 +172,19 @@

    Index

    - A - | B - | C + B | D | E - | F - | G | H | I - | K - | L - | M - | N - | O - | P - | R | S | T - | U
    -

    A

    - - - -
    -

    B

    - -
    - -

    C

    - - -
    @@ -353,87 +192,11 @@

    C

    D

    @@ -441,46 +204,16 @@

    D

    E

    - + -
    - -

    F

    - - - -
    - -

    G

    - - -
    @@ -535,15 +228,7 @@

    G

    H

    -
    @@ -552,245 +237,6 @@

    I

    - -
    - -

    K

    - - - -
    - -

    L

    - - - -
    - -

    M

    - - -
    - -

    N

    - - - -
    - -

    O

    - - -
    - -

    P

    - - -
    - -

    R

    - - -
    @@ -814,6 +260,8 @@

    S

  • s-edge
  • + + - @@ -891,46 +287,6 @@

    T

    - -
    - -

    U

    - - -
    diff --git a/docs/build/glossary.html b/docs/build/glossary.html index 8e761813..002f174a 100644 --- a/docs/build/glossary.html +++ b/docs/build/glossary.html @@ -7,7 +7,7 @@ - Glossary of HNX terms — HyperNetX 1.0.0 documentation + Glossary of HNX terms — HyperNetX 1.0.1 documentation @@ -180,7 +180,7 @@ elements and children of an EntitySet generate a specific partition for a bipartite graph. partition is isomorphic to a Hypergraph where the elements correspond to hyperedges and children correspond to the nodes. EntitySets are the basic objects used to construct dynamic hypergraphs -NX. See methods classes.hypergraph.Hypergraph.bipartite() and classes.hypergraph.Hypergraph.from_bipartite().

    +NX. See methods classes.hypergraph.Hypergraph.bipartite() and classes.hypergraph.Hypergraph.from_bipartite().

    degree

    Given a hypergraph (Nodes,Edges), the degree of a node in Nodes is the number of edges in Edges to which the node belongs. See also: s-degree

    diff --git a/docs/build/home.html b/docs/build/home.html index 54efa90f..4417d511 100644 --- a/docs/build/home.html +++ b/docs/build/home.html @@ -7,7 +7,7 @@ - HyperNetX (HNX) — HyperNetX 1.0.0 documentation + HyperNetX (HNX) — HyperNetX 1.0.1 documentation diff --git a/docs/build/index.html b/docs/build/index.html index 8f1e5140..c2f68ceb 100644 --- a/docs/build/index.html +++ b/docs/build/index.html @@ -7,7 +7,7 @@ - HyperNetX (HNX) — HyperNetX 1.0.0 documentation + HyperNetX (HNX) — HyperNetX 1.0.1 documentation diff --git a/docs/build/install.html b/docs/build/install.html index 2298e562..5db68008 100644 --- a/docs/build/install.html +++ b/docs/build/install.html @@ -7,7 +7,7 @@ - Installing HyperNetX — HyperNetX 1.0.0 documentation + Installing HyperNetX — HyperNetX 1.0.1 documentation diff --git a/docs/build/license.html b/docs/build/license.html index 17945953..5a6e5945 100644 --- a/docs/build/license.html +++ b/docs/build/license.html @@ -7,7 +7,7 @@ - License — HyperNetX 1.0.0 documentation + License — HyperNetX 1.0.1 documentation diff --git a/docs/build/nwhy.html b/docs/build/nwhy.html index a23e0b53..f0df4dac 100644 --- a/docs/build/nwhy.html +++ b/docs/build/nwhy.html @@ -7,7 +7,7 @@ - NWHy — HyperNetX 1.0.0 documentation + NWHy — HyperNetX 1.0.1 documentation diff --git a/docs/build/objects.inv b/docs/build/objects.inv index dbfe4851..1e177835 100644 Binary files a/docs/build/objects.inv and b/docs/build/objects.inv differ diff --git a/docs/build/overview/index.html b/docs/build/overview/index.html index 84cebc51..9affbefc 100644 --- a/docs/build/overview/index.html +++ b/docs/build/overview/index.html @@ -7,7 +7,7 @@ - Overview — HyperNetX 1.0.0 documentation + Overview — HyperNetX 1.0.1 documentation diff --git a/docs/build/publications.html b/docs/build/publications.html index 7d60efe3..d920d5be 100644 --- a/docs/build/publications.html +++ b/docs/build/publications.html @@ -7,7 +7,7 @@ - Publications — HyperNetX 1.0.0 documentation + Publications — HyperNetX 1.0.1 documentation diff --git a/docs/build/py-modindex.html b/docs/build/py-modindex.html deleted file mode 100644 index c761f75c..00000000 --- a/docs/build/py-modindex.html +++ /dev/null @@ -1,310 +0,0 @@ - - - - - - - - - - Python Module Index — HyperNetX 1.0.0 documentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - - -
    - - - - - -
    - -
    - - - - - - - - - - - - - - - - - - - -
    - -
      - -
    • »
    • - -
    • Python Module Index
    • - - -
    • - -
    • - -
    - - -
    -
    -
    -
    - - -

    Python Module Index

    - -
    - a | - c | - d | - r -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     
    - a
    - algorithms -
        - algorithms.homology_mod2 -
        - algorithms.s_centrality_measures -
     
    - c
    - classes -
        - classes.entity -
        - classes.hypergraph -
        - classes.staticentity -
     
    - d
    - drawing -
        - drawing.rubber_band -
        - drawing.two_column -
        - drawing.util -
     
    - r
    - reports -
        - reports.descriptive_stats -
    - - -
    - -
    -
    - -
    - -
    -

    - © Copyright 2018 Battelle Memorial Institute. - -

    -
    - - - - Built with Sphinx using a - - theme - - provided by Read the Docs. - -
    -
    -
    - -
    - -
    - - - - - - - - - - - \ No newline at end of file diff --git a/docs/build/reports/modules.html b/docs/build/reports/modules.html index 39710e6d..7ff9b3c5 100644 --- a/docs/build/reports/modules.html +++ b/docs/build/reports/modules.html @@ -7,7 +7,7 @@ - reports — HyperNetX 1.0.0 documentation + reports — HyperNetX 1.0.1 documentation @@ -189,8 +189,8 @@

    reportsreports package diff --git a/docs/build/reports/reports.html b/docs/build/reports/reports.html index ce30a973..edb5cc4b 100644 --- a/docs/build/reports/reports.html +++ b/docs/build/reports/reports.html @@ -7,7 +7,7 @@ - reports package — HyperNetX 1.0.0 documentation + reports package — HyperNetX 1.0.1 documentation @@ -107,8 +107,8 @@
  • Reports @@ -195,282 +195,11 @@

    reports package

    Submodules

    -
    -

    reports.descriptive_stats module

    -
    -
    This module contains methods which compute various distributions for hypergraphs:
      -
    • Edge size distribution

    • -
    • Node degree distribution

    • -
    • Component size distribution

    • -
    • Toplex size distribution

    • -
    • Diameter

    • -
    -
    -
    -

    Also computes general hypergraph information: number of nodes, edges, cells, aspect ratio, incidence matrix density

    -
    -
    -reports.descriptive_stats.centrality_stats(X)[source]
    -

    Computes basic centrality statistics for X

    -
    -
    Parameters
    -

    X – an iterable of numbers

    -
    -
    Returns
    -

    [min, max, mean, median, standard deviation] – List of centrality statistics for X

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.comp_dist(H, aggregated=False)[source]
    -

    Computes component sizes, number of nodes.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • aggregated – If aggregated is True, returns a dictionary of -component sizes (number of nodes) and counts. If aggregated -is False, returns a list of components sizes in H.

    • -
    -
    -
    Returns
    -

    comp_dist – List of component sizes or dictionary of component size distribution

    -
    -
    Return type
    -

    list or dictionary

    -
    -
    -
    -

    See also

    -

    s_comp_dist

    -
    -
    - -
    -
    -reports.descriptive_stats.degree_dist(H, aggregated=False)[source]
    -

    Computes degrees of nodes of a hypergraph.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • aggregated – If aggregated is True, returns a dictionary of -degrees and counts. If aggregated is False, returns a -list of degrees in H.

    • -
    -
    -
    Returns
    -

    degree_dist – List of degrees or dictionary of degree distribution

    -
    -
    Return type
    -

    list or dict

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.dist_stats(H)[source]
    -

    Computes many basic hypergraph stats and puts them all into a single dictionary object

    -
    -
      -
    • nrows = number of nodes (rows in the incidence matrix)

    • -
    • ncols = number of edges (columns in the incidence matrix)

    • -
    • aspect ratio = nrows/ncols

    • -
    • ncells = number of filled cells in incidence matrix

    • -
    • density = ncells/(nrows*ncols)

    • -
    • node degree list = degree_dist(H)

    • -
    • node degree dist = centrality_stats(degree_dist(H))

    • -
    • node degree hist = Counter(degree_dist(H))

    • -
    • max node degree = max(degree_dist(H))

    • -
    • edge size list = edge_size_dist(H)

    • -
    • edge size dist = centrality_stats(edge_size_dist(H))

    • -
    • edge size hist = Counter(edge_size_dist(H))

    • -
    • max edge size = max(edge_size_dist(H))

    • -
    • comp nodes list = s_comp_dist(H, s=1, edges=False)

    • -
    • comp nodes dist = centrality_stats(s_comp_dist(H, s=1, edges=False))

    • -
    • comp nodes hist = Counter(s_comp_dist(H, s=1, edges=False))

    • -
    • comp edges list = s_comp_dist(H, s=1, edges=True)

    • -
    • comp edges dist = centrality_stats(s_comp_dist(H, s=1, edges=True))

    • -
    • comp edges hist = Counter(s_comp_dist(H, s=1, edges=True))

    • -
    • num comps = len(s_comp_dist(H))

    • -
    -
    -
    -
    Parameters
    -

    H (Hypergraph) –

    -
    -
    Returns
    -

    dist_stats – Dictionary which keeps track of each of the above items (e.g., basic[‘nrows’] = the number of nodes in H)

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.edge_size_dist(H, aggregated=False)[source]
    -

    Computes edge sizes of a hypergraph.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • aggregated – If aggregated is True, returns a dictionary of -edge sizes and counts. If aggregated is False, returns a -list of edge sizes in H.

    • -
    -
    -
    Returns
    -

    edge_size_dist – List of edge sizes or dictionary of edge size distribution.

    -
    -
    Return type
    -

    list or dict

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.info(H, node=None, edge=None)[source]
    -

    Print a summary of simple statistics for H

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • obj (optional) – either a node or edge uid from the hypergraph

    • -
    • dictionary (optional) – If True then returns the info as a dictionary rather -than a string -If False (default) returns the info as a string

    • -
    -
    -
    Returns
    -

    info – Returns a string of statistics of the size, -aspect ratio, and density of the hypergraph. -Print the string to see it formatted.

    -
    -
    Return type
    -

    string

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.info_dict(H, node=None, edge=None)[source]
    -

    Create a summary of simple statistics for H

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • obj (optional) – either a node or edge uid from the hypergraph

    • -
    -
    -
    Returns
    -

    info_dict – Returns a dictionary of statistics of the size, -aspect ratio, and density of the hypergraph.

    -
    -
    Return type
    -

    dict

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.s_comp_dist(H, s=1, aggregated=False, edges=True, return_singletons=True)[source]
    -

    Computes s-component sizes, counting nodes or edges.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • s (positive integer, default is 1) –

    • -
    • aggregated – If aggregated is True, returns a dictionary of -s-component sizes and counts in H. If aggregated is -False, returns a list of s-component sizes in H.

    • -
    • edges – If edges is True, the component size is number of edges. -If edges is False, the component size is number of nodes.

    • -
    • return_singletons (bool, optional, default=True) –

    • -
    -
    -
    Returns
    -

    s_comp_dist – List of component sizes or dictionary of component size distribution in H

    -
    -
    Return type
    -

    list or dictionary

    -
    -
    -
    -

    See also

    -

    comp_dist

    -
    -
    - -
    -
    -reports.descriptive_stats.s_edge_diameter_dist(H)[source]
    -
    -
    Parameters
    -

    H (Hypergraph) –

    -
    -
    Returns
    -

    s_edge_diameter_dist – List of s-edge-diameters for hypergraph H starting with s=1 -and going up as long as the hypergraph is s-edge-connected

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.s_node_diameter_dist(H)[source]
    -
    -
    Parameters
    -

    H (Hypergraph) –

    -
    -
    Returns
    -

    s_node_diameter_dist – List of s-node-diameters for hypergraph H starting with s=1 -and going up as long as the hypergraph is s-node-connected

    -
    -
    Return type
    -

    list

    -
    -
    -
    - -
    -
    -reports.descriptive_stats.toplex_dist(H, aggregated=False)[source]
    -

    Computes toplex sizes for hypergraph H.

    -
    -
    Parameters
    -
      -
    • H (Hypergraph) –

    • -
    • aggregated – If aggregated is True, returns a dictionary of -toplex sizes and counts in H. If aggregated -is False, returns a list of toplex sizes in H.

    • -
    -
    -
    Returns
    -

    toplex_dist – List of toplex sizes or dictionary of toplex size distribution in H

    -
    -
    Return type
    -

    list or dictionary

    -
    -
    -
    - +
    +

    reports.descriptive_stats module

    -
    -

    Module contents

    +
    +

    Module contents

    diff --git a/docs/build/search.html b/docs/build/search.html index eaeb5f89..7243c541 100644 --- a/docs/build/search.html +++ b/docs/build/search.html @@ -7,7 +7,7 @@ - Search — HyperNetX 1.0.0 documentation + Search — HyperNetX 1.0.1 documentation diff --git a/docs/build/searchindex.js b/docs/build/searchindex.js index 61908666..7f405576 100644 --- a/docs/build/searchindex.js +++ b/docs/build/searchindex.js @@ -1 +1 @@ -Search.setIndex({docnames:["algorithms/algorithms","algorithms/modules","classes/classes","classes/modules","core","drawing/drawing","drawing/modules","glossary","home","index","install","license","nwhy","overview/index","publications","reports/modules","reports/reports","widget"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":3,"sphinx.domains.rst":2,"sphinx.domains.std":2,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":2,"sphinx.ext.viewcode":1,sphinx:56},filenames:["algorithms/algorithms.rst","algorithms/modules.rst","classes/classes.rst","classes/modules.rst","core.rst","drawing/drawing.rst","drawing/modules.rst","glossary.rst","home.rst","index.rst","install.rst","license.rst","nwhy.rst","overview/index.rst","publications.rst","reports/modules.rst","reports/reports.rst","widget.rst"],objects:{"":{algorithms:[0,0,0,"-"],classes:[2,0,0,"-"],drawing:[5,0,0,"-"],reports:[16,0,0,"-"]},"algorithms.homology_mod2":{add_to_column:[0,1,1,""],add_to_row:[0,1,1,""],betti:[0,1,1,""],betti_numbers:[0,1,1,""],bkMatrix:[0,1,1,""],boundary_group:[0,1,1,""],chain_complex:[0,1,1,""],homology_basis:[0,1,1,""],hypergraph_homology_basis:[0,1,1,""],interpret:[0,1,1,""],kchainbasis:[0,1,1,""],logical_dot:[0,1,1,""],logical_matadd:[0,1,1,""],logical_matmul:[0,1,1,""],matmulreduce:[0,1,1,""],reduced_row_echelon_form_mod2:[0,1,1,""],smith_normal_form_mod2:[0,1,1,""],swap_columns:[0,1,1,""],swap_rows:[0,1,1,""]},"algorithms.s_centrality_measures":{s_betweenness_centrality:[0,1,1,""],s_closeness_centrality:[0,1,1,""],s_eccentricity:[0,1,1,""],s_harmonic_centrality:[0,1,1,""],s_harmonic_closeness_centrality:[0,1,1,""]},"classes.entity":{Entity:[2,2,1,""],EntitySet:[2,2,1,""]},"classes.entity.Entity":{add:[2,3,1,""],add_element:[2,3,1,""],add_elements_from:[2,3,1,""],children:[2,4,1,""],clone:[2,3,1,""],complete_registry:[2,3,1,""],depth:[2,3,1,""],elements:[2,4,1,""],fullregistry:[2,3,1,""],incidence_dict:[2,4,1,""],intersection:[2,3,1,""],is_bipartite:[2,4,1,""],is_empty:[2,4,1,""],level:[2,3,1,""],levelset:[2,3,1,""],memberships:[2,4,1,""],merge_entities:[2,3,1,""],nested_incidence_dict:[2,3,1,""],properties:[2,4,1,""],registry:[2,4,1,""],remove:[2,3,1,""],remove_element:[2,3,1,""],remove_elements_from:[2,3,1,""],restrict_to:[2,3,1,""],size:[2,3,1,""],uid:[2,4,1,""],uidset:[2,4,1,""]},"classes.entity.EntitySet":{add:[2,3,1,""],clone:[2,3,1,""],collapse_identical_elements:[2,3,1,""],incidence_matrix:[2,3,1,""],restrict_to:[2,3,1,""]},"classes.hypergraph":{Hypergraph:[2,2,1,""]},"classes.hypergraph.Hypergraph":{add_edge:[2,3,1,""],add_edges_from:[2,3,1,""],add_node_to_edge:[2,3,1,""],add_nwhy:[2,3,1,""],adjacency_matrix:[2,3,1,""],auxiliary_matrix:[2,3,1,""],bipartite:[2,3,1,""],collapse_edges:[2,3,1,""],collapse_nodes:[2,3,1,""],collapse_nodes_and_edges:[2,3,1,""],component_subgraphs:[2,3,1,""],components:[2,3,1,""],connected_component_subgraphs:[2,3,1,""],connected_components:[2,3,1,""],convert_to_static:[2,3,1,""],dataframe:[2,3,1,""],degree:[2,3,1,""],diameter:[2,3,1,""],dim:[2,3,1,""],distance:[2,3,1,""],dual:[2,3,1,""],edge_adjacency_matrix:[2,3,1,""],edge_diameter:[2,3,1,""],edge_diameters:[2,3,1,""],edge_distance:[2,3,1,""],edge_neighbors:[2,3,1,""],edge_size_dist:[2,3,1,""],edges:[2,4,1,""],from_bipartite:[2,3,1,""],from_dataframe:[2,3,1,""],from_numpy_array:[2,3,1,""],get_id:[2,3,1,""],get_linegraph:[2,3,1,""],get_name:[2,3,1,""],incidence_dict:[2,4,1,""],incidence_matrix:[2,3,1,""],incidence_to_adjacency:[2,3,1,""],is_connected:[2,3,1,""],isstatic:[2,4,1,""],neighbors:[2,3,1,""],node_diameters:[2,3,1,""],nodes:[2,4,1,""],number_of_edges:[2,3,1,""],number_of_nodes:[2,3,1,""],order:[2,3,1,""],recover_from_state:[2,3,1,""],remove_edge:[2,3,1,""],remove_edges:[2,3,1,""],remove_node:[2,3,1,""],remove_nodes:[2,3,1,""],remove_singletons:[2,3,1,""],remove_static:[2,3,1,""],restrict_to_edges:[2,3,1,""],restrict_to_nodes:[2,3,1,""],s_component_subgraphs:[2,3,1,""],s_components:[2,3,1,""],s_connected_components:[2,3,1,""],s_degree:[2,3,1,""],save_state:[2,3,1,""],set_state:[2,3,1,""],shape:[2,4,1,""],singletons:[2,3,1,""],size:[2,3,1,""],toplexes:[2,3,1,""],translate:[2,3,1,""]},"classes.staticentity":{StaticEntity:[2,2,1,""],StaticEntitySet:[2,2,1,""]},"classes.staticentity.StaticEntity":{arr:[2,4,1,""],children:[2,4,1,""],data:[2,4,1,""],dataframe:[2,4,1,""],dimensions:[2,4,1,""],dimsize:[2,4,1,""],elements:[2,4,1,""],elements_by_level:[2,3,1,""],incidence_dict:[2,4,1,""],incidence_matrix:[2,3,1,""],index:[2,3,1,""],indices:[2,3,1,""],is_empty:[2,3,1,""],keyindex:[2,4,1,""],keys:[2,4,1,""],labels:[2,4,1,""],labs:[2,3,1,""],level:[2,3,1,""],properties:[2,5,1,""],restrict_to_indices:[2,3,1,""],restrict_to_levels:[2,3,1,""],size:[2,3,1,""],translate:[2,3,1,""],translate_arr:[2,3,1,""],turn_entity_data_into_dataframe:[2,3,1,""],uid:[2,4,1,""],uidset:[2,4,1,""],uidset_by_level:[2,3,1,""]},"classes.staticentity.StaticEntitySet":{collapse_identical_elements:[2,3,1,""],convert_to_entityset:[2,3,1,""],incidence_matrix:[2,3,1,""],restrict_to:[2,3,1,""]},"drawing.rubber_band":{draw:[5,1,1,""],draw_hyper_edge_labels:[5,1,1,""],draw_hyper_edges:[5,1,1,""],draw_hyper_labels:[5,1,1,""],draw_hyper_nodes:[5,1,1,""],get_default_radius:[5,1,1,""],layout_hyper_edges:[5,1,1,""],layout_node_link:[5,1,1,""]},"drawing.two_column":{draw:[5,1,1,""],draw_hyper_edges:[5,1,1,""],draw_hyper_labels:[5,1,1,""],layout_two_column:[5,1,1,""]},"drawing.util":{get_frozenset_label:[5,1,1,""],get_line_graph:[5,1,1,""],get_set_layering:[5,1,1,""],inflate:[5,1,1,""],inflate_kwargs:[5,1,1,""],transpose_inflated_kwargs:[5,1,1,""]},"reports.descriptive_stats":{centrality_stats:[16,1,1,""],comp_dist:[16,1,1,""],degree_dist:[16,1,1,""],dist_stats:[16,1,1,""],edge_size_dist:[16,1,1,""],info:[16,1,1,""],info_dict:[16,1,1,""],s_comp_dist:[16,1,1,""],s_edge_diameter_dist:[16,1,1,""],s_node_diameter_dist:[16,1,1,""],toplex_dist:[16,1,1,""]},algorithms:{homology_mod2:[0,0,0,"-"],s_centrality_measures:[0,0,0,"-"]},classes:{entity:[2,0,0,"-"],hypergraph:[2,0,0,"-"],staticentity:[2,0,0,"-"]},drawing:{rubber_band:[5,0,0,"-"],two_column:[5,0,0,"-"],util:[5,0,0,"-"]},reports:{descriptive_stats:[16,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","function","Python function"],"2":["py","class","Python class"],"3":["py","method","Python method"],"4":["py","property","Python property"],"5":["py","attribute","Python attribute"]},objtypes:{"0":"py:module","1":"py:function","2":"py:class","3":"py:method","4":"py:property","5":"py:attribute"},terms:{"0":[0,2,5,7,9,12,14],"00231":[0,14],"020":[0,14],"021":14,"030":14,"04197":14,"1":[0,2,5,7,9,12,14,16],"10":[0,2,14],"1000":2,"1007":14,"1140":[0,14],"11782":14,"1186":14,"12901":14,"15":14,"16":[0,14],"17th":14,"1_1":14,"2":[0,2,5,7,12,13,14],"2003":14,"2016":0,"2018":11,"2019":14,"2020":[0,14],"22":14,"27":0,"287":14,"2d":0,"2z":0,"3":[0,2,5,10,12,13,14],"35":5,"4":[2,13],"48478":14,"5":[2,5,13],"6":[2,13],"7":[10,13],"755":10,"76rl01830":13,"9":[0,10,12,14],"978":14,"abstract":0,"boolean":[0,2,12],"case":[2,13],"class":[4,7,8,9],"default":[0,2,5,16],"do":[2,7,11,12,13],"export":12,"final":0,"float":[0,2,5],"function":[2,5],"import":2,"int":[0,2,5,14],"long":16,"new":[0,2,5,9,12],"null":10,"public":[8,9],"return":[0,2,5,7,12,16],"static":[2,13],"super":17,"switch":7,"true":[0,2,5,12,16],"while":17,A:[0,2,5,7,11,12,14],AND:11,AS:11,As:[2,8,9],BE:11,BUT:11,BY:11,By:[2,5],FOR:11,For:[0,2,5,7,8,9,10,12,13,17],IF:11,IN:11,IS:11,If:[0,2,5,7,10,12,16],In:[0,2,5,12,13],It:[2,5,12],NO:11,NOT:11,Not:2,OF:[11,13],ON:11,OR:11,One:2,SUCH:11,Such:11,THE:11,TO:11,The:[0,2,5,7,8,9,12,13,17],Then:5,These:[0,17],To:[0,2,8,9],Will:2,_0:2,_1:2,_2:[0,2],_:2,__dict__:2,_edg:2,_node:2,_version:12,ab:[2,14],about:[8,9],abov:[2,5,11,16],ac05:13,accept:[5,12],access:[7,10],accomplish:0,accord:7,account:13,accuraci:13,aco5:13,across:5,action:0,activ:[10,17],ad:[0,2,5,13],adam:14,adaptor:12,add:2,add_edg:2,add_edges_from:2,add_el:2,add_elements_from:2,add_node_to_edg:2,add_nodes_from:2,add_nwhi:2,add_to_column:0,add_to_row:0,addit:[0,2],addon:[12,13,17],adjac:[0,2,7,8,9],adjacency_matrix:2,adjust:5,admit:[8,9],advanc:17,advis:11,after:[2,12],against:2,agenc:13,aggreg:16,ah:14,aksoi:[0,13,14],al:[0,14],algebra:[8,9],algorithm:[4,5,8,9,12,13,14,17],align:5,all:[0,2,5,7,10,12,13,16,17],allow:[2,5,17],alpha:5,alreadi:[2,17],also:[2,7,8,9,12,16,17],alter:0,altern:17,ami:14,among:[8,9],amount:5,an:[0,2,5,7,9,13,16,17],anaconda3:10,anaconda:9,analysi:12,analyt:[13,14],andrew:13,angl:5,ani:[0,2,7,11,12,13,17],annot:5,anoth:[0,5,7],api:9,apparatu:13,appear:[2,17],appli:[0,2,5],applic:2,approach:5,appropri:5,ar1:0,ar2:0,ar:[0,2,5,7,8,9,10,11,12,17],arbitrari:[5,8,9],arendt:[13,14],arg:[0,2],arg_set:2,argument:[2,5],argumetn:5,aris:11,around:5,arr:[0,2],arrai:[0,2,12],articl:14,arxiv:14,asc:0,aspect:16,assign:[2,5],associ:[0,2,11,12],assum:[2,13],attribut:[2,7],author:13,automat:2,auxiliari:[2,7],auxiliary_matrix:2,avail:[0,2,17],averag:12,ax:5,axi:5,azsecur:14,b:[2,5,7,14],back:12,backend:2,background:17,band:5,baric:14,base:[0,2,5,7,12,13,17],basi:0,basic:[2,7,8,9,13,16],bat:10,battel:[11,13],bd:0,becaus:[8,9],becom:[0,2],been:[0,12],befor:2,behavior:0,behind:5,being:0,belong:[2,7,12],below:10,berg:0,best:0,betti:0,betti_numb:0,between:[0,2,5,7,12,17],big:14,binari:[0,11],bioinformat:14,biolog:14,biomedcentr:14,bipartit:[2,5,7,17],bk:0,bkmatrix:0,bmc:14,bmcbioinformat:14,book:13,bool:[0,2,5,16],both:[2,7,8,9,12,17],bound:0,boundari:[0,5],boundary_group:0,box:5,bramer:14,brenda:[13,14],brett:14,brian:13,briefest:0,browser:[10,13],bsd:13,build:[2,10],build_doc:10,built:17,bulk:17,busi:11,button:17,c:[0,2,5,9,10,12,13,14],c_:0,c_b:[0,12],c_k:0,ca:14,calcul:5,call:[5,7,12],callahan:14,can:[2,5,7,8,9,12,13,17],cannot:2,capabl:17,cardin:2,care:2,carlo:14,categori:2,caus:[2,11,17],caution:2,cdot:0,cell:[0,2,16],center:5,central:[1,4,12,13,16],centrality_stat:16,certain:2,chain:0,chain_complex:0,chang:[2,5,17],check:[2,8,9,12],child:2,children:[2,7],chmod:10,choos:2,chosen:[2,5],circl:[5,17],ck:0,classmethod:2,claus:13,click:17,cliff:[13,14],cliqu:[8,9],clone:[2,10],close:[0,12],cockrel:14,code:11,col:12,colab:[2,9],coldict:2,collaps:[2,5,12,17],collapse_edg:[2,12],collapse_identical_el:2,collapse_nod:[2,12],collapse_nodes_and_edg:[2,12],collect:[2,5],collumn:5,colon:2,color:[2,5,17],column:[0,2,5,7,12,13,16],column_index:2,com:[10,14],combin:12,come:10,command:[2,10,17],comment:[8,9,13],commerci:13,commun:[8,9,13],comp:16,comp_dist:16,compar:12,complet:[7,13,17],complete_registri:2,complex:[0,2,8,9,12,14],compon:[0,2,5,7,12,16],component_subgraph:2,comput:[0,2,5,13,14,16],concentr:5,conda:[10,12],condit:[2,7,11],conf:14,conflict:2,connect:[0,2,5,7,8,9,12,16],connected:0,connected_compon:2,connected_component_subgraph:2,consecut:2,consent:11,consequenti:11,consid:2,constitut:13,construct:[0,2,7,12,13],constructor:[2,5,12,13],contact:[8,9,13],contain:[0,2,5,7,12,16,17],content:[1,3,4,6,15],continu:10,contract:[11,13],contributor:[8,9,11,13],control:[2,17],conveni:[2,5],convert:[2,5],convert_to_entityset:2,convert_to_stat:2,convex:5,cooper:13,coord:2,coordin:5,copi:[0,2,11,12],copyright:11,core:2,correct:5,correspond:[0,2,7],coset:0,could:2,count:[2,5,16],counter:16,creat:[2,10,12,13,16],creation:2,criteria:12,critic:14,cross:5,csr:2,csr_matrix:[0,2],ctrl:17,current:12,current_st:2,curvi:5,custom:5,cybersecur:14,cycl:[0,2,5],cyclic:0,d:[0,2,12,14],damag:11,daniel:14,data:[0,2,5,8,9,11,12,13,14],data_subset:2,datafram:[2,13],de:[13,17],dedup:2,deeper:2,defaultdict:2,defin:[0,2],degre:[2,7,12,16,17],degree_dist:16,delet:2,demo:17,denorm:0,densiti:16,depart:13,depend:[2,12],deprec:2,depth:[0,2,7],deriv:2,descend:2,descript:[0,2],descriptive_stat:[4,15],design:13,desir:2,dest:12,detail:17,determin:[0,2,5],develop:[8,9,12,13],deviat:16,df:2,diagon:[0,2],diagram:[5,17],diamet:[2,7,12,16],diamond:14,dict:[0,2,5,16],dictionari:[0,2,5,7,12,16],differ:[2,12],digraph:5,dim:[0,2,12],dimens:[0,2,12],dimension:[0,2,8,9],dimensionsl:2,dimsiz:2,direct:[2,5,11,12,17],directli:[2,8,9,13,17],dirti:5,disabl:5,discard:2,disclaim:11,disclos:13,disconnect:5,discov:0,discuss:0,disjoint:[2,7],disonnecct:5,dist:16,dist_stat:16,distanc:[0,2,5,7,12],distant:5,distinct:2,distinguish:[2,7,8,9],distribut:[11,12,16],divid:0,dlfer:0,doc:10,document:[2,10,11],doe:[2,5,13],doi:[0,14],domain:[0,14],done:[2,12],dot:0,down:17,dr:5,drag:17,draw:[4,9],draw_hyper_edg:5,draw_hyper_edge_label:5,draw_hyper_label:5,draw_hyper_nod:5,drawn:5,drop:2,dual:[2,7],duplic:[0,2],dustin:[13,14],dynam:[2,7],e0:2,e1:2,e2:2,e3:2,e:[0,2,5,7,10,12,14,16,17],e_1:2,e_2:2,e_end:2,e_n:2,e_start:2,each:[0,2,5,7,12,16,17],easier:5,ecc:0,eccentr:[0,12],echelon:0,ed:14,edg:[0,2,5,7,8,9,12,13,16,17],edge_adjac:2,edge_adjacency_matrix:2,edge_column_nam:2,edge_diamet:2,edge_dist:2,edge_incid:12,edge_kwarg:5,edge_label:[2,5],edge_labels_kwarg:5,edge_nam:2,edge_neighbor:2,edge_set:2,edge_size_dist:[2,12,16],edge_uid:2,edges_kwarg:5,edges_nam:2,edgeset:2,edit:10,effect:2,eg:0,eisfeld:14,either:[2,7,12,16],element:[0,2,5,7,12],element_subset:2,elements_by_level:2,emili:[13,14],emploi:2,employe:13,empti:[2,7,12],en:2,encapsul:12,end:2,endors:13,energi:13,ensur:2,ent1:2,ent2:2,entir:17,entiti:[3,4,5,7,8,9,11,13],entityset:[2,7],entri:[0,2,7,12],env:[10,12],environ:[9,13],epj:[0,14],epjd:[0,14],eq:0,eq_class:2,equal:[0,2,7,12],equat:0,equival:[0,2,12],equivalence_class:2,error:[0,2,12],essenc:0,et:[0,14],euler:17,evalu:2,even:11,event:11,everi:[0,2,7,12,17],everyth:17,ex:[2,10],exactli:7,exampl:[0,2,5,10,13,17],exceed:2,except:7,execut:10,exemplari:11,exhibit:0,exist:[0,2,5,7],expand:[5,17],explicit:0,explor:[8,9],expos:2,express:[11,13],ext:0,extend:17,extens:10,f:14,facecolor:5,fail:2,fals:[0,2,5,12,16],fan:14,fast:2,faster:12,favor:13,featur:[0,9],feng:14,ferrario:0,figur:5,file:[2,10,11],filepath:2,fill:16,fillna:2,filter:12,find:[5,8,9],firoz:14,first:[2,5],firstlevel:2,fit:11,fix:2,flexibl:2,fly:12,follow:[2,5,10,11,13],forc:17,fork:10,form:[1,4,11],format:[2,12,16],forth:12,found:[2,8,9],four:13,fpath:2,frac:12,fraction:[5,12],frame:2,from:[0,2,5,7,10,12,14,16,17],from_bipartit:[2,7],from_datafram:2,from_numpy_arrai:2,frozen:2,frozenset:2,fruchterman_reingold_layout:5,full:2,fullregistri:2,further:5,g:[0,5,12,14,16],gene:14,gener:[0,2,5,7,8,9,10,16],get_default_radiu:5,get_frozenset_label:5,get_id:2,get_line_graph:5,get_linegraph:2,get_nam:2,get_set_lay:5,get_singleton:12,github:[10,17],give:[2,17],given:[0,2,5,7,12],glossari:9,go:16,goal:12,good:[0,11],googl:13,gotten:2,gov:[8,9,13],govern:13,grant:11,graph:[0,2,5,7,8,9,12,14,17],greater:[0,2],group:0,grow:[8,9,13],guarante:5,h:[0,2,5,16],h_k:0,ha:[2,7,12,13,17],halfmann:14,handl:5,harmon:[0,12],hashabl:2,have:[0,2,5,7,8,9,12,13,17],header:[2,13],heath:14,held:2,heller:14,help:17,helper:[2,5],henc:2,henri:14,here:[12,17],herebi:11,herein:[11,13],hereinaft:11,hicss:14,hidden:17,hide:17,high:[0,12,13,14],higher:0,highlight:13,hist:16,hit:17,hnx:[0,2,10,12,13,17],hnxwidget:17,hold:17,holder:11,home:9,homolog:[1,4,8,9,13],homology_basi:0,homology_mod2:[1,4],honor:2,howev:11,hpda:13,html:10,http:[0,10,14],hugh:14,hull:5,hunter:14,hyper:[2,5,7,17],hyperedg:[2,7,8,9,12],hypergraph:[0,3,4,5,7,8,9,12,13,14,16,17],hypergraph_homology_basi:0,hypergraphedg:2,hypernet:13,hypernetwork:[0,14],hypernetx:[2,11,13],hypernetxerror:[0,2],hypernetxwidget:17,i:[0,2,7,12,17],i_m:0,i_n:0,icc:14,id:[2,5,7,12],ideal:0,ident:[0,2,5,17],identifi:[0,2,14],idx:2,ignacio:14,ignor:[0,2],illustr:5,im:0,imag:0,image_basi:0,immut:2,implement:12,impli:[5,11,13],impos:7,improv:17,incid:[2,7,8,9,12,16],incidence_dict:2,incidence_matrix:2,incidence_to_adjac:2,incident:11,includ:[2,8,9,11],inclus:[0,2],inde:2,independ:[5,17],index:[0,2,7,9,10],indic:[0,2,12],indirect:11,induc:[2,7],inf:2,infin:2,infinit:7,inflat:5,inflate_kwarg:5,info:16,info_dict:16,inform:[2,13,16],infring:13,inner:0,inseper:2,insert:2,insid:2,inspect:13,instal:[2,9],instanc:[2,7],instanti:[2,7],instead:[2,5,12],institut:[11,13],instruct:10,integ:[0,2,5,7,12,16],intend:5,intens:2,inter:2,interact:[13,17],interest:[0,2],interfac:17,intern:2,interpret:[0,12],interpreted_basi:0,interrupt:11,intersect:[0,2,5,7],intuit:7,invers:0,invert:0,investig:13,invis:5,is_bipartit:2,is_connect:2,is_empti:2,is_s_connect:12,isn:2,isomorph:[2,7],isstat:2,item:[2,5,16],iter:[0,2,5,16],ith:0,iti:7,its:[0,2,5,7,12,13,17],itself:[2,7],j:[0,7,14],jacob:14,jason:14,javascript:[13,17],jefferson:14,jenkin:14,ji:13,joslyn:[0,13,14],jth:0,jupyt:[10,13],jurisdict:13,k:[0,2,7],kaminski:14,katrina:14,kawaoka:14,kbasi:0,kchain:0,kchainbasi:0,kdx:2,keep:[2,16,17],kei:[0,2,5,7,12],kelli:14,kernel:0,kevin:14,keyindex:2,keyword:[2,5],km1basi:0,known:2,kocher:14,krang:0,kritzstein:13,kth:0,kving:14,kwarg:[0,2,5],l:[0,12,14],lab:2,label:[0,2,5],label_alpha:5,laboratori:13,larg:2,larger:17,largest:2,larissa:14,last:2,lastlevel:2,latter:2,lawfulli:11,layer:5,layout:5,layout_hyper_edg:5,layout_kwarg:5,layout_node_link:5,layout_two_column:5,le:14,learn:[8,9],leas:7,least:[2,5,7],lectur:14,left:[0,5],legal:13,len:16,length:[0,2,5,7,8,9],lesmi:13,less:[0,2,12],let:2,level1:2,level2:2,level:[2,5,7],levelset:[2,7],liabil:[11,13],liabl:11,librari:[0,2,8,9,12,13],licens:9,like:[2,5],limit:[2,11],line:[0,2,5,12],linecollect:5,linegraph:[0,2,7],linewidth:5,link:[2,17],linux:[10,13],linv:0,lisa:14,list:[0,2,5,11,12,16],liu:[12,13],llinv:0,lm:0,lmr:0,local:12,locat:[5,10,17],logic:0,logical_dot:0,logical_matadd:0,logical_matmul:0,longer:2,longest:[0,2],look:0,loss:11,loui:14,lower:5,lumsdain:13,m:[0,2,14],mac:[10,17],made:2,mai:[2,7,8,9,10,11,13,17],main:17,make:[2,5,13],manag:13,mani:[2,12,16],manipul:2,manual:5,manufactur:13,map:[0,5],marcin:14,mark:13,marrero:[0,14],mat1:0,mat2:0,mat:0,match:2,materi:13,mathbb:0,mathemat:13,matmulreduc:0,matplotlib:[5,10],matric:[0,5],matrix:[0,2,7,12,16],max:[0,16],max_degre:12,max_depth:2,max_level:2,max_siz:[2,12],maxim:[2,7],maximum:[2,7],maxlevel:2,mcdermott:14,mean:[0,2,16],measur:[1,4,13],median:[5,16],member:2,membership:[2,5,7,17],memori:[11,12,13],menacheri:14,merchant:11,merg:[2,11],merge_ent:2,method:[0,2,7,8,9,13,16],metric:[0,8,9,13],michael:14,might:17,min:[0,16],min_degre:12,min_level:2,min_siz:12,minim:[0,5,10,17],minimum:[2,5],minlevel:2,minu:[0,2],miss:5,mitchel:14,mod2:[1,4,13],mod:0,model:[8,9,13,14],modestli:2,modif:11,modifi:11,modul:[1,3,4,6,9,15],modulo:0,more:[2,7,8,9,10,12],most:[2,5,8,9],much:12,multi:[2,8,9],multidimension:14,multipl:[0,2,7,12,17],multipli:0,multiwai:[8,9],must:[0,2,11,12],mxn:0,n:[0,2,5,7,10,12],nama:2,name:[2,10,11,12,13,14,17],nan:2,natali:14,nation:13,natur:[8,9],navig:2,ncell:16,ncol:16,ndarrai:[0,2],necessarili:13,need:[0,2,5,10],neglig:11,neighbor:[2,12],neither:[11,13],neq:12,nest:2,nested_incidence_dict:2,network:[2,8,9,14],networkx:[2,5],netwrokx:5,newfpath:2,newuid:2,node:[0,2,5,7,12,13,16,17],node_column_nam:2,node_diamet:2,node_incid:12,node_label:[2,5],node_labels_kwarg:5,node_nam:2,node_radiu:5,node_set:2,node_size_dist:12,nodes_kwarg:5,nodes_nam:2,nodeset:2,non:[0,7],none:[0,2,5,12,16],nonempti:[2,7],nonexist:2,nonzero:7,nor:13,normal:[1,4,12],northwest:13,note:[0,2,7,10,12,14],notebook:[10,13],noth:2,notic:[9,11],np:[0,2],nrow:16,num:16,number:[0,2,5,7,12,16],number_of_edg:[2,12],number_of_nod:[2,12],numer:2,numpi:[0,2,5,12],nwgraph:12,nwhy:[0,2,9,10,13],nwhypergraph:[2,9],nx2:5,nx:[2,5,7],nxm:0,o:14,obj:16,object:[2,7,12,13,16],obtain:[0,2,7,11],occupi:7,occur:2,off:2,offer:2,offset:5,onc:[10,13],one:[0,2,5,7,12],oneapi:12,onetbb:12,onli:[0,2,7,10,12],open:10,oper:13,opinion:13,opt:12,optim:[5,9,12,13,17],option:[0,2,9,16],order:[0,2,5,14],ordereddict:2,org:[0,14],organ:13,orient:5,origin:[0,2,12],ortiz:0,osx:10,other:[0,2,5,7,11,12],otherwis:[2,7,10,11,12,13],our:[0,8,9],out:[0,5,8,9,11],outlin:17,output:2,outsid:2,over:[0,5,7,12],overlap:[5,12],overrid:5,overview:9,own:[7,13],p:[0,2,14],pacif:13,packag:[1,3,6,9,15],page:9,pair:[0,2,5,7,12],pairwis:2,panda:[2,13],paper:5,parallel:[5,12],param:2,paramet:[0,2,5,16],part:[5,13],partial_k:0,particular:[2,8,9,11,13],partit:[2,7],pass:[0,2,5,12],path:[0,2,5,8,9,10,12],pathogen:14,pd:2,perfect:17,perform:[2,12,13,14,17],permiss:11,permit:11,person:11,peter:14,pickl:2,pin:17,pip:[9,17],place:2,placehold:2,placement:17,planar:5,pleas:2,plot:5,pnnl:[8,9,10,13],po:5,point:5,poli:5,polycollect:5,polygon:5,poset:2,posit:[0,2,5,7,12,16,17],possibl:[5,11,17],post:0,power:[8,9],powershel:10,pp:14,practic:2,praggasti:[13,14],pre:5,precis:7,prefil:2,preliminari:12,prepar:13,prepend:2,present:2,preserv:[2,17],press:14,princip:13,principl:13,print:[0,16],prior:2,privat:13,proc:14,process:[2,12,13],procur:11,product:[0,13],profit:11,program:13,project:13,prompt:10,prop:2,properli:7,properti:[2,7,12,17],provid:[0,2,5,8,9,11,12],ps1:10,publish:11,purpos:[0,11],purvin:[13,14],put:16,py:7,pybind11:12,pytest:10,python:[10,12],qing:14,quantiti:[8,9],question:[8,9,13],quick:5,quit:2,r0:5,r:[0,5],rac:0,radiu:5,rais:[0,2],ralph:14,rang:[0,5],rather:16,ratio:[0,16],rauga:13,re:17,reachabl:12,read:[5,13],real:2,reason:[2,5],receiv:2,reciproc:[0,12],recommend:[2,5,13],recov:2,recover_from_st:2,rectangular:[0,7],recurs:0,redistribut:11,reduc:[0,5],reduced_row_echelon_form_mod2:0,refer:[2,13],referenc:[0,2],reflect:[2,13],regist:2,registri:[2,7],rel:[0,17],relat:[2,8,9],relationship:[0,2,8,9,14],releas:[13,17],remov:[2,17],remove_edg:2,remove_el:2,remove_elements_from:2,remove_nod:2,remove_singleton:2,remove_stat:2,render:5,rep:2,repeatedli:0,replac:[0,2],report:[4,9],repositori:[8,9],repres:[0,2,5,7,8,9,13],represent:[0,5,12],reproduc:[5,11],request:2,requir:[0,2,12],research:[8,9,13],reserv:5,respect:[0,2],respons:[13,14],restrict:[2,7],restrict_to:2,restrict_to_edg:2,restrict_to_indic:2,restrict_to_level:2,restrict_to_nod:2,result:[5,17],retain:11,retriev:2,return_count:2,return_equal_class:12,return_equivalence_class:2,return_index:2,return_po:5,return_singleton:[0,2,16],revers:[0,2,17],rich:12,right:[0,5,13],rigor:5,ring:5,role:[2,7],root:2,row:[0,2,7,12,16],rowdict:2,rubber:5,rubber_band:[4,6],run:[10,12,13],s12859:14,s13688:[0,14],s:[1,2,4,5,7,12,13,14,16],s_betweenness_centr:[0,12],s_centrality_measur:[1,4],s_closeness_centr:[0,12],s_comp_dist:16,s_compon:2,s_component_subgraph:2,s_components_subgraph:2,s_connect:2,s_connected_compon:[2,12],s_degre:[2,12],s_diamet:12,s_distanc:12,s_eccentr:[0,12],s_edge_connect:2,s_edge_diameter_dist:16,s_harmonic_centr:0,s_harmonic_closeness_centr:[0,12],s_linegraph:12,s_neighbor:12,s_node_diameter_dist:16,s_path:12,same:[0,2,5,7,12],sampl:2,satifi:2,satisfi:[2,7],save:2,save_st:2,scalabl:12,sci:0,scienc:[0,14],scip:2,scipi:[0,2],score:12,script:10,search:9,second:2,see:[2,5,7,10,13,16],self:2,sell:11,sens:7,sensibl:5,sequenc:[2,7],serv:[8,9],servic:[11,13],set:[0,2,5,7,8,9,12,17],set_nam:2,set_stat:2,setsystem:2,sh:10,shabang:10,shall:11,shallow:2,shape:2,share:[2,7,12],sheahan:14,shift:17,shortest:[0,2,7,12],shortest_path_length:2,should:[0,2,5],show:17,shufang:14,side:[0,2],sigma:[0,12],signatur:2,significantli:12,sim:14,similar:[2,17],simpl:[0,2,7,16],simplic:[8,9],simplici:[0,8,9],sinan:[13,14],sinc:[2,7,8,9],singl:[0,2,7,16],singleton:[0,2,8,9,12],size:[0,2,5,7,12,16,17],slightli:17,slower:12,small:[0,2,5],smaller:5,smallest:2,smith:[1,4,14],smith_normal_form_mod2:0,snf:0,so:[2,5,11],softwar:[11,13],some:[7,8,9,10],sometim:[5,17],song:14,sort:2,sort_column:2,sort_row:2,sortabl:[0,2],sourc:[0,2,5,10,11,16],space:[5,12],spars:[0,2,12],special:11,specif:[2,7,13],specifi:[2,5,10,12,17],spectral:5,sped:13,sponsor:13,spring_layout:5,springer:14,squar:7,src:12,stack:5,standard:16,start:[0,2,5,16,17],stat:16,state:[2,13,17],state_dict:2,staticent:[3,4],staticentityset:2,statist:16,still:2,storag:2,store:[0,2,12],str:[0,2],stratton:14,strict:[8,9,11],string:[2,5,16],structur:[2,7,8,9,12],studi:[8,9,13],style:5,subgraph:[0,2],subhypergraph:7,subject:11,sublicens:11,submatrix:7,submit:2,submodul:[1,3,4,6,15],subset:[2,5,7],substitut:11,subtract:2,success:7,sum:[0,12],sum_:[0,12],summari:16,suppli:5,support:[2,13],sure:2,surround:5,swap:0,swap_column:0,swap_row:0,symp:14,system:[2,5,8,9,10,14],t:[0,2,12],tabl:17,take:[2,5],tan:14,target:2,tbb:10,tbbroot:12,techniqu:5,tell:[8,9],tensor:2,term:[0,2],test:10,text:5,textbook:5,thackrai:14,than:[0,2,7,11,16],thei:[2,5,7,8,9,17],them:[2,7,10,16,17],theori:11,therebi:[8,9],therefor:[2,12],thereof:13,thi:[0,2,5,7,8,9,10,11,12,13,16,17],think:2,those:[0,13],three:12,through:[0,5,12],tiffani:14,time:[0,17],timothi:14,todo:2,togeth:[0,5],toggl:17,toni:[12,13],tool:[8,9],toolbar:17,toplex:[0,2,7,12,16],toplex_dist:16,topolog:[0,8,9,14],tort:11,total:0,tour:13,track:[0,2,16],trade:13,trademark:13,tradit:17,transform:[0,2],translat:2,translate_arr:2,transpar:5,transpos:2,transpose_inflated_kwarg:5,travers:17,treat:2,triloop:13,tripodi:14,trivial:0,truthi:2,tupl:[0,2],turn_entity_data_into_datafram:2,tutori:[2,9,10],two:[0,2,5,7,12,17],two_column:[4,6],type:[0,2,5,16],typic:5,u:[0,5,12],uid:[0,2,7,16],uidset:[2,7],uidset_by_level:2,un:17,under:[12,13],undesir:2,undirect:12,uniform:0,uniqu:[2,7],unit:13,unless:2,unpack:2,unreach:12,unweight:[2,7,12],up:[2,13,16],updat:2,upgrad:12,upon:17,us:[0,2,5,7,8,9,11,13],use_nwhi:[0,2],use_rep:2,user:[2,8,9,10,12,13,17],usual:5,util:[4,6],v0:2,v1:2,v2:2,v:[0,2,5,12,14],v_1:2,v_2:2,v_end:2,v_n:2,v_start:2,valu:[0,2,5,7,12],variou:[12,16],ve:13,vector:0,verifi:0,version:[9,10,12],vertex:[0,5,8,9,12],vertic:[0,2,5,12],via:[0,14],view:13,vineet:14,viral:14,virtual:10,virtualenv:9,visibl:17,visual:[9,13,17],vn:2,w:2,wa:[2,12,13],wai:[2,5,8,9,11],walk:[0,2,7,8,9,14],walter:14,want:[0,17],warranti:[11,13],water:14,waw:14,we:[0,2,8,9,12,13],web:14,weight:[2,7,12],well:[5,17],westhoff:14,what:[8,9],whatsoev:11,when:[2,12],whera:17,where:[0,2,5,7,12],whether:[2,11,12],which:[0,2,5,7,16,17],whitespac:5,whole:10,whose:[5,7,12],widget:[9,13],width:[2,7,8,9],window:[10,17],wish:10,with_color:5,with_edge_count:5,with_edge_label:5,with_node_count:5,with_node_label:5,within:[2,5,17],without:[11,17],work:[0,2,5,10,13],would:[2,13],wrangl:2,wrap:5,written:11,wshop:14,www:[0,14],x:[2,5,12,16],xor:0,xu:12,xx:2,xy:5,xyz:0,y:[2,5,12],yet:2,yield:2,yoshihiro:14,you:[2,5,8,9,10,13,17],young:13,your:[2,10,13],yun:13,z:[0,2],z_2:0,zalewski:14,zero:2},titles:["algorithms package","algorithms","classes package","classes","HyperNetX Packages","drawing package","drawing","Glossary of HNX terms","HyperNetX (HNX)","HyperNetX (HNX)","Installing HyperNetX","License","NWHy","Overview","Publications","reports","reports package","Hypernetx-Widget"],titleterms:{"0":13,"1":13,"class":[2,3,12],"import":12,"new":13,"public":14,Then:12,To:[10,12],activ:12,algorithm:[0,1],an:[10,12],anaconda:[10,12],api:12,attribut:12,block:12,build:12,central:0,colab:13,content:[0,2,5,9,16],descript:[8,9,12],descriptive_stat:16,draw:[5,6],entiti:2,environ:[10,12],featur:[13,17],form:0,glossari:7,hnx:[7,8,9],homolog:0,homology_mod2:0,hypergraph:2,hypernetx:[4,8,9,10,17],indic:9,instal:[10,12,17],intel:12,layout:17,licens:[11,13],measur:0,method:12,mod2:0,modul:[0,2,5,12,16],normal:0,notic:13,nwhy:12,nwhypergraph:12,option:10,other:17,overview:[13,17],packag:[0,2,4,5,16],panel:17,pip:[10,12],quick:12,report:[15,16],rubber_band:5,s:0,s_centrality_measur:0,select:17,side:17,slinegraph:12,smith:0,staticent:2,submodul:[0,2,5,16],tabl:9,tbb:12,term:7,test:12,thread:12,tool:17,tutori:13,two_column:5,us:[10,12,17],util:5,version:13,virtualenv:10,widget:17}}) \ No newline at end of file +Search.setIndex({docnames:["algorithms/algorithms","algorithms/modules","classes/classes","classes/modules","core","drawing/drawing","drawing/modules","glossary","home","index","install","license","nwhy","overview/index","publications","reports/modules","reports/reports","widget"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":3,"sphinx.domains.rst":2,"sphinx.domains.std":2,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":2,"sphinx.ext.viewcode":1,sphinx:56},filenames:["algorithms/algorithms.rst","algorithms/modules.rst","classes/classes.rst","classes/modules.rst","core.rst","drawing/drawing.rst","drawing/modules.rst","glossary.rst","home.rst","index.rst","install.rst","license.rst","nwhy.rst","overview/index.rst","publications.rst","reports/modules.rst","reports/reports.rst","widget.rst"],objects:{},objnames:{},objtypes:{},terms:{"0":[7,9,12,14],"00231":14,"020":14,"021":14,"030":14,"04197":14,"1":[7,9,12,14],"10":14,"1007":14,"1140":14,"11782":14,"1186":14,"12901":14,"15":14,"16":14,"17th":14,"1_1":14,"2":[7,12,13,14],"2003":14,"2018":11,"2019":14,"2020":14,"22":14,"287":14,"3":[10,12,13,14],"4":13,"48478":14,"5":13,"6":13,"7":[10,13],"755":10,"76rl01830":13,"9":[10,12,14],"978":14,"boolean":12,"case":13,"class":[4,7,8,9],"do":[7,11,12,13],"export":12,"int":14,"new":[9,12],"null":10,"public":[8,9],"return":[7,12],"static":13,"super":17,"switch":7,"true":12,"while":17,A:[7,11,12,14],AND:11,AS:11,As:[8,9],BE:11,BUT:11,BY:11,FOR:11,For:[7,8,9,10,12,13,17],IF:11,IN:11,IS:11,If:[7,10,12],In:[12,13],It:12,NO:11,NOT:11,OF:[11,13],ON:11,OR:11,SUCH:11,Such:11,THE:11,TO:11,The:[7,8,9,12,13,17],These:17,To:[8,9],_version:12,ab:14,about:[8,9],abov:11,ac05:13,accept:12,access:[7,10],accord:7,account:13,accuraci:13,aco5:13,activ:[10,17],ad:13,adam:14,adaptor:12,addon:[12,13,17],adjac:[7,8,9],admit:[8,9],advanc:17,advis:11,after:12,agenc:13,ah:14,aksoi:[13,14],al:14,algebra:[8,9],algorithm:[4,8,9,12,13,14,17],all:[7,10,12,13,17],allow:17,alreadi:17,also:[7,8,9,12,17],altern:17,ami:14,among:[8,9],an:[7,9,13,17],anaconda3:10,anaconda:9,analysi:12,analyt:[13,14],andrew:13,ani:[7,11,12,13,17],anoth:7,api:9,apparatu:13,appear:17,ar:[7,8,9,10,11,12,17],arbitrari:[8,9],arendt:[13,14],aris:11,arrai:12,articl:14,arxiv:14,associ:[11,12],assum:13,attribut:7,author:13,auxiliari:7,avail:17,averag:12,azsecur:14,b:[7,14],back:12,background:17,baric:14,base:[7,12,13,17],basic:[7,8,9,13],bat:10,battel:[11,13],becaus:[8,9],been:12,belong:[7,12],below:10,between:[7,12,17],big:14,binari:11,bioinformat:14,biolog:14,biomedcentr:14,bipartit:[7,17],bmc:14,bmcbioinformat:14,book:13,both:[7,8,9,12,17],bramer:14,brenda:[13,14],brett:14,brian:13,browser:[10,13],bsd:13,build:10,build_doc:10,built:17,bulk:17,busi:11,button:17,c:[9,10,12,13,14],c_b:12,ca:14,call:[7,12],callahan:14,can:[7,8,9,12,13,17],capabl:17,carlo:14,caus:[11,17],central:[12,13],chang:17,check:[8,9,12],children:7,chmod:10,circl:17,claus:13,click:17,cliff:[13,14],cliqu:[8,9],clone:10,close:12,cockrel:14,code:11,col:12,colab:9,collaps:[12,17],collapse_edg:12,collapse_nod:12,collapse_nodes_and_edg:12,color:17,column:[7,12,13],com:[10,14],combin:12,come:10,command:[10,17],comment:[8,9,13],commerci:13,commun:[8,9,13],compar:12,complet:[7,13,17],complex:[8,9,12,14],compon:[7,12],comput:[13,14],conda:[10,12],condit:[7,11],conf:14,connect:[7,8,9,12],consent:11,consequenti:11,constitut:13,construct:[7,12,13],constructor:[12,13],contact:[8,9,13],contain:[7,12,17],content:[1,3,4,6,15],continu:10,contract:[11,13],contributor:[8,9,11,13],control:17,cooper:13,copi:[11,12],copyright:11,correspond:7,creat:[10,12,13],criteria:12,critic:14,ctrl:17,current:12,cybersecur:14,d:[12,14],damag:11,daniel:14,data:[8,9,11,12,13,14],datafram:13,de:[13,17],degre:[7,12,17],demo:17,depart:13,depend:12,depth:7,descriptive_stat:[4,15],design:13,dest:12,detail:17,develop:[8,9,12,13],diagram:17,diamet:[7,12],diamond:14,dictionari:[7,12],differ:12,dim:12,dimens:12,dimension:[8,9],direct:[11,12,17],directli:[8,9,13,17],disclaim:11,disclos:13,disjoint:7,distanc:[7,12],distinguish:[7,8,9],distribut:[11,12],doc:10,document:[10,11],doe:13,doi:14,domain:14,done:12,down:17,drag:17,draw:[4,9],dual:7,dustin:[13,14],dynam:7,e:[7,10,12,14,17],each:[7,12,17],eccentr:12,ed:14,edg:[7,8,9,12,13,17],edge_incid:12,edge_size_dist:12,edit:10,eisfeld:14,either:[7,12],element:[7,12],emili:[13,14],employe:13,empti:[7,12],encapsul:12,endors:13,energi:13,entir:17,entiti:[3,4,7,8,9,11,13],entityset:7,entri:[7,12],env:[10,12],environ:[9,13],epj:14,epjd:14,equal:[7,12],equival:12,error:12,et:14,euler:17,even:11,event:11,everi:[7,12,17],everyth:17,ex:10,exactli:7,exampl:[10,13,17],except:7,execut:10,exemplari:11,exist:7,expand:17,explor:[8,9],express:[11,13],extend:17,extens:10,f:14,fals:12,fan:14,faster:12,favor:13,featur:9,feng:14,file:[10,11],filter:12,find:[8,9],firoz:14,fit:11,fly:12,follow:[10,11,13],forc:17,fork:10,form:11,format:12,forth:12,found:[8,9],four:13,frac:12,fraction:12,from:[7,10,12,14,17],from_bipartit:7,g:[12,14],gene:14,gener:[7,8,9,10],get_singleton:12,github:[10,17],give:17,given:[7,12],glossari:9,goal:12,good:11,googl:13,gov:[8,9,13],govern:13,grant:11,graph:[7,8,9,12,14,17],grow:[8,9,13],ha:[7,12,13,17],halfmann:14,harmon:12,have:[7,8,9,12,13,17],header:13,heath:14,heller:14,help:17,henri:14,here:[12,17],herebi:11,herein:[11,13],hereinaft:11,hicss:14,hidden:17,hide:17,high:[12,13,14],highlight:13,hit:17,hnx:[10,12,13,17],hnxwidget:17,hold:17,holder:11,home:9,homolog:[8,9,13],homology_mod2:[1,4],howev:11,hpda:13,html:10,http:[10,14],hugh:14,hunter:14,hyper:[7,17],hyperedg:[7,8,9,12],hypergraph:[3,4,7,8,9,12,13,14,17],hypernet:13,hypernetwork:14,hypernetx:[11,13],hypernetxwidget:17,i:[7,12,17],icc:14,id:[7,12],ident:17,identifi:14,ignacio:14,implement:12,impli:[11,13],impos:7,improv:17,incid:[7,8,9,12],incident:11,includ:[8,9,11],independ:17,index:[7,9,10],indic:12,indirect:11,induc:7,infinit:7,inform:13,infring:13,inspect:13,instal:9,instanc:7,instanti:7,instead:12,institut:[11,13],instruct:10,integ:[7,12],interact:[13,17],interfac:17,interpret:12,interrupt:11,intersect:7,intuit:7,investig:13,is_s_connect:12,isomorph:7,iti:7,its:[7,12,13,17],itself:7,j:[7,14],jacob:14,jason:14,javascript:[13,17],jefferson:14,jenkin:14,ji:13,joslyn:[13,14],jupyt:[10,13],jurisdict:13,k:7,kaminski:14,katrina:14,kawaoka:14,keep:17,kei:[7,12],kelli:14,kevin:14,kocher:14,kritzstein:13,kving:14,l:[12,14],laboratori:13,larger:17,larissa:14,lawfulli:11,le:14,learn:[8,9],leas:7,least:7,lectur:14,legal:13,length:[7,8,9],lesmi:13,less:12,level:7,levelset:7,liabil:[11,13],liabl:11,librari:[8,9,12,13],licens:9,limit:11,line:12,linegraph:7,link:17,linux:[10,13],lisa:14,list:[11,12],liu:[12,13],local:12,locat:[10,17],loss:11,loui:14,lumsdain:13,m:14,mac:[10,17],mai:[7,8,9,10,11,13,17],main:17,make:13,manag:13,mani:12,manufactur:13,marcin:14,mark:13,marrero:14,materi:13,mathemat:13,matplotlib:10,matrix:[7,12],max_degre:12,max_siz:12,maxim:7,maximum:7,mcdermott:14,measur:13,membership:[7,17],memori:[11,12,13],menacheri:14,merchant:11,merg:11,method:[7,8,9,13],metric:[8,9,13],michael:14,might:17,min_degre:12,min_siz:12,minim:[10,17],mitchel:14,mod2:13,model:[8,9,13,14],modif:11,modifi:11,modul:[1,3,4,6,9,15],more:[7,8,9,10,12],most:[8,9],much:12,multi:[8,9],multidimension:14,multipl:[7,12,17],multiwai:[8,9],must:[11,12],n:[7,10,12],name:[10,11,12,13,14,17],natali:14,nation:13,natur:[8,9],necessarili:13,need:10,neglig:11,neighbor:12,neither:[11,13],neq:12,network:[8,9,14],node:[7,12,13,17],node_incid:12,node_size_dist:12,non:7,none:12,nonempti:7,nonzero:7,nor:13,normal:12,northwest:13,note:[7,10,12,14],notebook:[10,13],notic:[9,11],number:[7,12],number_of_edg:12,number_of_nod:12,numpi:12,nwgraph:12,nwhy:[9,10,13],nwhypergraph:9,nx:7,o:14,object:[7,12,13],obtain:[7,11],occupi:7,onc:[10,13],one:[7,12],oneapi:12,onetbb:12,onli:[7,10,12],open:10,oper:13,opinion:13,opt:12,optim:[9,12,13,17],option:9,order:14,org:14,organ:13,origin:12,osx:10,other:[7,11,12],otherwis:[7,10,11,12,13],our:[8,9],out:[8,9,11],outlin:17,over:[7,12],overlap:12,overview:9,own:[7,13],p:14,pacif:13,packag:[1,3,6,9,15],page:9,pair:[7,12],panda:13,parallel:12,part:13,particular:[8,9,11,13],partit:7,pass:12,path:[8,9,10,12],pathogen:14,perfect:17,perform:[12,13,14,17],permiss:11,permit:11,person:11,peter:14,pin:17,pip:[9,17],placement:17,pnnl:[8,9,10,13],posit:[7,12,17],possibl:[11,17],power:[8,9],powershel:10,pp:14,praggasti:[13,14],precis:7,preliminari:12,prepar:13,preserv:17,press:14,princip:13,principl:13,privat:13,proc:14,process:[12,13],procur:11,product:13,profit:11,program:13,project:13,prompt:10,properli:7,properti:[7,12,17],provid:[8,9,11,12],ps1:10,publish:11,purpos:11,purvin:[13,14],py:7,pybind11:12,pytest:10,python:[10,12],qing:14,quantiti:[8,9],question:[8,9,13],ralph:14,rauga:13,re:17,reachabl:12,read:13,reciproc:12,recommend:13,rectangular:7,redistribut:11,refer:13,reflect:13,registri:7,rel:17,relat:[8,9],relationship:[8,9,14],releas:[13,17],remov:17,report:[4,9],repositori:[8,9],repres:[7,8,9,13],represent:12,reproduc:11,requir:12,research:[8,9,13],respons:[13,14],restrict:7,result:17,retain:11,return_equal_class:12,revers:17,rich:12,right:13,role:7,row:[7,12],rubber_band:[4,6],run:[10,12,13],s12859:14,s13688:14,s:[7,12,13,14],s_betweenness_centr:12,s_centrality_measur:[1,4],s_closeness_centr:12,s_connected_compon:12,s_degre:12,s_diamet:12,s_distanc:12,s_eccentr:12,s_harmonic_closeness_centr:12,s_linegraph:12,s_neighbor:12,s_path:12,same:[7,12],satisfi:7,scalabl:12,scienc:14,score:12,script:10,search:9,see:[7,10,13],sell:11,sens:7,sequenc:7,serv:[8,9],servic:[11,13],set:[7,8,9,12,17],sh:10,shabang:10,shall:11,share:[7,12],sheahan:14,shift:17,shortest:[7,12],show:17,shufang:14,sigma:12,significantli:12,sim:14,similar:17,simpl:7,simplic:[8,9],simplici:[8,9],sinan:[13,14],sinc:[7,8,9],singl:7,singleton:[8,9,12],size:[7,12,17],slightli:17,slower:12,smith:14,so:11,softwar:[11,13],some:[7,8,9,10],sometim:17,song:14,sourc:[10,11],space:12,spars:12,special:11,specif:[7,13],specifi:[10,12,17],sped:13,sponsor:13,springer:14,squar:7,src:12,start:17,state:[13,17],staticent:[3,4],store:12,stratton:14,strict:[8,9,11],structur:[7,8,9,12],studi:[8,9,13],subhypergraph:7,subject:11,sublicens:11,submatrix:7,submodul:[1,3,4,6,15],subset:7,substitut:11,success:7,sum:12,sum_:12,support:13,symp:14,system:[8,9,10,14],t:12,tabl:17,tan:14,tbb:10,tbbroot:12,tell:[8,9],test:10,thackrai:14,than:[7,11],thei:[7,8,9,17],them:[7,10,17],theori:11,therebi:[8,9],therefor:12,thereof:13,thi:[7,8,9,10,11,12,13,17],those:13,three:12,through:12,tiffani:14,time:17,timothi:14,toggl:17,toni:[12,13],tool:[8,9],toolbar:17,toplex:[7,12],topolog:[8,9,14],tort:11,tour:13,trade:13,trademark:13,tradit:17,travers:17,triloop:13,tripodi:14,tutori:[9,10],two:[7,12,17],two_column:[4,6],u:12,uid:7,uidset:7,un:17,under:[12,13],undirect:12,uniqu:7,unit:13,unreach:12,unweight:[7,12],up:13,upgrad:12,upon:17,us:[7,8,9,11,13],user:[8,9,10,12,13,17],util:[4,6],v:[12,14],valu:[7,12],variou:12,ve:13,version:[9,10,12],vertex:[8,9,12],vertic:12,via:14,view:13,vineet:14,viral:14,virtual:10,virtualenv:9,visibl:17,visual:[9,13,17],wa:[12,13],wai:[8,9,11],walk:[7,8,9,14],walter:14,want:17,warranti:[11,13],water:14,waw:14,we:[8,9,12,13],web:14,weight:[7,12],well:17,westhoff:14,what:[8,9],whatsoev:11,when:12,whera:17,where:[7,12],whether:[11,12],which:[7,17],whole:10,whose:[7,12],widget:[9,13],width:[7,8,9],window:[10,17],wish:10,within:17,without:[11,17],work:[10,13],would:13,written:11,wshop:14,www:14,x:12,xu:12,y:12,yoshihiro:14,you:[8,9,10,13,17],young:13,your:[10,13],yun:13,zalewski:14},titles:["algorithms package","algorithms","classes package","classes","HyperNetX Packages","drawing package","drawing","Glossary of HNX terms","HyperNetX (HNX)","HyperNetX (HNX)","Installing HyperNetX","License","NWHy","Overview","Publications","reports","reports package","Hypernetx-Widget"],titleterms:{"0":13,"1":13,"class":[2,3,12],"import":12,"new":13,"public":14,Then:12,To:[10,12],activ:12,algorithm:[0,1],an:[10,12],anaconda:[10,12],api:12,attribut:12,block:12,build:12,colab:13,content:[0,2,5,9,16],descript:[8,9,12],descriptive_stat:16,draw:[5,6],entiti:2,environ:[10,12],featur:[13,17],glossari:7,hnx:[7,8,9],homology_mod2:0,hypergraph:2,hypernetx:[4,8,9,10,17],indic:9,instal:[10,12,17],intel:12,layout:17,licens:[11,13],method:12,modul:[0,2,5,12,16],notic:13,nwhy:12,nwhypergraph:12,option:10,other:17,overview:[13,17],packag:[0,2,4,5,16],panel:17,pip:[10,12],quick:12,report:[15,16],rubber_band:5,s_centrality_measur:0,select:17,side:17,slinegraph:12,staticent:2,submodul:[0,2,5,16],tabl:9,tbb:12,term:7,test:12,thread:12,tool:17,tutori:13,two_column:5,us:[10,12,17],util:5,version:13,virtualenv:10,widget:17}}) \ No newline at end of file diff --git a/docs/build/widget.html b/docs/build/widget.html index 6a53528f..06447db2 100644 --- a/docs/build/widget.html +++ b/docs/build/widget.html @@ -7,7 +7,7 @@ - Hypernetx-Widget — HyperNetX 1.0.0 documentation + Hypernetx-Widget — HyperNetX 1.0.1 documentation diff --git a/docs/source/conf.py b/docs/source/conf.py index e2f7b209..76582fce 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -19,7 +19,7 @@ import os import shlex -__version__ = "1.0.0" +__version__ = "1.0.1" # If extensions (or modules to document with autodoc) are in another directory, diff --git a/setup.py b/setup.py index cec73023..87c61475 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup import sys -__version__ = "1.0" +__version__ = "1.0.1" if sys.version_info < (3, 7): sys.exit("HyperNetX requires Python 3.7 or later.")