Skip to content

graphs: use by_weight in matching - #42750

Merged
vbraun merged 3 commits into
sagemath:developfrom
ProfTR55:13112-matching-by-weight
Sep 6, 2026
Merged

vbraun merged 3 commits into
sagemath:developfrom
ProfTR55:13112-matching-by-weight

Conversation

@ProfTR55

@ProfTR55 ProfTR55 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Part of #13112, following #42740.

Graph.matching and BipartiteGraph.matching now take by_weight, weight_function and check_weight, in the order used by the rest of the graph module. use_edge_labels is deprecated in their favour, and by_weight takes its position, so the arguments before it keep their positional meaning.

The two files go together. BipartiteGraph.matching delegates to Graph.matching for 'Edmonds' and 'LP', so converting only one would make the library raise its own deprecation warning on that call.

A weight function can now be supplied, which was not expressible before:

sage: g = Graph([(0, 1, {'cost': 1}), (1, 2, {'cost': 9}), (2, 3, {'cost': 2})])
sage: g.matching(weight_function=lambda e: e[2]['cost'])
[(1, 2, {'cost': 9})]

Two things worth flagging:

  • As in graphs: use by_weight in edge_connectivity #42740, the weight comes from GenericGraph._get_weight_function. The local helper it replaces returned 1 for any non-numeric label, so such a label was silently weighted 1; check_weight now rejects it. A behaviour change, not only a rename.
  • BipartiteGraph.matching does not delegate for 'Hopcroft-Karp' and 'Eppstein', so it sets by_weight = True itself when a weight_function is given, in order to reject that combination rather than ignore the weights. Its error message names by_weight accordingly.

Tests

Doctests pass for matching.py, graph.py, generic_graph.py and matching_covered_graph.py, and all matching doctests pass in bipartite_graph.py. The relabel and matching_polynomial failures in my local run appear identically with an unmodified copy of the file — my build tree is one release behind.

📝 Checklist

  • The title is concise and informative.
  • The description explains in detail what this PR is about.
  • I have linked a relevant issue or discussion.
  • I have created tests covering the changes.
  • I have updated the documentation accordingly.

⌛ Dependencies

None, though it follows the pattern settled in #42740.

Following sagemath#13112, Graph.matching and BipartiteGraph.matching now take the
by_weight / weight_function / check_weight combination used elsewhere in
the graph module, and use_edge_labels is deprecated in its favour.

The two must change together: BipartiteGraph.matching delegates to
Graph.matching for the Edmonds and LP algorithms, so converting only one
of them would make the delegation itself raise the deprecation warning.

As in sagemath#42740, the weight is obtained through
GenericGraph._get_weight_function rather than a local helper, so a weight
function can be supplied, and a label that is not a number is now rejected
by check_weight instead of being silently treated as 1.
@github-actions

github-actions Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Documentation preview for this PR (built with commit 818ee65; changes) is ready! 🎉
This preview will update shortly after each push to this PR.

@dcoudert

dcoudert commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

Check the failing doctests

The deprecation of use_edge_labels in BipartiteGraph.matching made this
caller emit a warning, which broke its doctests. It is the only caller of
matching outside sage.graphs.

The use of use_edge_labels in Graph.incidence_matrix and in bliss is
unrelated: there it selects whether labels appear in the edge tuples, and
whether they are used as colours, not as weights.

@dcoudert dcoudert left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Thanks.

vbraun pushed a commit to vbraun/sage that referenced this pull request Sep 6, 2026
Following sagemath#13112, sagemath#42740 and sagemath#42750.

The local weight helper read the label with G.edge_label(u, v) because the
constraint loop iterated without labels. The loop now iterates with them and
slices for the frozenset, so the weight function receives the edge in the
form the rest of the module uses.

The call to flow in bounded_outdegree_orientation still passes
use_edge_labels; flow has not been converted yet.
vbraun pushed a commit to vbraun/sage that referenced this pull request Sep 6, 2026
Part of sagemath#13112, following sagemath#42740 and sagemath#42750.

