From b76de88c9f29a9e1e4cfee59881fd9b5235d4806 Mon Sep 17 00:00:00 2001 From: Louis Navarre <louisnavarre@hotmail.com> Date: Tue, 17 Jan 2023 10:46:13 +0000 Subject: [PATCH] Add --c-header flag to generate headers --- create_graph_dumb.py | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/create_graph_dumb.py b/create_graph_dumb.py index d748761..0143e23 100644 --- a/create_graph_dumb.py +++ b/create_graph_dumb.py @@ -1,5 +1,7 @@ import random import argparse +import warnings +import os def create_random_graph(args): @@ -39,6 +41,25 @@ def ntf_parse(args): return nodes, len(data) +def to_header_file(nodes, nb_links, output): + # Check that the extension is correct. + _, file_extension = os.path.splitext(output) + if file_extension != ".h": + warnings.warn(f'The extension of the output file is not ".h": {output}') + + s = "" + + # Create the array containing the links. + for node_id, neighs in nodes.items(): + for (neigh_id, cost) in neighs: + s += f"\t{{{node_id}, {neigh_id}, {cost}}},\n" + s = s[:-2] + "\n" + + with open(output, "w+") as fd: + content = f'#include <stdint.h>\n\n#define NB_NODES {len(nodes)}\n#define NB_LINKS {nb_links}\n\nint64_t links[NB_LINKS][3] = {{\n{s}}};' + fd.write(content) + + def to_binary_file(nodes, nb_links, output): nb_nodes = len(nodes) with open(output, "wb+") as fd: @@ -50,19 +71,20 @@ def to_binary_file(nodes, nb_links, output): for j, cost in nodes[node]: fd.write(node.to_bytes(4, "big")) fd.write(j.to_bytes(4, "big")) - fd.write(cost.to_bytes(4, "big")) + fd.write(cost.to_bytes(4, "big", signed=True)) if __name__ == "__main__": parser = argparse.ArgumentParser() - parser.add_argument("--ntf", type=str, default=None, + parser.add_argument("-t", "--ntf", type=str, default=None, help="Parse an NTF file instead of creating a graph") - parser.add_argument("--output", type=str, + parser.add_argument("-o", "--output", type=str, help="Output file", default="graph.bin") parser.add_argument("-n", "--nodes", type=int, help="Number of nodes. Unused if '--ntf'", default=5) parser.add_argument("-l", "--links", type=int, help="Number of links. Unused if '--ntf'", default=10) + parser.add_argument("--c-header", action="store_true", help="Writes the graph as a C header file (.h) instead of a binary file") args = parser.parse_args() if args.ntf: @@ -70,4 +92,7 @@ if __name__ == "__main__": else: graph, nb_links = create_random_graph(args) - to_binary_file(graph, nb_links, args.output) + if args.c_header: + to_header_file(graph, nb_links, args.output) + else: + to_binary_file(graph, nb_links, args.output) -- GitLab