Skip to content

Faster Implementation of Structural Holes - #7249

Merged
rossbar merged 27 commits into
networkx:mainfrom
Shiyun-Hu:fast_implement_structural_holes
Mar 17, 2025
Merged

rossbar merged 27 commits into
networkx:mainfrom
Shiyun-Hu:fast_implement_structural_holes

Conversation

@Shiyun-Hu

Copy link
Copy Markdown
Contributor

Use sparse matrices to compute constraints and effective sizes fast.

Usually researchers would like to obtain structural hole measures for all nodes in a social network. This process can be really slow with current implementation of networkx.

Current algorithm can be accelerated with matrix operations. The constraints can be calculated as row sums of elementwise square of $$P+P^2,$$ where $P = (p_{ij})$ is the matrix of (sum-)normalized mutual weights. Similarly, the effective sizes can be calculated as row sums of $E-PM^T$, where $E$ is the matrix of ones and $M = (m_{ij})$ is the matrix of (max-)normalized mutual weights. Mutual weights can be calculated simply to the sum of adjacency matrix and its transpose.

Experiments show that the efficiency gain is large. For Erdos-Renyi network with $n=1000$ and $p=0.1$, algorithm based on matrix operations can be over 100 times faster than current implementation.

The matrix-based algorithm calculates structural hole measures for all nodes at once. I maintain the original algorithm if the user only wants to obtain structural hole measures only for a few nodes.

Use sparse matrices to compute constraints and effective sizes.

@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.

Can you remove the extra file that got uploaded?
Also, can you leave the constraint function where it was in the code -- just change it in place. Then we can easily see what is being changed using the github diff.

Thanks!

@Shiyun-Hu

Copy link
Copy Markdown
Contributor Author

Can you remove the extra file that got uploaded? Also, can you leave the constraint function where it was in the code -- just change it in place. Then we can easily see what is being changed using the github diff.

Thanks!

Sure! I just deleted the extra file and put functions in the same order as the original order. Two functions are changed: effective_size and constraint.

P.S. Automatic code checks show that "ModuleNotFoundError: No module named 'numpy'". I wonder what to do to fix this problem.

P.P.S. This is my first time contributing on GitHub, so please let me know if there's anything I can to to improve the code :) Many thanks!

Update conftest.py to solve numpy import error
Comment thread networkx/algorithms/structuralholes.py Outdated

return result

else:

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.

You can pull this code out of the else clause because the if clause has returned. Maybe put a comment like # results for only requested nodes to make it clear what the difference between nodes is None and not... :)

This looks quite good. Thanks. I haven't gone through it in detail yet, but it's quite promising.

@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.

The style issues can be fixed using the black and ruff linter programs. It is probably easiest to use them via the pre-commit helper system. See the contributing guide number 4 for how to get that installed.

Put the imports for numpy inside the functions so the package can be run even by someone who doesn't have numpy installed. In your case, it'd be good to have it inside the if-statement that actually uses it, so people could use the function even without it installed. You should also add the function name to the conftest.py file where it forms a list of functions that use numpy.

If you have questions, ask. and we'll take a look and guide you through the first PR steps. :} Thanks!

Use a try..except.. clause to allow users to compute structural holes for all nodes using old algorithm if numpy is not installed.
Fixed bug when numpy is not installed and node is None.
@Shiyun-Hu

Copy link
Copy Markdown
Contributor Author

The style issues can be fixed using the black and ruff linter programs. It is probably easiest to use them via the pre-commit helper system. See the contributing guide number 4 for how to get that installed.

Put the imports for numpy inside the functions so the package can be run even by someone who doesn't have numpy installed. In your case, it'd be good to have it inside the if-statement that actually uses it, so people could use the function even without it installed. You should also add the function name to the conftest.py file where it forms a list of functions that use numpy.

If you have questions, ask. and we'll take a look and guide you through the first PR steps. :} Thanks!

