diff --git a/.flake8 b/.flake8
index 32a72cc..fbf6de0 100644
--- a/.flake8
+++ b/.flake8
@@ -5,11 +5,14 @@ exclude =
graphblas_algorithms/*/tests/,
graphblas_algorithms/*/*/tests/,
build/
+# E203 for black; B042 because ArpackNoConvergence mirrors SciPy's signature.
extend-ignore =
E203,
SIM105,
SIM401,
-# E203 whitespace before ':' (to be compatible with black)
+ B042,
+# No trailing comments below: flake8 would read them as part of the pattern.
per-file-ignores =
- __init__.py:F401,F403, # allow unused and star imports
- graphblas_algorithms/nxapi/exception.py:F401,
+ __init__.py:F401,F403
+ _nx_graphblas/__init__.py:E501
+ graphblas_algorithms/nxapi/exception.py:F401
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index b18fd29..4c9a7f1 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,6 +1,10 @@
version: 2
updates:
- - package-ecosystem: 'github-actions'
- directory: '/'
+ - package-ecosystem: "github-actions"
+ directory: "/"
schedule:
- interval: 'weekly'
+ interval: "weekly"
+ # Wait a week after a release before proposing it, so a compromised or
+ # broken release has time to be noticed and yanked.
+ cooldown:
+ default-days: 7
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 97bb856..18d2bf3 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -16,8 +16,10 @@ jobs:
name: pre-commit-hooks
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-python@v5
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- python-version: "3.10"
- - uses: pre-commit/action@v3.0.0
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.11"
+ - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
diff --git a/.github/workflows/publish_pypi.yml b/.github/workflows/publish_pypi.yml
index f848ad6..8fbb4e7 100644
--- a/.github/workflows/publish_pypi.yml
+++ b/.github/workflows/publish_pypi.yml
@@ -3,7 +3,10 @@ name: Publish to PyPI
on:
push:
tags:
- - '20*'
+ - "20*"
+
+permissions:
+ contents: read
jobs:
build_and_deploy:
@@ -14,20 +17,21 @@ jobs:
shell: bash -l {0}
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
+ persist-credentials: false
fetch-depth: 0
- name: Set up Python
- uses: actions/setup-python@v5
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
- python-version: "3.10"
+ python-version: "3.11"
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
python -m pip install build twine
- name: Build wheel and sdist
run: python -m build --sdist --wheel
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: releases
path: dist
@@ -35,7 +39,7 @@ jobs:
- name: Check with twine
run: python -m twine check --strict dist/*
- name: Publish to PyPI
- uses: pypa/gh-action-pypi-publish@v1.8.11
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
with:
user: __token__
- password: ${{ secrets.PYPI_TOKEN }}
+ password: ${{ secrets.PYPI_TOKEN }} # zizmor: ignore[use-trusted-publishing]
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 47ca7bc..4a0bcbc 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -3,65 +3,144 @@ name: Tests
on:
pull_request:
push:
- branches: [ main ]
+ branches: [main]
+
+permissions:
+ contents: read
jobs:
test:
+ name: pytest (${{ matrix.os }}, ${{ matrix.python-version }})
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash -l {0}
strategy:
- fail-fast: true
+ # One failing cell should not cancel the others.
+ fail-fast: false
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
- python-version: ["3.10", "3.11", "3.12"]
+ python-version: ["3.11", "3.12", "3.13"]
+ include:
+ # Additional architectures, at one Python version to limit the cost.
+ - os: macos-15-intel
+ python-version: "3.13"
+ - os: ubuntu-24.04-arm
+ python-version: "3.13"
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
+ persist-credentials: false
fetch-depth: 0
- name: Setup mamba
- uses: conda-incubator/setup-miniconda@v3
+ uses: conda-incubator/setup-miniconda@be893c923ea9cf1cf7cd510fbdde27c7e18cbdcb # v4.1.0
id: setup_mamba
continue-on-error: true
with:
- miniforge-variant: Mambaforge
+ miniforge-variant: Miniforge3
miniforge-version: latest
use-mamba: true
python-version: ${{ matrix.python-version }}
- channels: conda-forge,${{ contains(matrix.python-version, 'pypy') && 'defaults' || 'nodefaults' }}
- channel-priority: ${{ contains(matrix.python-version, 'pypy') && 'flexible' || 'strict' }}
+ channels: conda-forge
+ channel-priority: strict
activate-environment: graphblas
- auto-activate-base: false
- name: Setup conda
- uses: conda-incubator/setup-miniconda@v3
+ uses: conda-incubator/setup-miniconda@be893c923ea9cf1cf7cd510fbdde27c7e18cbdcb # v4.1.0
id: setup_conda
if: steps.setup_mamba.outcome == 'failure'
continue-on-error: false
with:
auto-update-conda: true
python-version: ${{ matrix.python-version }}
- channels: conda-forge,${{ contains(matrix.python-version, 'pypy') && 'defaults' || 'nodefaults' }}
- channel-priority: ${{ contains(matrix.python-version, 'pypy') && 'flexible' || 'strict' }}
+ channels: conda-forge
+ channel-priority: strict
activate-environment: graphblas
- auto-activate-base: false
- name: Install dependencies
run: |
- $(command -v mamba || command -v conda) install python-suitesparse-graphblas scipy pandas donfig pyyaml numpy python-graphblas \
- pytest-cov pytest-randomly pytest-mpl networkx
+ # conda, not mamba: on Windows the action's bash wrapper for mamba runs `cmd.exe /C`,
+ # which Git Bash rewrites to `cmd.exe C:/`, so the install silently does nothing.
+ conda install python-suitesparse-graphblas scipy pandas donfig pyyaml numpy python-graphblas \
+ pytest-cov pytest-randomly pytest-xdist networkx rich setuptools
# matplotlib lxml pygraphviz pydot sympy # Extra networkx deps we don't need yet
# Sometimes we prefer to use the latest release of NetworkX or the latest development from github
# pip install git+https://github.com/networkx/networkx.git@main --no-deps
pip install -e . --no-deps
- - name: PyTest
+ - name: pytest
run: |
python -c 'import sys, graphblas_algorithms; assert "networkx" not in sys.modules'
- coverage run --branch -m pytest --color=yes -v --check-structure
- coverage report
- # NETWORKX_GRAPH_CONVERT=graphblas pytest --color=yes --pyargs networkx --cov --cov-append
- ./run_nx_tests.sh --color=yes --cov --cov-append
+ coverage run --branch -m pytest --color=yes -v
coverage report
coverage xml
- name: Coverage
- uses: codecov/codecov-action@v3
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
+
+ networkx:
+ # One cell, since the suite is slow and tests the dispatch layer, not the platform.
+ name: NetworkX suite through the backend
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash -l {0}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 0
+ - name: Setup mamba
+ uses: conda-incubator/setup-miniconda@be893c923ea9cf1cf7cd510fbdde27c7e18cbdcb # v4.1.0
+ id: setup_mamba
+ continue-on-error: true
+ with:
+ miniforge-variant: Miniforge3
+ miniforge-version: latest
+ use-mamba: true
+ python-version: "3.13"
+ channels: conda-forge
+ channel-priority: strict
+ activate-environment: graphblas
+ - name: Setup conda
+ uses: conda-incubator/setup-miniconda@be893c923ea9cf1cf7cd510fbdde27c7e18cbdcb # v4.1.0
+ if: steps.setup_mamba.outcome == 'failure'
+ continue-on-error: false
+ with:
+ auto-update-conda: true
+ python-version: "3.13"
+ channels: conda-forge
+ channel-priority: strict
+ activate-environment: graphblas
+ - name: Install dependencies
+ run: |
+ # pytest-mpl brings matplotlib, which NetworkX's drawing tests need.
+ conda install python-suitesparse-graphblas scipy pandas donfig pyyaml numpy python-graphblas \
+ pytest-cov pytest-randomly pytest-mpl pytest-xdist networkx
+ pip install -e . --no-deps
+ - name: NetworkX test suite
+ id: nx_suite
+ # Advisory: the step may fail, the job passes, the counts are in the step summary.
+ continue-on-error: true
+ run: |
+ # The runner adds no pipefail to a custom shell, and `tee` would set the step's status.
+ set -o pipefail
+ ./run_nx_tests.sh --color=yes -n auto -q --cov --cov-report=xml | tee nx-suite.log
+ - name: Publish the suite result
+ if: always()
+ env:
+ SUITE_OUTCOME: ${{ steps.nx_suite.outcome }}
+ run: |
+ # The step summary and annotations do not render color escapes.
+ summary=$(tail -n 1 nx-suite.log 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g')
+ summary=${summary:-"the suite produced no output"}
+ {
+ echo "### NetworkX suite through this backend"
+ echo
+ echo '```'
+ echo "$summary"
+ echo '```'
+ } >> "$GITHUB_STEP_SUMMARY"
+ if [ "$SUITE_OUTCOME" != "success" ]; then
+ echo "::warning::NetworkX suite did not pass: $summary"
+ fi
+ - name: Coverage
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e4525c5..d5959ed 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -3,7 +3,8 @@
# Before first use: `pre-commit install`
# To run: `pre-commit run --all-files`
# To update: `pre-commit autoupdate`
-# - &flake8_dependencies below needs updated manually
+#
+# Pins track python-graphblas so both repos format code the same way.
ci:
# See: https://pre-commit.ci/#configuration
autofix_prs: false
@@ -11,95 +12,165 @@ ci:
autoupdate_commit_msg: "chore: update pre-commit hooks"
autofix_commit_msg: "style: pre-commit fixes"
skip: [no-commit-to-branch]
-fail_fast: true
+fail_fast: false
default_language_version:
- python: python3
+ python: python3
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.5.0
+ rev: v6.0.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
+ - id: check-executables-have-shebangs
+ - id: check-illegal-windows-names
- id: check-merge-conflict
- # - id: check-symlinks
- id: check-ast
+ # - id: check-json # No json files yet
- id: check-toml
- id: check-yaml
+ - id: check-vcs-permalinks
- id: debug-statements
+ - id: destroyed-symlinks
+ - id: detect-private-key
+ - id: forbid-submodules
- id: end-of-file-fixer
exclude_types: [svg]
- id: mixed-line-ending
- id: trailing-whitespace
- id: name-tests-test
args: ["--pytest-test-first"]
+ exclude: /tests/_[^/]+\.py$ # helper modules, which pytest does not collect
- repo: https://github.com/abravalheri/validate-pyproject
- rev: v0.15
+ rev: v0.27
hooks:
- id: validate-pyproject
name: Validate pyproject.toml
# I don't yet trust ruff to do what autoflake does
- repo: https://github.com/PyCQA/autoflake
- rev: v2.2.1
+ rev: v2.4.0
hooks:
- id: autoflake
args: [--in-place]
+ # We can probably remove `isort` if we come to trust `ruff --fix`,
+ # but we'll need to figure out the configuration to do this in `ruff`
- repo: https://github.com/pycqa/isort
- rev: 5.13.2
+ rev: 9.0.2
hooks:
- id: isort
+ # Let's keep `pyupgrade` even though `ruff --fix` probably does most of it
- repo: https://github.com/asottile/pyupgrade
- rev: v3.15.0
+ rev: v3.22.0
hooks:
- id: pyupgrade
- args: [--py310-plus]
+ args: [--py311-plus]
- repo: https://github.com/MarcoGorelli/auto-walrus
- rev: v0.2.2
+ rev: 0.4.1
hooks:
- id: auto-walrus
args: [--line-length, "100"]
- - repo: https://github.com/psf/black
- rev: 23.12.1
+ - repo: https://github.com/psf/black-pre-commit-mirror
+ rev: 26.10.1
hooks:
- id: black
- # - id: black-jupyter
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.1.9
+ rev: v0.17.3
hooks:
- - id: ruff
+ - id: ruff-check
args: [--fix-only, --show-fixes]
+ # Let's keep `flake8` even though `ruff` does much of the same.
+ # `flake8-bugbear` and `flake8-simplify` have caught things missed by `ruff`.
- repo: https://github.com/PyCQA/flake8
- rev: 6.1.0
+ rev: 7.5.0
hooks:
- id: flake8
- additional_dependencies: &flake8_dependencies
- # These versions need updated manually
- - flake8==6.1.0
- - flake8-bugbear==23.12.2
- - flake8-simplify==0.21.0
- - repo: https://github.com/asottile/yesqa
- rev: v1.5.0
- hooks:
- - id: yesqa
- additional_dependencies: *flake8_dependencies
+ args: ["--config=.flake8"]
+ additional_dependencies:
+ # These versions need updated manually
+ - flake8==7.5.0
+ - flake8-bugbear==26.10.27
+ - flake8-simplify==0.31.1
- repo: https://github.com/codespell-project/codespell
- rev: v2.2.6
+ rev: v2.4.3
hooks:
- id: codespell
- types_or: [python, rst, markdown]
- additional_dependencies: [tomli]
- files: ^(graphblas_algorithms|docs)/
+ types_or: [python, markdown, toml, yaml]
+ additional_dependencies:
+ - tomli; python_version<'3.11'
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.1.9
+ rev: v0.17.3
hooks:
- - id: ruff
+ - id: ruff-check
+ # - id: ruff-format # we prefer black; uncomment to compare with ruff's formatter
# `pyroma` may help keep our package standards up to date if best practices change.
# This is probably a "low value" check though and safe to remove if we want faster pre-commit.
- repo: https://github.com/regebro/pyroma
- rev: "4.2"
+ rev: "5.0.1"
hooks:
- id: pyroma
args: [-n, "10", .]
+ - repo: https://github.com/shellcheck-py/shellcheck-py
+ rev: "v0.11.0.1-1"
+ hooks:
+ - id: shellcheck
+ - repo: https://github.com/rbubley/mirrors-prettier
+ rev: v3.9.10
+ hooks:
+ - id: prettier
+ args: [--prose-wrap=preserve]
+ - repo: https://github.com/pre-commit/pygrep-hooks
+ rev: v1.10.0
+ hooks:
+ - id: python-check-blanket-noqa
+ - id: python-check-blanket-type-ignore
+ - id: python-no-eval
+ - id: python-no-log-warn
+ - id: text-unicode-replacement-char
+ - repo: https://github.com/ComPWA/taplo-pre-commit
+ rev: v0.9.3
+ hooks:
+ - id: taplo-format
+ args: ["--option", "column_width=100"]
+ - repo: https://github.com/rhysd/actionlint
+ rev: v1.7.12
+ hooks:
+ - id: actionlint
+ - repo: https://github.com/zizmorcore/zizmor-pre-commit
+ rev: v1.32.0
+ hooks:
+ - id: zizmor
+ - repo: https://github.com/python-jsonschema/check-jsonschema
+ rev: 0.39.0
+ hooks:
+ - id: check-dependabot
+ - id: check-github-workflows
+ - repo: https://github.com/adrienverge/yamllint
+ rev: v1.38.0
+ hooks:
+ - id: yamllint
+ - repo: meta
+ hooks:
+ - id: check-hooks-apply
+ - id: check-useless-excludes
+ - repo: local
+ hooks:
+ - id: disallow-caps
+ name: Disallow improper capitalization
+ language: pygrep
+ # `\b`, not python-graphblas's `\<` and `\>`, which Python's `re` reads as literals.
+ entry: PyBind|\bNumpy\b|Cmake|CCache|Github|PyTest|\bRST\b|PyLint
+ exclude: .pre-commit-config.yaml$
+ - id: disallow-words
+ name: Disallow certain words
+ language: pygrep
+ entry: "[Ff]alsey"
+ exclude: .pre-commit-config.yaml$
+ - id: disallow-dashes
+ name: Disallow em/en-dash and ' -- ' as a separator
+ language: pygrep
+ entry: "—|–| -- |[A-Za-z0-9]--"
+ types_or: [python, markdown, toml, yaml, shell]
+ exclude: .pre-commit-config.yaml$
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.5.0
+ rev: v6.0.0
hooks:
- - id: no-commit-to-branch # no commit directly to main
+ - id: no-commit-to-branch # no commit directly to main
diff --git a/.yamllint.yml b/.yamllint.yml
new file mode 100644
index 0000000..172e34d
--- /dev/null
+++ b/.yamllint.yml
@@ -0,0 +1,11 @@
+---
+extends: default
+rules:
+ # GitHub workflows use `on:` as a mapping key, which the default truthy rule rejects.
+ truthy:
+ check-keys: false
+ document-start: disable
+ line-length: disable
+ # prettier writes one space before an inline comment; yamllint's default wants two.
+ comments:
+ min-spaces-from-content: 1
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 7cfcb10..f0eb584 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -13,13 +13,13 @@ educational level, family status, culture, or political belief.
Examples of unacceptable behavior by participants include:
-* The use of sexualized language or imagery
-* Personal attacks
-* Trolling or insulting/derogatory comments
-* Public or private harassment
-* Publishing other's private information, such as physical or electronic
+- The use of sexualized language or imagery
+- Personal attacks
+- Trolling or insulting/derogatory comments
+- Public or private harassment
+- Publishing other's private information, such as physical or electronic
addresses, without explicit permission
-* Other unethical or unprofessional conduct
+- Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
@@ -52,7 +52,7 @@ that is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.
-This Code of Conduct is adapted from the [Numba Code of Conduct][numba], which is based on the [Contributor Covenant][homepage],
+This Code of Conduct is adapted from the [Numba Code of Conduct][numba], which is based on the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version],
and the [Swift Code of Conduct][swift].
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..d399e14
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,30 @@
+.PHONY: all plugin-info readme check lint test test-nx clean
+
+all: readme plugin-info
+
+# The plugin info is read off the dispatch table that `readme` writes; a prerequisite, unlike
+# the order in `all`, also holds under `make -j`.
+plugin-info: readme
+ python _nx_graphblas/__init__.py
+
+# maketree writes both the README tree and interface.py's dispatch table.
+readme:
+ python scripts/maketree.py
+
+check:
+ pytest graphblas_algorithms/tests/test_match_nx.py -v
+
+lint:
+ pre-commit run --all-files
+
+test:
+ pytest --color=yes -v
+
+test-nx:
+ ./run_nx_tests.sh --color=yes -n auto
+
+# Named directories only, never the whole working copy.
+clean:
+ find _nx_graphblas graphblas_algorithms scripts -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true
+ find _nx_graphblas graphblas_algorithms scripts -name '*.pyc' -delete 2>/dev/null || true
+ rm -rf build/ dist/ ./*.egg-info .pytest_cache/
diff --git a/README.md b/README.md
index ed66df3..1b2972a 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@
[](https://codecov.io/gh/python-graphblas/graphblas-algorithms)
[](https://doi.org/10.5281/zenodo.7329185)
[](https://discord.com/invite/vur45CbwMz)
+
`graphblas-algorithms` is a collection of GraphBLAS algorithms written using
@@ -16,7 +17,7 @@
It may be used directly or as an experimental
[backend to NetworkX](https://networkx.org/documentation/stable/reference/classes/index.html#backends).
-Why use GraphBLAS Algorithms? Because it is *fast*, *flexible*, and *familiar* by using the NetworkX API.
+Why use GraphBLAS Algorithms? Because it is _fast_, _flexible_, and _familiar_ by using the NetworkX API.
Are we missing any [algorithms](#Plugin-Algorithms) that you want?
[Please let us know!](https://github.com/python-graphblas/graphblas-algorithms/issues)
@@ -26,9 +27,11 @@ Are we missing any [algorithms](#Plugin-Algorithms) that you want?
### Installation
+
```
conda install -c conda-forge graphblas-algorithms
```
+
```
pip install graphblas-algorithms
```
@@ -70,12 +73,12 @@ Algorithms whose result is a subgraph will return `ga.Graph`.
## Plugin for NetworkX
-Dispatching to plugins is a new feature in Networkx 3.0.
When both `networkx` and `graphblas-algorithms` are installed in an
environment, calls to NetworkX algorithms can be dispatched to the
equivalent version in `graphblas-algorithms`.
### Dispatch Example
+
```python
import networkx as nx
import graphblas_algorithms as ga
@@ -91,13 +94,14 @@ T5 = nx.k_truss(G2, 5)
```
`G2` is not a `nx.Graph`, but it does have an attribute
-`__networkx_plugin__ = "graphblas"`. This tells NetworkX to
-dispatch the k_truss call to graphblas-algorithms. This link
-connection exists because graphblas-algorithms registers
-itself as a "networkx.plugin" entry point.
+`__networkx_backend__ = "graphblas"`. This tells NetworkX to
+dispatch the k_truss call to graphblas-algorithms. That link
+exists because graphblas-algorithms registers itself under
+the "networkx.backends" entry point group.
The result `T5` is a `ga.Graph` representing the 5-truss structure of the
original graph. To convert to a NetworkX Graph, use:
+
```python
T5.to_networkx()
```
@@ -112,7 +116,7 @@ The following NetworkX algorithms have been implemented
by graphblas-algorithms and can be used following the
dispatch pattern shown above.
-[//]: # (Begin auto-generated code)
+[//]: # "Begin auto-generated code"
```
graphblas_algorithms.nxapi
@@ -246,4 +250,4 @@ graphblas_algorithms.nxapi
└── is_triad
```
-[//]: # (End auto-generated code)
+[//]: # "End auto-generated code"
diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py
index 6ffa061..31fe839 100644
--- a/_nx_graphblas/__init__.py
+++ b/_nx_graphblas/__init__.py
@@ -1,4 +1,18 @@
+"""Backend info NetworkX reads through the ``networkx.backend_info`` entry point.
+
+``_functions`` and ``_extra_parameters`` are generated from the dispatcher and from our
+signatures: run ``python _nx_graphblas/__init__.py``, or ``make plugin-info``, after adding
+or removing an algorithm. ``_nx_graphblas/core.py`` holds the code that writes them.
+"""
+
+
def get_info():
+ # NetworkX looks for `extra_parameters` inside each function's own dict, so the
+ # parameter table has to stay wrapped in that key rather than be the dict itself.
+ functions = {
+ name: {"extra_parameters": _extra_parameters[name]} if name in _extra_parameters else {}
+ for name in _functions
+ }
return {
"backend_name": "graphblas",
"project": "graphblas-algorithms",
@@ -6,102 +20,119 @@ def get_info():
"url": "https://github.com/python-graphblas/graphblas-algorithms",
"short_summary": "OpenMP-enabled sparse linear algebra backend.",
# "description": "TODO",
- "functions": {
- "adjacency_matrix": {},
- "all_pairs_bellman_ford_path_length": {
- "extra_parameters": {
- "chunksize : int or str, optional": "Split the computation into chunks; "
- 'may specify size as string or number of rows. Default "10 MiB"',
- },
- },
- "all_pairs_shortest_path_length": {
- "extra_parameters": {
- "chunksize : int or str, optional": "Split the computation into chunks; "
- 'may specify size as string or number of rows. Default "10 MiB"',
- },
- },
- "ancestors": {},
- "average_clustering": {},
- "bellman_ford_path": {},
- "bellman_ford_path_length": {},
- "bethe_hessian_matrix": {},
- "bfs_layers": {},
- "boundary_expansion": {},
- "clustering": {},
- "complement": {},
- "compose": {},
- "conductance": {},
- "cut_size": {},
- "degree_centrality": {},
- "descendants": {},
- "descendants_at_distance": {},
- "difference": {},
- "directed_modularity_matrix": {},
- "disjoint_union": {},
- "edge_boundary": {},
- "edge_expansion": {},
- "efficiency": {},
- "ego_graph": {},
- "eigenvector_centrality": {},
- "fast_could_be_isomorphic": {},
- "faster_could_be_isomorphic": {},
- "floyd_warshall": {},
- "floyd_warshall_numpy": {},
- "floyd_warshall_predecessor_and_distance": {},
- "full_join": {},
- "generalized_degree": {},
- "google_matrix": {},
- "has_path": {},
- "hits": {},
- "in_degree_centrality": {},
- "inter_community_edges": {},
- "intersection": {},
- "intra_community_edges": {},
- "is_connected": {},
- "is_dominating_set": {},
- "is_isolate": {},
- "is_k_regular": {},
- "isolates": {},
- "is_regular": {},
- "is_simple_path": {},
- "is_tournament": {},
- "is_triad": {},
- "is_weakly_connected": {},
- "katz_centrality": {},
- "k_truss": {},
- "laplacian_matrix": {},
- "lowest_common_ancestor": {},
- "mixing_expansion": {},
- "modularity_matrix": {},
- "mutual_weight": {},
- "negative_edge_cycle": {},
- "node_boundary": {},
- "node_connected_component": {},
- "node_expansion": {},
- "normalized_cut_size": {},
- "normalized_laplacian_matrix": {},
- "number_of_isolates": {},
- "out_degree_centrality": {},
- "overall_reciprocity": {},
- "pagerank": {},
- "reciprocity": {},
- "reverse": {},
- "score_sequence": {},
- "single_source_bellman_ford_path_length": {},
- "single_source_shortest_path_length": {},
- "single_target_shortest_path_length": {},
- "s_metric": {},
- "square_clustering": {
- "extra_parameters": {
- "chunksize : int or str, optional": "Split the computation into chunks; "
- 'may specify size as string or number of rows. Default "256 MiB"',
- },
- },
- "symmetric_difference": {},
- "tournament_matrix": {},
- "transitivity": {},
- "triangles": {},
- "union": {},
- "volume": {},
- },
+ "functions": functions,
}
+
+
+# fmt: off
+_functions = (
+ # BEGIN: functions
+ "adjacency_matrix",
+ "all_pairs_bellman_ford_path_length",
+ "all_pairs_shortest_path_length",
+ "ancestors",
+ "average_clustering",
+ "bellman_ford_path",
+ "bellman_ford_path_length",
+ "bethe_hessian_matrix",
+ "bfs_layers",
+ "boundary_expansion",
+ "clustering",
+ "complement",
+ "compose",
+ "conductance",
+ "cut_size",
+ "degree_centrality",
+ "descendants",
+ "descendants_at_distance",
+ "difference",
+ "directed_modularity_matrix",
+ "disjoint_union",
+ "edge_boundary",
+ "edge_expansion",
+ "efficiency",
+ "ego_graph",
+ "eigenvector_centrality",
+ "fast_could_be_isomorphic",
+ "faster_could_be_isomorphic",
+ "floyd_warshall",
+ "floyd_warshall_numpy",
+ "floyd_warshall_predecessor_and_distance",
+ "full_join",
+ "generalized_degree",
+ "google_matrix",
+ "has_path",
+ "hits",
+ "in_degree_centrality",
+ "inter_community_edges",
+ "intersection",
+ "intra_community_edges",
+ "is_connected",
+ "is_dominating_set",
+ "is_isolate",
+ "is_k_regular",
+ "is_regular",
+ "is_simple_path",
+ "is_tournament",
+ "is_triad",
+ "is_weakly_connected",
+ "isolates",
+ "k_truss",
+ "katz_centrality",
+ "laplacian_matrix",
+ "lowest_common_ancestor",
+ "mixing_expansion",
+ "modularity_matrix",
+ "mutual_weight",
+ "negative_edge_cycle",
+ "node_boundary",
+ "node_connected_component",
+ "node_expansion",
+ "normalized_cut_size",
+ "normalized_laplacian_matrix",
+ "number_of_isolates",
+ "out_degree_centrality",
+ "overall_reciprocity",
+ "pagerank",
+ "reciprocity",
+ "reverse",
+ "s_metric",
+ "score_sequence",
+ "single_source_bellman_ford_path_length",
+ "single_source_shortest_path_length",
+ "single_target_shortest_path_length",
+ "square_clustering",
+ "symmetric_difference",
+ "tournament_matrix",
+ "transitivity",
+ "triangles",
+ "union",
+ "volume",
+ # END: functions
+)
+
+_extra_parameters = {
+ # BEGIN: extra_parameters
+ "all_pairs_bellman_ford_path_length": {
+ "chunksize : int or str, optional": 'Split the computation into chunks; may specify size as string or number of rows. Default "10 MiB"',
+ },
+ "all_pairs_shortest_path_length": {
+ "chunksize : int or str, optional": 'Split the computation into chunks; may specify size as string or number of rows. Default "10 MiB"',
+ },
+ "square_clustering": {
+ "chunksize : int or str, optional": 'Split the computation into chunks; may specify size as string or number of rows. Default "256 MiB"',
+ },
+ # END: extra_parameters
+}
+# fmt: on
+
+if __name__ == "__main__":
+ import sys
+ from pathlib import Path
+
+ # Running this file as a script puts _nx_graphblas/ on sys.path, not the repo root,
+ # so the package it lives in would not be importable without this.
+ sys.path.insert(0, str(Path(__file__).parent.parent))
+ from _nx_graphblas.core import main
+
+ main()
diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py
new file mode 100644
index 0000000..d8ee320
--- /dev/null
+++ b/_nx_graphblas/core.py
@@ -0,0 +1,124 @@
+"""Keep the backend info in ``_nx_graphblas/__init__.py`` in step with the dispatcher.
+
+Run ``python _nx_graphblas/__init__.py``, or ``make plugin-info``, after adding or removing
+an algorithm. The generated blocks are delimited by ``BEGIN:``/``END:`` comments.
+"""
+
+import inspect
+from pathlib import Path
+
+# Backend protocol hooks on the Dispatcher; not algorithms.
+_BACKEND_METHODS = {"convert_from_nx", "convert_to_nx", "on_start_tests", "can_run", "should_run"}
+
+# Docs for parameters beyond NetworkX's signature, keyed by ("function", "parameter") or by
+# "parameter" alone; the specific key wins. The generator appends the live default.
+_PARAM_DOCS = {
+ "chunksize": (
+ "chunksize : int or str, optional",
+ "Split the computation into chunks; may specify size as string or number of rows.",
+ ),
+}
+
+
+def get_functions():
+ from graphblas_algorithms.interface import Dispatcher
+
+ return {
+ key: val
+ for key, val in sorted(vars(Dispatcher).items())
+ if callable(val) and not key.startswith("_") and key not in _BACKEND_METHODS
+ }
+
+
+def dq_repr(s):
+ """Quote like black does: double quotes unless the string itself contains one."""
+ rs = repr(s)
+ if rs.startswith("'") and '"' not in rs:
+ return f'"{rs[1:-1]}"'
+ return rs
+
+
+def _format_default(value):
+ return f'"{value}"' if isinstance(value, str) else repr(value)
+
+
+def get_extra_parameters(functions=None):
+ """Parameters our signature accepts that the NetworkX signature does not.
+
+ Returns the table, the parameters with no entry in `_PARAM_DOCS`, and the names NetworkX
+ does not dispatch (left out of the table).
+ """
+ from networkx.utils.backends import _registered_algorithms
+
+ if functions is None:
+ functions = get_functions()
+ rv = {}
+ undocumented = []
+ unregistered = []
+ for name, func in functions.items():
+ if name not in _registered_algorithms:
+ unregistered.append(name)
+ continue
+ nx_params = set(inspect.signature(_registered_algorithms[name].orig_func).parameters)
+ our_sig = inspect.signature(func)
+ params = {}
+ for pname in sorted(set(our_sig.parameters) - nx_params):
+ param = our_sig.parameters[pname]
+ if param.kind in (param.VAR_KEYWORD, param.VAR_POSITIONAL):
+ continue
+ doc = _PARAM_DOCS.get((name, pname)) or _PARAM_DOCS.get(pname)
+ if doc is None:
+ header, prose = f"{pname} : optional", ""
+ undocumented.append(f"{name}({pname})")
+ else:
+ header, prose = doc
+ if param.default is inspect.Parameter.empty:
+ params[header] = prose
+ else:
+ params[header] = f"{prose} Default {_format_default(param.default)}".lstrip()
+ if params:
+ rv[name] = params
+ return rv, undocumented, unregistered
+
+
+def update_text(text, lines_to_add, target, indent=" " * 4):
+ begin = f"# BEGIN: {target}\n"
+ end = f"# END: {target}\n"
+ for marker in (begin, end):
+ # `index` below raises on a missing marker; a duplicate would splice into the wrong block.
+ if text.count(marker) != 1:
+ raise ValueError(
+ f"expected {marker.strip()!r} exactly once, found {text.count(marker)}"
+ )
+ start = text.index(begin)
+ stop = text.index(end)
+ to_add = "\n".join(f"{indent}{line}" for line in lines_to_add)
+ return f"{text[:start]}{begin}{to_add}\n{indent}{text[stop:]}"
+
+
+def main(filepath=None):
+ filepath = Path(__file__).parent / "__init__.py" if filepath is None else Path(filepath)
+ orig_text = filepath.read_text()
+
+ functions = get_functions()
+ text = update_text(orig_text, [f'"{name}",' for name in sorted(functions)], "functions")
+
+ extra_params, undocumented, unregistered = get_extra_parameters(functions)
+ lines = []
+ for name in sorted(extra_params):
+ params = extra_params[name]
+ lines.append(f'"{name}": {{')
+ lines.extend(f" {dq_repr(h)}: {dq_repr(params[h])}," for h in sorted(params))
+ lines.append("},")
+ text = update_text(text, lines, "extra_parameters")
+
+ if undocumented:
+ print("No description in _PARAM_DOCS for: " + ", ".join(sorted(undocumented)))
+ if unregistered:
+ print("Not dispatchable in this NetworkX, so not documented: " + ", ".join(unregistered))
+ if text != orig_text:
+ filepath.write_text(text)
+ print(f"Updated {filepath}")
+ else:
+ print(f"No changes needed for {filepath}")
+ return text
diff --git a/conftest.py b/conftest.py
deleted file mode 100644
index 89730c5..0000000
--- a/conftest.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import pytest
-
-
-def pytest_addoption(parser):
- parser.addoption(
- "--check-structure",
- "--checkstructure",
- default=None,
- action="store_true",
- help="Check that `graphblas_algorithms.nxapi` matches networkx structure",
- )
-
-
-def pytest_runtest_setup(item):
- if "checkstructure" in item.keywords and not item.config.getoption("--check-structure"):
- pytest.skip("need --check-structure option to run")
diff --git a/dev-requirements.txt b/dev-requirements.txt
new file mode 100644
index 0000000..2748ee7
--- /dev/null
+++ b/dev-requirements.txt
@@ -0,0 +1,38 @@
+# Development dependencies for a pip environment: roughly what `environment.yml`
+# installs with conda. `pyproject.toml`'s `test` extra is a smaller set, only what
+# running this package's own tests needs.
+python-graphblas
+networkx
+scipy
+# python-graphblas default dependencies
+donfig
+numba
+suitesparse-graphblas
+pyyaml
+# networkx default dependencies
+matplotlib
+pandas
+# networkx extra dependencies
+lxml
+pydot
+pygraphviz
+sympy
+# For updating algorithm list in README
+rich
+# For linting
+pre-commit
+# For testing
+pytest
+pytest-cov
+# NetworkX's image-comparison tests skip without it.
+pytest-mpl
+pytest-xdist
+setuptools
+# For benchmarking
+requests
+# For debugging
+icecream
+ipykernel
+ipython
+# For type annotations
+mypy
diff --git a/environment.yml b/environment.yml
index 06142d1..e2bff97 100644
--- a/environment.yml
+++ b/environment.yml
@@ -9,50 +9,57 @@
# $ pre-commit install
#
# At times, one may need to use a development version of networkx or python-graphblas.
-# To do this, you will need to uninstall, git clone, and run setup.py develop. For example:
+# To do this, uninstall the conda package, clone the repository, and install it in place:
#
# $ conda remove --force python-graphblas
# $ git clone git@github.com:python-graphblas/python-graphblas.git
# $ cd python-graphblas
-# $ python setup.py develop --no-deps
+# $ pip install -e . --no-deps
#
# $ conda remove --force networkx
# $ git clone git@github.com:networkx/networkx.git
# $ cd networkx
-# $ python setup.py develop --no-deps
+# $ pip install -e . --no-deps
+#
+# `dev-requirements.txt` is the pip mirror of this file; keep the two in lockstep.
name: graphblas-algorithms-dev
channels:
- - conda-forge
- - nodefaults # Only install packages from conda-forge for faster solving
+ - conda-forge
+ - nodefaults # Only install packages from conda-forge for faster solving
dependencies:
- - python
- - python-graphblas
- - networkx
- # python-graphblas default dependencies
- - donfig
- - numba
- - python-suitesparse-graphblas
- - pyyaml
- # networkx default dependencies
- - matplotlib
- - pandas
- - scipy
- # networkx extra dependencies
- - lxml
- - pydot
- - pygraphviz
- - sympy
- # For updating algorithm list in README
- - rich
- # For linting
- - pre-commit
- # For testing
- - pytest-cov
- # For benchmarking
- - requests
- # For debugging
- - icecream
- - ipykernel
- - ipython
- # For type annotations
- - mypy
+ - python
+ - python-graphblas
+ - networkx
+ # python-graphblas default dependencies
+ - donfig
+ - numba
+ - python-suitesparse-graphblas
+ - pyyaml
+ # networkx default dependencies
+ - matplotlib
+ - pandas
+ - scipy
+ # networkx extra dependencies
+ - lxml
+ - pydot
+ - pygraphviz
+ - sympy
+ # For updating algorithm list in README
+ - rich
+ # For linting
+ - pre-commit
+ # For testing
+ - pytest
+ - pytest-cov
+ - pytest-xdist
+ # NetworkX's image-comparison tests skip without it.
+ - pytest-mpl
+ - setuptools
+ # For benchmarking
+ - requests
+ # For debugging
+ - icecream
+ - ipykernel
+ - ipython
+ # For type annotations
+ - mypy
diff --git a/graphblas_algorithms/algorithms/cluster.py b/graphblas_algorithms/algorithms/cluster.py
index 0b9ab21..f84a219 100644
--- a/graphblas_algorithms/algorithms/cluster.py
+++ b/graphblas_algorithms/algorithms/cluster.py
@@ -3,21 +3,21 @@
from graphblas.semiring import plus_first, plus_pair, plus_times
__all__ = [
- "single_triangle",
- "triangles",
- "total_triangles",
- "transitivity",
- "transitivity_directed",
+ "average_clustering",
+ "average_clustering_directed",
"clustering",
"clustering_directed",
+ "generalized_degree",
"single_clustering",
"single_clustering_directed",
- "average_clustering",
- "average_clustering_directed",
+ "single_generalized_degree",
"single_square_clustering",
+ "single_triangle",
"square_clustering",
- "generalized_degree",
- "single_generalized_degree",
+ "total_triangles",
+ "transitivity",
+ "transitivity_directed",
+ "triangles",
]
diff --git a/graphblas_algorithms/algorithms/community/quality.py b/graphblas_algorithms/algorithms/community/quality.py
index d2b1d95..39e5c16 100644
--- a/graphblas_algorithms/algorithms/community/quality.py
+++ b/graphblas_algorithms/algorithms/community/quality.py
@@ -1,6 +1,6 @@
from graphblas.semiring import plus_pair
-__all__ = ["intra_community_edges", "inter_community_edges"]
+__all__ = ["inter_community_edges", "intra_community_edges"]
def intra_community_edges(G, partition):
diff --git a/graphblas_algorithms/algorithms/cuts.py b/graphblas_algorithms/algorithms/cuts.py
index 918dc56..40f0b49 100644
--- a/graphblas_algorithms/algorithms/cuts.py
+++ b/graphblas_algorithms/algorithms/cuts.py
@@ -4,14 +4,14 @@
from .boundary import edge_boundary, node_boundary
__all__ = [
- "cut_size",
- "volume",
- "normalized_cut_size",
+ "boundary_expansion",
"conductance",
+ "cut_size",
"edge_expansion",
"mixing_expansion",
"node_expansion",
- "boundary_expansion",
+ "normalized_cut_size",
+ "volume",
]
diff --git a/graphblas_algorithms/algorithms/dag.py b/graphblas_algorithms/algorithms/dag.py
index 63eb560..5a30616 100644
--- a/graphblas_algorithms/algorithms/dag.py
+++ b/graphblas_algorithms/algorithms/dag.py
@@ -1,6 +1,6 @@
from ._bfs import _bfs_plain
-__all__ = ["descendants", "ancestors"]
+__all__ = ["ancestors", "descendants"]
def descendants(G, source):
diff --git a/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py b/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py
index 7391dbe..56e3773 100644
--- a/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py
+++ b/graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py
@@ -6,7 +6,7 @@
from .._helpers import is_converged
from ..exceptions import ConvergenceFailure
-__all__ = ["pagerank", "google_matrix"]
+__all__ = ["google_matrix", "pagerank"]
def pagerank(
diff --git a/graphblas_algorithms/algorithms/reciprocity.py b/graphblas_algorithms/algorithms/reciprocity.py
index 173cb1d..bb77783 100644
--- a/graphblas_algorithms/algorithms/reciprocity.py
+++ b/graphblas_algorithms/algorithms/reciprocity.py
@@ -2,7 +2,7 @@
from .exceptions import EmptyGraphError
-__all__ = ["reciprocity", "overall_reciprocity"]
+__all__ = ["overall_reciprocity", "reciprocity"]
def reciprocity(G, mask=None):
diff --git a/graphblas_algorithms/algorithms/regular.py b/graphblas_algorithms/algorithms/regular.py
index cf3a057..bb0ada2 100644
--- a/graphblas_algorithms/algorithms/regular.py
+++ b/graphblas_algorithms/algorithms/regular.py
@@ -1,6 +1,6 @@
from graphblas import monoid
-__all__ = ["is_regular", "is_k_regular"]
+__all__ = ["is_k_regular", "is_regular"]
def is_regular(G):
diff --git a/graphblas_algorithms/algorithms/shortest_paths/unweighted.py b/graphblas_algorithms/algorithms/shortest_paths/unweighted.py
index ec87b65..53cf639 100644
--- a/graphblas_algorithms/algorithms/shortest_paths/unweighted.py
+++ b/graphblas_algorithms/algorithms/shortest_paths/unweighted.py
@@ -5,9 +5,9 @@
from ..exceptions import NoPath
__all__ = [
+ "all_pairs_shortest_path_length",
"single_source_shortest_path_length",
"single_target_shortest_path_length",
- "all_pairs_shortest_path_length",
]
diff --git a/graphblas_algorithms/algorithms/shortest_paths/weighted.py b/graphblas_algorithms/algorithms/shortest_paths/weighted.py
index a83a060..520e8bc 100644
--- a/graphblas_algorithms/algorithms/shortest_paths/weighted.py
+++ b/graphblas_algorithms/algorithms/shortest_paths/weighted.py
@@ -6,11 +6,11 @@
from ..exceptions import NoPath, Unbounded
__all__ = [
- "single_source_bellman_ford_path_length",
"bellman_ford_path",
"bellman_ford_path_length",
"bellman_ford_path_lengths",
"negative_edge_cycle",
+ "single_source_bellman_ford_path_length",
]
diff --git a/graphblas_algorithms/classes/digraph.py b/graphblas_algorithms/classes/digraph.py
index 1e9fe5f..29def96 100644
--- a/graphblas_algorithms/classes/digraph.py
+++ b/graphblas_algorithms/classes/digraph.py
@@ -443,7 +443,6 @@ def __missing__(self, key):
class DiGraph(Graph):
__networkx_backend__ = "graphblas"
- __networkx_plugin__ = "graphblas"
# "-" properties ignore self-edges, "+" properties include self-edges
# Ideally, we would have "max_rowwise+" come before "max_element+".
diff --git a/graphblas_algorithms/classes/graph.py b/graphblas_algorithms/classes/graph.py
index f3e2239..1f156a9 100644
--- a/graphblas_algorithms/classes/graph.py
+++ b/graphblas_algorithms/classes/graph.py
@@ -302,7 +302,6 @@ def __missing__(self, key):
class Graph:
__networkx_backend__ = "graphblas"
- __networkx_plugin__ = "graphblas"
# "-" properties ignore self-edges, "+" properties include self-edges
# Ideally, we would have "max_rowwise+" come before "max_element+".
diff --git a/graphblas_algorithms/linalg/modularitymatrix.py b/graphblas_algorithms/linalg/modularitymatrix.py
index 1efff65..2e72d53 100644
--- a/graphblas_algorithms/linalg/modularitymatrix.py
+++ b/graphblas_algorithms/linalg/modularitymatrix.py
@@ -2,7 +2,7 @@
from .laplacianmatrix import _laplacian_helper
-__all__ = ["modularity_matrix", "directed_modularity_matrix"]
+__all__ = ["directed_modularity_matrix", "modularity_matrix"]
def modularity_matrix(G, nodelist=None, is_weighted=False, *, name="modularity_matrix"):
diff --git a/graphblas_algorithms/nxapi/cluster.py b/graphblas_algorithms/nxapi/cluster.py
index 8e61f9b..378ea69 100644
--- a/graphblas_algorithms/nxapi/cluster.py
+++ b/graphblas_algorithms/nxapi/cluster.py
@@ -8,12 +8,12 @@
from ._utils import normalize_chunksize, partition
__all__ = [
- "triangles",
- "transitivity",
- "clustering",
"average_clustering",
- "square_clustering",
+ "clustering",
"generalized_degree",
+ "square_clustering",
+ "transitivity",
+ "triangles",
]
diff --git a/graphblas_algorithms/nxapi/cuts.py b/graphblas_algorithms/nxapi/cuts.py
index 8343109..4120681 100644
--- a/graphblas_algorithms/nxapi/cuts.py
+++ b/graphblas_algorithms/nxapi/cuts.py
@@ -2,14 +2,14 @@
from graphblas_algorithms.classes.digraph import to_graph
__all__ = [
- "cut_size",
- "volume",
- "normalized_cut_size",
+ "boundary_expansion",
"conductance",
+ "cut_size",
"edge_expansion",
"mixing_expansion",
"node_expansion",
- "boundary_expansion",
+ "normalized_cut_size",
+ "volume",
]
diff --git a/graphblas_algorithms/nxapi/dag.py b/graphblas_algorithms/nxapi/dag.py
index 56150e3..d00734f 100644
--- a/graphblas_algorithms/nxapi/dag.py
+++ b/graphblas_algorithms/nxapi/dag.py
@@ -3,7 +3,7 @@
from .exception import NetworkXError
-__all__ = ["descendants", "ancestors"]
+__all__ = ["ancestors", "descendants"]
def descendants(G, source):
diff --git a/graphblas_algorithms/nxapi/isomorphism/isomorph.py b/graphblas_algorithms/nxapi/isomorphism/isomorph.py
index 1dedb64..14c55d6 100644
--- a/graphblas_algorithms/nxapi/isomorphism/isomorph.py
+++ b/graphblas_algorithms/nxapi/isomorphism/isomorph.py
@@ -13,13 +13,7 @@ def fast_could_be_isomorphic(G1, G2):
return algorithms.fast_could_be_isomorphic(G1, G2)
-fast_graph_could_be_isomorphic = fast_could_be_isomorphic
-
-
def faster_could_be_isomorphic(G1, G2):
G1 = to_graph(G1)
G2 = to_graph(G2)
return algorithms.faster_could_be_isomorphic(G1, G2)
-
-
-faster_graph_could_be_isomorphic = faster_could_be_isomorphic
diff --git a/graphblas_algorithms/nxapi/linalg/modularitymatrix.py b/graphblas_algorithms/nxapi/linalg/modularitymatrix.py
index 76e160f..42e946a 100644
--- a/graphblas_algorithms/nxapi/linalg/modularitymatrix.py
+++ b/graphblas_algorithms/nxapi/linalg/modularitymatrix.py
@@ -3,7 +3,7 @@
from graphblas_algorithms.classes.graph import to_undirected_graph
from graphblas_algorithms.utils import not_implemented_for
-__all__ = ["modularity_matrix", "directed_modularity_matrix"]
+__all__ = ["directed_modularity_matrix", "modularity_matrix"]
@not_implemented_for("directed")
diff --git a/graphblas_algorithms/nxapi/reciprocity.py b/graphblas_algorithms/nxapi/reciprocity.py
index 54192e5..083ee50 100644
--- a/graphblas_algorithms/nxapi/reciprocity.py
+++ b/graphblas_algorithms/nxapi/reciprocity.py
@@ -4,7 +4,7 @@
from .exception import NetworkXError
-__all__ = ["reciprocity", "overall_reciprocity"]
+__all__ = ["overall_reciprocity", "reciprocity"]
@not_implemented_for("undirected", "multigraph")
diff --git a/graphblas_algorithms/nxapi/regular.py b/graphblas_algorithms/nxapi/regular.py
index a1fb650..f4ee257 100644
--- a/graphblas_algorithms/nxapi/regular.py
+++ b/graphblas_algorithms/nxapi/regular.py
@@ -3,7 +3,7 @@
from graphblas_algorithms.classes.graph import to_undirected_graph
from graphblas_algorithms.utils import not_implemented_for
-__all__ = ["is_regular", "is_k_regular"]
+__all__ = ["is_k_regular", "is_regular"]
def is_regular(G):
diff --git a/graphblas_algorithms/nxapi/shortest_paths/unweighted.py b/graphblas_algorithms/nxapi/shortest_paths/unweighted.py
index f1700f3..c88baa5 100644
--- a/graphblas_algorithms/nxapi/shortest_paths/unweighted.py
+++ b/graphblas_algorithms/nxapi/shortest_paths/unweighted.py
@@ -5,9 +5,9 @@
from ..exception import NodeNotFound
__all__ = [
+ "all_pairs_shortest_path_length",
"single_source_shortest_path_length",
"single_target_shortest_path_length",
- "all_pairs_shortest_path_length",
]
diff --git a/graphblas_algorithms/nxapi/tournament.py b/graphblas_algorithms/nxapi/tournament.py
index 6c1bb1f..14b90ea 100644
--- a/graphblas_algorithms/nxapi/tournament.py
+++ b/graphblas_algorithms/nxapi/tournament.py
@@ -2,8 +2,6 @@
from graphblas_algorithms.classes.digraph import to_directed_graph
from graphblas_algorithms.utils import not_implemented_for
-from .simple_paths import is_simple_path as is_path # noqa: F401
-
__all__ = ["is_tournament", "score_sequence", "tournament_matrix"]
diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py
new file mode 100644
index 0000000..f2ba4b3
--- /dev/null
+++ b/graphblas_algorithms/tests/_dispatched.py
@@ -0,0 +1,8 @@
+"""What the `Dispatcher` offers, for the tests that walk every dispatched name."""
+
+
+def dispatcher_functions():
+ """The algorithms the `Dispatcher` offers NetworkX, without the protocol hooks."""
+ from _nx_graphblas.core import get_functions
+
+ return get_functions()
diff --git a/graphblas_algorithms/tests/test_core.py b/graphblas_algorithms/tests/test_core.py
index 68dbeb7..9217c7c 100644
--- a/graphblas_algorithms/tests/test_core.py
+++ b/graphblas_algorithms/tests/test_core.py
@@ -1,4 +1,5 @@
import pathlib
+import tomllib
import pytest
@@ -9,17 +10,12 @@
except ImportError: # pragma: no cover (import)
setuptools = None
-try:
- import tomli
-except ImportError: # pragma: no cover (import)
- tomli = None
-
def test_version():
assert ga.__version__ > "2022.11.0"
-@pytest.mark.skipif("not setuptools or not tomli or not ga.__file__")
+@pytest.mark.skipif("not setuptools or not ga.__file__")
def test_packages():
"""Ensure all packages are declared in pyproject.toml."""
# Currently assume s`pyproject.toml` is at the same level as `graphblas_algorithms` folder.
@@ -33,7 +29,7 @@ def test_packages():
if not pyproject.exists():
pytest.skip("Did not find pyproject.toml")
with pyproject.open("rb") as f:
- pkgs2 = sorted(tomli.load(f)["tool"]["setuptools"]["packages"])
+ pkgs2 = sorted(tomllib.load(f)["tool"]["setuptools"]["packages"])
assert (
pkgs == pkgs2
), "If there are extra items on the left, add them to pyproject.toml:tool.setuptools.packages"
diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py
index 1924ff7..5c6cc1c 100644
--- a/graphblas_algorithms/tests/test_match_nx.py
+++ b/graphblas_algorithms/tests/test_match_nx.py
@@ -9,38 +9,26 @@
For now, though, let's try to match and stay up-to-date with NetworkX!
"""
+
+import re
import sys
from collections import namedtuple
from pathlib import Path
import pytest
+from graphblas_algorithms.tests._dispatched import dispatcher_functions
+
try:
- import networkx as nx # noqa: F401
+ import networkx as nx
except ImportError:
pytest.skip(
"Matching networkx namespace requires networkx to be installed", allow_module_level=True
)
-else:
- try:
- from networkx.utils import backends
-
- IS_NX_30_OR_31 = False
- except ImportError: # pragma: no cover (import)
- # This is the location in nx 3.1
- from networkx.classes import backends # noqa: F401
-
- IS_NX_30_OR_31 = True
def isdispatched(func):
"""Can this NetworkX function dispatch to other backends?"""
- if IS_NX_30_OR_31:
- return (
- callable(func)
- and hasattr(func, "dispatchname")
- and func.__module__.startswith("networkx")
- )
return (
callable(func)
and hasattr(func, "preserve_edge_attrs")
@@ -53,8 +41,6 @@ def dispatchname(func):
# Haha, there should be a better way to get this
if not isdispatched(func):
raise ValueError(f"Function is not dispatched in NetworkX: {func.__name__}")
- if IS_NX_30_OR_31:
- return func.dispatchname
return func.name
@@ -70,7 +56,7 @@ def nx_info():
rv = {} # {modulepath: {dispatchname: NameInfo}}
for modname, module in sys.modules.items():
cur = {}
- if not modname.startswith("networkx.") and modname != "networkx" or "tests" in modname:
+ if (not modname.startswith("networkx.") and modname != "networkx") or "tests" in modname:
continue
for key, val in vars(module).items():
if not key.startswith("_") and isdispatched(val):
@@ -83,28 +69,24 @@ def nx_info():
@pytest.fixture(scope="module")
def gb_info():
- rv = {} # {modulepath: {dispatchname: NameInfo}}
- from graphblas_algorithms import nxapi # noqa: F401
- from graphblas_algorithms.interface import Dispatcher
+ """Where each name we implement lives, read from `nxapi` as `scripts/maketree.py` reads it.
- ga_map = {
- fullname(val): key
- for key, val in vars(Dispatcher).items()
- if callable(val) and fullname(val).startswith("graphblas_algorithms.nxapi.")
- }
+ Reading the generated dispatch table instead would make it its own witness.
+ """
+ from networkx.utils.backends import _registered_algorithms
+
+ from graphblas_algorithms import nxapi # noqa: F401 (populates sys.modules)
+
+ rv = {} # {modulepath: {dispatchname: NameInfo}}
for modname, module in sys.modules.items():
cur = {}
if not modname.startswith("graphblas_algorithms.nxapi") or "tests" in modname:
continue
for key, val in vars(module).items():
- try:
- fname = fullname(val)
- except Exception:
+ if key.startswith("_") or key not in _registered_algorithms or not callable(val):
continue
- if key.startswith("_") or fname not in ga_map:
- continue
- dname = ga_map[fname]
- cur[dname] = NameInfo(dname, fname, f"{modname}.{key}")
+ if getattr(val, "__module__", "").startswith("graphblas_algorithms.nxapi."):
+ cur[key] = NameInfo(key, fullname(val), f"{modname}.{key}")
if cur:
rv[modname] = cur
return rv
@@ -132,7 +114,6 @@ def gb_names_to_info(gb_info):
return rv
-@pytest.mark.checkstructure
def test_nonempty(nx_info, gb_info, nx_names_to_info, gb_names_to_info):
assert len(nx_info) > 15
assert len(gb_info) > 15
@@ -153,7 +134,6 @@ def module_exists(info):
return info[2].rsplit(".", 1)[0] in sys.modules
-@pytest.mark.checkstructure
def test_dispatched_funcs_in_nxapi(nx_names_to_info, gb_names_to_info):
"""Are graphblas_algorithms functions in the correct locations in nxapi?"""
failing = False
@@ -220,18 +200,149 @@ def test_print_dispatched_implemented(nx_names_to_info, gb_names_to_info):
def test_algorithms_in_readme(nx_names_to_info, gb_names_to_info):
- """Ensure all algorithms are mentioned in README.md."""
+ """Ensure all algorithms are mentioned in README.md, each as a whole word.
+
+ A substring match would count `reciprocity` as documented by `overall_reciprocity`.
+ """
implemented = nx_names_to_info.keys() & gb_names_to_info.keys()
path = Path(__file__).parent.parent.parent / "README.md"
if not path.exists():
- return
- with path.open("r") as f:
- text = f.read()
- missing = set()
- for name in sorted(implemented):
- if name not in text:
- missing.add(name)
- if missing:
- msg = f"Algorithms missing in README.md: {', '.join(sorted(missing))}"
- print(msg)
- raise AssertionError(msg)
+ pytest.skip("README.md is not shipped with the package")
+ text = path.read_text()
+ assert implemented, "no implemented names to check"
+ missing = {name for name in implemented if not re.search(rf"\b{re.escape(name)}\b", text)}
+ assert not missing, f"Algorithms missing in README.md: {', '.join(sorted(missing))}"
+
+
+def _maketree_or_skip():
+ """Import `scripts/maketree.py` by path; `scripts/` is not a package, nor shipped."""
+ import importlib.util
+
+ path = Path(__file__).parent.parent.parent / "scripts" / "maketree.py"
+ if not path.exists():
+ pytest.skip("generators are not shipped with the package")
+ spec = importlib.util.spec_from_file_location("maketree", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_autogenerated_code_is_fresh(tmp_path):
+ """The committed generated blocks are what the generators would write today.
+
+ The generators write into copies, so a stale checkout fails here instead of being repaired,
+ and all three files are compared before anything is asserted.
+ """
+ maketree = _maketree_or_skip()
+ repo = Path(__file__).parent.parent.parent
+
+ from _nx_graphblas.core import main as plugin_main
+
+ plugin_file = repo / "_nx_graphblas" / "__init__.py"
+ plugin_copy = tmp_path / "plugin_init.py"
+ plugin_copy.write_text(plugin_file.read_text())
+ plugin_fresh = plugin_main(plugin_copy) == plugin_file.read_text()
+
+ readme = repo / "README.md"
+ interface = repo / "graphblas_algorithms" / "interface.py"
+ readme_copy = tmp_path / "README.md"
+ interface_copy = tmp_path / "interface.py"
+ readme_copy.write_text(readme.read_text(encoding="utf-8"), encoding="utf-8")
+ interface_copy.write_text(interface.read_text(encoding="utf-8"), encoding="utf-8")
+ maketree.main(print_to_console=False, readme_path=readme_copy, interface_path=interface_copy)
+
+ stale = []
+ if interface_copy.read_text(encoding="utf-8") != interface.read_text(encoding="utf-8"):
+ stale.append("graphblas_algorithms/interface.py (run `make readme`)")
+ if not plugin_fresh:
+ stale.append("_nx_graphblas/__init__.py (run `make plugin-info`)")
+ if readme_copy.read_text(encoding="utf-8") != readme.read_text(encoding="utf-8"):
+ stale.append("README.md (run `make readme`)")
+ assert not stale, "Generated code is out of date: " + "; ".join(stale)
+
+
+class _FakeModule:
+ """Stands in for an `nxapi` module the scan will walk."""
+
+ def __init__(self, name, **names):
+ self.__name__ = name
+ for key, val in names.items():
+ setattr(self, key, val)
+
+
+def test_a_public_name_networkx_does_not_dispatch_stops_the_generator(monkeypatch):
+ """A name in `__all__` that NetworkX does not dispatch is reported, not dropped."""
+ maketree = _maketree_or_skip()
+ module = _FakeModule("graphblas_algorithms.nxapi.invented", __all__=["not_a_networkx_name"])
+ monkeypatch.setitem(sys.modules, "graphblas_algorithms.nxapi.invented", module)
+ with pytest.raises(ValueError, match="not_a_networkx_name") as excinfo:
+ maketree.get_names()
+ assert "graphblas_algorithms.nxapi.invented" in str(excinfo.value)
+
+
+def test_a_module_without_all_is_read_by_the_functions_it_defines(monkeypatch):
+ """Without `__all__`, a function the module defines counts and one it imports does not."""
+ maketree = _maketree_or_skip()
+
+ def invented_name(): # pragma: no cover (never called)
+ pass
+
+ invented_name.__module__ = "graphblas_algorithms.nxapi.invented"
+ module = _FakeModule(
+ "graphblas_algorithms.nxapi.invented", invented_name=invented_name, borrowed=nx.pagerank
+ )
+ monkeypatch.setitem(sys.modules, "graphblas_algorithms.nxapi.invented", module)
+ with pytest.raises(ValueError, match="invented_name") as excinfo:
+ maketree.get_names()
+ assert "borrowed" not in str(excinfo.value)
+
+
+def test_todays_public_surface_passes_the_generator():
+ """Every public `nxapi` name is dispatched today, and the generator finds each one."""
+ maketree = _maketree_or_skip()
+ assert len(maketree.get_names()) == len(dispatcher_functions())
+
+
+def test_plugin_info_matches_dispatcher():
+ """The committed `_nx_graphblas` advertises what the `Dispatcher` offers.
+
+ Unlike the freshness test, this also runs on an installed package, which has no `scripts/`.
+ """
+ from _nx_graphblas import get_info
+ from _nx_graphblas.core import get_extra_parameters
+
+ functions = dispatcher_functions()
+ assert functions, "no dispatched functions to check"
+ advertised = get_info()["functions"]
+ assert set(advertised) == set(functions), (
+ "Plugin info is out of sync (run `make plugin-info`). "
+ f"Only in _nx_graphblas: {sorted(set(advertised) - set(functions))}; "
+ f"only in Dispatcher: {sorted(set(functions) - set(advertised))}"
+ )
+ fresh, _undocumented, _unregistered = get_extra_parameters(functions)
+ expected = {
+ name: {"extra_parameters": fresh[name]} if name in fresh else {} for name in functions
+ }
+ assert advertised == expected, "Extra parameters are out of sync (run `make plugin-info`)"
+
+
+def test_every_dispatched_name_resolves_to_a_wrapper():
+ """Every dispatch table entry is an `nxapi` wrapper, never the kernel of the same name."""
+ wrong = {}
+ for name, func in sorted(dispatcher_functions().items()):
+ module = getattr(func, "__module__", None)
+ if module is None or not module.startswith("graphblas_algorithms.nxapi"):
+ wrong[name] = module
+ assert not wrong, f"dispatched names not resolving to a wrapper: {wrong}"
+
+
+def test_nxapi_linalg_keeps_its_own_submodules():
+ """`nxapi.linalg` keeps its own submodules, which share names with `linalg`'s.
+
+ A star import from a submodule without `__all__` can put the kernel package's modules here.
+ """
+ from graphblas_algorithms import nxapi
+
+ for name in ("graphmatrix", "laplacianmatrix", "modularitymatrix", "bethehessianmatrix"):
+ module = getattr(nxapi.linalg, name)
+ assert module.__name__ == f"graphblas_algorithms.nxapi.linalg.{name}", module.__name__
diff --git a/pyproject.toml b/pyproject.toml
index b1625c6..011eb5f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,68 +1,61 @@
[build-system]
build-backend = "setuptools.build_meta"
-requires = [
- "setuptools >=64",
- "setuptools-git-versioning",
-]
+requires = ["setuptools >=77", "setuptools-git-versioning"]
[project]
name = "graphblas-algorithms"
dynamic = ["version"]
description = "Graph algorithms written in GraphBLAS and backend for NetworkX"
readme = "README.md"
-requires-python = ">=3.10"
-license = {file = "LICENSE"}
+requires-python = ">=3.11"
+# PEP 639 expression; setuptools >=77 rejects it beside a "License ::" classifier.
+license = "Apache-2.0"
+license-files = ["LICENSE"]
authors = [
- {name = "Erik Welch", email = "erik.n.welch@gmail.com"},
- {name = "Jim Kitchen"},
- {name = "Graphblas-algorithms contributors"},
+ { name = "Erik Welch", email = "erik.n.welch@gmail.com" },
+ { name = "Jim Kitchen" },
+ { name = "Graphblas-algorithms contributors" },
]
maintainers = [
- {name = "Erik Welch", email = "erik.n.welch@gmail.com"},
- {name = "Jim Kitchen", email = "jim22k@gmail.com"},
+ { name = "Erik Welch", email = "erik.n.welch@gmail.com" },
+ { name = "Jim Kitchen", email = "jim22k@gmail.com" },
]
keywords = [
- "graphblas",
- "graph",
- "sparse",
- "matrix",
- "lagraph",
- "suitesparse",
- "Networks",
- "Graph Theory",
- "Mathematics",
- "network",
- "discrete mathematics",
- "math",
+ "graphblas",
+ "graph",
+ "sparse",
+ "matrix",
+ "lagraph",
+ "suitesparse",
+ "Networks",
+ "Graph Theory",
+ "Mathematics",
+ "network",
+ "discrete mathematics",
+ "math",
]
classifiers = [
- "Development Status :: 4 - Beta",
- "License :: OSI Approved :: Apache Software License",
- "Operating System :: MacOS :: MacOS X",
- "Operating System :: POSIX :: Linux",
- "Operating System :: Microsoft :: Windows",
- "Programming Language :: Python",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.10",
- "Programming Language :: Python :: 3.11",
- "Programming Language :: Python :: 3.12",
- "Programming Language :: Python :: 3 :: Only",
- "Intended Audience :: Developers",
- "Intended Audience :: Other Audience",
- "Intended Audience :: Science/Research",
- "Topic :: Scientific/Engineering",
- "Topic :: Scientific/Engineering :: Bio-Informatics",
- "Topic :: Scientific/Engineering :: Information Analysis",
- "Topic :: Scientific/Engineering :: Mathematics",
- "Topic :: Scientific/Engineering :: Physics",
- "Topic :: Software Development :: Libraries :: Python Modules",
-]
-dependencies = [
- "python-graphblas >=2023.1.0",
+ "Development Status :: 4 - Beta",
+ "Operating System :: MacOS :: MacOS X",
+ "Operating System :: POSIX :: Linux",
+ "Operating System :: Microsoft :: Windows",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3 :: Only",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Other Audience",
+ "Intended Audience :: Science/Research",
+ "Topic :: Scientific/Engineering",
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
+ "Topic :: Scientific/Engineering :: Information Analysis",
+ "Topic :: Scientific/Engineering :: Mathematics",
+ "Topic :: Scientific/Engineering :: Physics",
+ "Topic :: Software Development :: Libraries :: Python Modules",
]
-
-[project.entry-points."networkx.plugins"]
-graphblas = "graphblas_algorithms.interface:Dispatcher"
+dependencies = ["python-graphblas >=2023.1.0"]
[project.entry-points."networkx.backends"]
graphblas = "graphblas_algorithms.interface:Dispatcher"
@@ -78,52 +71,51 @@ changelog = "https://github.com/python-graphblas/graphblas-algorithms/releases"
[project.optional-dependencies]
test = [
- "pytest",
- "networkx >=3.0",
- "scipy >=1.9",
- "setuptools",
- "tomli",
-]
-all = [
- "graphblas-algorithms[test]",
+ "pytest",
+ "pytest-xdist",
+ "networkx >=3.6",
+ "rich", # scripts/maketree.py, which the generated-code freshness test runs
+ "scipy >=1.9",
+ "setuptools",
]
+all = ["graphblas-algorithms[test]"]
[tool.setuptools]
# Let's be explicit (we test this too)
# TODO: it would be nice if setuptools (or our build backend) could handle this automatically and reliably.
# $ python -c 'from setuptools import find_packages ; [print(x) for x in sorted(find_packages())]'
# $ find graphblas_algorithms/ -name __init__.py -print | sort | sed -e 's/\/__init__.py//g' -e 's/\//./g'
-# $ python -c 'import tomli ; [print(x) for x in sorted(tomli.load(open("pyproject.toml", "rb"))["tool"]["setuptools"]["packages"])]'
+# $ python -c 'import tomllib ; [print(x) for x in sorted(tomllib.load(open("pyproject.toml", "rb"))["tool"]["setuptools"]["packages"])]'
packages = [
- "_nx_graphblas",
- "graphblas_algorithms",
- "graphblas_algorithms.algorithms",
- "graphblas_algorithms.algorithms.centrality",
- "graphblas_algorithms.algorithms.community",
- "graphblas_algorithms.algorithms.components",
- "graphblas_algorithms.algorithms.isomorphism",
- "graphblas_algorithms.algorithms.link_analysis",
- "graphblas_algorithms.algorithms.operators",
- "graphblas_algorithms.algorithms.shortest_paths",
- "graphblas_algorithms.algorithms.tests",
- "graphblas_algorithms.algorithms.traversal",
- "graphblas_algorithms.classes",
- "graphblas_algorithms.generators",
- "graphblas_algorithms.linalg",
- "graphblas_algorithms.nxapi",
- "graphblas_algorithms.nxapi.centrality",
- "graphblas_algorithms.nxapi.community",
- "graphblas_algorithms.nxapi.components",
- "graphblas_algorithms.nxapi.generators",
- "graphblas_algorithms.nxapi.isomorphism",
- "graphblas_algorithms.nxapi.linalg",
- "graphblas_algorithms.nxapi.link_analysis",
- "graphblas_algorithms.nxapi.operators",
- "graphblas_algorithms.nxapi.shortest_paths",
- "graphblas_algorithms.nxapi.tests",
- "graphblas_algorithms.nxapi.traversal",
- "graphblas_algorithms.tests",
- "graphblas_algorithms.utils",
+ "_nx_graphblas",
+ "graphblas_algorithms",
+ "graphblas_algorithms.algorithms",
+ "graphblas_algorithms.algorithms.centrality",
+ "graphblas_algorithms.algorithms.community",
+ "graphblas_algorithms.algorithms.components",
+ "graphblas_algorithms.algorithms.isomorphism",
+ "graphblas_algorithms.algorithms.link_analysis",
+ "graphblas_algorithms.algorithms.operators",
+ "graphblas_algorithms.algorithms.shortest_paths",
+ "graphblas_algorithms.algorithms.tests",
+ "graphblas_algorithms.algorithms.traversal",
+ "graphblas_algorithms.classes",
+ "graphblas_algorithms.generators",
+ "graphblas_algorithms.linalg",
+ "graphblas_algorithms.nxapi",
+ "graphblas_algorithms.nxapi.centrality",
+ "graphblas_algorithms.nxapi.community",
+ "graphblas_algorithms.nxapi.components",
+ "graphblas_algorithms.nxapi.generators",
+ "graphblas_algorithms.nxapi.isomorphism",
+ "graphblas_algorithms.nxapi.linalg",
+ "graphblas_algorithms.nxapi.link_analysis",
+ "graphblas_algorithms.nxapi.operators",
+ "graphblas_algorithms.nxapi.shortest_paths",
+ "graphblas_algorithms.nxapi.tests",
+ "graphblas_algorithms.nxapi.traversal",
+ "graphblas_algorithms.tests",
+ "graphblas_algorithms.utils",
]
[tool.setuptools-git-versioning]
@@ -133,7 +125,7 @@ dirty_template = "{tag}+{ccount}.g{sha}.dirty"
[tool.black]
line-length = 100
-target-version = ["py310", "py311", "py312"]
+target-version = ["py311", "py312", "py313"]
[tool.isort]
sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"]
@@ -143,22 +135,25 @@ float_to_top = true
default_section = "THIRDPARTY"
known_first_party = "graphblas_algorithms"
line_length = 100
-skip = [
- "graphblas_algorithms/nxapi/__init__.py",
- "scripts/bench.py",
-]
+skip = ["graphblas_algorithms/nxapi/__init__.py", "scripts/bench.py"]
[tool.pytest.ini_options]
minversion = "6.0"
testpaths = "graphblas_algorithms"
xfail_strict = false
-markers = [
- "checkstructure: Skipped unless --check-structure passed",
+addopts = [
+ "--strict-config", # Force error if config is misspelled
+ "--strict-markers", # Force error if a marker is misspelled or otherwise unregistered
+ "-ra", # Print summary of all fails/errors
]
+[tool.codespell]
+# "THIRDPARTY" is an isort section name, not a misspelling.
+ignore-words-list = "thirdparty"
+
[tool.coverage.run]
branch = true
-source = ["graphblas_algorithms"]
+source = ["graphblas_algorithms", "_nx_graphblas"]
omit = []
[tool.coverage.report]
@@ -167,105 +162,123 @@ precision = 1
fail_under = 0
skip_covered = true
skip_empty = true
-exclude_lines = [
- "pragma: no cover",
- "raise AssertionError",
- "raise NotImplementedError",
-]
+exclude_lines = ["pragma: no cover", "raise AssertionError", "raise NotImplementedError"]
[tool.ruff]
-# https://github.com/charliermarsh/ruff/
+# https://docs.astral.sh/ruff/
line-length = 100
-target-version = "py310"
+target-version = "py311"
+
+[tool.ruff.lint]
unfixable = [
- "F841" # unused-variable (Note: can leave useless expression)
-]
-select = [
- "ALL",
+ "F841", # unused-variable (Note: can leave useless expression)
]
+select = ["ALL"]
external = [
- # noqa codes that ruff doesn't know about: https://github.com/charliermarsh/ruff#external
+ # noqa codes that ruff doesn't know about: https://docs.astral.sh/ruff/settings/#lint_external
]
ignore = [
- # Would be nice to fix these
- "D100", # Missing docstring in public module
- "D101", # Missing docstring in public class
- "D102", # Missing docstring in public method
- "D103", # Missing docstring in public function
- "D104", # Missing docstring in public package
- "D105", # Missing docstring in magic method
- # "D107", # Missing docstring in `__init__`
- "D401", # First line of docstring should be in imperative mood:
- # "D417", # Missing argument description in the docstring:
- "PLE0605", # Invalid format for `__all__`, must be `tuple` or `list` (Note: broken in v0.0.237)
+ # Would be nice to fix these
+ "D100", # Missing docstring in public module
+ "D101", # Missing docstring in public class
+ "D102", # Missing docstring in public method
+ "D103", # Missing docstring in public function
+ "D104", # Missing docstring in public package
+ "D105", # Missing docstring in magic method
+ # "D107", # Missing docstring in `__init__`
+ "D401", # First line of docstring should be in imperative mood:
+ # "D417", # Missing argument description in the docstring:
+ "PLE0605", # Invalid format for `__all__`, must be `tuple` or `list` (Note: broken in v0.0.237)
- # Maybe consider
- # "SIM300", # Yoda conditions are discouraged, use ... instead (Note: we're not this picky)
- # "SIM401", # Use dict.get ... instead of if-else-block (Note: if-else better for coverage and sometimes clearer)
- # "TRY004", # Prefer `TypeError` exception for invalid type (Note: good advice, but not worth the nuisance)
- # "TRY200", # Use `raise from` to specify exception cause (Note: sometimes okay to raise original exception)
- "UP038", # Use `X | Y` in `isinstance` call instead of `(X, Y)` (Note: using `|` seems to be slower)
+ # Maybe consider
+ # "SIM300", # Yoda conditions are discouraged, use ... instead (Note: we're not this picky)
+ # "SIM401", # Use dict.get ... instead of if-else-block (Note: if-else better for coverage and sometimes clearer)
+ # "TRY004", # Prefer `TypeError` exception for invalid type (Note: good advice, but not worth the nuisance)
+ # "B904", # Use `raise from` to specify exception cause (Note: sometimes okay to raise original exception)
- # Intentionally ignored
- "COM812", # Trailing comma missing
- "D203", # 1 blank line required before class docstring (Note: conflicts with D211, which is preferred)
- "D400", # First line should end with a period (Note: prefer D415, which also allows "?" and "!")
- "F403", # `from .classes import *` used; unable to detect undefined names (Note: used to match networkx)
- "N802", # Function name ... should be lowercase
- "N803", # Argument name ... should be lowercase (Maybe okay--except in tests)
- "N806", # Variable ... in function should be lowercase
- "N807", # Function name should not start and end with `__`
- "N818", # Exception name ... should be named with an Error suffix (Note: good advice)
- "PLR0911", # Too many return statements
- "PLR0912", # Too many branches
- "PLR0913", # Too many arguments to function call
- "PLR0915", # Too many statements
- "PLR2004", # Magic number used in comparison, consider replacing magic with a constant variable
- "PLW2901", # Outer for loop variable ... overwritten by inner assignment target (Note: good advice, but too strict)
- "RET502", # Do not implicitly `return None` in function able to return non-`None` value
- "RET503", # Missing explicit `return` at the end of function able to return non-`None` value
- "RET504", # Unnecessary variable assignment before `return` statement
- "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` (Note: no annotations yet)
- "S110", # `try`-`except`-`pass` detected, consider logging the exception (Note: good advice, but we don't log)
- "S112", # `try`-`except`-`continue` detected, consider logging the exception (Note: good advice, but we don't log)
- "SIM102", # Use a single `if` statement instead of nested `if` statements (Note: often necessary)
- "SIM105", # Use contextlib.suppress(...) instead of try-except-pass (Note: try-except-pass is much faster)
- "SIM108", # Use ternary operator ... instead of if-else-block (Note: if-else better for coverage and sometimes clearer)
- "TRY003", # Avoid specifying long messages outside the exception class (Note: why?)
- "FIX001", "FIX002", "FIX003", "FIX004", # flake8-fixme (like flake8-todos)
+ # Intentionally ignored
+ "COM812", # Trailing comma missing
+ "D203", # 1 blank line required before class docstring (Note: conflicts with D211, which is preferred)
+ "D400", # First line should end with a period (Note: prefer D415, which also allows "?" and "!")
+ "E721", # Use `is` for type comparisons (Note: we compare dtypes, where `==` is the intended check)
+ "F403", # `from .classes import *` used; unable to detect undefined names (Note: used to match networkx)
+ "N802", # Function name ... should be lowercase
+ "N803", # Argument name ... should be lowercase (Maybe okay, except in tests)
+ "N806", # Variable ... in function should be lowercase
+ "N807", # Function name should not start and end with `__`
+ "N818", # Exception name ... should be named with an Error suffix (Note: good advice)
+ "PLC0415", # `import` should be at top-level (Note: deferred imports avoid import cycles)
+ "PLR0911", # Too many return statements
+ "PLR0912", # Too many branches
+ "PLR0913", # Too many arguments to function call
+ "PLR0917", # Too many positional arguments
+ "PLR0915", # Too many statements
+ "PLR2004", # Magic number used in comparison, consider replacing magic with a constant variable
+ "PLW1641", # Object does not implement `__hash__` (Note: our mapping and set classes are mutable)
+ "PLW2901", # Outer for loop variable ... overwritten by inner assignment target (Note: good advice, but too strict)
+ "RET502", # Do not implicitly `return None` in function able to return non-`None` value
+ "RET503", # Missing explicit `return` at the end of function able to return non-`None` value
+ "RET504", # Unnecessary variable assignment before `return` statement
+ "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` (Note: no annotations yet)
+ "RUF021", # parenthesize-chained-operators (Note: its fix pushes lines past flake8's length limit)
+ "RUF046", # Value being cast is already the right type (Note: `int(round(x))` says what it means)
+ "RUF059", # Unpacked variable is never used (Note: we unpack shapes and index pairs and use one half)
+ "S110", # `try`-`except`-`pass` detected, consider logging the exception (Note: good advice, but we don't log)
+ "S112", # `try`-`except`-`continue` detected, consider logging the exception (Note: good advice, but we don't log)
+ "SIM102", # Use a single `if` statement instead of nested `if` statements (Note: often necessary)
+ "SIM103", # Return the condition directly (Note: the explicit branches read better here)
+ "SIM105", # Use contextlib.suppress(...) instead of try-except-pass (Note: try-except-pass is much faster)
+ "SIM108", # Use ternary operator ... instead of if-else-block (Note: if-else better for coverage and sometimes clearer)
+ "TRY003", # Avoid specifying long messages outside the exception class (Note: why?)
- # Ignored categories
- "C90", # mccabe (Too strict, but maybe we should make things less complex)
- "I", # isort (Should we replace `isort` with this?)
- "ANN", # flake8-annotations (We don't use annotations yet)
- "BLE", # flake8-blind-except (Maybe consider)
- "FBT", # flake8-boolean-trap (Why?)
- "DJ", # flake8-django (We don't use django)
- "EM", # flake8-errmsg (Perhaps nicer, but too much work)
- "ICN", # flake8-import-conventions (Doesn't allow "_" prefix such as `_np`)
- "PYI", # flake8-pyi (We don't have stub files yet)
- "SLF", # flake8-self (We can use our own private variables--sheesh!)
- "TID", # flake8-tidy-imports (Rely on isort and our own judgement)
- "TCH", # flake8-type-checking (Note: figure out type checking later)
- "ARG", # flake8-unused-arguments (Sometimes helpful, but too strict)
- "TD", # flake8-todos (Maybe okay to add some of these)
- "ERA", # eradicate (We like code in comments!)
- "PD", # pandas-vet (Intended for scripts that use pandas, not libraries)
+ # Ignored categories
+ "C90", # mccabe (Too strict, but maybe we should make things less complex)
+ "CPY", # flake8-copyright (We don't put a copyright header in every file)
+ "I", # isort (Should we replace `isort` with this?)
+ "ANN", # flake8-annotations (We don't use annotations yet)
+ "BLE", # flake8-blind-except (Maybe consider)
+ "FBT", # flake8-boolean-trap (Why?)
+ "DJ", # flake8-django (We don't use django)
+ "EM", # flake8-errmsg (Perhaps nicer, but too much work)
+ "ICN", # flake8-import-conventions (Doesn't allow "_" prefix such as `_np`)
+ "PYI", # flake8-pyi (We don't have stub files yet)
+ "SLF", # flake8-self (We can use our own private variables, sheesh!)
+ "TID", # flake8-tidy-imports (Rely on isort and our own judgement)
+ "TC", # flake8-type-checking (Note: figure out type checking later)
+ "ARG", # flake8-unused-arguments (Sometimes helpful, but too strict)
+ "TD", # flake8-todos (Maybe okay to add some of these)
+ "FIX", # flake8-fixme (like flake8-todos)
+ "ERA", # eradicate (We like code in comments!)
+ "PD", # pandas-vet (Intended for scripts that use pandas, not libraries)
]
-[tool.ruff.per-file-ignores]
-"__init__.py" = ["F401"] # Allow unused imports (w/o defining `__all__`)
-"graphblas_algorithms/**/tests/*py" = ["S101", "T201", "D103", "D100"] # Allow assert, print, and no docstring
-"graphblas_algorithms/interface.py" = ["PIE794"] # Allow us to use `mod = nxapi.` repeatedly
-"graphblas_algorithms/nxapi/exception.py" = ["F401"] # Allow unused imports (w/o defining `__all__`)
-"scripts/*.py" = ["INP001", "S101", "T201"] # Not a package, allow assert, allow print
+[tool.ruff.lint.per-file-ignores]
+"__init__.py" = ["F401"] # Allow unused imports (w/o defining `__all__`)
+"_nx_graphblas/__init__.py" = ["E501"] # Generated; one line per parameter description
+"_nx_graphblas/core.py" = ["T201"] # Printing is how this reports what it regenerated
+"graphblas_algorithms/**/tests/*py" = [
+ "S101",
+ "T201",
+ "D103",
+ "D100",
+] # Allow assert, print, and no docstring
+"graphblas_algorithms/interface.py" = ["PIE794"] # Allow us to use `mod = nxapi.` repeatedly
+"graphblas_algorithms/nxapi/exception.py" = ["F401"] # Allow unused imports (w/o defining `__all__`)
+"scripts/*.py" = [
+ "INP001", # Not a package
+ "S101", # Allow assert
+ "S113", # requests without a timeout (Note: these are interactive download helpers)
+ "SIM115", # Allow opening a file without a context manager
+ "T201", # Allow print
+ "FURB", # refurb (Note: too opinionated for one-off scripts)
+]
-[tool.ruff.flake8-builtins]
+[tool.ruff.lint.flake8-builtins]
builtins-ignorelist = ["copyright"]
-[tool.ruff.flake8-pytest-style]
+[tool.ruff.lint.flake8-pytest-style]
fixture-parentheses = false
mark-parentheses = false
-[tool.ruff.pydocstyle]
+[tool.ruff.lint.pydocstyle]
convention = "numpy"
diff --git a/run_nx_tests.sh b/run_nx_tests.sh
index 740ab26..e0e638a 100755
--- a/run_nx_tests.sh
+++ b/run_nx_tests.sh
@@ -1,6 +1,4 @@
#!/bin/bash
-NETWORKX_GRAPH_CONVERT=graphblas \
NETWORKX_TEST_BACKEND=graphblas \
NETWORKX_FALLBACK_TO_NX=True \
pytest --pyargs networkx "$@"
-# pytest --pyargs networkx --cov --cov-report term-missing "$@"
diff --git a/scripts/maketree.py b/scripts/maketree.py
index e4deed5..93f648e 100755
--- a/scripts/maketree.py
+++ b/scripts/maketree.py
@@ -4,20 +4,15 @@
This updates API tree in README.md and dispatch functions in `graphblas_algorithms/interface.py`.
"""
+
+import inspect
+import sys
from io import StringIO
from pathlib import Path
import rich
-from graphblas.core.utils import _autogenerate_code
from rich.tree import Tree
-from graphblas_algorithms.tests import test_match_nx
-from graphblas_algorithms.tests.test_match_nx import get_fullname
-
-
-def get_fixture(attr):
- return getattr(test_match_nx, attr).__wrapped__
-
def trim(name):
for prefix in ["networkx.algorithms.", "networkx."]:
@@ -26,11 +21,94 @@ def trim(name):
raise ValueError(f"{name!r} does not begin with a recognized prefix")
+def nx_fullname(name, func):
+ """`func`'s NetworkX path, plus " (name)" when it is registered under another name.
+
+ For example `bipartite_average_clustering` is `bipartite.cluster.average_clustering`.
+ """
+ fullname = f"{func.__module__}.{func.__name__}"
+ if not fullname.endswith(f".{name}"):
+ fullname += f" ({name})"
+ return fullname
+
+
+def public_names(modname, module):
+ """`module.__all__` if it has one, else the public functions `modname` itself defines."""
+ if (names := getattr(module, "__all__", None)) is not None:
+ return list(names)
+ return [
+ key
+ for key, val in vars(module).items()
+ if not key.startswith("_")
+ and inspect.isfunction(val)
+ and getattr(val, "__module__", "") == modname
+ ]
+
+
def get_names():
- nx_names_to_info = get_fixture("nx_names_to_info")(get_fixture("nx_info")())
- gb_names_to_info = get_fixture("gb_names_to_info")(get_fixture("gb_info")())
- implemented = nx_names_to_info.keys() & gb_names_to_info.keys()
- return sorted(trim(get_fullname(next(iter(nx_names_to_info[name])))) for name in implemented)
+ """Names we implement: the `nxapi` functions that NetworkX's registry knows.
+
+ Scanning `nxapi`, not the `Dispatcher`, keeps the generated table from being its own input.
+ A public `nxapi` name NetworkX does not dispatch raises, rather than being left out of the
+ generated code while it stays importable. On the older supported NetworkX this also stops on a
+ wrapper for a name only the newer one dispatches.
+ """
+ from networkx.utils.backends import _registered_algorithms
+
+ from graphblas_algorithms import nxapi # noqa: F401 (populates sys.modules)
+
+ implemented = set()
+ unregistered = {}
+ for modname, module in sys.modules.items():
+ if not modname.startswith("graphblas_algorithms.nxapi") or "tests" in modname:
+ continue
+ if any(part.startswith("_") for part in modname.split(".")[1:]):
+ continue
+ missing = [
+ name for name in public_names(modname, module) if name not in _registered_algorithms
+ ]
+ if missing:
+ unregistered[modname] = sorted(missing)
+ for key, val in vars(module).items():
+ if key.startswith("_") or key not in _registered_algorithms or not callable(val):
+ continue
+ if getattr(val, "__module__", "").startswith("graphblas_algorithms.nxapi."):
+ implemented.add(key)
+ if unregistered:
+ import networkx
+
+ found = "; ".join(
+ f"{mod}: {', '.join(names)}" for mod, names in sorted(unregistered.items())
+ )
+ raise ValueError(
+ f"networkx {networkx.__version__} does not dispatch these public nxapi names, "
+ f"so the generated code would leave them out: {found}"
+ )
+ return sorted(trim(nx_fullname(name, _registered_algorithms[name])) for name in implemented)
+
+
+README_BEGIN = '[//]: # "Begin auto-generated code"'
+README_END = '[//]: # "End auto-generated code"'
+INTERFACE_BEGIN = "# Begin auto-generated code: dispatch"
+INTERFACE_END = "# End auto-generated code: dispatch"
+
+
+def splice(path, text, begin, end):
+ """Replace what lies between the `begin` and `end` markers of `path` with `text`.
+
+ Each marker, with its newline, must appear exactly once, so a damaged or duplicated marker
+ raises instead of leaving the file unchanged or splicing into the wrong block. UTF-8 on
+ both sides, since the README tree is box-drawing characters.
+ """
+ old = path.read_text(encoding="utf-8")
+ begin, end = f"{begin}\n", f"{end}\n"
+ counts = {m.strip(): old.count(m) for m in (begin, end)}
+ if any(n != 1 for n in counts.values()):
+ found = ", ".join(f"{m!r} found {n} times" for m, n in counts.items())
+ raise ValueError(f"{path}: expected each generator marker exactly once, but {found}")
+ start = old.index(begin) + len(begin)
+ stop = old.index(end, start)
+ path.write_text(old[:start] + text + old[stop:], encoding="utf-8")
# Dispatched functions that are only available from `nxapi`
@@ -40,7 +118,24 @@ def get_names():
}
-def main(print_to_console=True, update_readme=True, update_interface=True):
+def main(
+ print_to_console=True,
+ update_readme=True,
+ update_interface=True,
+ readme_path=None,
+ interface_path=None,
+):
+ """Write the algorithm tree into README.md and the dispatch table into interface.py.
+
+ The paths default to this checkout's files; a test passes copies.
+ """
+ repo = Path(__file__).parent.parent
+ readme_path = repo / "README.md" if readme_path is None else Path(readme_path)
+ interface_path = (
+ repo / "graphblas_algorithms" / "interface.py"
+ if interface_path is None
+ else Path(interface_path)
+ )
fullnames = get_names()
# Step 1: add to README.md
tree = Tree("graphblas_algorithms.nxapi")
@@ -66,13 +161,7 @@ def addtree(path):
rich.print(tree, file=s)
s.seek(0)
text = s.read()
- _autogenerate_code(
- Path(__file__).parent.parent / "README.md",
- f"\n```\n{text}```\n\n",
- begin="[//]: # (Begin auto-generated code)",
- end="[//]: # (End auto-generated code)",
- callblack=False,
- )
+ splice(readme_path, f"\n```\n{text}```\n\n", README_BEGIN, README_END)
# Step 2: add to interface.py
lines = []
prev_mod = None
@@ -97,13 +186,10 @@ def addtree(path):
lines.append("")
lines.append(" del mod")
lines.append("")
- text = "\n".join(lines)
+ # The text's last line becomes the END marker's indent, so end at the class body's.
+ text = "\n".join(lines) + " " * 4
if update_interface:
- _autogenerate_code(
- Path(__file__).parent.parent / "graphblas_algorithms" / "interface.py",
- text,
- specializer="dispatch",
- )
+ splice(interface_path, text, INTERFACE_BEGIN, INTERFACE_END)
return tree