2020-2021/SNT/03_Internet/Simulation/build.py

46 lines
1.2 KiB
Python
Raw Normal View History

import yaml
import cairosvg
import jinja2
from pathlib import Path
import networkx as nx
import matplotlib.pyplot as plt
#cairosvg.svg2pdf(url="role.svg", write_to="role.pdf")
def graph(roles):
g = nx.Graph()
g.add_nodes_from([str(role["num"]) for role in roles])
for role in roles:
for lien in role["liens"]:
g.add_edge(str(role["num"]), str(list(lien.keys())[0]))
return g
with open("roles.yml", "r") as f:
topos = yaml.load(f, Loader=yaml.SafeLoader)
with open("role.svg", "r") as f:
template = jinja2.Template(f.read())
for topo, desc in topos.items():
for role in desc["roles"]:
card = template.render(**role)
Path(topo).mkdir(exist_ok=True)
dest = f"{topo}/role{role['num']}.svg"
with open(dest, "w") as f:
f.write(card)
cairosvg.svg2pdf(url=dest, write_to=dest.replace("svg", "pdf"))
plt.figure(figsize=(5,5))
ax = plt.gca()
ax.set_title('Random graph')
ax.set_title(f"Forme du réseau: {topo}")
g = graph(desc['roles'])
nx.draw(g, with_labels=True,
node_color='lightgreen',
node_size=700,
ax=ax)
_ = ax.axis('off')
plt.savefig(f"{topo}/forme.pdf")
plt.cla()