グラフ連続自動生成.py
code:python
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import random
import math
def create_graph():
num = 22
cm = 9
A = np.zeros((num, num))
for i in range(1,5):
A0,i = random.randint(1, cm) for k in range(4):
for i in range(4):
j = random.randint(5,8)
for i in range(5,9):
j = random.randint(1,3)
if 1 <= j or j <= 4:
Aj,i = random.randint(1,cm) for i in range(9,13):
j = random.randint(5,8)
Aj,i = random.randint(1,cm) for i in range(13,17):
j = random.randint(9,12)
Aj,i = random.randint(1,cm) for i in range(17,21):
j = random.randint(13,16)
Aj,i = random.randint(1,cm) for i in range(21-4,21):
Ai,21 = random.randint(1, cm) # 試験的に全エッジを接続
"""
for k in range(4):
for i in range(4):
for j in range(4):
print(1+k*4+i, 5+k*4+j)
"""
G = nx.DiGraph()
G = nx.from_numpy_matrix(A, create_using=G)
#pos = nx.circular_layout(G) #pos = nx.shell_layout(G) #pos = nx.spring_layout(G) #pos = nx.spectral_layout(G) #pos = nx.random_layout(G) return G
#####################
def check_graph(path):
loop = 0
for i in path:
print(i, end=' ')
loop += 1
print()
return loop, i
#####################
def plot_graph(G, count, path, cost):
pos = {
}
# 設問の出力
plt.figure()
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_list='weight')
edge_labels = {(i, j): int(w'weight') for i, j, w in G.edges(data=True)} nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,font_size=7,alpha=1,label_pos=0.7)
title1 = 'problem' + format(count,'0>2') + '.png'
title2 = 'problem' + format(count,'0>2') + '.png'
plt.text(0,10,title1)
plt.savefig(title2)
plt.close()
# 正答の出力
plt.figure()
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_list='weight')
edge_labels = {(i, j): int(w'weight') for i, j, w in G.edges(data=True)} nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,font_size=7,alpha=1,label_pos=0.7)
title3 = 'problem' + format(count,'0>2') + '.png' + ', ' + str(path) + ', ' + str(int(cost))
title4 = 'solution' + format(count,'0>2') + '.png'
plt.text(0,10,title3)
plt.savefig(title4)
plt.close()
#####################
def main():
num = int(input('生成するグラフの数? '))
count = 0
while count < num:
G = create_graph()
result = nx.all_shortest_paths(G,source=0,target=21,weight='weight')
chk, path = check_graph(result)
print('最短経路の数',chk)
if chk == 1:
cost = nx.shortest_path_length(G,source=0,target=21,weight='weight')
count += 1
plot_graph(G, count, path, cost)
else:
print('複数の最短経路が存在したので、作り直します')
#####################
if __name__ == '__main__':
main()