import numpy as np
import shed
import path
import sys
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
import networkx as nx
from scipy.spatial import distance
from scipy.optimize import linprog
def check (Cpath, G):
for i in range(len(Cpath.chain) - 1):
if (Cpath[i], Cpath[i+1]) in nx.non_edges(G):
return False
if Cpath not in G[Cpath[i]][Cpath[i+1]]['flow']:
return False
return True
def simplex_new_paths(G, edge, points, V):
old_paths = G[edge[0]][edge[1]]['flow']
w = G[edge[0]][edge[1]]
capacity = G[edge[0]][edge[1]]['capacity']
G.remove_edge(edge[0], edge[1])
print(edge, w['flow'], w['capacity'])
new_paths = []
k = []
for p in old_paths:
try:
new_paths.append(path.Path(nx.shortest_path(G, p[0], p[-1]), None))
k.append(p.getK(points))
except nx.NetworkXNoPath as e:
print(e)
return None, None, None
for p in new_paths:
k.append(p.getK(points))
size = len(old_paths)
A_e = []
A_e.append([])
b_e = [capacity]
for j in range(size * 2):
if j % 2 == 0:
A_e[0].append(1)
else:
A_e[0].append(0)
for i in range(size):
A_e.append([])
b_e.append(V[old_paths[i][0]][old_paths[i][-1]])
for j in range(size * 2):
if j == 2 * i or j == 2 * i + 1:
A_e[i+1].append(1)
else:
A_e[i+1].append(0)
# res = linprog(k, A_ub=A_u, b_ub=b_u, A_eq=A_e, b_eq=b_e, bounds=(0, None))
res = linprog(k, A_eq=A_e, b_eq=b_e, bounds=(0, None))
G.add_edge(edge[0], edge[1], w)
n = []
o = []
on_del = []
print(res.x)
for i in range(size):
if res.x[i * 2 + 1] != 0.:
n.append(path.Path(new_paths[i].chain, res.x[i * 2 + 1]))
if res.x[i * 2] != 0.:
o.append(path.Path(old_paths[i].chain, res.x[i * 2]))
else:
on_del.append(path.Path(old_paths[i].chain, res.x[i * 2]))
return o, n, on_del
# Создание случайного графа при помощи триангуляции Делоне
N = 20
p = shed.builtPoints(N, 10, 10)
# p =[[2,0], [5,0], [3, 4], [2, 1], [6, 9], [7, 8]]
# capacit = [[0, 40, 0, 25, 0, 0], [42, 0, 10, 20, 0, 48], [0, 4, 0, 36, 30, 5],
# [30, 35, 0, 46, 0, 0], [0, 0, 11, 0, 0, 36], [0, 28, 39, 0, 37, 0]]
tri = Delaunay(p)
print(p)
e, f = shed.getEdgesDelaunay(tri)
G = nx.DiGraph()
for edge in e:
# G.add_edge(edge[0], edge[1], weight=round(distance.euclidean(p[edge[0]], p[edge[1]]), 3),capacity=capacit[edge[0]][edge[1]], flow=[], problem=True)
G.add_edge(edge[0], edge[1], weight=round(distance.euclidean(p[edge[0]], p[edge[1]]), 3),
capacity=np.random.randint(50)+1, flow=[], problem=True)
print (edge[0], edge[1], G[edge[0]][edge[1]])
# Создание случайной матрциы перевозок
V = shed.builtRandomTransit(N, 10)
shed.pprint(V)
# Матрица, содержащая итоговый план перевозок
result_flows = [[[] for i in range(N)] for j in range(N)]
# Поиск всех кратчайших путей и добавление путей к ребрам
paths = nx.all_pairs_dijkstra_path(G)
for i in range(N):
for j in range(N):
for k in range(len(paths[i][j]) - 1):
G[paths[i][j][k]][paths[i][j][k + 1]]['flow'].append(path.Path(paths[i][j], V[i][j]))
# Первая пробверка на проблемные ребра
for u, v, d in G.edges(data=True):
sum_flow = sum([paths_edge.flow for paths_edge in d['flow']])
if sum_flow <= d['capacity']:
d['problem'] = False
# Получение остаточного графа
for i in range(N):
for j in range(N):
if i == j:
result_flows[i][j] = path.Path([i], 0)
else:
tmp_path = path.Path(paths[i][j], None)
if tmp_path.complete(V[i][j], G):
result_flows[i][j].append(path.Path(paths[i][j], V[i][j]))
V[i][j] = 0
for k in range(len(tmp_path.chain) - 1):
G[tmp_path[k]][tmp_path[k + 1]]['capacity'] -= V[i][j]
G[tmp_path[k]][tmp_path[k + 1]]['flow'].remove(tmp_path)
if G[tmp_path[k]][tmp_path[k + 1]]['capacity'] == 0:
G.remove_edge(tmp_path[k], tmp_path[k + 1])
# #Отрисовка графа
# positions_vertexes = [(p[i][0], p[i][1]) for i in range(N)]
# edge_labels=dict([((u,v,),(d['capacity'])) for u,v,d in G.edges(data=True)])
# nx.draw_networkx_edge_labels(G,positions_vertexes,edge_labels=edge_labels,label_pos=0.75)
# nx.draw_networkx(G, positions_vertexes, with_labels=True, arrows=True, node_color='Red')
# plt.show()
#
# #Предварительные результаты, полученные сразу
shed.ppprint(result_flows)
for u,v,d in G.edges(data=True):
print(u, v, d['problem'], d['flow'], d['capacity'])
# Список проблемных ребер
problem_edges = []
for u, v, d in G.edges(data=True):
if d['problem']:
problem_edges.append((u, v, d))
# Пока есть проблемные ребра
while (len(problem_edges) != 0):
# print (problem_edges)
for u, v, d in problem_edges:
if d['problem']:
old_paths, new_paths, on_delete = simplex_new_paths(G, (u, v), p, V)
# old_paths, new_paths, on_delete = simplex_new_paths(G, (u, v), p, V)
if old_paths is None:
sys.exit("Задача неразрешима. Нет пути")
print(old_paths, "---->", new_paths, "|||||||||", on_delete)
for tmp in on_delete:
for j in range(len(tmp.chain) - 1):
G[tmp[j]][tmp[j + 1]]['flow'].remove(tmp)
if sum([paths_edge.flow for paths_edge in G[tmp[j]][tmp[j + 1]]['flow']]) <= G[tmp[j]][tmp[j + 1]]['capacity']:
G[tmp[j]][tmp[j + 1]]['problem'] = False
G[u][v]['flow'] = old_paths[:]
for oP in old_paths:
for j in range(len(oP.chain) - 1):
index = G[oP[j]][oP[j + 1]]['flow'].index(oP)
G[oP[j]][oP[j + 1]]['flow'][index].flow = oP.flow
if sum([paths_edge.flow for paths_edge in G[oP[j]][oP[j + 1]]['flow']]) <= G[oP[j]][oP[j + 1]]['capacity']:
G[oP[j]][oP[j + 1]]['problem'] = False
for nP in new_paths:
for j in range(len(nP.chain) - 1):
if nP not in G[nP[j]][nP[j + 1]]['flow']:
G[nP[j]][nP[j + 1]]['flow'].append(path.Path(nP.chain, nP.flow))
else:
index = G[nP[j]][nP[j + 1]]['flow'].index(nP)
G[nP[j]][nP[j + 1]]['flow'][index].flow = nP.flow
if sum([paths_edge.flow for paths_edge in G[nP[j]][nP[j + 1]]['flow']]) > G[nP[j]][nP[j + 1]]['capacity']:
G[nP[j]][nP[j + 1]]['problem'] = True
G[u][v]['problem'] = False
print(G[u][v]['flow'])
for i in G[u][v]['flow']:
if i.complete(i.flow, G):
result_flows[i[0]][i[-1]].append(i)
V[i[0]][i[-1]] -= i.flow
for j in range(len(i.chain) - 1):
G[i[j]][i[j + 1]]['flow'].remove(i)
G[i[j]][i[j + 1]]['capacity'] -= i.flow
if G[i[j]][i[j + 1]]['capacity'] == 0 and not G[i[j]][i[j + 1]]['flow']:
G.remove_edge(i[j], i[j + 1])
# # Обновление проблемных путей
problem_edges = []
for u, v, d in G.edges(data=True):
if d['problem']:
problem_edges.append((u, v, d))
#
#
for u,v,d in G.edges(data=True):
print(u, v, d['problem'], d['flow'], d['capacity'])
ost_paths = {}
for u,v,d in G.edges(data=True):
for f in d['flow']:
if check(f,G):
if ost_paths.get((f[0],f[-1])) is None:
ost_paths[(f[0],f[-1])] = [f]
else:
if f not in ost_paths[(f[0],f[-1])]:
ost_paths[(f[0],f[-1])].append(f)
print (ost_paths)
for i in ost_paths:
sum_flow = sum([ip.flow for ip in ost_paths[i]])
result_flows[i[0]][i[1]] = ost_paths[i]
V[i[0]][i[1]]-= sum_flow
#
# print ("Edges")
# for u,v,d in G.edges(data=True):
# print (u,v, d['problem'],d['flow'],d['capacity'])
#
shed.ppprint(result_flows)
shed.pprint(V)