`minimum_outdegree_orientation` now takes `by_weight`, `weight_function`
and `check_weight`, and `use_edge_labels` is deprecated in their favour.

One detail specific to this function: its local weight helper read the
label with `G.edge_label(u, v)`, because the constraint loop iterated
with `labels=False` and so only had the endpoints. The loop now iterates
with labels and slices where the endpoints are needed:

```python
p.sum(weight_function(e) * outgoing(u, e[:2],
orientation[frozenset(e[:2])])
      for e in G.edge_iterator(vertices=[u]))
```

`_scream_if_not_simple` is called at the top, so `(u, v)` still
identifies an edge uniquely.

A weight function can now be supplied:

```python
sage: g = graphs.PetersenGraph()
sage: _ = [g.set_edge_label(u, v, {'w': 1}) for u, v in
g.edge_iterator(labels=False)]
sage: g.set_edge_label(0, 1, {'w': 100})
sage: max(g.minimum_outdegree_orientation(weight_function=lambda e:
e[2]['w']).out_degree())
3
```

As in the previous two, the weight comes from
`GenericGraph._get_weight_function`, so a label that is not a number is
now rejected by `check_weight` instead of being silently weighted 1.

`bounded_outdegree_orientation` in the same file still calls `flow(...,
use_edge_labels=True)`. `flow` is one of the functions left in
`generic_graph.py`, so that call is left alone and will be updated with
it.

### Tests

Doctests pass with `--long` for `orientations.py`, `graph.py`,
`digraph.py`, `thematic_tutorials/linear_programming.rst` and the
`lp_doctest.py` book test — every place in the tree that mentions this
function. None of them passed `use_edge_labels`.

### 📝 Checklist

<!-- Put an `x` in all the boxes that apply. -->

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [x] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [x] I have updated the documentation accordingly.

### ⌛ Dependencies

None.

URL: sagemath#42760
Reported by: Muhammet Doğukan Bingöl
Reviewer(s): David Coudert
@vbraun
vbraun merged commit 0bff468 into sagemath:develop Sep 6, 2026
25 of 26 checks passed
vbraun pushed a commit to vbraun/sage that referenced this pull request Sep 16, 2026
Following sagemath#13112, sagemath#42740, sagemath#42750 and sagemath#42760.

flow, _ford_fulkerson and multicommodity_flow now take the by_weight /
weight_function / check_weight combination, and use_edge_labels is
deprecated in favour of by_weight.

flow keeps True as the default, which is what its signature already did.
Its documentation claimed the default was False, which was wrong; the
documentation is corrected rather than the behaviour.

_ford_fulkerson is private, so it gets no deprecation: the parameter is
simply renamed, and flow passes down the weight function it has already
resolved rather than resolving it twice.

edge_cut keeps its own use_edge_labels parameter for now, since it belongs
to a later batch, but its calls to flow are updated so that the library
does not raise its own deprecation warning. The calls in
edge_disjoint_paths, vertex_disjoint_paths, bounded_outdegree_orientation
and one doctest in graph.py are updated for the same reason.
vbraun pushed a commit to vbraun/sage that referenced this pull request Sep 16, 2026
Release Manager
sagemathgh-42772: graphs: use by_weight in flow and multicommodity_flow
    
Part of sagemath#13112, following sagemath#42740, sagemath#42750 and sagemath#42760.

`flow`, `_ford_fulkerson` and `multicommodity_flow` now take
`by_weight`, `weight_function` and `check_weight`, and `use_edge_labels`
is deprecated in their favour.

```python
sage: D = DiGraph([(0, 1, {'cap': 3}), (1, 2, {'cap': 2})])
sage: D.flow(0, 2, weight_function=lambda e: e[2]['cap'])
2
```

Three things worth flagging.

**A documentation bug in `flow`.** Its signature has always had
`use_edge_labels=True`, but the docstring said `(default: ``False``)`.
`by_weight` therefore keeps `True` as the default — changing it would
silently change the result of `G.flow(x, y)` on a labelled graph — and
the documentation is corrected instead. Whether the default *should* be
`False`, for consistency with the rest of the module, seems worth
deciding separately.

