import numpy as np import shed import path import sys import matplotli

  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
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)