Many thanks to great suggestions! I just updated the codes so that users without Numpy can still use the old algorithm to calculate structural hole measures for all nodes. Now all checks have passed.

Please let me know if there's any further adjustments needed :)

@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.

I didn't look into the algorithm as a whole, but noticed some specifics about the implementation that I think can improve readability which will hopefully make review/discussion of the algorithm easier!

Comment thread networkx/algorithms/structuralholes.py Resolved
Comment thread networkx/algorithms/structuralholes.py Resolved
Comment thread networkx/algorithms/structuralholes.py Resolved
@Shiyun-Hu
Shiyun-Hu requested review from dschult and rossbar March 7, 2024 13:47

@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 is a very nice improvement! Thanks for putting this together @Shiyun-Hu
It makes me wonder about whether the whole module should be re-thought (including making some of these function private helper functions). But that is definitely beyond this PR. And this PR nicely retains all the code that works without numpy/scipy (and uses it when only some nodes from G are requested).

I have minor comments/suggestions (see below for details):

  • As written, the code actually requires scipy as well as numpy (nx.adjacency_matrix uses a scipy sparse matrixI think the check should be for whether scipy is installed rather than numpy. That is, adjacency_matrix requires scipy.
    • Also, the object np.newaxis can be replaced by None. But we can keep np.newaxis for readability by importing both numpy (for newaxis) and scipy (to check if adjacency_matrix will work).
    • We could also/instead of importing scipy, construct the adjacency_matrix as the check for whether scipy and numpy are available.
    • Another approach to all this which would allow this to work without scipy would be to use to_numpy_matrix instead of adjacency_matrix. We eventually turn the matrix into a numpy array anyway. It would also require changes to some of the expressions (like removing .toarray() and similar).
    • Minimal change to address all this: add import scipy inside the try/except. This is what I suggest below.
  • The comments for isolated nodes look like they came from the pure-python part of the code, and I made suggestions to streamline them.
  • I cleaned up the zip(list(G.nodes)), ... syntax to zip(G, ...

Comment thread networkx/algorithms/structuralholes.py Resolved
Comment thread networkx/algorithms/structuralholes.py Resolved
Comment thread networkx/algorithms/structuralholes.py Resolved
Comment thread networkx/algorithms/structuralholes.py Resolved
@rossbar

rossbar commented Mar 13, 2024

Copy link
Copy Markdown
Contributor

Another approach to all this which would allow this to work without scipy would be to use to_numpy_matrix instead of adjacency_matrix. We eventually turn the matrix into a numpy array anyway. It would also require changes to some of the expressions (like removing .toarray() and similar).

Agreed (though to_numpy_array, not to_numpy_matrix) --- The 1 - mw1 @ mw2 is a necessarily dense operation (i.e. sparse arrays can't be used). Now that doesn't mean that using sparse arrays for prior calculations isn't worth it - the operations may be more performant and/or memory efficient - but it's not a given. Definitely worth thinking about!

@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 think this is ready for merging. I think all requests have been addressed.

@dschult

dschult commented Mar 16, 2025

Copy link
Copy Markdown
Member

I merged this with main, and updated the tests to reflect recent changes to how isolated nodes with self-loops were tested.

Up until now, all tests ran on the whole graph. So the nodes= kwarg was not tested. Since this PR makes the two code pathways separate for nodes=None and nodes=[0], I added tests of effective_size and constraint when the nodes parameter is used.

@rossbar, I reused test code by Subclassing the test class. If there is a better way to do this with parametrized code, let me know. That could be a separate PR or this one.

 - Change import check to scipy (with varnames) to reflect reality
 - Add comments about returning scalars.

@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 @Shiyun-Hu and @dschult for the excellent review!

@rossbar
rossbar merged commit 7ccc559 into networkx:main Mar 17, 2025
@Shiyun-Hu

Copy link
Copy Markdown
Contributor Author

Thank you @rossbar @dschult ! So proud to have made a contribution to this excellent package :)

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