**`_ford_fulkerson` gets no deprecation.** It is private, so the
parameter is simply renamed. `flow` passes down the weight function it
has already resolved, so `_get_weight_function` is not called twice; a
direct call still resolves it, since the method is doctested on its own.

**`edge_cut` is not converted here.** It belongs to a later batch, and
keeps its own `use_edge_labels` parameter, but its two calls to `flow`
now pass `by_weight` so that the library does not raise its own
deprecation warning. The calls in `edge_disjoint_paths`,
`vertex_disjoint_paths`, `bounded_outdegree_orientation` and one doctest
in `graph.py` are updated for the same reason.

As in the earlier ones, the weight comes from
`GenericGraph._get_weight_function`, so a label that is not a number is
now rejected by `check_weight` rather than silently treated as capacity
1.

### Tests

Doctests pass with `--long` for `generic_graph.py`, `graph.py`,
`digraph.py`, `orientations.py` and `connectivity.pyx`. I checked the
whole tree, `src/doc` included, for callers passing `use_edge_labels` to
these three methods; the ones listed above are all of them.

### 📝 Checklist

<!-- Put an `x` in all the boxes that apply. -->

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [x] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [x] I have updated the documentation accordingly.

### ⌛ Dependencies

None.
    
URL: sagemath#42772
Reported by: Muhammet Doğukan Bingöl
Reviewer(s): David Coudert
vbraun pushed a commit to vbraun/sage that referenced this pull request Sep 29, 2026
Release Manager
sagemathgh-42839: graphs: use by_weight in edge_cut, multiway_cut and max_cut
    
Part of sagemath#13112. Replaces the `use_edge_labels` parameter of `edge_cut`,
`multiway_cut` and `max_cut` by the `by_weight` / `weight_function` /
`check_weight` triple used elsewhere in the graph module, deprecating
the old
name via `rename_keyword`.

Follows sagemath#42740, sagemath#42750, sagemath#42760 and sagemath#42772.

### A fix in `edge_cut`

The saturation test compared the weight of an edge of the graph with the
weight
of a label of the *flow* graph:

```python
if (not use_edge_labels or
        weight(g.edge_label(u, v)) == weight(l)):
```

`l` there is a flow value, not an edge label, so a user-supplied
`weight_function` would have been applied to it. It now compares the
capacity of
the arc with the flow it carries:

```python
if (not by_weight or
        weight_function((u, v, g.edge_label(u, v))) == l):
```

This was invisible before because `weight` was the identity on numbers.

### Behaviour change

`max_cut` used to treat a non-real label as a weight of `1`
(`x if x in RR else 1`), and `edge_cut` did the same for `{}`. Both now
go
through `_get_weight_function`, which raises `ValueError` naming the
offending
edge. This is the same semantics as the methods converted in the earlier
PRs,
and it turns a silent wrong answer into a diagnostic.

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [x] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [ ] I have updated the documentation accordingly.
    
URL: sagemath#42839
Reported by: Muhammet Doğukan Bingöl
Reviewer(s): David Coudert
vbraun pushed a commit to vbraun/sage that referenced this pull request Oct 6, 2026
Release Manager
sagemathgh-42905: graphs: use by_weight in longest_path and longest_cycle
    
Part of sagemath#13112. Replaces the `use_edge_labels` parameter of
`longest_path` and
`longest_cycle` by the `by_weight` / `weight_function` / `check_weight`
triple
used elsewhere in the graph module, deprecating the old name via
`rename_keyword`.

Follows sagemath#42740, sagemath#42750, sagemath#42760, sagemath#42772 and sagemath#42839.

### Recursive calls

Both methods recurse on connected components or blocks, and both return
a
`(weight, subgraph)` pair or a bare subgraph depending on `by_weight`.
Since
`_get_weight_function` always returns a function, and a non-`None`
`weight_function` turns `by_weight` on, the recursive calls pass the
resolved
function only when it is used:

```python
weight_function=weight_function if by_weight else None,
check_weight=False,
```

Otherwise a call with `by_weight=False` would get pairs back from its
recursive
calls.

