Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
gh-36278: `sage.graphs`: some care with return ... else statements in some .pyx files
    
We change this kind of statements in files `src/sage/graphs/*.pyx`:
```py
if ....:
    return ...
else:
    return ...
```
to
```py
if ....:
    return ...
return ...
```

### 📝 Checklist

<!-- Put an `x` in all the boxes that apply. -->
<!-- If your change requires a documentation PR, please link it
appropriately -->
<!-- If you're unsure about any of these, don't hesitate to ask. We're
here to help! -->
<!-- Feel free to remove irrelevant items. -->

- [x] The title is concise, informative, and self-explanatory.
- [x] 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

<!-- List all open PRs that this PR logically depends on
- #12345: short description why this is a dependency
- #34567: ...
-->

<!-- If you're unsure about any of these, don't hesitate to ask. We're
here to help! -->
    
URL: #36278
Reported by: David Coudert
Reviewer(s): github-actions[bot], Kwankyu Lee
  • Loading branch information
Release Manager committed Sep 22, 2023
2 parents 342e32b + 58af879 commit 991a463
Show file tree
Hide file tree
Showing 13 changed files with 192 additions and 239 deletions.
3 changes: 1 addition & 2 deletions src/sage/graphs/bliss.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,7 @@ cdef canonical_form_from_edge_list(int Vnr, list Vout, list Vin, int Lnr=1, list

if certificate:
return new_edges, relabel
else:
return new_edges
return new_edges


cpdef canonical_form(G, partition=None, return_graph=False, use_edge_labels=True, certificate=False):
Expand Down
3 changes: 1 addition & 2 deletions src/sage/graphs/centrality.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ def centrality_betweenness(G, bint exact=False, bint normalize=True):
"""
if exact:
return centrality_betweenness_C(G, <mpq_t> 0, normalize=normalize)
else:
return centrality_betweenness_C(G, <double>0, normalize=normalize)
return centrality_betweenness_C(G, <double>0, normalize=normalize)


@cython.cdivision(True)
Expand Down
94 changes: 44 additions & 50 deletions src/sage/graphs/comparability.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -306,15 +306,13 @@ def greedy_is_comparability(g, no_certificate=False, equivalence_class=False):
# added twice.
return True, sorted(set(edges))
else:
return True
else:
if no_certificate:
certif.append(certif[0])
cycle = [v for v, _ in certif]
return False, cycle
else:
return False
return True
if no_certificate:
certif.append(certif[0])
cycle = [v for v, _ in certif]
return False, cycle
return False
def greedy_is_comparability_with_certificate(g, certificate=False):
Expand Down Expand Up @@ -361,8 +359,7 @@ def greedy_is_comparability_with_certificate(g, certificate=False):
if not isit:
if certificate:
return False, certif
else:
return False
return False
elif not certificate:
return True
Expand Down Expand Up @@ -552,8 +549,7 @@ def is_comparability(g, algorithm="greedy", certificate=False, check=True,
if certificate:
from sage.graphs.digraph import DiGraph
return True, DiGraph(g)
else:
return True
return True
if algorithm == "greedy":
comparability_test = greedy_is_comparability_with_certificate(g, certificate=certificate)
Expand Down Expand Up @@ -677,46 +673,44 @@ def is_permutation(g, algorithm="greedy", certificate=False, check=True,
....: break

"""
if certificate:
# First poset, we stop if it fails
isit, certif = is_comparability(g, algorithm=algorithm, certificate=True,
solver=solver, verbose=verbose)
if not isit:
return False, certif
# Second poset
isit, co_certif = is_comparability(g.complement(), algorithm=algorithm, certificate=True,
solver=solver, verbose=verbose)
if not isit:
return False, co_certif
# Building the two orderings
tmp = list(co_certif.edges(labels=False, sort=False))
for u, v in certif.edge_iterator(labels=False):
co_certif.add_edge(v, u)
certif.add_edges(tmp)
ordering = certif.topological_sort()
co_ordering = co_certif.topological_sort()
# Try to build the Permutation graph from the permutations, just to make
# sure nothing weird happened !
if check:
from sage.graphs.graph_generators import GraphGenerators
pg = GraphGenerators().PermutationGraph(ordering, co_ordering)
if not pg.is_isomorphic(g):
raise ValueError("There is a mistake somewhere ! It looks like "
"the Permutation Graph model computed does "
"not match the input graph !")
return True, (ordering, co_ordering)
# No certificate... A piece of cake
else:
if not certificate:
# No certificate... A piece of cake
return (is_comparability(g, algorithm=algorithm, solver=solver, verbose=verbose) and
is_comparability(g.complement(), algorithm=algorithm, solver=solver, verbose=verbose))
# First poset, we stop if it fails
isit, certif = is_comparability(g, algorithm=algorithm, certificate=True,
solver=solver, verbose=verbose)
if not isit:
return False, certif
# Second poset
isit, co_certif = is_comparability(g.complement(), algorithm=algorithm, certificate=True,
solver=solver, verbose=verbose)
if not isit:
return False, co_certif
# Building the two orderings
tmp = list(co_certif.edges(labels=False, sort=False))
for u, v in certif.edge_iterator(labels=False):
co_certif.add_edge(v, u)
certif.add_edges(tmp)
ordering = certif.topological_sort()
co_ordering = co_certif.topological_sort()
# Try to build the Permutation graph from the permutations, just to make
# sure nothing weird happened !
if check:
from sage.graphs.graph_generators import GraphGenerators
pg = GraphGenerators().PermutationGraph(ordering, co_ordering)
if not pg.is_isomorphic(g):
raise ValueError("There is a mistake somewhere ! It looks like "
"the Permutation Graph model computed does "
"not match the input graph !")
return True, (ordering, co_ordering)
def is_transitive(g, certificate=False):
r"""
Expand Down
45 changes: 20 additions & 25 deletions src/sage/graphs/connectivity.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1177,8 +1177,7 @@ def edge_connectivity(G,
return 0
elif vertices:
return [0, [], [{}, {}]]
else:
return [0, []]
return [0, []]

if implementation == "boost":
from sage.graphs.base.boost_graph import edge_connectivity
Expand Down Expand Up @@ -1275,29 +1274,27 @@ def edge_connectivity(G,
if value_only:
return obj

else:
val = [obj]

in_set = p.get_values(in_set, convert=bool, tolerance=integrality_tolerance)
val = [obj]
in_set = p.get_values(in_set, convert=bool, tolerance=integrality_tolerance)

if g.is_directed():
edges = [(u, v, l) for u, v, l in g.edge_iterator() if in_cut[u, v]]
else:
edges = [(u, v, l) for u, v, l in g.edge_iterator() if in_cut[frozenset((u, v))]]
if g.is_directed():
edges = [(u, v, l) for u, v, l in g.edge_iterator() if in_cut[u, v]]
else:
edges = [(u, v, l) for u, v, l in g.edge_iterator() if in_cut[frozenset((u, v))]]

val.append(edges)
val.append(edges)

if vertices:
a = {}
b = {}
for v in g:
if in_set[0, v]:
a.add(v)
else:
b.add(v)
val.append([a, b])
if vertices:
a = {}
b = {}
for v in g:
if in_set[0, v]:
a.add(v)
else:
b.add(v)
val.append([a, b])

return val
return val


def vertex_connectivity(G, value_only=True, sets=False, k=None, solver=None, verbose=0,
Expand Down Expand Up @@ -1503,8 +1500,7 @@ def vertex_connectivity(G, value_only=True, sets=False, k=None, solver=None, ver
return max(g.order() - 1, 0)
elif not sets:
return max(g.order() - 1, 0), []
else:
return max(g.order() - 1, 0), [], [[], []]
return max(g.order() - 1, 0), [], [[], []]

if value_only:
if G.is_directed():
Expand Down Expand Up @@ -3298,8 +3294,7 @@ cdef class TriconnectivitySPQR:
cdef _LinkedListNode * head = _LinkedList_get_head(self.highpt[v])
if head:
return head.data
else:
return 0
return 0

cdef __del_high(self, int e_index):
"""
Expand Down
9 changes: 3 additions & 6 deletions src/sage/graphs/distances_all_pairs.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,7 @@ def is_distance_regular(G, parameters=False):
bi[diameter] = None
ci[0] = None
return bi, ci
else:
return True
return True


###################################
Expand Down Expand Up @@ -1882,8 +1881,7 @@ def diameter(G, algorithm=None, source=None):
if LB < 0 or LB > n:
from sage.rings.infinity import Infinity
return +Infinity
else:
return int(LB)
return int(LB)


###########
Expand Down Expand Up @@ -2722,8 +2720,7 @@ def floyd_warshall(gg, paths=True, distances=False):
if not gverts:
if distances and paths:
return {}, {}
else:
return {}
return {}

cdef unsigned int n = max(gverts) + 1

Expand Down
9 changes: 4 additions & 5 deletions src/sage/graphs/generic_graph_pyx.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -487,11 +487,10 @@ def small_integer_to_graph6(n):
"""
if n < 63:
return chr(n + 63)
else:
# get 18-bit rep of n
n = int_to_binary_string(n)
n = '0'*(18 - len(n)) + n
return chr(126) + binary_string_to_graph6(n)
# get 18-bit rep of n
n = int_to_binary_string(n)
n = '0'*(18 - len(n)) + n
return chr(126) + binary_string_to_graph6(n)


def length_and_string_from_graph6(s):
Expand Down
54 changes: 27 additions & 27 deletions src/sage/graphs/genus.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -597,31 +597,31 @@ def simple_connected_graph_genus(G, set_embedding=False, check=True, minimal=Tru

if minimal and G.is_planar(set_embedding=set_embedding):
return 0

if check:
if not G.is_connected():
raise ValueError("Cannot compute the genus of a disconnected graph")

if G.is_directed() or G.has_multiple_edges() or G.has_loops():
G = G.to_simple()

G, vmap = G.relabel(inplace=False, return_map=True)
backmap = {u: v for v, u in vmap.items()}
G = Graph(G, sparse=False)
GG = simple_connected_genus_backtracker(G._backend.c_graph()[0])

if minimal:
style = 1
cutoff = 1
else:
if check:
if not G.is_connected():
raise ValueError("Cannot compute the genus of a disconnected graph")

if G.is_directed() or G.has_multiple_edges() or G.has_loops():
G = G.to_simple()

G, vmap = G.relabel(inplace=False, return_map=True)
backmap = {u: v for v, u in vmap.items()}
G = Graph(G, sparse=False)
GG = simple_connected_genus_backtracker(G._backend.c_graph()[0])

if minimal:
style = 1
cutoff = 1
else:
style = 2
cutoff = 1 + (G.num_edges() - G.num_verts()) / 2 # rounding here is ok

g = GG.genus(style=style, cutoff=cutoff, record_embedding=set_embedding)
if set_embedding:
oE = {}
E = GG.get_embedding()
for v in E:
oE[backmap[v]] = [backmap[x] for x in E[v]]
oG.set_embedding(oE)
return g
style = 2
cutoff = 1 + (G.num_edges() - G.num_verts()) / 2 # rounding here is ok

g = GG.genus(style=style, cutoff=cutoff, record_embedding=set_embedding)
if set_embedding:
oE = {}
E = GG.get_embedding()
for v in E:
oE[backmap[v]] = [backmap[x] for x in E[v]]
oG.set_embedding(oE)
return g
6 changes: 2 additions & 4 deletions src/sage/graphs/graph_coloring.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -555,8 +555,7 @@ def vertex_coloring(g, k=None, value_only=False, hex_colors=False, solver=None,
return 0
elif hex_colors:
return dict()
else:
return []
return []
# - Independent set
if not g.size():
if value_only:
Expand Down Expand Up @@ -1754,11 +1753,10 @@ def round_robin(n):
g.set_edge_label(n - 1, i, i)
for j in range(1, (n - 1) // 2 + 1):
g.set_edge_label(my_mod(i - j, n - 1), my_mod(i + j, n - 1), i)
return g
else:
g = round_robin(n + 1)
g.delete_vertex(n)
return g
return g


def linear_arboricity(g, plus_one=None, hex_colors=False, value_only=False,
Expand Down
19 changes: 9 additions & 10 deletions src/sage/graphs/hyperbolicity.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -327,8 +327,7 @@ cdef tuple hyperbolicity_basic_algorithm(int N,
# Last, we return the computed value and the certificate
if h_LB != -1:
return (h_LB, certificate)
else:
return (-1, [])
return (-1, [])


######################################################################
Expand Down Expand Up @@ -825,10 +824,10 @@ cdef tuple hyperbolicity_BCCM(int N,
# Last, we return the computed value and the certificate
if not certificate:
return (-1, [], h_UB)
else:
# When using far-apart pairs, the loops may end before improving the
# upper-bound
return (h, certificate, h_UB)

# When using far-apart pairs, the loops may end before improving the
# upper-bound
return (h, certificate, h_UB)


######################################################################
Expand Down Expand Up @@ -1043,10 +1042,10 @@ cdef tuple hyperbolicity_CCL(int N,
# Last, we return the computed value and the certificate
if not certificate:
return (-1, [], h_UB)
else:
# When using far-apart pairs, the loops may end before improving the
# upper-bound
return (h, certificate, h_UB if GOTO_RETURN else h)

# When using far-apart pairs, the loops may end before improving the
# upper-bound
return (h, certificate, h_UB if GOTO_RETURN else h)


def hyperbolicity(G,
Expand Down
Loading

0 comments on commit 991a463

Please sign in to comment.