Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise an error when generating a graph with too many edges. #129

Merged
merged 1 commit into from
Sep 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions cyaron/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ def graph(point_count, edge_count, **kwargs):
directed = kwargs.get("directed", False)
self_loop = kwargs.get("self_loop", True)
repeated_edges = kwargs.get("repeated_edges", True)
if not repeated_edges:
max_edge = Graph._calc_max_edge(point_count, directed, self_loop)
if edge_count > max_edge:
raise Exception("the number of edges of this kind of graph which has %d vertexes must be less than or equal to %d." % (point_count, max_edge))

weight_limit = kwargs.get("weight_limit", (1, 1))
if not list_like(weight_limit):
weight_limit = (1, weight_limit)
Expand Down Expand Up @@ -309,6 +314,11 @@ def DAG(point_count, edge_count, **kwargs):
self_loop = kwargs.get("self_loop", False) # DAG default has no loop
repeated_edges = kwargs.get("repeated_edges", True)
loop = kwargs.get("loop", False)
if not repeated_edges:
max_edge = Graph._calc_max_edge(point_count, not loop, self_loop)
if edge_count > max_edge:
raise Exception("the number of edges of this kind of graph which has %d vertexes must be less than or equal to %d." % (point_count, max_edge))

weight_limit = kwargs.get("weight_limit", (1, 1))
if not list_like(weight_limit):
weight_limit = (1, weight_limit)
Expand Down Expand Up @@ -369,6 +379,11 @@ def UDAG(point_count, edge_count, **kwargs):

self_loop = kwargs.get("self_loop", True)
repeated_edges = kwargs.get("repeated_edges", True)
if not repeated_edges:
max_edge = Graph._calc_max_edge(point_count, False, self_loop)
if edge_count > max_edge:
raise Exception("the number of edges of this kind of graph which has %d vertexes must be less than or equal to %d." % (point_count, max_edge))

weight_limit = kwargs.get("weight_limit", (1, 1))
if not list_like(weight_limit):
weight_limit = (1, weight_limit)
Expand Down Expand Up @@ -450,3 +465,12 @@ def hack_spfa(point_count, **kwargs):
graph.add_edge(u, v, weight=weight_gen())

return graph

@staticmethod
def _calc_max_edge(point_count, directed, self_loop):
max_edge = point_count * (point_count - 1)
if not directed:
max_edge //= 2
if self_loop:
max_edge += point_count
return max_edge