### Behaviour change

`longest_path` used to treat a `{}` label as a weight of `1`
(`x if (x is not None and x != {}) else 1`). The documentation of
`longest_cycle` promised the same, but its code only replaced `None`.
Both now
go through `_get_weight_function`, which raises `ValueError` naming the
offending edge, as in the methods converted in the earlier PRs.

With `algorithm='heuristic'`, `longest_path` now also rejects a
`weight_function`, as it already rejected `use_edge_labels`.

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [x] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [ ] I have updated the documentation accordingly.
    
URL: sagemath#42905
Reported by: Muhammet Doğukan Bingöl
Reviewer(s): David Coudert
vbraun pushed a commit to vbraun/sage that referenced this pull request Oct 8, 2026
Release Manager
sagemathgh-42905: graphs: use by_weight in longest_path and longest_cycle
    
Part of sagemath#13112. Replaces the `use_edge_labels` parameter of
`longest_path` and
`longest_cycle` by the `by_weight` / `weight_function` / `check_weight`
triple
used elsewhere in the graph module, deprecating the old name via
`rename_keyword`.

Follows sagemath#42740, sagemath#42750, sagemath#42760, sagemath#42772 and sagemath#42839.

### Recursive calls

Both methods recurse on connected components or blocks, and both return
a
`(weight, subgraph)` pair or a bare subgraph depending on `by_weight`.
Since
`_get_weight_function` always returns a function, and a non-`None`
`weight_function` turns `by_weight` on, the recursive calls pass the
resolved
function only when it is used:

```python
weight_function=weight_function if by_weight else None,
check_weight=False,
```

Otherwise a call with `by_weight=False` would get pairs back from its
recursive
calls.

### Behaviour change

`longest_path` used to treat a `{}` label as a weight of `1`
(`x if (x is not None and x != {}) else 1`). The documentation of
`longest_cycle` promised the same, but its code only replaced `None`.
Both now
go through `_get_weight_function`, which raises `ValueError` naming the
offending edge, as in the methods converted in the earlier PRs.

With `algorithm='heuristic'`, `longest_path` now also rejects a
`weight_function`, as it already rejected `use_edge_labels`.

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [x] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [ ] I have updated the documentation accordingly.
    
URL: sagemath#42905
Reported by: Muhammet Doğukan Bingöl
Reviewer(s): David Coudert
vbraun pushed a commit to vbraun/sage that referenced this pull request Oct 11, 2026
Release Manager
sagemathgh-42905: graphs: use by_weight in longest_path and longest_cycle
    
Part of sagemath#13112. Replaces the `use_edge_labels` parameter of
`longest_path` and
`longest_cycle` by the `by_weight` / `weight_function` / `check_weight`
triple
used elsewhere in the graph module, deprecating the old name via
`rename_keyword`.

Follows sagemath#42740, sagemath#42750, sagemath#42760, sagemath#42772 and sagemath#42839.

### Recursive calls

Both methods recurse on connected components or blocks, and both return
a
`(weight, subgraph)` pair or a bare subgraph depending on `by_weight`.
Since
`_get_weight_function` always returns a function, and a non-`None`
`weight_function` turns `by_weight` on, the recursive calls pass the
resolved
function only when it is used:

```python
weight_function=weight_function if by_weight else None,
check_weight=False,
```

Otherwise a call with `by_weight=False` would get pairs back from its
recursive
calls.

### Behaviour change

`longest_path` used to treat a `{}` label as a weight of `1`
(`x if (x is not None and x != {}) else 1`). The documentation of
`longest_cycle` promised the same, but its code only replaced `None`.
Both now
go through `_get_weight_function`, which raises `ValueError` naming the
offending edge, as in the methods converted in the earlier PRs.

With `algorithm='heuristic'`, `longest_path` now also rejects a
`weight_function`, as it already rejected `use_edge_labels`.

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [x] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [ ] I have updated the documentation accordingly.
    
URL: sagemath#42905
Reported by: Muhammet Doğukan Bingöl
Reviewer(s): David Coudert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants