Skip to content

ENH: adding magnetic_laplacian_matrix - #8562

Merged
dschult merged 48 commits into
networkx:mainfrom
mcbosch:add-magneticlaplacian-for-issue-8560
Aug 20, 2026
Merged

dschult merged 48 commits into
networkx:mainfrom
mcbosch:add-magneticlaplacian-for-issue-8560

Conversation

@mcbosch

@mcbosch mcbosch commented Mar 11, 2026

Copy link
Copy Markdown
Contributor

I added a magnetic_laplacian_matrix function on networkx/linalg/laplacianmatrix.py. I also added a test to verify it's workable. The Laplacian matrix works for DiGraph and Graph, nevertheless for an undirected graph returns a normal Laplacian Matrix.

The Laplacian Matrix has been built as reference [1]. Here allows having weights on edges and does a mean in a symetrization process. The magnetic Laplacian is $L^{(q)}$, a Hermitian matrix associated to a directed graph $G=(V,E)$ with weights $w_{jk}$ for edges $(j,k)\in E$. Given a parameter $q\in [0, 1/2]$, it is defined as:

$$ L^{(q)} = D - A^{(q)}$$

where D is the degree of the underlying undirected graph, and $A^{(q)}$ is the Hermitian Magnetic Adjacency Matrix defined as

$$A^{(q)}_{jk} = w_{jk}'\cdot e^{2\pi iq\theta_{jk}}\cdot$$

where $w_{jk}'$ is $0$ if neither $(j,k)$ or $(j,k)$ are in $E$, and $(w_{jk}+w_{kj}))/2$ in other case, and $\theta_{jk}$ is either 1, -1 or 0 if the edge $(i,j)$ is in the specified direction, oposite or in both in $E$ respectively.

If this contribution seems correct maybe it's a good idea to add spectral functions and normalized version.

References
.. [1] Fanuel, M., Alaíz, C. M., Fernández, Á., & Suykens, J. A. (2018).
Magnetic eigenmaps for the visualization of directed graphs.
Applied and Computational Harmonic Analysis, 44(1), 189–199.

@mcbosch
mcbosch marked this pull request as draft March 14, 2026 15:35
@mcbosch
mcbosch marked this pull request as ready for review March 14, 2026 20:01
@mcbosch
mcbosch force-pushed the add-magneticlaplacian-for-issue-8560 branch from 3ca9006 to 97473eb Compare March 14, 2026 21:21
mcbosch

This comment was marked as duplicate.

@mcbosch

This comment was marked as resolved.

@mcbosch
mcbosch force-pushed the add-magneticlaplacian-for-issue-8560 branch from 5298a54 to cc1630f Compare April 8, 2026 07:36
@mcbosch
mcbosch force-pushed the add-magneticlaplacian-for-issue-8560 branch from cc1630f to 9403b63 Compare April 10, 2026 14:11

@mcbosch mcbosch left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Main edit in file laplacianmatrix.py:

Added a simplified version of the magnetic Laplacian magnetic_laplacian_matrix and a normalized version normalized_magnetic_laplacian. Given a directed graph $G = (V, E)$ (or undirected treated as symmetric directed) and a phase $q\in[0,0.5]$, it computes the Magnetic Laplacian of the symmetrized version of G (with adjacency matrix $A'=0.5(A+A^T)$ ). Then the magnetic laplacian is $L^{(q)} = D - H^{(q)}$, where $D$ is the diagonal matrix with node degrees and $H_{uv}=A'_{uv}e^{\alpha(u,v)}$, where $\alpha(u,v)= 2 \pi i q$ (resp. $-2 \pi i q$) if (u,v) was (resp. wasn't) in $E$ and $(v,u)$ wasn't (resp. was) in $$E$. In case that $(u,v), (v,u) \in E$; then $\alpha(u,v) = \alpha(v,u) = 0$.

Returns an scipy.sparse.csr_matrix.

Good upgrade should be adding a potential parameter which corresponds to the function $\alpha$. But it should be discussed how first.

File spectrum.py:

Added two functions magnteic_spectrum and normalized_magnetic_spectrum which computes the spectrum of the magnetic Laplacian and the normalized version respectively with scipy.linalg.eigh(nx.linalg.magnetic_laplacian_matrix(G,q).todense(), eigvals_only=True)

@dschult

dschult commented Apr 11, 2026

Copy link
Copy Markdown
Member

In terms of the scipy parts of this PR, you should use a csr_array instead of a csr_matrix. The *_matrix classes are discouraged for new code and will be deprecated soon. For the spectra, can you use the sparse eigenvalue finders? Any reason we have to convert to a dense numpy array in order to get the eigenvalues?

@mcbosch

mcbosch commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor Author

I did it that way because is it how it's computed in the other functions (laplacian_spectrum, normalized_laplacian_spectrum, etc.). Actually, If we use scipy.sparse.linalg.eigs we have to add some parameters such as k, the number of eigenvalues to compute; that must be smaller than N-1 for the way is computed. Moreover, scipy.sparse.linalg.eigs has a default value k=6 which will result on errors for graphs with less than 7 nodes. Maybe that's an issue to solve with the Scipy community.

Regard the other scipy terms and the *_matrix classes I will correct it to be more consistent. Thanks for the review

There are other ways that you use "sparse eigenvalue finders"?

@mcbosch mcbosch left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the last review, the name of the functions have been changed removing the _matrix part, and it has been checked the format of the matrix; having a csr_array.

Returns an scipy.sparse.csr_array.

N.B: I searched for other options to compute the spectrum using the sparse format to have better performance. Other functions (scipy.sparse.linalg.eigh; scipy.sparse.linalg.eigs), with better computing performance, searches the k highest eigenvalues. I have aimed to scipy.linalg.eigh because the first eigenvalues are interesting and to maintain the structure of the other spectral methods.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean that you want to find the lowest eigenvalues, while these routines find the highest? Or do you mean that you want to find all the eigenvalues?

I dint think we will need the entire spectrum for most real world problems. Though maybe its helpful for small problems.

We should be able to turn the "lowest eigenvalues" into the "highest eigenvalues and vice versa fairly easily.

But I guess if it is done with dense matrices and complete spectra for the other laplacians these are questions beyond this PR. Sorry for the distraction.

Other distractions include: the spectrum functions all seems to be about one-liners with no clarity that it is the best way to get the eigenvalues one might want. Perhaps we should replace the spectrum.py module with examples sections in the doc_strings of the matrix creation routines. But again -- bigger than this PR.

As for code review, I've gone through the code part and have these comments. Havent looked at tests or docs yet.

Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
dschult
dschult previously approved these changes Apr 23, 2026

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good!
I'm sure the tests could be parametrized. But that can be done in a follow-up.
This looks good to me!

I've got a couple of tweaks for the docs. I'm approving this in any case.

Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
@mcbosch

mcbosch commented Apr 24, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for all the review comments. I went through them and addressed them.

In the last commit (only changed 6 lines in the doc-string) I got errors in the workflows, but check them, and they are 403 Forbiden responses from conda.anaconda.org during pixi install, might be an error with the connection and not related with the PR. But I don't think I have permissions to re-run the jobs.

Regarding the documentation I have one question before I do more commits: do I just need to add the new function to the Laplacian Matrix section of doc/reference/linalg.rst, or is there anything else I should update? I wanted to confirm before making further changes. Thanks!

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two other very minor tweaks.

Comment thread networkx/linalg/laplacianmatrix.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mcbosch for taking another crack at it. This generally LGTM to me now - @dschult you had approved this in the past but enough has changed that it's worth another look!

IMV, there are two outstanding API questions:

  1. Should normalized_magnetic_laplacian be a separate function, or should it be a normalize= keyword argument to magnetic_laplacian? My preference would be the kwarg approach just to keep the API surface small
  2. Adding the corresponding _spectrum functions. As mentioned, I'm not a fan of this pattern; however, it's so well-established that I think we go with precedent here and keep these function (or function, if we remove the normalized_ version.

That would be my preference anyway, but if folks feels strongly about having 2 separate functions for the unnormalized/normalized versions I would acquiesce!

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's go forward with this as a single magnetic_laplacian function
with normalize keyword. And let's keep the separate function for
the _spectrum -- leaving deprecation/removal of the _spectrum
API surface to a separate PR covering all these _spectrum variants.

I've got two minor space-saving suggestions below.
And melding the normalized function into a keyword and related docs shift
is still needed of course. Let us know if you have questions.
And -- if the timing is bad for you let us know -- we could make the last changes and maybe get it in for the upcoming v3.7 release. :}

Comment thread networkx/linalg/tests/test_spectrum.py Resolved
Comment thread networkx/linalg/laplacianmatrix.py Resolved
@mcbosch

mcbosch commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for all the reviews and help :). I've already changed the normalized function by the keyword option. Now I'll update the docstring. I thought in order to start the _spectrum deprecation I could add an example on how to compute the spectrum in the docstring without the _spectrum functions, as @dschult sayed in an earlier comment:

Other distractions include: the spectrum functions all seems to be about one-liners with no clarity that it is the best way to get the eigenvalues one might want. Perhaps we should replace the spectrum.py module with examples sections in the doc_strings of the matrix creation routines. But again -- bigger than this PR.

But maybe it's better to discuss how we want this spectrum examples for a future separated Issue/PR working in the spectrum.py.

@dschult

dschult commented Aug 9, 2026

Copy link
Copy Markdown
Member

I think we should wait on the deprecation of the spectrum.py module. Otherwise this will take forever to get in :)

