-
Notifications
You must be signed in to change notification settings - Fork 1
/
initialize.py
1692 lines (1495 loc) · 56.4 KB
/
initialize.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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Created by Kohei Kai(2017)
import GeneticAlgorithm as ga
import random
from decimal import Decimal
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import sys, time
import copy
import csv
import math
# # 遺伝子情報の長さ
# GENOM_LENGTH = 50
# 遺伝子集団の長さ
MAX_GENOM_LIST = 30
# 各両親から生成される子個体の数
MAX_CHILDREN = 10
# # 遺伝子選択数
# SELECT_GENOM = 20
# # 個体突然変異確率
# INDIVIDUAL_MUTATION = 0.1
# # 遺伝子突然変異確率
# GENOM_MUTATION = 0.1
# 繰り返す世代数
MAX_GENERATION = 30
# 使用できる車両数
m = 3
# 車両の最大積載量
CAPACITY = 160
# セービング値の効果をコントロールする係数
LAMBDA = 1
# N_near()関数で,どこまで近くのノードに局所探索するか
NEAR = 10
# penaltyFunction()で,容量制約違反に課すペナルティの係数
ALPHA = 1
# penaltyFunction()で,経路長違反に課すペナルティの係数
BETA = 1.0
# penaltyFunction()で,経路長違反とする距離
D = float("inf")
SERVICE = 0
"""
避難所情報のデータフレームを生成する
@INPUT:
filepath: 読み出すファイルパス
data_name: 読み出すファイル名
@OUTPUT:
読み出したデータのデータフレーム
"""
def createDataFrame(filepath, data_name):
input_path = filepath + data_name + ".csv"
return pd.read_csv(input_path)
"""
避難所の距離に基づいたコスト行列を返す
@INPUT:
num_shelter : 避難所数
@OUTPUT:
arr : コスト行列
"""
def createCostMatrix(num_shelter):
dis = []
arr = np.empty((0, num_shelter), float) #小数点以下を加える→float型
for i in range(num_shelter):
for j in range(num_shelter):
x_crd = df.ix[j].x - df.ix[i].x
y_crd = df.ix[j].y - df.ix[i].y
dis.append(round(np.sqrt(np.power(x_crd, 2) + np.power(y_crd, 2)), 2))
if j == num_shelter - 1:
arr = np.append(arr, np.array([dis]), axis=0)
dis = []
# print(df[0:11])
# print("コスト行列-----------------------------------")
# print(arr)
# print("---------------------------------------------")
np.savetxt("./output/cost.csv", arr, delimiter=',', fmt='%.2f')
return arr
"""
セービング法によりヒューリスティックな解を生成する
@INPUT:
num_shelter : 避難所数
cost : 避難所間のコスト行列
@OUTPUT:
"""
def savingMethod(num_shelter, cost):
"""
各避難所間のコストからセービング値を計算
経路結合のための初期化をする
"""
s = np.zeros((num_shelter, num_shelter), int)
q = np.zeros((num_shelter), int)
nex = np.zeros((num_shelter), int)
tail = np.zeros((num_shelter), int)
dr = np.zeros((num_shelter), int)
for i in range(1, num_shelter):
q[i] = df.ix[i].d
nex[i] = 0
tail[i] = i
dr[i] = cost[0][i] + cost[i][0]
for i in range(1, num_shelter):
# for j in range(i+1, num_shelter):
for j in range(1, num_shelter):
s[i][j] = cost[i][0] + cost[0][j] - (LAMBDA * cost[i][j])
# print(s) #セービング値
"""
経路の結合処理
"""
random_order1 = [i for i in range(1, num_shelter)]
random.shuffle(random_order1)
random_order2 = [i for i in range(1, num_shelter)]
random.shuffle(random_order2)
# smax = 1
while(True):
smax = 0
# for i in range(1, num_shelter): #1から順に
for i in random_order1: # ランダムにノードを選ぶ
if q[i] > 0:
# for j in range(1, num_shelter):
for j in random_order2:
if i != j and q[j] > 0:
ti = tail[i]
if q[i] + q[j] <= CAPACITY and s[ti][j] > smax:
smax = s[ti][j]
g = i
h = j
if smax > 0:
nex[tail[g]] = h
tail[g] = tail[h]
dr[g] = dr[g] + dr[h] - smax
q[g] = q[g] + q[h]
q[h] = 0
if smax == 0:
break
"""
経路の出力
"""
route = []
heiro = []
demand = []
distance = []
# plot = []
drt = 0
for i in random_order1:
if q[i] > 0:
ii = i
while(True):
heiro.append(ii)
# plot.append(heiro)
# graphPlot(pathToRoute(createEdgeSet(plot)), isFirst=0, isLast=0)
ii = nex[ii]
if ii == 0:
distance.append(dr[i]) # その経路の移動コスト
demand.append(q[i]) # その経路の総需要
drt += dr[i]
route.append(heiro)
heiro = []
# graphPlot(pathToRoute(createEdgeSet(route)), isFirst=0, isLast=0)
break
# print("route:{}".format(route))
print("demand:{}".format(demand))
print("distance:{}".format(distance))
print(drt)
# graphPlot(pathToRoute(createEdgeSet(route)), isFirst=0, isLast=1)
return route
"""
セービングファイルを作成する
s_arrは,
[i j s]
[i j s]
......
という構造になっており,
i-j間のセービング値がsであり,sについて降順にソートしている
"""
# s_x = np.zeros((num_shelter, num_shelter), int) #小数点以下を加える→float型
# s_arr = np.empty((0, 3), int)
#
# for i in range(1, num_shelter):
# for j in range(i+1, num_shelter):
# saving[i][j] = cost[i][0] + cost[0][j] - cost[i][j]
# if saving[i][j] > 0:
# s_arr = np.append(s_arr, np.array([[i, j, saving[i][j]]]), axis=0)
# s_arr = s_arr[s_arr[:, 2].argsort()][::-1]
# # print(saving)
# print(s_arr)
"""
セービング法で構築されたルートに,
デポを出発してデポに帰るようにエッジを辿る
3次元配列を生成する.
@INPUT:
route:セービング法で構築されたルート(0は表示されていない)
@OUTPUT:
path:ルートを辿るエッジの3次元配列(0も表示)
"""
def createEdgeSet(route):
E = []
Path = []
for edge in route:
for i, node in enumerate(edge):
if i == 0:
E.append([0, node])
pre_node = node
if len(edge) == 1:
E.append([node, 0])
else:
E.append([pre_node, node])
pre_node = node
if i == len(edge)-1:
E.append([node, 0])
Path.append(E)
E = []
# print(Path)
return Path
"""
ペナルティ関数による評価を行う
@INPUT:
route: 解の2次元リスト
option: どのように評価するか
2: 容量超過量F_cのみ
1: ペナルティ関数による評価
0: 総移動コストのみの評価
@OUTPUT:
F_p: 関数による評価値
"""
def penaltyFunction(route, option):
F_p = 0
F = 0
F_c = 0
F_d = 0
R_demands = 0
R_cost = 0
service = -1*SERVICE
path = routeToPath(route)
# ルート総距離
for e in route:
F += cost[int(e[0])][int(e[1])]
if option == 0:
return round(F, 2)
for edges in path:
"""
容量制約違反の計算
"""
nodes = np.unique(edges)
for n in nodes: # 各ルートの合計需要
R_demands += df.ix[n].d
service += SERVICE
if R_demands > CAPACITY:
F_c += R_demands - CAPACITY # ルート内の需要超過
else:
F_c += 0
# F_c += abs(R_demands - CAPACITY) # ルート内の需要超過
R_demands = 0
"""
route duration制約違反の計算
"""
for e in edges:
R_cost += cost[int(e[0])][int(e[1])]
R_cost += service
if R_cost > D:
F_d += R_cost - D
else:
F_d += 0
# F_d += abs(R_cost - D)
R_cost = 0
service = -1*SERVICE
# ペナルティ関数
F_p = F + (ALPHA * F_c) + (BETA * F_d)
# F_p = F + (ALPHA * F_c)
# print("F:{}, F_c:{}, F_d:{}".format(F, F_c, F_d))
if option == 1:
return round(F_p, 2) # ペナルティ間数値
else:
return round(F_c + F_d, 2) # ペナルティ項のみ
"""
経路を分割することでルート数を増やす関数
セービング法によって生成された初期解のうち,
もっとも顧客数の多いルートを選び真ん中で分割する
@INPUT:
path
(m): 固定したいルート数
@OUTPUT:
path
"""
def routeSplit(path):
routeLength = []
routeCost = []
routeCapa = []
s_option = 1
# 0: ランダム
# 1: エッジ数
# 2: 距離
# 3: 需要量
# print("パス:{}".format(path))
while(True):
for route in path:
r_cost = 0
r_demand = 0
routeLength.append(len(route)) # ルート毎の顧客数リスト
for n in np.unique(route):
r_demand += df.ix[n].d
for e in route:
r_cost += cost[int(e[0])][int(e[1])]
routeCapa.append(r_demand) # ルート毎の需要量
routeCost.append(round(r_cost, 2)) # ルート毎の距離リスト
# print("routeLength:{}".format(routeLength))
# print("routeCapa:{}".format(routeCapa))
# print("routeCost:{}".format(routeCost))
# エッジ数4以上のところからランダムに選ぶ
if s_option == 0:
IdxList = [i for i, x in enumerate(routeLength) if x >= 4]
print(IdxList)
# エッジ数の多いルートを選ぶ
elif s_option == 1:
IdxList = [i for i, x in enumerate(routeLength) if x == max(routeLength)]
# ルート内の距離が一番長いルートを選ぶ
elif s_option == 2:
IdxList = [i for i, x in enumerate(routeCost) if x == max(routeCost)]
# ルート内の需要が一番多いルートを選ぶ
elif s_option == 3:
IdxList = [i for i, x in enumerate(routeCapa) if x == max(routeCapa)]
maxIdx = random.choice(IdxList)
# print("maxIdx:{}".format(maxIdx))
# print("それぞれの顧客数:{}".format(routeLength))
# 分割するルート
split = path[maxIdx]
# 分割するルートを除いたパス
path.pop(maxIdx)
# print("split:{}".format(split))
# print("残ったパス:{}".format(path))
# 分割するインデックス
Idx = math.floor(len(split)/2 - 1)
# print("Idx:{}".format(Idx))
#分岐点となるノードを決定する
pointA = split[Idx][1] if split[Idx][1] in split[Idx] and split[Idx][1] in split[Idx+1] \
else split[Idx][0]
pointB = split[Idx+1][1] if split[Idx+1][0] == pointA else split[Idx+1][0]
routeA = split[:Idx+1] + [[pointA, 0]]
routeB = [[0, pointB]] + split[Idx+2:]
# print("routeA:{}".format(routeA))
# print("routeB:{}".format(routeB))
path.append(routeA)
path.append(routeB)
# print("分割後パス:{}".format(path))
routeLength = []
if len(path) >= m:
break
return path
"""
あるノードから近いノード集合を返す
引数nodeで与えたノードから,近くにあるノードをnear番目まで選んだ集合
@INPUT:
node:ノード
near:近くのノードをいくつ探すか
@OUTPUT:
near_cost:近くのノード集合
"""
def N_near(node, near):
near_cost = np.empty((0, 2), int)
for i, c in enumerate(cost[int(node)][:]):
if i == 0:
continue
near_cost = np.append(near_cost, np.array([[i, c]]), axis=0)
near_cost = near_cost[near_cost[:, 1].argsort()] # nodeに近い順にソート
# print(near_cost)
# print(near_cost[1:near+1, 0])
return near_cost[1:near+1, 0]
def localSearch(path):
# EdgeSet = []
# for edge in path:
# for j in edge:
# EdgeSet.append(j)
# 顧客ノードの部分集合
List = [i for i in range(1, num_shelter)]
random.shuffle(List) # ランダムな順に並べる
print(List)
for i in range(1, len(List)):
v = List[i]
"""
近傍操作関数
@INPUT:
v: 近傍操作対象ノード
path: 解の3次元リスト
f_option: ペナルティ関数をどのように評価するか
2: 容量超過
1: ペナルティ関数による評価
0: 総移動コストのみの評価
reduce_route: 経路数が減る遷移を許容するか
1: 許容する
0: 許容しない
"""
def Neighborhoods(v, path, f_option, reduce_route):
EdgeSet = []
# DefaultEdgeSet = []
path_cost = 0
bestSet = []
flag = False
# 解を構成する全てのエッジ集合を生成
for edge in path:
for j in edge:
EdgeSet.append(j)
# DefaultEdgeSet = copy.deepcopy(EdgeSet)
bestSet = copy.deepcopy(EdgeSet)
# print("デフォ:{}".format(DefaultEdgeSet))
# 元の解のペナルティ関数評価値を保持
P_eval = penaltyFunction(bestSet, f_option)
# print("デフォルト:{}".format(P_eval))
# 渡されたノードvに繋がるエッジ2つ
link_v = [i for i in EdgeSet if (v in i)]
v_minus = link_v[0][0] if v == link_v[0][1] else link_v[0][1]
v_plus = link_v[1][1] if v == link_v[1][0] else link_v[1][0]
# print("link_v:{}".format(link_v))
# print("link_v[0]:{}".format(link_v[0])) # ノードvに向かうエッジ
# print("link_v[1]:{}".format(link_v[1])) # ノードvを出るエッジ
# ノードvからnearだけ近いノードをそれぞれwとして選ぶ
for w in N_near(v, NEAR):
w = int(w)
link_w = [i for i in EdgeSet if (w in i)]
if(len(link_v) < 2 or len(link_w) < 2):
# print("ノードに対するエッジが2つない")
EdgeSet = copy.deepcopy(bestSet)
continue
# 同じエッジを選ぶ可能性があるものは排除
# if link_v[0] == link_w[0] or link_v[1] == link_w[0] or \
# link_v[0] == link_w[1] or link_v[1] == link_w[1]:
# continue
# ノードwに向かうエッジ
w_minus = link_w[0][0] if w == link_w[0][1] else link_w[0][1]
# ノードwを出るエッジ
w_plus = link_w[1][1] if w == link_w[1][0] else link_w[1][0]
# print("w:" + str(w))
# print("w-:{}".format(link_w[0]))
# print("w+:{}".format(link_w[1]))
# print("link_w[0]:{}".format(link_w[0]))
# print("link_w[1]:{}".format(link_w[1]))
"""
(1,0)Interchange
"""
# if neighbor == "10inter":
# print("(1,0)Interchange①やるよー")
"""
(1,0)Interchange①
"""
# 選んだwに対して
# 元々繋がっているエッジ
l1 = cost[w_minus][w] # w-→w
l2 = cost[v_minus][v] # v-→v
l3 = cost[v][v_plus] # v→v+
# # つなぎ直すエッジ
l4 = cost[w_minus][v]
l5 = cost[v][w]
l6 = cost[v_minus][v_plus]
# if l1 + l2 + l3 > l4 + l5 + l6:
# print("10inter① " + str(v) + ":" + str(w) + "適用")
try:
EdgeSet.remove(link_w[0]) #-を含む方
EdgeSet.remove(link_v[0])
EdgeSet.remove(link_v[1]) #+を含む方
EdgeSet.append([w_minus, v])
EdgeSet.append([v, w])
EdgeSet.append([v_minus, v_plus])
flag = True
except ValueError:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# [n, n]のようなエッジを持たないように修正
for es in EdgeSet:
if es[0] == es[1]:
# ルート数が減る遷移をどうするか
if es[0] == 0 and reduce_route == 1:
EdgeSet.remove([0, 0])
else:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# デポを含まない巡回路ができた場合
if(isHeiro(routeToPath(EdgeSet)) != 0):
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
current_function = penaltyFunction(EdgeSet, f_option)
# ペナルティ関数により評価
if(f_option == 2):
# 元の解も改良解も実行可能な場合,距離の短い方を返す
if P_eval <= 0 and current_function <= 0:
if(l1 + l2 + l3 > l4 + l5 + l6):
print("修正")
return EdgeSet
else:
EdgeSet = copy.deepcopy(bestSet)
if(current_function < P_eval):
return EdgeSet
EdgeSet = copy.deepcopy(bestSet)
# ペナルティ関数値が元より大きい
elif current_function > P_eval:
EdgeSet = copy.deepcopy(bestSet)
else:
P_eval = current_function
bestSet = copy.deepcopy(EdgeSet)
return bestSet
flag = False
"""
(1,0)Interchange②
"""
# 元々繋がっているエッジ
l1 = cost[w][w_plus] # w→w+
l2 = cost[v_minus][v] # v-→v
l3 = cost[v][v_plus] # v→v+
# つなぎ直すエッジ
l4 = cost[w_plus][v]
l5 = cost[v][w]
l6 = cost[v_minus][v_plus]
# if l1 + l2 + l3 > l4 + l5 + l6:
# print("10inter② " + str(v) + ":" + str(w) + "適用")
try:
EdgeSet.remove(link_w[1]) #+を含む方
EdgeSet.remove(link_v[0])
EdgeSet.remove(link_v[1]) #+を含む方
EdgeSet.append([w_plus, v])
EdgeSet.append([v, w])
EdgeSet.append([v_minus, v_plus])
flag = True
except ValueError:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# [n, n]のようなエッジを持たないように修正
for es in EdgeSet:
if es[0] == es[1]:
if es[0] == 0 and reduce_route == 1:
EdgeSet.remove([0, 0])
else:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# デポを含まない巡回路ができた場合
if(isHeiro(routeToPath(EdgeSet)) != 0):
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
current_function = penaltyFunction(EdgeSet, f_option)
# ペナルティ関数により評価
if(f_option == 2):
# 元の解も改良解も実行可能な場合,距離の短い方を返す
if P_eval <= 0 and current_function <= 0:
if(l1 + l2 + l3 > l4 + l5 + l6):
return EdgeSet
else:
EdgeSet = copy.deepcopy(bestSet)
if(current_function < P_eval):
return EdgeSet
EdgeSet = copy.deepcopy(bestSet)
elif current_function > P_eval:
EdgeSet = copy.deepcopy(bestSet)
else:
P_eval = current_function
bestSet = copy.deepcopy(EdgeSet)
return bestSet
flag = False
"""
(0,1)Interchange
"""
# if neighbor == "01inter":
# print("(0,1)Interchange①やるよー")
"""
(0,1)Interchange①
"""
# 選んだwに対して
# 元々繋がっているエッジ
l1 = cost[w_minus][w]
l2 = cost[w][w_plus]
l3 = cost[v_minus][v]
# つなぎ直すエッジ
l4 = cost[w_minus][w_plus]
l5 = cost[v_minus][w]
l6 = cost[v][w]
# if l1 + l2 + l3 > l4 + l5 + l6:
# print("01inter① " + str(v) + ":" + str(w) + "適用")
try:
EdgeSet.remove(link_w[0]) #-を含む方
EdgeSet.remove(link_w[1])
EdgeSet.remove(link_v[0]) #-を含む方
EdgeSet.append([w_minus, w_plus])
EdgeSet.append([v_minus, w])
EdgeSet.append([v, w])
flag = True
except ValueError:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# [n, n]のようなエッジを持たないように修正
for es in EdgeSet:
if es[0] == es[1]:
# ルート数が減る遷移をどうするか
if es[0] == 0 and reduce_route == 1:
EdgeSet.remove([0, 0])
else:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# デポを含まない巡回路ができた場合
if(isHeiro(routeToPath(EdgeSet)) != 0):
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
current_function = penaltyFunction(EdgeSet, f_option)
# ペナルティ関数により評価
if(f_option == 2):
# 元の解も改良解も実行可能な場合,距離の短い方を返す
if P_eval <= 0 and current_function <= 0:
if(l1 + l2 + l3 > l4 + l4 + l5):
return EdgeSet
else:
EdgeSet = copy.deepcopy(bestSet)
if(current_function < P_eval):
return EdgeSet
EdgeSet = copy.deepcopy(bestSet)
elif current_function > P_eval:
EdgeSet = copy.deepcopy(bestSet)
else:
P_eval = current_function
bestSet = copy.deepcopy(EdgeSet)
return bestSet
flag = False
"""
(0,1)Interchange②
"""
# 元々繋がっているエッジ
l1 = cost[w_minus][w]
l2 = cost[w][w_plus]
l3 = cost[v][v_plus]
# つなぎ直すエッジ
l4 = cost[w_minus][w_plus]
l5 = cost[v_plus][w]
l6 = cost[v][w]
# if l1 + l2 + l3 > l4 + l5 + l6:
# print("01inter② " + str(v) + ":" + str(w) + "適用")
try:
EdgeSet.remove(link_w[0]) #-を含む方
EdgeSet.remove(link_w[1])
EdgeSet.remove(link_v[1]) #-を含む方
EdgeSet.append([w_minus, w_plus])
EdgeSet.append([v_plus, w])
EdgeSet.append([v, w])
flag = True
except ValueError:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# [n, n]のようなエッジを持たないように修正
for es in EdgeSet:
if es[0] == es[1] and reduce_route == 1:
if es[0] == 0:
# ルート数が減る遷移をどうするか
EdgeSet.remove([0, 0])
else:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# デポを含まない巡回路ができた場合
if(isHeiro(routeToPath(EdgeSet)) != 0):
EdgeSet = copy.deepcopy(DefaultEdgeSet)
flag = False
if flag == True:
current_function = penaltyFunction(EdgeSet, f_option)
# ペナルティ関数により評価
if(f_option == 2):
# 元の解も改良解も実行可能な場合,距離の短い方を返す
if P_eval <= 0 and current_function <= 0:
if(l1 + l2 + l3 > l4 + l5 + l6):
return EdgeSet
else:
EdgeSet = copy.deepcopy(bestSet)
if(current_function < P_eval):
return EdgeSet
EdgeSet = copy.deepcopy(bestSet)
elif current_function > P_eval:
EdgeSet = copy.deepcopy(bestSet)
else:
P_eval = current_function
bestSet = copy.deepcopy(EdgeSet)
return bestSet
flag = False
"""
(1,1)Interchange
"""
# if neighbor == "11inter":
# print("(1,1)Interchangeやるよー")
"""
(1,1)Interchange①
"""
"""
w--を求めるステップ
"""
path = routeToPath(EdgeSet)
# ノードwがどのルートに含まれるか求める
for i, route in enumerate(path):
for n in route:
if w in n:
route_num = i
break
# print("{}を含むルートは:{}".format(w, path[route_num]))
# if(len(path[route_num]) < 3):
# continue
# ノードw-を持つリストを作る
w_minus2list = [x for x in path[route_num] \
if(w_minus in x and x != link_w[0])]
node_flag = False
try:
# リストからノードw-でない方をノードw--として選択
w_minus_minus = w_minus2list[0][0] if w_minus2list[0][1] == w_minus \
else w_minus2list[0][1]
node_flag = True
except IndexError:
print("w--作成で失敗")
node_flag = False
# 同じエッジを選ぶ可能性があるものは排除
# if link_v[0] == w_minus2list[0] or link_v[1] == w_minus2list[0] \
# or link_w[0] == w_minus2list[0] or link_w[1] == w_minus2list[0]:
# continue
if node_flag == True:
# 選んだwに対して
# 元々繋がっているエッジ
l1 = cost[w_minus_minus][w_minus]
l2 = cost[w_minus][w]
l3 = cost[v_minus][v]
l4 = cost[v][v_plus]
# つなぎ直すエッジ
l5 = cost[w_minus_minus][v]
l6 = cost[w_minus][v_plus]
l7 = cost[v_minus][w_minus]
l8 = cost[v][w]
# if l1 + l2 + l3 + l4 > l5 + l6 + l7 + l8:
# print("11inter① " + str(v) + ":" + str(w) + "適用")
try:
# print("w-のリスト:{}".format(w_minus2list[0]))
# print("link_w[0]:{}".format(link_w[0]))
# print("link_v[0]:{}".format(link_v[0]))
# print("link_v[1]:{}".format(link_v[1]))
EdgeSet.remove(w_minus2list[0]) #--を含む方
EdgeSet.remove(link_w[0])
EdgeSet.remove(link_v[0])
EdgeSet.remove(link_v[1])
EdgeSet.append([w_minus_minus, v])
EdgeSet.append([w_minus, v_plus])
EdgeSet.append([v_minus, w_minus])
EdgeSet.append([v, w])
flag = True
except ValueError:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# [n, n]のようなエッジを持たないように修正
for es in EdgeSet:
if es[0] == es[1] and reduce_route == 1:
if es[0] == 0:
EdgeSet.remove([0, 0])
else:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# デポを含まない巡回路ができた場合
if(isHeiro(routeToPath(EdgeSet)) != 0):
# print("リセット1")
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
current_function = penaltyFunction(EdgeSet, f_option)
# ペナルティ関数により評価
if(f_option == 2):
# 元の解も改良解も実行可能な場合,距離の短い方を返す
if P_eval <= 0 and current_function <= 0:
if(l1 + l2 + l3 + l4 > l5 + l6 + l7 + l8):
return EdgeSet
else:
EdgeSet = copy.deepcopy(bestSet)
if(current_function < P_eval):
return EdgeSet
EdgeSet = copy.deepcopy(bestSet)
elif current_function > P_eval:
EdgeSet = copy.deepcopy(bestSet)
else:
P_eval = current_function
bestSet = copy.deepcopy(EdgeSet)
return bestSet
flag = False
"""
(1,1)Interchange②
"""
"""
w++を求めるステップ
"""
# ノードw+を持つリストを作る
w_plus2list = [x for x in path[route_num] \
if(w_plus in x and x != link_w[1])]
node_flag = False
try:
# リストからノードw+でない方をノードw++として選択
w_plus_plus = w_plus2list[0][1] if w_plus2list[0][0] == w_plus \
else w_plus2list[0][0]
node_flag = True
except IndexError:
print("w++の作成に失敗")
node_flag = False
# print("{}を含むルートは:{}".format(w, path[route_num]))
# print("リスト:{}".format(w_plus2list[0]))
# print("w+:{}".format(w_plus))
# print("w++:{}".format(w_plus_plus))
if node_flag == True:
# 元々繋がっているエッジ
l1 = cost[w_plus][w_plus_plus]
l2 = cost[w][w_plus]
l3 = cost[v_minus][v]
l4 = cost[v][v_plus]
# つなぎ直すエッジ
l5 = cost[v][w_plus_plus]
l6 = cost[v_minus][w_plus]
l7 = cost[v_plus][w_plus]
l8 = cost[v][w]
# 同じエッジを選ぶ可能性があるものは排除
# if link_v[0] == w_plus2list[0] or link_v[1] == w_plus2list[0] \
# or link_w[0] == w_plus2list[0] or link_w[1] == w_plus2list[0]:
# continue
# if l1 + l2 + l3 + l4 > l5 + l6 + l7 + l8:
# print("11inter② " + str(v) + ":" + str(w) + "適用")
try:
EdgeSet.remove(w_plus2list[0]) #++を含む方
EdgeSet.remove(link_w[1])
EdgeSet.remove(link_v[0])
EdgeSet.remove(link_v[1])
EdgeSet.append([v, w_plus_plus])
EdgeSet.append([v_minus, w_plus])
EdgeSet.append([v_plus, w_plus])
EdgeSet.append([v, w])
flag = True
except ValueError:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# [n, n]のようなエッジを持たないように修正
for es in EdgeSet:
if es[0] == es[1] and reduce_route == 1:
if es[0] == 0:
EdgeSet.remove([0, 0])
else:
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
# デポを含まない巡回路ができた場合
if(isHeiro(routeToPath(EdgeSet)) != 0):
# print("リセット2")
EdgeSet = copy.deepcopy(bestSet)
flag = False
if flag == True:
current_function = penaltyFunction(EdgeSet, f_option)
# ペナルティ関数により評価
if(f_option == 2):
# 元の解も改良解も実行可能な場合,距離の短い方を返す
if P_eval <= 0 and current_function <= 0:
if(l1 + l2 + l3 + l4 > l5 + l6 + l7 + l8):
return EdgeSet
else:
EdgeSet = copy.deepcopy(bestSet)
if(current_function < P_eval):
return EdgeSet
EdgeSet = copy.deepcopy(bestSet)
elif current_function > P_eval:
EdgeSet = copy.deepcopy(bestSet)
else:
P_eval = current_function
bestSet = copy.deepcopy(EdgeSet)
return bestSet
flag = False
"""
2-opt近傍
"""
# if neighbor == "2opt":
"""
2-opt①
"""
# print("2opt①やるよー")
l1 = cost[v_minus][v] # 元のエッジ
l2 = cost[w_minus][w] # 元のエッジ
l3 = cost[v][w]
l4 = cost[v_minus][w_minus]