Skip to content

Instantly share code, notes, and snippets.

@thor
Last active June 12, 2020 23:04
Show Gist options
  • Save thor/8e5b6b82668006bf1c38a81fca44c8e7 to your computer and use it in GitHub Desktop.
Save thor/8e5b6b82668006bf1c38a81fca44c8e7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import numpy as np
def generate_submodules(node: str, count: int) -> str:
submodules = f"""{node}[{count}]: <> like INode {{
@display("r=$rangeScale;p=$posX,$posY"); \n}}
"""
return submodules
def generate_connections(
vertices: np.ndarray, node: str, port: str, channel: str
) -> str:
connections = []
for x, y in vertices:
connections.append(
f"{node}[{x}].{port}++ <--> {channel} {{weight = {matrix[x][y]};}} <--> {node}[{y}].{port}++;"
)
return "\n".join(connections)
def generate_network(
matrix: np.ndarray, node: str, port: str, channel: str, network: str
):
import textwrap as tw
vertices: np.ndarray = np.argwhere(matrix > 0)
submodules = generate_submodules(node, len(matrix))
connections = generate_connections(vertices, node, port, channel)
template = f"""\
network {network}
{{
parameters:
submodules: \n{tw.indent(submodules, ' ')}
connections allowunconnected: \n{tw.indent(connections, ' ')}
}}
"""
print(tw.dedent(template))
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="""\
Given an adjacency matrix of size NxN where all edges\
between nodes have a value higher than 0, generate a\
NED network for use in the discrete event simulatior\
OMNeT++.
While you may specify most names, the script assumes\
that the weight property for the channel in question\
is set to "weight".""",
epilog="Author: Thor K. Høgås <thor at roht dot no>",
)
parser.add_argument(
"matrix",
type=argparse.FileType("r", encoding="UTF-8"),
help="Path to the file containing an adjacency matrix",
)
parser.add_argument("--node", type=str, default="node", help="Name of the nodes")
parser.add_argument(
"--port",
type=str,
default="port",
help="Name of the gate on the nodes to use for connections",
)
parser.add_argument(
"--channel",
type=str,
default="CMN",
help="Name of the channel to use in connections",
)
parser.add_argument(
"--network", type=str, default="ImportNetwork", help="Name of the network"
)
args = parser.parse_args()
args.matrix.close()
matrix = np.loadtxt(args.matrix.name)
arguments = vars(args)
arguments.pop("matrix")
generate_network(matrix, **arguments)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment