[SOLVED] Running a program until networkx.check_planarity() returns True

Issue

I have the following function that generates a graph.

import numpy as np
import networkx as nx
import random
def random_graph(vertices, connectivity):
    #Creates random symmetric graph
    arr = np.random.randint(0,10,(vertices,vertices))
    sym = (arr+arr.T)
    
    #removing self loops with fixing diagonal
    np.fill_diagonal(sym,0)
    
    #connectivity of graph -> 0 for highest connections, 9 for least connections
    mat = (sym>connectivity).astype(int)
    
    #convert to dictionary
    G = {k:[i for i,j in enumerate(v) if j==1] for k,v in enumerate(mat)}
    return G

I use that function with a randomly generated connectivity, unfortunately the generated graph is not always planar, so I want to run the function until I get a planar graph. The planarity of the graph is checked with the function check_planarity from networkx. The function check_planarity returns a boolean, if it’s true, the graph is planar, if false the graph is not planar and I need to generate a new graph until it’s planar. This is what I have tried:

while True:
    random_connectivity = random.randint(4, 9)
    G = random_graph(5, random_connectivity)
    g = nx.Graph(G)
    planar = nx.check_planarity(g)
    if planar:
        break
    else: 
        pass

As you can see from the loop above, first I generate random_connectivity, them I create the graph with that connectivity and then with networkx I check the planarity. Then I try to check if it’s planar or not and if not I run the program again. Unfortunately it doesn’t work because it often returns a non planar graph. I also tried unpacking planar and checking the first element of the unpacked list but it doesn’t work:

planar_check = [x[0] for x in planar]

When trying the line of code above I get the following traceback:

Traceback (most recent call last):
  File "c:\Users\besan\OneDrive\Desktop\LAM da correggere\test.py", line 64, in <module>  
    planar_check = [x[0] for x in planar]
  File "c:\Users\besan\OneDrive\Desktop\LAM da correggere\test.py", line 64, in <listcomp>
    planar_check = [x[0] for x in planar]
TypeError: 'bool' object is not subscriptable

Solution

Solved by directly checking the first element of planar insead of unpacking it:

planar = nx.check_planarity(g)[0]

Answered By – Emilio

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *