-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3in1test.py
172 lines (146 loc) · 6.73 KB
/
3in1test.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import json
import networkx as nx
import plotly.graph_objects as go
import plotly.colors as pc
from dash import Dash, dcc, html
from dash.dependencies import Input, Output
from collections import defaultdict
from tqdm import tqdm
import os
def load_combined_data(json_file_path):
with open(json_file_path, 'r') as f:
return json.load(f)
def create_graph_from_combined_data(data):
G = nx.Graph()
print("Loading nodes and edges...")
for node_id, node_data in tqdm(data['nodes'].items(), desc="Loading nodes"):
G.add_node(node_id, pos=(float(node_data['longitude']), float(node_data['latitude'])),
shape=node_data.get('shape', 'circle'), type=node_data['type'],
display=node_data.get('display', node_id))
for edge in tqdm(data['edge_list'], desc="Loading edges"):
G.add_edge(edge['source'], edge['target'], level=edge.get('level'), path_type=edge.get('path_type'))
return G
def find_transformer_to_intersection_paths(G):
transformer_intersection_paths = set()
for node, data in G.nodes(data=True):
if data['type'] == 'Transformer':
for neighbor in nx.bfs_tree(G, node):
if G.nodes[neighbor]['type'] == 'Intersection':
path = nx.shortest_path(G, node, neighbor)
for i in range(len(path) - 1):
transformer_intersection_paths.add((path[i], path[i+1]))
break
return transformer_intersection_paths
def create_figure(graphs, color_mapping):
print("Creating visualization...")
fig = go.Figure()
node_x, node_y, node_color, node_size, node_symbol, node_text, node_ids = [], [], [], [], [], [], []
for file_name, G in graphs.items():
edge_color = color_mapping[file_name]
transformer_intersection_paths = find_transformer_to_intersection_paths(G)
for edge in G.edges(data=True):
start_node, end_node = edge[0], edge[1]
x0, y0 = G.nodes[start_node]['pos']
x1, y1 = G.nodes[end_node]['pos']
# Check edge level and assign color
if (start_node, end_node) in transformer_intersection_paths or (end_node, start_node) in transformer_intersection_paths:
line_color = 'navy'
elif edge[2].get('level') == 1:
line_color = 'red'
elif edge[2].get('level') == 2:
line_color = 'green'
else:
line_color = edge_color
fig.add_trace(go.Scatter(x=[x0, x1], y=[y0, y1], mode='lines',
line=dict(width=5, color=line_color),
hoverinfo='text',
hovertext=f"File: {file_name}, Start: {start_node}, End: {end_node}, Level: {edge[2].get('level')}"))
for node, data in G.nodes(data=True):
x, y = data['pos']
node_x.append(x)
node_y.append(y)
node_ids.append(node)
if data['type'] == 'Substation':
node_color.append('red')
node_size.append(20)
node_symbol.append('square')
node_text.append(data['display'])
elif data['type'] == 'Transformer':
node_color.append(edge_color)
node_size.append(12)
node_symbol.append('triangle-up')
node_text.append(data['display'])
elif data['type'] == 'Intersection':
node_color.append('red')
node_size.append(10)
node_symbol.append('circle')
node_text.append(data['display'])
else:
node_color.append('lightgray')
node_size.append(5)
node_symbol.append('circle')
node_text.append('')
fig.add_trace(go.Scatter(
x=node_x, y=node_y,
mode='markers+text',
marker=dict(color=node_color, size=node_size, symbol=node_symbol),
text=node_text,
textposition="top center",
hoverinfo='none',
customdata=node_ids,
))
fig.update_layout(showlegend=False, hovermode='closest',
margin=dict(b=20, l=5, r=5, t=40),
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
return fig
def print_network_summary(combined_data):
print("\nNetwork Summary:")
print(f"Total nodes: {len(combined_data['nodes'])}")
print(f"Total edges: {len(combined_data['edge_list'])}")
print(f"Max hierarchy level: {combined_data['metadata']['max_level']}")
print(f"Number of transformers: {len(combined_data['metadata']['roots'])}")
print(f"Number of intersections: {len(combined_data['metadata']['intersections'])}")
print(f"Number of main paths: {len(combined_data['paths']['main_paths'])}")
print(f"Number of secondary paths: {sum(len(paths) for paths in combined_data['paths']['secondary_paths'].values())}")
print("Starting main process...")
file_paths = [
r"C:\Users\eljapo22\gephi\Node2Edge2JSON\feeders\combined_structure_BottomLeft.json",
r"C:\Users\eljapo22\gephi\Node2Edge2JSON\feeders\combined_structure_Middle.json",
r"C:\Users\eljapo22\gephi\Node2Edge2JSON\feeders\combined_structure_TopLeft.json"
]
color_mapping = {
'combined_structure_BottomLeft.json': 'lightblue',
'combined_structure_TopLeft.json': 'orange',
'combined_structure_Middle.json': 'purple',
}
graphs = {}
combined_data = {}
for file_path in file_paths:
file_name = os.path.basename(file_path)
combined_data[file_name] = load_combined_data(file_path)
graphs[file_name] = create_graph_from_combined_data(combined_data[file_name])
print_network_summary(combined_data[file_name])
app = Dash(__name__)
app.layout = html.Div([
html.H1("Combined Network Map"),
dcc.Graph(figure=create_figure(graphs, color_mapping), id='graph', style={'height': '80vh'}),
html.Div(id='click-data', style={'margin-top': '20px'})
])
@app.callback(
Output('click-data', 'children'),
Input('graph', 'clickData')
)
def display_click_data(clickData):
if clickData is None:
return "Double-click a transformer node to see its unique ID"
point = clickData['points'][0]
node_id = point['customdata']
for file_name, data in combined_data.items():
node_data = data['nodes'].get(node_id)
if node_data and node_data['type'] == 'Transformer':
return f"Transformer Unique ID: {node_id} (File: {file_name})"
return "Double-click a transformer node to see its unique ID"
if __name__ == '__main__':
print("Starting server...")
app.run_server(debug=True)