forked from matrix-org/meshsim
-
Notifications
You must be signed in to change notification settings - Fork 3
/
meshsim_nx.py
executable file
·91 lines (73 loc) · 2.38 KB
/
meshsim_nx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# Copyright 2019 New Vector Ltd
#
# This file is part of meshsim.
#
# meshsim is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# meshsim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with coap-proxy. If not, see <https://www.gnu.org/licenses/>.
import json
from random import randint
from math import sqrt
import networkx as nx
class Server:
_id = 0
def __init__(self):
self.x = randint(0, 1000)
self.y = randint(0, 1000)
self.id = Server._id
Server._id = Server._id + 1
self.neighbours = []
def distance(self, server):
return sqrt((server.x - self.x)**2 + (server.y - self.y)**2)
def connect(self, server):
self.neighbours.append(server)
MAX_SERVERS = 200
def main():
graph = nx.Graph()
servers = []
for i in range(0, MAX_SERVERS):
server = Server()
servers.append(server)
graph.add_node(server.id)
for i in range(0, MAX_SERVERS):
for j in range(i+1, MAX_SERVERS):
distance = servers[i].distance(servers[j]);
if distance < 100:
servers[i].connect(servers[j])
graph.add_edge(i, j, weight=distance)
paths = nx.shortest_path(graph, weight='weight')
costs = nx.shortest_path_length(graph, weight='weight')
data = {
'nodes': [],
'links': [],
'costs': list(costs),
'paths': {
u: {
v: paths[u][v][1] if len(paths[u][v])>1 else None
for v in paths[u].keys()
} for u in paths.keys()
},
}
for server in servers:
data['nodes'].append({
'name': server.id,
'x': server.x,
'y': server.y,
})
for neighbour in server.neighbours:
data['links'].append({
'source': server.id,
'target': neighbour.id,
})
print json.dumps(data, sort_keys=True, indent=4)
main()