Spaces:
Sleeping
Sleeping
File size: 11,380 Bytes
c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b e9ddf07 c7e858b | 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | #!/usr/bin/python
import gradio as gr
import csv
import random
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import geopy.distance
#import osmnx as ox
#from shapely import geometry
import sys
#import os
IsEdge=[0,1,0,0,0]
#Capasity=[1,4,16,64,258]
Capasity=[1,2,3,4,5,6,7,8,9.,8,7,7,5,5,5,4,4,4,4,3,3,3,3,3,2,2,2,1,1,1]
def Geodist ( i,j ):
return ( int(geopy.distance.geodesic( (v_lat[i],v_lon[i]), (v_lat[j],v_lon[j]),ellipsoid='GRS-80').km ))
def PathCheck(path):
try:
start = path[0]
except:
print("No any path!")
sys.exit(1)
return
def PathDistanceLink(path):
PathCheck(path)
distance = 0
numlink = 0
start = path[0]
pathlegend = '(#'+str(v_id[start])+')'+str(v_nodename[start])
for i in range(1, len(path)):
end = path[i]
distance += Geodist ( start,end )
elabel=str(int(distance))+'км'
edge_labels[(start,end)] = elabel
pathlegend += '—'+elabel+'—(#'+str(v_id[end])+')'+str(v_nodename[end])
numlink += 1
start = end
pathlegend = f'Расстоние: {round(distance,0)}км, Ребер:{numlink} \n{pathlegend}'
#print (pathlegend)
return distance,numlink,pathlegend
def PathCapacity(orderedcapacity, path):
PathCheck(path)
numweaknodes = 0
totalcapacity = 0
capacitylegend = ''
for i in range(len(path)):
start = path[i]
addcapacity = OrderedCapacity - v_capasity[start]
if addcapacity > 0:
numweaknodes += 1
totalcapacity += addcapacity
capacitylegend += '(#'+str(start) +')='+ str(round(addcapacity,0)) + 'Гб/с '
capacitylegend = f'Всего добавить:{totalcapacity}Гб/с \nСлабыхУзлов:{numweaknodes} Добавить: {capacitylegend} '
#print (capacitylegend)
return numweaknodes,totalcapacity,capacitylegend
def drawpath(curpath,curcolor,nodesize,nodshape,edgewidth,edgestyle,label):
curpath_edges = list(zip(curpath,curpath[1:]))
nx.draw_networkx_nodes(graph,pos,nodelist=curpath,node_color=curcolor, node_size=nodesize, label=label,node_shape=nodshape)
nx.draw_networkx_edges(graph,pos,edgelist=curpath_edges,edge_color=curcolor,width=edgewidth,style=edgestyle)
#nx.draw_networkx_edge_labels(graph, pos,edge_labels)
return
#________________________________________________________________________________________________
# ЧТЕНИЕ ФАЙЛОВ
def read_init_file(FileVertex,FileEdges):
# ЧТЕНИЕ ФАЙЛА МОЩНОСТЕЙ (ВЕРШИН)
numstr = 0
with open('file_nodes.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
v_id.append( numstr)
v_nodename.append( row['Город'])
v_lat.append( round( float (row['Широта']),2))
v_lon.append( round( float(row['Долгота']),2))
v_capasity.append(round( float(row['Мощность']),2))
numstr += 1
# ЧТЕНИЕ ФАЙЛА СОЕДИНЕНИЙ (РЕБЕР)
vgraph = np.loadtxt('file_connectivity.csv', delimiter=",")
vGeodist=np.zeros((numstr, numstr))
vweight=np.zeros((numstr, numstr))
for i in range (numstr):
for j in range (numstr):
vGeodist[i][j] = Geodist(i,j)
if ( i >= j ):
vgraph[i][j] = 0
vGeodist[i][j] = 0
vGeodist[i][j] = Geodist(i,j)
vweight[i][j] = np.minimum( v_capasity[i],v_capasity[j] ) * vgraph[i][j]
return numstr, v_id ,v_nodename, v_lat, v_lon, v_capasity, vweight
def CalcFixBrokenNode(BreakedNode,Cutoff):
FileVertex='mapmos-cap.csv'
FileEdges='mapmos-matrix.csv'
numstr, v_id ,v_nodename, v_lat, v_lon, v_capasity, vweight = read_init_file(FileVertex,FileEdges)
#Source, Target, = 8,19
OrderedCapacity =4
#customer_path= [8,58,10,22,20,1,48,60,44,67,54]
fig = plt.Figure()
labels = {}
for i in range(numstr):
labels[i] = str(v_id[i])+'/'+str( v_nodename[i] )
for i in range(numstr):
for j in range(numstr):
if vweight[i][j] !=0:
graph.add_edge(i,j , weight= vweight[i][j] )
av = 3* ( vweight.min()+ vweight .max() )/4
elarge = [(u, v) for (u, v, d) in graph.edges(data=True) if d["weight"] > av]
esmall = [(u, v) for (u, v, d) in graph.edges(data=True) if d["weight"] <= av]
for i in range(numstr):
pos[i] = (float(v_lon[i]), float(v_lat[i]))
fig = plt.figure(figsize=(20,10))
fig.set_facecolor("Honeydew")
nx.draw_networkx_nodes(graph, pos, node_color="lightgrey",node_size=400, alpha=0.5,node_shape='o')
nx.draw_networkx_labels(graph,pos,labels)
nx.draw_networkx_edges(graph, pos, edgelist=elarge, alpha=0.5, width=3,edge_color='g',style="dashed",label='мощность >75%')
nx.draw_networkx_edges(graph, pos, edgelist=esmall, alpha=0.5, width=1,edge_color='g',style="dotted",label='мощность < 75%')
pathmin_distance = []
pathmin_numlink = []
pathmin_numweaknodes = []
pathmin_sumaddedcapacity = []
pathmin_integral = []
max_int = sys.maxsize
min_int = -sys.maxsize - 1
Distance,Numlink,Numweaknodes,Sumaddedcapacity = max_int, max_int, max_int,max_int
#print ( PathOptions(customer_path) )
pathlegend1 = PathDistanceLink(customer_path)[2]
pathlegend2 = 'Не существует'
#print ( pathlegend1 )
#numweaknodes,totalcapacity,capacitylegend1 = PathCapacity(16, customer_path)
#print( capacitylegend1)
drawpath(customer_path,'Crimson',200,'o',5,':','Исходный маршрут')
nx.draw_networkx_nodes(graph,pos,nodelist=[customer_path[BreakedNode],customer_path[BreakedNode]],node_color='Black', node_size=400,node_shape='X')
Source = customer_path[BreakedNode-1]
Target = customer_path[BreakedNode+1]
path_min_distance = []
max_int = sys.maxsize
min_int = -sys.maxsize - 1
Distance = max_int
#print(customer_path)
for path in nx.all_simple_paths(graph , source=Source, target=Target,cutoff=Cutoff ):
midpath = path[1 : len(path)-1]
#print(path,' / ',midpath)
#print ( len( list(set(midpath) & set(customer_path ) ) ) )
if len( list(set(midpath) & set(customer_path ) ) )==0 :
drawpath(path,'Blue',100,'o',1,':','')
PDistance = PathDistanceLink(path)[0]
if Distance > PDistance:
path_min_distance = path
Distance = PDistance
pathlegend2 = PathDistanceLink(path)[2]
newpath = customer_path[ :BreakedNode ]+path_min_distance+customer_path[ BreakedNode+1 : ]
pathlegend3 = PathDistanceLink(newpath)[2]
#print ( pathlegend3 )
#numweaknodes,totalcapacity,capacitylegend2 = PathCapacity(16, newpath)
#print( capacitylegend2 )
drawpath(path_min_distance,'Blue',200,'o',5,'-','Новый маршрут')
ax = plt.gca()
ax.set_title(GTitle,weight='bold',fontsize=24)
plt.legend(loc='upper right', shadow=True, fontsize=20)
plt.grid(True)
plt.box(True)
plt.xlabel('Долгота')
plt.ylabel('Широта')
plt.tight_layout()
#plt.savefig("mapmos-gradio.pdf")
plt.show()
#Legends= "Исходный маршрут. "+pathlegend1+'\nИзменение маршрута. '+pathlegend2+"\nНовый маршрут. "+pathlegend3
return pathlegend1,pathlegend2,pathlegend3, fig
graph = nx.Graph()
pos={}
v_id = []
v_nodename = []
v_lat = []
v_lon = []
v_capasity = []
edge_labels = {}
FileVertex='mapmos-cap.csv'
FileEdges='mapmos-matrix.csv'
numstr, v_id ,v_nodename, v_lat, v_lon, v_capasity, vweight = read_init_file(FileVertex,FileEdges)
#Source, Target= 8,19
OrderedCapacity =4
customer_path= [8,58,10,22,20,1,41,66,57,49,51,60,44, 25,7,17,67,54]
Source, Target = customer_path[0], customer_path[-1]
GTitle=f'Маршрут: [#{v_id[Source] }]{v_nodename[Source]} ({ v_lat[Source] } , {v_lon[ Source ]})—[#{v_id[Target] }]{v_nodename[Target] }({ v_lat[Target] } , { v_lon[ Target ]}) '
#CalcFixBrokenNode(4,3)
'''
demo = gr.Interface(
CalcFixBrokenNode,
[
gr.Slider(1, len(customer_path)-2, value=5, step=1, label="Поврежденный узел"),
gr.Radio([1,2,3,4], info="Переключений"),
],
[
"text",
"text",
"text",
"plot"
]
)
demo.launch()
'''
# Gradio interface
theme=gr.themes.Default( primary_hue=gr.themes.colors.red, secondary_hue=gr.themes.colors.pink )
with gr.Blocks(theme=theme) as demo:
#FileVertex = gr.Textbox(label="FileVertex", value='mapmos-cap.csv')
#FileEdges = gr.Textbox(label="FileEdges", value='mapmos-matrix.csv')
#Source = gr.Number(label="Source", value=19)
#Target = gr.Number(label="Target", value=18)
#Cutoff = gr.Number(label="Cutoff", value=3)
#OrderedCapacity = gr.Number(label="OrderedCapacity", value=4)
#customer_path = gr.Textbox(label="customer_path", value=[6,8,22,1,48,60,44,67,54] )
#BreakedNode = gr.Number(label='BreakedNode', value = 4).
#m1 = [0,0,0,0]
with gr.Row():
with gr.Column(scale=10):
plot = gr.Plot()
text1=gr.Textbox(label="Исходный маршрут", info="", lines=1, value="")
text3=gr.Textbox(label="Новый маршрут", info="", lines=1, value='')
with gr.Column(scale=1):
with gr.Row():
text2=gr.Textbox(label="Изменение маршрута", info="Расстояния (км), Пропускные способности (гб/с)", lines=1, value="")
BreakedNode = gr.Slider(
minimum=1, maximum=len(customer_path)-2, value=5, step=1, label="# Узла", info='Номер поврежденного узла с начала маршрута'
)
Cutoff = gr.Radio([1,2,3,4], value=2,label="Переключений", info='Количество переключение в обходном маршруте')
#Method = gr.Radio([1,2,3,4], value=1,label="Меньше", info='1- расстояние 2-переключений 3-слабых узлов 4-добавить мощности')
#Method=gr.CheckboxGroup([1, 2, 3,4], label="Меньше", info="1- расстояние 2-переключений 3-слабых узлов 4-добавить мощности")
#gr.Checkbox(label=m1, info="Меньше расстояние")
#mm2=gr.Checkbox(info="Меньше переключений"),
#mm3=gr.Checkbox(info="Меньше слабых узлов"),
#mm4=gr.Checkbox(info="Меньше добавить мощности"),
#Cutoff = gr.Slider(
# minimum=1, maximum=4, value=2, step=1, label="Переключений"
# )
#Cut = gr.Radio([1, 2, 3,4], value=1, label="Переключений", info=""),
btn = gr.Button("Рассчитать")
btn.click(CalcFixBrokenNode, inputs=[BreakedNode, Cutoff], outputs=[text1,text2, text3, plot])
demo.launch()
|