Ask Your Question
1

How to add edges while keeping the original graph unchanged

asked 2024-03-11 09:44:12 +0100

licheng gravatar image

updated 2024-03-11 09:47:02 +0100

I see that the commands for adding vertices and edges in Sage will alter the original graph. So I write the following code which makes the origin graph unchanged.

def addedge(g, edges_to_add):
    G1 = g.copy() 
    G1.add_edge(edges_to_add)  
    return G1

I need to sequentially add one edge from the complement of the graph to observe their properties, such as Hamiltonicity.

 def addedge(g, edges_to_add):
        G1 = g.copy() 
        G1.add_edge(edges_to_add)  
        return G1
s = 'J~f[MN@PQg?'
G = Graph(s, sparse=True); 
complement_edges = G.complement().edges(labels=False, sort=False)

for edge in complement_edges:
    G1=addedge(G,edge)
    if not G1.is_hamiltonian():
        print("The modified graph is non-Hamiltonian  with the added edge:", edge)
    else:
        print()
    #print("The modified graph is Hamiltonian with the added edge:",edge)

I am not sure if this edge addition is highly efficient because, as we discussed in previous issues (see common in the answer )(calculate-the-toughness-of-a-graph, it's best to avoid copy() if it's being repeatedly used.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2024-03-11 11:30:46 +0100

rburing gravatar image

updated 2024-03-11 11:33:22 +0100

You could make one mutable copy and modify it in place:

def edges_to_add_to_attain_property(graph, prop):
    G = graph.copy(immutable=False)
    prev_edge = None
    for edge in G.complement().edges(labels=False, sort=False):
        if prev_edge is not None:
            G.delete_edge(prev_edge)
        G.add_edge(edge)
        if prop(G):
            yield edge
        prev_edge = edge

Example:

sage: G = Graph('J~f[MN@PQg?', sparse=True)
sage: G.graph6_string()
'J~f[MN@PQg?'
sage: list(edges_to_add_to_attain_property(G, lambda H: not H.is_hamiltonian()))
[(0, 9),
 (0, 10),
 (1, 4),
 (1, 6),
 (2, 5),
 (2, 7),
 (3, 6),
 (3, 7),
 (3, 8),
 (3, 9),
 (4, 7),
 (5, 8),
 (7, 10)]
sage: G.graph6_string() # G is not modified
'J~f[MN@PQg?'

Note G.complement() internally also makes a copy, but it's probably worth it as the backend (C code) probably calculates the complement efficiently.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2024-03-11 09:44:12 +0100

Seen: 201 times

Last updated: Mar 11