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

91 lines
2.4 KiB
Python
Raw Normal View History

import yaml
2021-02-02 10:40:39 +00:00
from weasyprint import HTML, CSS
import jinja2
from pathlib import Path
import networkx as nx
import matplotlib.pyplot as plt
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
def topo_logo(topo, roles):
plt.figure(figsize=(2, 2))
ax = plt.gca()
# ax.set_title(f"Forme du réseau: {topo}")
g = graph(roles)
nx.draw(g, node_color="white", node_size=100, ax=ax)
_ = ax.axis("off")
plt.margins(0.2)
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
plt.savefig(
f"{topo}/logo.png",
transparent=True,
)
plt.cla()
plt.figure(figsize=(4, 4))
2021-02-02 10:40:39 +00:00
ax = plt.gca()
# ax.set_title(f"Forme du réseau: {topo}")
2021-02-02 10:40:39 +00:00
g = graph(roles)
nx.draw(
g,
with_labels=True,
font_color="#fff",
font_size=20,
font_weight="bold",
node_color="#333",
node_size=1000,
ax=ax,
)
_ = ax.axis("off")
2021-02-02 10:40:39 +00:00
plt.margins(0.2)
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
plt.savefig(
f"{topo}/shape.png",
transparent=True,
)
2021-02-02 10:40:39 +00:00
plt.cla()
def topo_card(topo="", description="", scenarios=[], template="", css=[], **kwrds):
card = template.render(topo=topo, description=description, scenarios=scenarios)
dest = f"{topo}/topo.html"
with open(dest, "w") as f:
f.write(card)
HTML(dest).write_pdf(dest.replace("html", "pdf"), stylesheets=css)
def role_card(role, topo, template, css=[], **kwrds):
2021-02-02 10:40:39 +00:00
card = template.render(topo=topo, **role)
dest = f"{topo}/role{role['num']}.html"
with open(dest, "w") as f:
f.write(card)
HTML(dest).write_pdf(dest.replace("html", "pdf"), stylesheets=css)
2021-02-02 10:40:39 +00:00
with open("config.yml", "r") as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
css = [CSS(config["css"])]
templates = {}
for name, template_file in config["templates"].items():
with open(template_file, "r") as f:
templates[name] = jinja2.Template(f.read(), undefined=jinja2.StrictUndefined)
2021-02-02 11:18:51 +00:00
for topo, desc in config["levels"].items():
2021-02-02 10:40:39 +00:00
Path(topo).mkdir(exist_ok=True)
topo_logo(topo, desc["roles"])
topo_card(**desc, topo=topo, template=templates["topo"], css=css)
2021-02-02 10:40:39 +00:00
for role in desc["roles"]:
role_card(role=role, topo=topo, template=templates["roles"], css=css)