Generating Graphs (การสร้างกราฟ)

ผมจะเริ่มจากการสร้าง complete graph ซึ่งเป็น graph ที่ทุก node เชื่อมต่อกับ node อื่นทั้งหมด

นี่คือ generator function ที่รับลิสต์ของ nodes แล้วไล่คู่ nodes ทั้งหมดที่ไม่ซ้ำกัน ถ้าคุณไม่คุ้นเคยกับ generator functions คุณสามารถอ่านเกี่ยวกับมันได้ที่ https://thinkcomplex.com/gen

def all_pairs(nodes):
    for i, u in enumerate(nodes):
        for j, v in enumerate(nodes):
            if i>j:
                yield u, v

เราสามารถใช้ all_pairs เพื่อสร้าง complete graph:

def make_complete_graph(n):
    G = nx.Graph()
    nodes = range(n)
    G.add_nodes_from(nodes)
    G.add_edges_from(all_pairs(nodes))
    return G

make_complete_graph รับจำนวน nodes n แล้วคืนค่า Graph ใหม่ที่มี n nodes และมี edges ระหว่าง nodes ทุกคู่

โค้ดต่อไปนี้สร้าง complete graph ที่มี 10 nodes แล้ววาดออกมา:

complete = make_complete_graph(10)
nx.draw_circular(complete,
                 node_color=COLORS[2],
                 node_size=1000,
                 with_labels=True)

Figure 2-3 แสดงผลลัพธ์ อีกไม่นานเราจะแก้โค้ดนี้เพื่อสร้าง ER graphs แต่ก่อนอื่นเราจะพัฒนาฟังก์ชันสำหรับตรวจสอบว่า graph เชื่อมต่อหรือไม่

Figure 2-3. complete graph ที่มี 10 nodes