But we should replace the normalized spectrum function with a keyword arg in the regular spectrum function -- similar to the laplacian functions themselves.

Steps toward deprecation of spectrum involve multiple PRs:

  • first PR: add doc-string examples for the matrix creation function that show how to get the spectrum.
  • second step: decide whether we will do the usual warning/remove two-step deprecation process, or the unusual "keep the old functions available but remove from all documentation" style of deprecation.

Let's get this new function merged before we mix it up with the spectrum changes. So, leave out any examples involving spectrum from the doc-strings. At least thats my thoughts right now. Open for suggestions.

@dschult
dschult dismissed their stale review August 11, 2026 20:10

so I can approve when final form is realized

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took the liberty of switching the normalized spectrum function to a keyword (to match magnetic_laplacian).
I also:

  • changed the name to magnetic_laplacian_matrix from magnetic_laplacian to match the rest of the functions here (and to show it is not the continuous laplacian in some way I guess.
  • changed the new tests to use assert_allclose instead of assert_almost_equal as recommended by numpy.
  • docstring cleanup
  • test cleanup (keep expected answer near its test, etc)

I think this is ready for a final review

This no longer accurately describes the test class.
Check that the shape of the returned array is consistent
with nodelist.
Matches the params that are kwarg-only in magnetic_laplacian.
Align wording with magnetic_laplacian_matrix docstring.
Preferring builtin exceptions where possible.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mcbosch for sticking with this through all the back-and-forth w.r.t. the API! This LGTM too - I took the liberty of pushing up a few final tweaks, mostly to ensure better alignment between the docstrings of magnetic_laplacian_matrix and magnetic_spectrum. I also took the liberty of changine one exception type from NetworkXError -> ValueError (for the check on q) as IMO builtin exceptions are generally preferred when they make sense!

I'll go ahead and merge once CI's green - thanks again @mcbosch and @dschult for the careful review!

@dschult
dschult merged commit 32e06d5 into networkx:main Aug 20, 2026
43 checks passed
@dschult dschult added this to the 3.7 milestone Aug 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants