Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/normalized hypergraph laplacian #648

Merged
merged 28 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
41cc8d1
fix: rewrite `normalized_hypergraph_laplacian`
kaiser-dan Jan 24, 2025
a74ea93
test: add unit tests for updated laplacian
kaiser-dan Jan 24, 2025
5a924a3
doc: update `normalized_hypergraph_laplacian` doc
kaiser-dan Jan 24, 2025
c85c72b
test: added issue #657 m.w.e. as test
kaiser-dan Jan 25, 2025
4881074
fix(test): fix typo in unit test
kaiser-dan Jan 26, 2025
5de2a16
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 28, 2025
938e51b
test: add sqrt(d) eigenvector, true_L tests
kaiser-dan Jan 28, 2025
6717ec7
Merge branch 'fix/normalized_hypergraph_laplacian' of github.com:kais…
kaiser-dan Jan 28, 2025
60f3802
feat: update weighted argument for laplacian
kaiser-dan Jan 28, 2025
573eaad
doc: update normalized_hypergraph_laplacian args
kaiser-dan Jan 28, 2025
726340b
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
e1cf910
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
91b7522
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
1fc3593
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
5689658
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
6f128f4
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
292017c
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
10a6738
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
fd0197b
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
be0e6c9
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 28, 2025
251e21d
feat: update weighted argument for laplacian
kaiser-dan Jan 28, 2025
1b0fa8e
doc: update normalized_hypergraph_laplacian args
kaiser-dan Jan 28, 2025
60762ea
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 29, 2025
059d05c
test: separated #647 m.w.e. into new test
kaiser-dan Jan 29, 2025
88cdd4c
feat: update scipy sparse array to modern use
kaiser-dan Jan 29, 2025
da60d74
Merge branch 'fix/normalized_hypergraph_laplacian' of github.com:kais…
kaiser-dan Jan 29, 2025
1d5598b
chore: update diags_array scipy use in 'laplacian'
kaiser-dan Jan 29, 2025
327e6cd
Update xgi/linalg/laplacian_matrix.py
kaiser-dan Jan 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 40 additions & 15 deletions tests/linalg/test_matrix.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import numpy as np
import pytest
from scipy.linalg import eigh
from scipy.sparse import csr_array
from scipy.sparse.linalg import norm as spnorm

import xgi
from xgi.exception import XGIError


def test_incidence_matrix(edgelist1, edgelist3, edgelist4):
Expand Down Expand Up @@ -605,24 +607,47 @@ def test_normalized_hypergraph_laplacian():

assert isinstance(L2, np.ndarray)
assert np.all(L1.toarray() == L2)
assert np.all(np.diag(L2) == 0.5)

L3, d = xgi.normalized_hypergraph_laplacian(H, index=True)
evals = eigh(L2, eigvals_only=True)
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved
negative_evals = list(filter(lambda e: e < 0, evals))
assert (not negative_evals) or (np.allclose(negative_evals, 0))

L3, d = xgi.normalized_hypergraph_laplacian(H, index=True)
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved
assert d == {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8}
true_L = np.array(
[
[0.5, -0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0],
[-0.5, 0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0],
[-0.5, -0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.5, -0.35355339, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, -0.35355339, 0.5, -0.35355339, -0.35355339],
[0.0, 0.0, 0.0, 0.0, 0.0, -0.35355339, 0.5, -0.5],
[0.0, 0.0, 0.0, 0.0, 0.0, -0.35355339, -0.5, 0.5],
]
)
assert np.allclose(true_L, L2)

el_mwe = [
{1, 2, 3},
{1, 4, 5},
{1, 6, 7, 8},
{4, 9, 10, 11, 12},
{1, 13, 14, 15, 16},
{4, 17, 18},
]
H = xgi.Hypergraph(el_mwe)
L = xgi.normalized_hypergraph_laplacian(H, sparse=False)
evals = eigh(L, eigvals_only=True)
assert np.all(evals >= 0)

# Weights error handling
## Type errors
with pytest.raises(XGIError):
xgi.normalized_hypergraph_laplacian(H, weights=1)
with pytest.raises(XGIError):
xgi.normalized_hypergraph_laplacian(H, weights="1")

## Length errors
with pytest.raises(XGIError): # too few
xgi.normalized_hypergraph_laplacian(H, weights=[1])
with pytest.raises(XGIError): # too many
xgi.normalized_hypergraph_laplacian(
H, weights=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
)

## Value errors
with pytest.raises(XGIError): # zeros
xgi.normalized_hypergraph_laplacian(H, weights=[0, 1, 1, 1])
with pytest.raises(XGIError): # negatives
xgi.normalized_hypergraph_laplacian(H, weights=[-1, 1, 1, 1])


def test_empty_order(edgelist6):
Expand Down
73 changes: 65 additions & 8 deletions xgi/linalg/laplacian_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,15 @@
from warnings import warn

import numpy as np
from scipy.sparse import csr_array, diags
from scipy.sparse import csr_array, diags, identity
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

from ..exception import XGIError
from .hypergraph_matrix import adjacency_matrix, clique_motif_matrix, degree_matrix
from .hypergraph_matrix import (
adjacency_matrix,
clique_motif_matrix,
degree_matrix,
incidence_matrix
)

__all__ = [
"laplacian",
Expand Down Expand Up @@ -183,13 +188,15 @@ def multiorder_laplacian(
return (L_multi, rowdict) if index else L_multi


def normalized_hypergraph_laplacian(H, sparse=True, index=False):
def normalized_hypergraph_laplacian(H, weights=None, sparse=True, index=False):
"""Compute the normalized Laplacian.

Parameters
----------
H : Hypergraph
Hypergraph
weights : list of floats or None, optional
Hyperedge weights, by default None (every edge weighted as 1).
sparse : bool, optional
whether or not the laplacian is sparse, by default True
index : bool, optional
Expand All @@ -209,6 +216,12 @@ def normalized_hypergraph_laplacian(H, sparse=True, index=False):
XGIError
If there are isolated nodes.

XGIError
If there are an incorrect number of edge weights.

XGIError
If there are non-positive edge weights.

References
----------
"Learning with Hypergraphs: Clustering, Classification, and Embedding"
Expand All @@ -221,16 +234,60 @@ def normalized_hypergraph_laplacian(H, sparse=True, index=False):
"Every node must be a member of an edge to avoid divide by zero error!"
)

D = degree_matrix(H)
A, rowdict = clique_motif_matrix(H, sparse=sparse, index=True)
if weights is not None:
if weights is not list:
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved
raise XGIError("Edge weights must be given as a list!")
if len(weights) != H.num_edges:
raise XGIError("There must be as many edge weights as there are edges!")
if np.any(weights <= 0):
raise XGIError("Edge weights must be strictly positive!")


Dv = degree_matrix(H)
(
H_,
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved
rowdict,
_ # Discard edge name-index mapping
) = incidence_matrix(H, sparse=sparse, index=True)

if sparse:
Dinvsqrt = csr_array(diags(np.power(D, -0.5)))
Dv_invsqrt = csr_array(diags(np.power(Dv, -0.5)))
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

De_inv = diags(list(
map(
lambda x: 1/x,
np.sum(H_, axis=0)
)
))
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

if weights is not None:
W = diags(weights)
else:
W = identity(H.num_edges)
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

eye = csr_array((H.num_nodes, H.num_nodes))
eye.setdiag(1)
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved
else:
Dinvsqrt = np.diag(np.power(D, -0.5))
Dv_invsqrt = np.diag(np.power(Dv, -0.5))

De_inv = np.diag(list(
map(
lambda x: 1/x,
np.sum(H_, axis=0)
)
))
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

if weights is not None:
W = np.diag(weights)
else:
W = np.identity(H.num_edges)
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

eye = np.eye(H.num_nodes)

L = 0.5 * (eye - Dinvsqrt @ A @ Dinvsqrt)

# PERF: There is a faster way to do this calculation if unweighted.
# W can be ignored entirely if unweighted, but it adds a couple conditionals and complicates the code.
# It is untested, but I suspect the performance change is negligible.
L = (eye - (Dv_invsqrt @ H_ @ W @ De_inv @ np.transpose(H_) @ Dv_invsqrt))
kaiser-dan marked this conversation as resolved.
Show resolved Hide resolved

return (L, rowdict) if index else L
Loading