How to use unroute method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

net_stuff.py

Source: net_stuff.py Github

copy
1import socket
2import os
3
4def un_routing():
5    try:
6        vivox_ms = socket.gethostbyname('mpx5j.vivox.com')
7        r6s_vcs = socket.gethostbyname('disp-rbswp-5-1.vivox.com')
8        r6s_vcs1 = socket.gethostbyname('mphpp-rbswp-5-1-1.vivox.com')
9        r6s_vcs2 = socket.gethostbyname('mphpp-rbswp-5-1-2.vivox.com')
10        r6s_vcs3 = socket.gethostbyname('mphpp-rbswp-5-1-3.vivox.com')
11        r6s_vcs4 = socket.gethostbyname('mphpp-rbswp-5-1-4.vivox.com')
12        r6s_vcs5 = socket.gethostbyname('mphpp-rbswp-5-1-5.vivox.com')
13        pubg_vcs = socket.gethostbyname('ec2-18-220-247-8.us-east-2.compute.amazonaws.com')
14        vxx1 = socket.gethostbyname('mphpp-zmxbp-5-2-5.vivox.com')
15        vxx2 = socket.gethostbyname('tst5a.vivox.com')
16        vxx3 = socket.gethostbyname('vdisp-plabdev-5-1.vivox.com')
17        vxx4 = socket.gethostbyname('nmap.vivox.com')
18        vxx5 = socket.gethostbyname('sg-xbd-5-2.vivox.com')
19        vxx6 = socket.gethostbyname('vmph-hrpd-5-1.vivox.com')
20        vxx7 = socket.gethostbyname('74.201.99.77')  # why im i even trying to get the hostname of those ip's ?
21        vxx8 = socket.gethostbyname('74.201.98.0')
22        vxx_fn = socket.gethostbyname('disp-fnwp-5-1.vivox.com')
23        vxx_fn2 = socket.gethostbyname('mphpp-fnwp-5-1-10.vivox.com')
24        vxx_fn3 = socket.gethostbyname('mphpp-fnwp-5-1-11.vivox.com')
25        vxx_fn4 = socket.gethostbyname('mphpp-fnwp-5-1-2.vivox.com')
26        vxx_fn5 = socket.gethostbyname('mphpp-fnwp-5-1-12.vivox.com')
27        vxx_fn6 = socket.gethostbyname('mphpp-fnwp-5-1-3.vivox.com')
28        vxx_fn7 = socket.gethostbyname('mphpp-fnwp-5-1-13.vivox.com')
29        vxx_fn8 = socket.gethostbyname('mphpp-fnwp-5-1-4.vivox.com')
30        vxx_fn9 = socket.gethostbyname('mphpp-fnwp-5-1-14.vivox.com')
31        vxx_fn10 = socket.gethostbyname('mphpp-fnwp-5-1-15.vivox.com')
32        vxx_fn11 = socket.gethostbyname('mphpp-fnwp-5-1-6.vivox.com')
33        vxx_fn12 = socket.gethostbyname('mphpp-fnwp-5-1-7.vivox.com')
34        vxx_fn13 = socket.gethostbyname('mphpp-fnwp-5-1-8.vivox.com')
35        vxx_fn14 = socket.gethostbyname('mphpp-fnwp-5-1-9.vivox.com')
36        vxx_h1Z1 = socket.gethostbyname('disp-h1zp-5-1.vivox.com')
37        vxx_h1Z12 = socket.gethostbyname('mphpp-h1zp-5-1-1.vivox.com')
38        vxx_h1Z13 = socket.gethostbyname('mphpp-h1zp-5-1-2.vivox.com')
39        vxx_h1Z14 = socket.gethostbyname('mphpp-h1zp-5-1-3.vivox.com')
40        vxx_h1Z15 = socket.gethostbyname('mphpp-h1zp-5-1-4.vivox.com')
41        vxx_h1Z16 = socket.gethostbyname('mphpp-h1zp-5-1-5.vivox.com')
42        unroute_master = 'cmdp.exe route delete ' + vivox_ms
43        unroute_r6s = 'cmdp.exe route delete ' + r6s_vcs
44        unroute_r6s1 = 'cmdp.exe route delete ' + r6s_vcs1
45        unroute_r6s2 = 'cmdp.exe route delete ' + r6s_vcs2
46        unroute_r6s3 = 'cmdp.exe route delete ' + r6s_vcs3
47        unroute_r6s4 = 'cmdp.exe route delete ' + r6s_vcs4
48        unroute_r6s5 = 'cmdp.exe route delete ' + r6s_vcs5
49        unroute_pubg = 'cmdp.exe route delete ' + pubg_vcs
50        unroute_vxx1 = 'cmdp.exe route delete ' + vxx1
51        unroute_vxx2 = 'cmdp.exe route delete ' + vxx2
52        unroute_vxx3 = 'cmdp.exe route delete ' + vxx3
53        unroute_vxx4 = 'cmdp.exe route delete ' + vxx4
54        unroute_vxx5 = 'cmdp.exe route delete ' + vxx5
55        unroute_vxx6 = 'cmdp.exe route delete ' + vxx6
56        unroute_vxx7 = 'cmdp.exe route delete ' + vxx7
57        unroute_vxx8 = 'cmdp.exe route delete ' + vxx8
58        unroute_pubgx = 'cmdp.exe route delete  18.0.0.0/8'
59        unroute_fn = 'cmdp.exe route delete ' + vxx_fn
60        unroute_fn2 = 'cmdp.exe route delete ' + vxx_fn2
61        unroute_fn3 = 'cmdp.exe route delete ' + vxx_fn3
62        unroute_fn4 = 'cmdp.exe route delete ' + vxx_fn4
63        unroute_fn5 = 'cmdp.exe route delete ' + vxx_fn5
64        unroute_fn6 = 'cmdp.exe route delete ' + vxx_fn6
65        unroute_fn7 = 'cmdp.exe route delete ' + vxx_fn7
66        unroute_fn8 = 'cmdp.exe route delete ' + vxx_fn8
67        unroute_fn9 = 'cmdp.exe route delete ' + vxx_fn9
68        unroute_fn10 = 'cmdp.exe route delete ' + vxx_fn10
69        unroute_fn11 = 'cmdp.exe route delete ' + vxx_fn11
70        unroute_fn12 = 'cmdp.exe route delete ' + vxx_fn12
71        unroute_fn13 = 'cmdp.exe route delete ' + vxx_fn13
72        unroute_H1Z1 = 'cmdp.exe route delete ' + vxx_h1Z1
73        unroute_H1Z12 = 'cmdp.exe route delete ' + vxx_h1Z12
74        unroute_H1Z13 = 'cmdp.exe route delete ' + vxx_h1Z13
75        unroute_H1Z14 = 'cmdp.exe route delete ' + vxx_h1Z14
76        unroute_H1Z15 = 'cmdp.exe route delete ' + vxx_h1Z15
77        unroute_H1Z16 = 'cmdp.exe route delete ' + vxx_h1Z16
78        os.system(unroute_master + '>nul 2>&1')
79        os.system(unroute_pubg + '>nul 2>&1')
80        os.system(unroute_pubgx + '>nul 2>&1')
81        os.system(unroute_r6s + '>nul 2>&1')
82        os.system(unroute_r6s1 + '>nul 2>&1')
83        os.system(unroute_r6s2 + '>nul 2>&1')
84        os.system(unroute_r6s3 + '>nul 2>&1')
85        os.system(unroute_r6s4 + '>nul 2>&1')
86        os.system(unroute_r6s5 + '>nul 2>&1')
87        os.system(unroute_vxx1 + '>nul 2>&1')
88        os.system(unroute_vxx2 + '>nul 2>&1')
89        os.system(unroute_vxx3 + '>nul 2>&1')
90        os.system(unroute_vxx4 + '>nul 2>&1')
91        os.system(unroute_vxx5 + '>nul 2>&1')
92        os.system(unroute_vxx6 + '>nul 2>&1')
93        os.system(unroute_vxx7 + '>nul 2>&1')
94        os.system(unroute_vxx8 + '>nul 2>&1')
95        os.system(unroute_fn + '>nul 2>&1')
96        os.system(unroute_fn2 + '>nul 2>&1')
97        os.system(unroute_fn3 + '>nul 2>&1')
98        os.system(unroute_fn4 + '>nul 2>&1')
99        os.system(unroute_fn5 + '>nul 2>&1')
100        os.system(unroute_fn6 + '>nul 2>&1')
101        os.system(unroute_fn7 + '>nul 2>&1')
102        os.system(unroute_fn8 + '>nul 2>&1')
103        os.system(unroute_fn9 + '>nul 2>&1')
104        os.system(unroute_fn10 + '>nul 2>&1')
105        os.system(unroute_fn11 + '>nul 2>&1')
106        os.system(unroute_fn12 + '>nul 2>&1')
107        os.system(unroute_fn13 + '>nul 2>&1')
108        os.system(unroute_H1Z1 + '>nul 2>&1')
109        os.system(unroute_H1Z12 + '>nul 2>&1')
110        os.system(unroute_H1Z13 + '>nul 2>&1')
111        os.system(unroute_H1Z14 + '>nul 2>&1')
112        os.system(unroute_H1Z15 + '>nul 2>&1')
113        os.system(unroute_H1Z16 + '>nul 2>&1')
114    except socket.error:
115        pass
116
117def routing_vvx():
118    try:
119        IP = socket.gethostbyname(socket.gethostname())
120        vivox_ms = socket.gethostbyname('mpx5j.vivox.com')
121        vxx1 = socket.gethostbyname('mphpp-zmxbp-5-2-5.vivox.com')
122        vxx2 = socket.gethostbyname('tst5a.vivox.com')
123        vxx3 = socket.gethostbyname('vdisp-plabdev-5-1.vivox.com')
124        vxx4 = socket.gethostbyname('nmap.vivox.com')
125        vxx5 = socket.gethostbyname('sg-xbd-5-2.vivox.com')
126        vxx6 = socket.gethostbyname('vmph-hrpd-5-1.vivox.com')
127        vxx7 = socket.gethostbyname('74.201.99.77')  # why im i even trying to get the hostname of those ip's ?
128        vxx8 = socket.gethostbyname('74.201.98.0')
129        route_vxx1 = 'cmdp.exe route -p add' + vxx1 + 'mask' + '255.255.255.255' + IP
130        route_vxx2 = 'cmdp.exe route -p add' + vxx2 + 'mask' + '255.255.255.255' + IP
131        route_vxx3 = 'cmdp.exe route -p add' + vxx3 + 'mask' + '255.255.255.255' + IP
132        route_vxx4 = 'cmdp.exe route -p add' + vxx4 + 'mask' + '255.255.255.255' + IP
133        route_vxx5 = 'cmdp.exe route -p add' + vxx5 + 'mask' + '255.255.255.255' + IP
134        route_vxx6 = 'cmdp.exe route -p add' + vxx6 + 'mask' + '255.255.255.255' + IP
135        route_vxx7 = 'cmdp.exe route -p add' + vxx7 + 'mask' + '255.255.255.255' + IP
136        route_vxx8 = 'cmdp.exe route -p add' + vxx8 + 'mask' + '255.255.255.255' + IP
137        route_master = 'cmdp.exe route -p add' + vivox_ms + 'mask' + '255.255.255.255' + IP
138        os.system(route_vxx1 + '>nul 2>&1')
139        os.system(route_vxx2 + '>nul 2>&1')
140        os.system(route_vxx3 + '>nul 2>&1')
141        os.system(route_vxx4 + '>nul 2>&1')
142        os.system(route_vxx5 + '>nul 2>&1')
143        os.system(route_vxx6 + '>nul 2>&1')
144        os.system(route_vxx7 + '>nul 2>&1')
145        os.system(route_vxx8 + '>nul 2>&1')
146        os.system(route_master + '>nul 2>&1')
147    except socket.error:
148        pass
149
150
151def routing_r6():
152    try:
153        IP = socket.gethostbyname(socket.gethostname())
154        r6s_vcs = socket.gethostbyname('disp-rbswp-5-1.vivox.com')
155        r6s_vcs1 = socket.gethostbyname('mphpp-rbswp-5-1-1.vivox.com')
156        r6s_vcs2 = socket.gethostbyname('mphpp-rbswp-5-1-2.vivox.com')
157        r6s_vcs3 = socket.gethostbyname('mphpp-rbswp-5-1-3.vivox.com')
158        r6s_vcs4 = socket.gethostbyname('mphpp-rbswp-5-1-4.vivox.com')
159        r6s_vcs5 = socket.gethostbyname('mphpp-rbswp-5-1-5.vivox.com')
160        route_r6s = 'cmdp.exe route -p add' + r6s_vcs + 'mask' + '255.255.255.255 ' + IP
161        route_r6s1 = 'cmdp.exe route -p add' + r6s_vcs1 + 'mask' + '255.255.255.255 ' + IP
162        route_r6s2 = 'cmdp.exe route -p add' + r6s_vcs2 + 'mask' + '255.255.255.255 ' + IP
163        route_r6s3 = 'cmdp.exe route -p add' + r6s_vcs3 + 'mask' + '255.255.255.255 ' + IP
164        route_r6s4 = 'cmdp.exe route -p add' + r6s_vcs4 + 'mask' + '255.255.255.255 ' + IP
165        route_r6s5 = 'cmdp.exe route -p add' + r6s_vcs5 + 'mask' + '255.255.255.255 ' + IP
166        os.system(route_r6s + '>nul 2>&1')
167        os.system(route_r6s1 + '>nul 2>&1')
168        os.system(route_r6s2 + '>nul 2>&1')
169        os.system(route_r6s3 + '>nul 2>&1')
170        os.system(route_r6s4 + '>nul 2>&1')
171        os.system(route_r6s5 + '>nul 2>&1')
172    except socket.error:
173        pass
174
175
176def routing_r6_console():
177    try:
178        IP = socket.gethostbyname(socket.gethostname())
179        r6s_vcsp = socket.gethostbyname('disp-rbspsp-5-1.vivox.com')
180        r6s_vcsp1 = socket.gethostbyname('mphpp-rbspsp-5-1-10.vivox.com')
181        r6s_vcsp2 = socket.gethostbyname('mphpp-rbspsp-5-1-1.vivox.com')
182        r6s_vcsp3 = socket.gethostbyname('mphpp-rbspsp-5-1-11.vivox.com')
183        r6s_vcsp4 = socket.gethostbyname('mphpp-rbspsp-5-1-2.vivox.com')
184        r6s_vcsp5 = socket.gethostbyname('mphpp-rbspsp-5-1-12.vivox.com')
185        r6s_vcsp6 = socket.gethostbyname('mphpp-rbspsp-5-1-3.vivox.com')
186        r6s_vcsp7 = socket.gethostbyname('mphpp-rbspsp-5-1-13.vivox.com')
187        r6s_vcsp8 = socket.gethostbyname('mphpp-rbspsp-5-1-4.vivox.com')
188        r6s_vcsp9 = socket.gethostbyname('mphpp-rbspsp-5-1-14.vivox.com')
189        r6s_vcsp10 = socket.gethostbyname('mphpp-rbspsp-5-1-5.vivox.com')
190        r6s_vcsp11 = socket.gethostbyname('mphpp-rbspsp-5-1-15.vivox.com')
191        r6s_vcsp12 = socket.gethostbyname('mphpp-rbspsp-5-1-6.vivox.com')
192        r6s_vcsp13 = socket.gethostbyname('mphpp-rbspsp-5-1-16.vivox.com')
193        r6s_vcsp14 = socket.gethostbyname('mphpp-rbspsp-5-1-7.vivox.com')
194        r6s_vcsp15 = socket.gethostbyname('mphpp-rbspsp-5-1-8.vivox.com')
195        r6s_vcsp16 = socket.gethostbyname('mphpp-rbspsp-5-1-9.vivox.com')
196        r6s_vcsxb = socket.gethostbyname('disp-rbsxbp-5-1.vivox.com')
197        r6s_vcsxb1 = socket.gethostbyname('mphpp-rbsxbp-5-1-2.vivox.com')
198        r6s_vcsxb2 = socket.gethostbyname('mphpp-rbsxbp-5-1-3.vivox.com')
199        r6s_vcsxb3 = socket.gethostbyname('mphpp-rbsxbp-5-1-4.vivox.com')
200        r6s_vcsxb4 = socket.gethostbyname('mphpp-rbsxbp-5-1-5.vivox.com')
201        r6s_vcsxb5 = socket.gethostbyname('mphpp-rbsxbp-5-1-6.vivox.com')
202        r6s_vcsxb6 = socket.gethostbyname('mphpp-rbsxbp-5-1-7.vivox.com')
203        r6s_vcsxb7 = socket.gethostbyname('mphpp-rbsxbp-5-1-8.vivox.com')
204        route_r6s_vcsp = 'cmdp.exe route -p add' + r6s_vcsp + 'mask' + '255.255.255.255' + IP
205        route_r6s_vcsp1 = 'cmdp.exe route -p add' + r6s_vcsp1 + 'mask' + '255.255.255.255' + IP
206        route_r6s_vcsp2 = 'cmdp.exe route -p add' + r6s_vcsp2 + 'mask' + '255.255.255.255' + IP
207        route_r6s_vcsp3 = 'cmdp.exe route -p add' + r6s_vcsp3 + 'mask' + '255.255.255.255' + IP
208        route_r6s_vcsp4 = 'cmdp.exe route -p add' + r6s_vcsp4 + 'mask' + '255.255.255.255' + IP
209        route_r6s_vcsp5 = 'cmdp.exe route -p add' + r6s_vcsp5 + 'mask' + '255.255.255.255' + IP
210        route_r6s_vcsp6 = 'cmdp.exe route -p add' + r6s_vcsp6 + 'mask' + '255.255.255.255' + IP
211        route_r6s_vcsp7 = 'cmdp.exe route -p add' + r6s_vcsp7 + 'mask' + '255.255.255.255' + IP
212        route_r6s_vcsp8 = 'cmdp.exe route -p add' + r6s_vcsp8 + 'mask' + '255.255.255.255' + IP
213        route_r6s_vcsp9 = 'cmdp.exe route -p add' + r6s_vcsp9 + 'mask' + '255.255.255.255' + IP
214        route_r6s_vcsp10 = 'cmdp.exe route -p add' + r6s_vcsp10 + 'mask' + '255.255.255.255' + IP
215        route_r6s_vcsp11 = 'cmdp.exe route -p add' + r6s_vcsp11 + 'mask' + '255.255.255.255' + IP
216        route_r6s_vcsp12 = 'cmdp.exe route -p add' + r6s_vcsp12 + 'mask' + '255.255.255.255' + IP
217        route_r6s_vcsp13 = 'cmdp.exe route -p add' + r6s_vcsp13 + 'mask' + '255.255.255.255' + IP
218        route_r6s_vcsp14 = 'cmdp.exe route -p add' + r6s_vcsp14 + 'mask' + '255.255.255.255' + IP
219        route_r6s_vcsp15 = 'cmdp.exe route -p add' + r6s_vcsp15 + 'mask' + '255.255.255.255' + IP
220        route_r6s_vcsp16 = 'cmdp.exe route -p add' + r6s_vcsp16 + 'mask' + '255.255.255.255' + IP
221        route_r6s_vcxb = 'cmdp.exe route -p add' + r6s_vcsxb + 'mask' + '255.255.255.255' + IP
222        route_r6s_vcxb1 = 'cmdp.exe route -p add' + r6s_vcsxb1 + 'mask' + '255.255.255.255' + IP
223        route_r6s_vcxb2 = 'cmdp.exe route -p add' + r6s_vcsxb2 + 'mask' + '255.255.255.255' + IP
224        route_r6s_vcxb3 = 'cmdp.exe route -p add' + r6s_vcsxb3 + 'mask' + '255.255.255.255' + IP
225        route_r6s_vcxb4 = 'cmdp.exe route -p add' + r6s_vcsxb4 + 'mask' + '255.255.255.255' + IP
226        route_r6s_vcxb5 = 'cmdp.exe route -p add' + r6s_vcsxb5 + 'mask' + '255.255.255.255' + IP
227        route_r6s_vcxb6 = 'cmdp.exe route -p add' + r6s_vcsxb6 + 'mask' + '255.255.255.255' + IP
228        route_r6s_vcxb7 = 'cmdp.exe route -p add' + r6s_vcsxb7 + 'mask' + '255.255.255.255' + IP
229        os.system(route_r6s_vcsp + '>nul 2>&1')
230        os.system(route_r6s_vcsp1 + '>nul 2>&1')
231        os.system(route_r6s_vcsp2 + '>nul 2>&1')
232        os.system(route_r6s_vcsp3 + '>nul 2>&1')
233        os.system(route_r6s_vcsp4 + '>nul 2>&1')
234        os.system(route_r6s_vcsp5 + '>nul 2>&1')
235        os.system(route_r6s_vcsp6 + '>nul 2>&1')
236        os.system(route_r6s_vcsp7 + '>nul 2>&1')
237        os.system(route_r6s_vcsp8 + '>nul 2>&1')
238        os.system(route_r6s_vcsp10 + '>nul 2>&1')
239        os.system(route_r6s_vcsp11 + '>nul 2>&1 ')
240        os.system(route_r6s_vcsp12 + '>nul 2>&1')
241        os.system(route_r6s_vcsp13 + '>nul 2>&1')
242        os.system(route_r6s_vcsp14 + '>nul 2>&1')
243        os.system(route_r6s_vcsp15 + '>nul 2>&1')
244        os.system(route_r6s_vcsp16 + '>nul 2>&1')
245        os.system(route_r6s_vcxb + '>nul 2>&1')
246        os.system(route_r6s_vcxb1 + '>nul 2>&1')
247        os.system(route_r6s_vcxb2 + '>nul 2>&1')
248        os.system(route_r6s_vcxb3 + '>nul 2>&1')
249        os.system(route_r6s_vcxb4 + '>nul 2>&1')
250        os.system(route_r6s_vcxb5 + '>nul 2>&1')
251        os.system(route_r6s_vcxb6 + '>nul 2>&1')
252        os.system(route_r6s_vcxb7 + '>nul 2>&1')
253    except socket.error:
254        pass
255
256def routing_pubg():
257    try:
258        IP = socket.gethostbyname(socket.gethostname())
259        route_pubgx = 'cmdp.exe route -p add 18.0.0.0/8 ' + IP
260        os.system(route_pubgx + '>nul 2>&1')
261
262    except socket.error:
263        pass
264
265def routing_fortnite():
266    try:
267        IP = socket.gethostbyname(socket.gethostname())
268        vxx_fn = socket.gethostbyname('disp-fnwp-5-1.vivox.com')
269        vxx_fn2 = socket.gethostbyname('mphpp-fnwp-5-1-10.vivox.com')
270        vxx_fn3 = socket.gethostbyname('mphpp-fnwp-5-1-11.vivox.com')
271        vxx_fn4 = socket.gethostbyname('mphpp-fnwp-5-1-2.vivox.com')
272        vxx_fn5 = socket.gethostbyname('mphpp-fnwp-5-1-12.vivox.com')
273        vxx_fn6 = socket.gethostbyname('mphpp-fnwp-5-1-3.vivox.com')
274        vxx_fn7 = socket.gethostbyname('mphpp-fnwp-5-1-13.vivox.com')
275        vxx_fn8 = socket.gethostbyname('mphpp-fnwp-5-1-4.vivox.com')
276        vxx_fn9 = socket.gethostbyname('mphpp-fnwp-5-1-14.vivox.com')
277        vxx_fn10 = socket.gethostbyname('mphpp-fnwp-5-1-15.vivox.com')
278        vxx_fn11 = socket.gethostbyname('mphpp-fnwp-5-1-6.vivox.com')
279        vxx_fn12 = socket.gethostbyname('mphpp-fnwp-5-1-7.vivox.com')
280        vxx_fn13 = socket.gethostbyname('mphpp-fnwp-5-1-8.vivox.com')
281        vxx_fn14 = socket.gethostbyname('mphpp-fnwp-5-1-9.vivox.com')
282        route_fn = 'cmdp.exe route -p add' + vxx_fn + 'mask' + '255.255.255.255' + IP
283        route_fn2 = 'cmdp.exe route -p add' + vxx_fn2 + 'mask' + '255.255.255.255' + IP
284        route_fn3 = 'cmdp.exe route -p add' + vxx_fn3 + 'mask' + '255.255.255.255' + IP
285        route_fn4 = 'cmdp.exe route -p add' + vxx_fn4 + 'mask' + '255.255.255.255' + IP
286        route_fn5 = 'cmdp.exe route -p add' + vxx_fn5 + 'mask' + '255.255.255.255' + IP
287        route_fn6 = 'cmdp.exe route -p add' + vxx_fn6 + 'mask' + '255.255.255.255' + IP
288        route_fn7 = 'cmdp.exe route -p add' + vxx_fn7 + 'mask' + '255.255.255.255' + IP
289        route_fn8 = 'cmdp.exe route -p add' + vxx_fn8 + 'mask' + '255.255.255.255' + IP
290        route_fn9 = 'cmdp.exe route -p add' + vxx_fn9 + 'mask' + '255.255.255.255' + IP
291        route_fn10 = 'cmdp.exe route -p add' + vxx_fn10 + 'mask' + '255.255.255.255' + IP
292        route_fn11 = 'cmdp.exe route -p add' + vxx_fn11 + 'mask' + '255.255.255.255' + IP
293        route_fn12 = 'cmdp.exe route -p add' + vxx_fn12 + 'mask' + '255.255.255.255' + IP
294        route_fn13 = 'cmdp.exe route -p add' + vxx_fn13 + 'mask' + '255.255.255.255' + IP
295        route_fn14 = 'cmdp.exe route -p add' + vxx_fn14 + 'mask' + '255.255.255.255' + IP
296        os.system(route_fn + '>nul 2>&1')
297        os.system(route_fn2 + '>nul 2>&1')
298        os.system(route_fn3 + '>nul 2>&1')
299        os.system(route_fn4 + '>nul 2>&1')
300        os.system(route_fn5 + '>nul 2>&1')
301        os.system(route_fn6 + '>nul 2>&1')
302        os.system(route_fn7 + '>nul 2>&1')
303        os.system(route_fn8 + '>nul 2>&1')
304        os.system(route_fn9 + '>nul 2>&1')
305        os.system(route_fn10 + '>nul 2>&1')
306        os.system(route_fn11 + '>nul 2>&1')
307        os.system(route_fn12 + '>nul 2>&1 ')
308        os.system(route_fn13 + '>nul 2>&1')
309        os.system(route_fn14 + '>nul 2>&1')
310    except socket.error:
311        pass
312
313
314def routing_h1z1():
315    try:
316        IP = socket.gethostbyname(socket.gethostname())
317        vxx_h1Z1 = socket.gethostbyname('disp-h1zp-5-1.vivox.com')
318        vxx_h1Z12 = socket.gethostbyname('mphpp-h1zp-5-1-1.vivox.com')
319        vxx_h1Z13 = socket.gethostbyname('mphpp-h1zp-5-1-2.vivox.com')
320        vxx_h1Z14 = socket.gethostbyname('mphpp-h1zp-5-1-3.vivox.com')
321        vxx_h1Z15 = socket.gethostbyname('mphpp-h1zp-5-1-4.vivox.com')
322        vxx_h1Z16 = socket.gethostbyname('mphpp-h1zp-5-1-5.vivox.com')
323        route_h1z1 = 'cmdp.exe route -p add' + vxx_h1Z1 + 'mask' + '255.255.255.255' + IP
324        route_h1z12 = 'cmdp.exe route -p add' + vxx_h1Z12 + 'mask' + '255.255.255.255' + IP
325        route_h1z13 = 'cmdp.exe route -p add' + vxx_h1Z13 + 'mask' + '255.255.255.255' + IP
326        route_h1z14 = 'cmdp.exe route -p add' + vxx_h1Z14 + 'mask' + '255.255.255.255' + IP
327        route_h1z15 = 'cmdp.exe route -p add' + vxx_h1Z15 + 'mask' + '255.255.255.255' + IP
328        route_h1z16 = 'cmdp.exe route -p add' + vxx_h1Z16 + 'mask' + '255.255.255.255' + IP
329        os.system(route_h1z1 + '>nul 2>&1')
330        os.system(route_h1z12 + '>nul 2>&1')
331        os.system(route_h1z13 + '>nul 2>&1')
332        os.system(route_h1z14 + '>nul 2>&1')
333        os.system(route_h1z15 + '>nul 2>&1')
334        os.system(route_h1z16 + '>nul 2>&1')
335    except socket.error:
336        pass
337
338
339def dns_setup():
340    try:
341        os.system('netsh interface ip set dns name="Ethernet 2" source=static addr=none >nul 2>&1')
342        os.system('netsh interface ip add dns name="Ethernet 2" addr=8.8.8.8 index=1 >nul 2>&1')
343        os.system('netsh interface ip add dns name="Ethernet 2" addr=8.8.4.4 index=2 >nul 2>&1')
344        os.system('netsh interface ip set dns name="Ethernet 1" source=static addr=none >nul 2>&1')
345        os.system('netsh interface ip add dns name="Ethernet 1" addr=8.8.8.8 index=1 >nul 2>&1')
346        os.system('netsh interface ip add dns name="Ethernet 1" addr=8.8.4.4 index=2  >nul 2>&1')
347        os.system('netsh interface ip set dns name="Ethernet" source=static addr=none >nul 2>&1')
348        os.system('netsh interface ip add dns name="Ethernet" addr=8.8.8.8 index=1 >nul 2>&1')
349        os.system('netsh interface ip add dns name="Ethernet" addr=8.8.4.4 index=2 >nul 2>&1')
350        os.system('netsh interface ip set dns name="Wi-Fi" source=static addr=none >nul 2>&1')
351        os.system('netsh interface ip add dns name="Wi-Fi" addr=8.8.8.8 index=1 >nul 2>&1')
352        os.system('netsh interface ip add dns name="Wi-Fi" addr=8.8.4.4 index=2 >nul 2>&1')
353        os.system('netsh interface ip set dns name="Local Area Connection" source=static addr=none >nul 2>&1')
354        os.system('netsh interface ip add dns name="Local Area Connection" addr=8.8.8.8 index=1 >nul 2>&1')
355        os.system('netsh interface ip add dns name="Local Area Connection" addr=8.8.4.4 index=2 >nul 2>&1')
356        os.system('netsh interface ip set dns name="Wireless Network Connection" source=static addr=none >nul 2>&1')
357        os.system('netsh interface ip add dns name="Wireless Network Connection" addr=8.8.8.8 index=1 >nul 2>&1')
358        os.system('netsh interface ip add dns name="Wireless Network Connection" addr=8.8.4.4 index=2 >nul 2>&1')
359        os.system('netsh interface ip set dns name="Wi-Fi" source=static addr=none >nul 2>&1')
360        os.system('netsh interface ip add dns name="Wi-Fi" addr=8.8.8.8 index=1 >nul 2>&1')
361        os.system('netsh interface ip add dns name="Wi-Fi" addr=8.8.4.4 index=2 >nul 2>&1')
362    except socket.error:
363     pass
364
365
Full Screen

main_function.py

Source: main_function.py Github

copy
1# -*- coding: utf-8 -*-
2"""
3Created on Thu Nov 29 15:35:08 2018
4
5@author: Kuan
6"""
7import math
8import copy
9import datetime
10import pandas as pd
11import pyodbc 
12import time
13#import pprint
14#%% sql sever setting
15#server = '' 
16#database = '' 
17#username = '' 
18#password = '' 
19#cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
20
21server = '' 
22database = '' 
23username = '' 
24password = ''
25cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
26#%% parameter setting
27Max_mile = 20 # upper limit for a ride
28service_time = 5 # service time when  arrive locstion 
29down_service_time = 1
30time_window = 30 # aditional time windows
31constant_a = 3
32constant_b = 5
33Max_trip_interval = 15 #minutes
34new_tw = 5
35Large_cost = 99999
36#%% input three sql data sheet
37
38## a funtion to transfer the form of data
39## transfer into pandas or list 
40def datafit(data,form):
41    colList = []
42    for colInfo in data.description:
43        colList.append(colInfo[0])
44    rowList = []
45    while True:
46        try:
47            row = data.fetchone()
48            if row:
49                rowList.append(list(row))
50            else:
51                break
52        except:   
53            continue;
54    if form == "pandas":
55        sql_data = pd.DataFrame(rowList) 
56        sql_data.columns = colList 
57    elif form == "list":
58        sql_data = rowList
59    return sql_data
60
61
62## delete the data has been create and recalculate 
63cursor = cnxn.cursor()
64cursor.execute('delete from VRP_HAS_MATCHED') 
65cnxn.commit()
66 
67#print "---sql_resource---"
68cursor.execute("SELECT * from VRP_CAR_USEABLE ")
69sql_resource = datafit(cursor,"list") 
70
71#print ("---sql_cost---")
72cursor.execute("SELECT * from VRP_TRAVEL_MATRIX_DATA ")
73sql_cost = datafit(cursor,"list")
74
75#print ("---sql_request---")
76cursor.execute("SELECT * from VRP_PRE_ORDER")
77sql_request = datafit(cursor,"list")
78
79## if you want the data in a specific day
80#cursor.execute("SELECT * from VRP_CAR_USEABLE where take_date ='2019/01/14'")
81#cursor.execute("SELECT * from VRP_TRAVEL_MATRIX_DATA where take_date ='2019/01/14'")
82#cursor.execute("SELECT * from VRP_PRE_ORDER where take_date ='2019/01/14'")
83
84## if you want the data in a specific period
85#cursor.execute("SELECT * from VRP_CAR_USEABLE where take_date between '2019/01/14' and '2019/01/18'")
86#cursor.execute("SELECT * from VRP_TRAVEL_MATRIX_DATA where take_date between '2019/01/14' and '2019/01/18'")
87#cursor.execute("SELECT * from VRP_PRE_ORDER where take_date between '2019/01/14' and '2019/01/18'")
88
89#%% Main procedure 
90def main_funtion(request,cost,resource): 
91      
92    ## a funtion to transfer the time format
93    def time_form(intime):
94        str_intime = str(intime)
95        int_intime = int(str_intime[11])*10*60+int(str_intime[12])*60+int(str_intime[14])*10+int(str_intime[15])
96        return int_intime 
97    
98    ## calculate the route time
99    def total_time(route):
100        tt_time = 0
101        for c in range(len(route)-1):
102            tt_time += t[Day_order[route[c]][1],Day_order[route[c+1]][1]]          
103        return tt_time
104    
105    ## calculate the route distant
106    def total_distant(route):
107        tt_dist = 0
108        for c in range(len(route)-1):
109            tt_dist += d[Day_order[route[c]][1],Day_order[route[c+1]][1]]          
110        return tt_dist
111    
112    ## give the route a start customer
113    ## 
114    def route_seed_initialer(unroute_list,village,Day):
115        ## sort the unroute customers acordding to the pick up time
116        now_unroute_list = []
117        for i in unroute_list:
118            now_unroute_list.append(Day_order[i])
119        sort_now_unroute_list = sorted(now_unroute_list, key = lambda x : (x[2]))
120        sort_unroute_list = []
121        for i in sort_now_unroute_list:
122            sort_unroute_list.append(i[0]) 
123        ## sort the car drivers acordding to the starting service time    
124        all_car_key_info = []
125        for i in unuse_resource_info[village][Day]:
126            all_car_key_info.append(resource_info[i])
127        sort_all_car_key_info = sorted(all_car_key_info, key = lambda x : (x[-7]))
128        sort_all_car_key = []
129        for i in sort_all_car_key_info:
130            sort_all_car_key.append(i[0])  
131        ## give the route a start customer
132        ## return the unroute list without the customerhave been matched
133        new_unroute_list = copy.copy(sort_unroute_list)
134        for j in sort_unroute_list:
135            unservable_time = 0
136            break_sign = 0
137            for i in sort_all_car_key: #i就是車號
138                current_routeA = [i,j,-j,i]
139                if check_feasible_route(current_routeA,i) == 0: #輸入路徑與車號
140                    break_sign += 1
141                    useed_resource_info[village][Day][i] = [i,j,-j,i]   
142                    new_unroute_list.remove(j)
143                    unuse_resource_info[village][Day].remove(i)
144                    break
145                else:
146                    unservable_time += 1
147                    len(sort_all_car_key[sort_all_car_key.index(i):])
148            if unservable_time == len(sort_all_car_key):
149                if Day not in unservable_requests.keys():
150                    unservable_requests[Day] = []
151                    unservable_requests[Day].append(j)
152                else:
153                    unservable_requests[Day].append(j)
154                new_unroute_list.remove(j)
155            if break_sign>0:
156                break
157            #只要有一個人可以放進一台車就可以
158#        print "in ",useed_resource_info[village][Day]
159        return new_unroute_list    
160    
161    def route_seed_initialer2(unroute_list,village,Day):
162#        print unroute_list,village,Day
163        now_unroute_list = []
164        for i in unroute_list:
165            now_unroute_list.append(Day_order[i])
166        sort_now_unroute_list = sorted(now_unroute_list, key = lambda x : (x[2]))
167        sort_unroute_list = []
168        for i in sort_now_unroute_list:
169            sort_unroute_list.append(i[0])
170        seed_list = copy.copy(sort_unroute_list)
171        new_unroute_list = []
172        for i in range(len(sort_unroute_list)-1):
173            req_i = sort_unroute_list[i]
174            req_i_1 = sort_unroute_list[i+1]
175            LDTk = Day_order[req_i][7]
176            TTDkPk_1 = t[Day_order[req_i][5],Day_order[req_i_1][1]]
177            EPTk_1 = Day_order[req_i_1][2]
178            if LDTk+TTDkPk_1<=EPTk_1:
179                seed_list.remove(req_i_1)
180                new_unroute_list.append(req_i_1)
181        for i in unuse_resource_info[village][Day]:
182            unservable_time = 0
183            for j in seed_list: 
184                current_routeA = [i,j,-j,i]
185                if check_feasible_route(current_routeA,i) == 0:
186                    useed_resource_info[village][Day][i] = [i,j,-j,i]
187                    seed_list.remove(j)
188                    break                  
189                else:
190                    unservable_time += 1
191        for i in useed_resource_info[village][Day].keys():
192            if i in unuse_resource_info[village][Day]:
193                unuse_resource_info[village][Day].remove(i)
194#        print "in ",useed_resource_info[village][Day]
195        return new_unroute_list+seed_list  
196   
197    def check_feasible_route(feasible_route,car_number):
198#        print feasible_route,car_number
199        debug_time = Day_order[feasible_route[0]][2] ## first customer pick time 
200        max_car_capacity = resource_info[car_number][-1] ## car capacity
201  
202        route_feasible_or_not = True
203        ## check if the trip exceeds the max trip miles
204        if route_feasible_or_not == True:
205            temp_store_list = [] 
206            cal_sign = 0
207            cal_anchor = 0
208            
209            for i in feasible_route :
210                if type(i) ==  int:
211                    temp_store_list.append(i)
212                    if i not in temp_store_list or -i not in temp_store_list:        
213                        cal_sign += 1
214                    elif i < 0 and -i in temp_store_list:
215                        cal_sign -= 1
216                    if cal_sign == 0:
217                        cal_route = temp_store_list[cal_anchor:feasible_route.index(i)+1]
218#                        print cal_anchor,feasible_route.index(i)+1
219                        o_dist = total_distant(cal_route)
220#                        for test_c in range(len(cal_route)-1):
221#                            o_dist += d[Day_order[cal_route[test_c]][1],Day_order[cal_route[test_c+1]][1]]         
222                        
223                        if o_dist >= Max_mile:
224                            route_feasible_or_not = False 
225#                        else:
226#                            print cal_route,car_number,total_distant(cal_route)
227                            
228                        cal_anchor = feasible_route.index(i)+1 
229        ## check if the capacity exceeds the car limit               
230        passenger_in_car = 0 
231        if route_feasible_or_not == True: 
232            for x in feasible_route:
233                if x > 0 :
234                    passenger_in_car += Day_order[x][4] 
235                elif x <0:
236                    passenger_in_car -= Day_order[x][4]
237                if passenger_in_car > max_car_capacity:
238
239                    route_feasible_or_not = False
240                    break
241                
242        ## check the route time window  
243        debug_route_time = []
244        debug_real_time = []    
245        if route_feasible_or_not == True: 
246            for i in range(len(feasible_route)):
247                pre_node = Day_order[feasible_route[i-1]][1]            
248                now_node = Day_order[feasible_route[i]][1]
249    
250                e_time = Day_order[feasible_route[i]][2] #early最早上車
251                l_time = Day_order[feasible_route[i]][3] #latest 最晚上車
252    
253                if i == 0:
254                    debug_route_time.append(debug_time)
255                    debug_real_time.append(debug_time)
256                    next_node = Day_order[feasible_route[i+1]][1]
257                    if now_node == next_node:
258                        continue
259                    else:
260                        if feasible_route[i] < 0:
261#                            print feasible_route[i-1]
262                            debug_time += down_service_time
263#                            debug_time += service_time 
264                        else:    
265                            debug_time += service_time                   
266                elif i == len(feasible_route)-1:    
267                    debug_time = debug_time+t[pre_node,now_node]
268                    debug_route_time.append(debug_time)
269                    debug_real_time.append(l_time)
270                elif i > 0:
271#                    print pre_node,now_node
272                    debug_time = max([debug_time+t[pre_node,now_node],e_time])
273                    debug_route_time.append(debug_time)
274                    debug_real_time.append(l_time)
275                    next_node = Day_order[feasible_route[i+1]][1]
276                    if now_node == next_node:
277                        continue
278                    else:
279                        if feasible_route[i] < 0:
280                            debug_time += down_service_time   
281                        else:    
282                            debug_time += service_time
283            for i,j in zip(debug_route_time,debug_real_time):
284                if  i > j:
285#                    print i,j
286#                    debug1 = 1
287                    route_feasible_or_not = False                    
288
289        if route_feasible_or_not == True:  
290            debug_signal = 0
291        else:
292            debug_signal = 1
293#        if 14410 in feasible_route:
294#            print feasible_route,car_number,route_feasible_or_not
295           
296        return debug_signal
297
298    def regret_insert(unroute_list,village,Day):
299#        print "unroute_list",unroute_list,village,Day
300#        for fadfad in range(10):
301        while len(unroute_list) > 0:
302#            print "unroute_list",unroute_list
303            current_list = useed_resource_info[village][Day].values()
304#            print useed_resource_info
305#            print "current_list",current_list
306            car_keys = useed_resource_info[village][Day].keys()        
307            temp_route = copy.copy(current_list)
308    #        print "temp_route:",temp_route
309            c2_value = []
310            c2_route = []
311            c2_place = []
312            c2_customer = []
313#            print "----"
314            for customer in unroute_list:
315#                print customer
316                min_c1_route = []
317                min_c1_value = []
318                min_c1_place = []
319                customer_p = customer
320                customer_d = -customer_p
321                for o_route in temp_route: 
322                    car_number = car_keys[current_list.index(o_route)]
323                    o_route_tt_dist = 0
324                    for test_c in range(len(o_route)-1):
325                        o_route_tt_dist += d[Day_order[o_route[test_c]][1],Day_order[o_route[test_c+1]][1]]                      
326                    c1_value = []
327                    c1_place = []
328                    for p_place in range(1,len(o_route)+1):         
329                        test_p_route =  copy.copy(o_route)
330                        test_p_route.insert(p_place,customer_p)
331#                        print
332#                        print "test_p_route-----------",test_p_route                        
333#                        feasibility1 = check_feasible_route(test_p_route,car_number)
334#                        print "-----------feasibility1",feasibility1
335                        feasibility1 = 0
336                        if feasibility1 == 0:
337                            for d_place in range(p_place+1,len(test_p_route)):
338                                #print d_place,"----"
339                                test_d_route = copy.copy(test_p_route)
340                                test_d_route.insert(d_place,customer_d)
341#                                print"--"                                
342                                feasibility2 = check_feasible_route(test_d_route,car_number)
343#                                if (316 in test_d_route and 318 in test_d_route) or (317 in test_d_route and 318 in test_d_route):
344#                                    print test_d_route,feasibility2
345#                                    print "--"
346#                                print"--"
347                                if feasibility2 == 0:###############
348                                    ##################################################################
349#                                    tt_dist = total_distant(test_d_route)
350#                                    print test_d_route
351#                                    for test_c in range(len(test_d_route)-1):
352##                                        print test_d_route[test_c],test_d_route[test_c+1],d[Day_order[test_d_route[test_c]][1],Day_order[test_d_route[test_c+1]][1]]
353#                                        tt_dist += d[Day_order[test_d_route[test_c]][1],Day_order[test_d_route[test_c+1]][1]]
354#                                    c1 = tt_dist-o_route_tt_dist
355                                    c1 = total_distant(test_d_route)
356#                                    print test_d_route,c1
357                                    ##################################################################
358                                    c1_value.append(c1)
359                                    c1_place.append([p_place,d_place])
360                                
361                    min_c1_route.append(o_route)  
362#                    print c1_value
363                    if len(c1_value) > 0:
364                        min_value = min(c1_value)
365                        min_place = c1_place[c1_value.index(min_value)]                           
366                        min_c1_value.append(min_value)
367                        min_c1_place.append(min_place)
368                    else:                
369                        min_c1_value.append(Large_cost)
370                        min_c1_place.append([-Large_cost,-Large_cost])     
371#                print "min_c1_value",min_c1_value
372                min_min_c1_value = min(min_c1_value)
373                min_c1_index = min_c1_value.index(min_min_c1_value)
374                min_min_c1_place = min_c1_place[min_c1_index]
375                min_min_c1_route = min_c1_route[min_c1_index]
376                c2_customer.append([customer,-customer])
377#                print c2_customer
378                c2 = 0
379                if min_c1_value.count(Large_cost) != len(min_c1_value):
380#                    print min_c1_value
381                    for mmc in range(len(min_c1_value)):
382#                        print min_c1_route[mmc],min_min_c1_route
383#                        if min_c1_route[mmc] != min_min_c1_route:
384                            
385                        c2 += min_c1_value[mmc] - min_min_c1_value
386#                        print "------------",c2
387                else:
388                    c2 = -Large_cost
389                c2_value.append(c2)
390                c2_route.append(min_min_c1_route)
391                c2_place.append(min_min_c1_place)  
392#                print c2_value,c2_route,c2_place
393#            print c2_value  
394            if c2_value.count(-Large_cost) != len(c2_value):
395#                print "1111111111111"
396                max_c2_value = max(c2_value)
397#                print max_c2_value
398                max_c2_index = c2_value.index(max_c2_value)
399                max_c2_route = c2_route[max_c2_index]
400                max_c2_place = c2_place[max_c2_index]
401                max_c2_customer = c2_customer[max_c2_index]
402                max_c2_index = current_list.index(max_c2_route)        
403                for insert_p,insert_c in zip(max_c2_place,max_c2_customer):
404                    max_c2_route.insert(insert_p,insert_c)
405                current_list[max_c2_index] = max_c2_route
406                unroute_list.remove(max_c2_customer[0])         
407            else:
408#                print "----",Day,unroute_list
409#                unservable_requests[Day] = unroute_list ##route2
410#                break
411                unroute_list = route_seed_initialer(unroute_list,village,Day)
412                
413        return current_list
414    
415#    def tw_reducer(feasible_route,car_number):
416##        print feasible_route
417##        if True:
418##            for i in feasible_route:
419##                print Day_order[i][2],Day_order[i][3]
420#        debug_time = Day_order[feasible_route[0]][2]
421#        endtime = resource_info[car_number][-2]
422#        debug_route_time = []
423#        debug_real_time = []
424#        for i in range(len(feasible_route)):          
425#            pre_node = Day_order[feasible_route[i-1]][1]            
426#            now_node = Day_order[feasible_route[i]][1]
427#            e_time = Day_order[feasible_route[i]][2]
428#            l_time = Day_order[feasible_route[i]][3]
429#            if i == 0:
430#                debug_route_time.append(debug_time)
431#                debug_real_time.append(debug_time)
432#                next_node = Day_order[feasible_route[i+1]][1]
433#                if now_node == next_node:
434#                    continue
435#                else:
436#                    if feasible_route[i] < 0:
437##                            print feasible_route[i-1]
438#                        debug_time += down_service_time
439##                            debug_time += service_time
440#                        
441#                    else:    
442#                        debug_time += service_time              
443#            elif i == len(feasible_route)-1:
444#                debug_time = debug_time+t[pre_node,now_node]
445#                debug_route_time.append(debug_time)
446#                debug_real_time.append(endtime)
447#            elif i > 0:
448#                debug_time = max([debug_time+t[pre_node,now_node],e_time])
449#                debug_route_time.append(debug_time)
450#                debug_real_time.append(l_time)   
451#                next_node = Day_order[feasible_route[i+1]][1]
452#                if now_node == next_node:
453#                    continue
454#                else:
455#                    if feasible_route[i] < 0:
456##                            print feasible_route[i-1]
457#                        debug_time += down_service_time
458##                            debug_time += service_time
459#                        
460#                    else:    
461#                        debug_time += service_time                 
462#        for i,j in zip(feasible_route,debug_route_time):
463#
464#            if i > 0:
465#    
466#                Day_order[i][2] = math.floor(j - new_tw/2)
467#                Day_order[i][3] = math.floor(j + new_tw/2)
468#            elif i < 0:
469#    
470#                Day_order[-i][6] = math.floor(j - new_tw/2)
471#                Day_order[-i][7] = math.floor(j + new_tw/2)
472#                Day_order[i][2] = math.floor(j - new_tw/2)
473#                Day_order[i][3] = math.floor(j + new_tw/2)
474
475
476    def relocation_operator(original_plan):
477        all_reinsert_info = {}
478        for i in original_plan:
479            for j in original_plan[i]:
480                if j > 0 :
481                    all_reinsert_info[j] = i 
482        all_route = original_plan.keys()
483        
484        relocation_for_remove_time = 0
485        relocation_for_insert_time = 0
486        for relocate_time in range(1):
487            for i in all_reinsert_info:
488                
489                relocation_for_remove_start_time = time.time()
490                car_c = all_reinsert_info[i]
491                remoeve_route_c = original_plan[car_c][:]
492                if type(i) == int:
493                    remoeve_route_c.remove(i)
494                    remoeve_route_c.remove(-i)
495                    relocation_for_remove_end_time = time.time()
496                    relocation_for_remove_time += (relocation_for_remove_end_time-relocation_for_remove_start_time)
497                    for l in all_route:
498                        if l != car_c:
499                            for m in range(1,len(original_plan[l])+1):
500                                for n in range(m+1,len(original_plan[l])+1):
501                                    if i in original_plan[car_c]:  
502                                        relocation_for_insert_start_time = time.time()
503                                        insert__route_c = original_plan[l][:]
504                                        insert__route_c.insert(m,i)
505                                        insert__route_c.insert(n,-i)
506                                        relocation_for_insert_end_time = time.time()
507                                        relocation_for_insert_time += (relocation_for_insert_end_time-relocation_for_insert_start_time)
508        #                                print insert__route_c,check_feasible_route(insert__route_c,l)
509                                        if check_feasible_route(insert__route_c,l) == 0:
510        #                                    print insert__route_c,check_feasible_route(insert__route_c,l)
511                                            if total_distant(original_plan[car_c])+total_distant(original_plan[l])-total_distant(remoeve_route_c)-total_distant(insert__route_c) > 0:
512#                                                print total_distant(original_plan[car_c])+total_distant(original_plan[l])-total_distant(remoeve_route_c)-total_distant(insert__route_c) 
513                                                original_plan[car_c] = remoeve_route_c
514                                                original_plan[l] = insert__route_c
515                                                all_reinsert_info[i] = l   
516                                            if len(remoeve_route_c) == 0 or len(insert__route_c) == 0 :
517                                                print "need to cut car"                                            
518                                    else:
519                                        break 
520        return original_plan
521    def exchange_operator(original_plan):
522        all_reinsert_info = {}
523        for i in original_plan:
524#            print i,original_plan[i]
525            for j in original_plan[i]:
526#                print j
527                if j > 0 and type(j) == int:
528                    all_reinsert_info[j] = i
529        exchange_first_insert = 0
530        exchange_second_insert = 0
531    #    exchange_start_time = time.time()
532        for exchange_time in range(1):
533            for i in all_reinsert_info:
534                for j in all_reinsert_info:
535                    car_r = all_reinsert_info[i]
536                    car_s = all_reinsert_info[j]
537                    if i != j and car_r != car_s:
538            #            print 
539            #            print Day_order[i],Day_order[j]
540                        EPTi = Day_order[i][2]
541                        LPTi = Day_order[i][3]
542                        EDTi = Day_order[i][6]
543                        LDTi = Day_order[i][7]       
544                        EPTj = Day_order[j][2]
545                        LPTj = Day_order[j][3]
546                        EDTj = Day_order[j][6]
547                        LDTj = Day_order[j][7]           
548                        if (EPTi <= LPTj and EPTj <= LPTi) or (EDTi <= LDTj and EDTj <= LDTi):                    
549       
550                            remoeve_route_r = original_plan[car_r][:]
551                            remoeve_route_r.remove(i)
552                            remoeve_route_r.remove(-i)
553                            
554                            best_insert_route_r = []
555                            exchange_first_start_insert = time.time()
556                            for m in range(1,len(remoeve_route_r)+1):
557                                for n in range(m+1,len(remoeve_route_r)+1):
558    #                                print m,n
559                                    insert_route_r = remoeve_route_r[:]
560    #                                insert_route_r = copy.deepcopy(remoeve_route_r)
561                                    insert_route_r.insert(m,j)
562                                    insert_route_r.insert(n,-j)
563    #                                print insert_route_r,check_feasible_route(insert_route_r,car_r)
564                                    if check_feasible_route(insert_route_r,car_r) == 0:
565                                        if len(best_insert_route_r) == 0:
566                                            best_insert_route_r = insert_route_r
567                                        else:
568                                            if total_distant(insert_route_r) < total_distant(best_insert_route_r):
569                                                best_insert_route_r = insert_route_r
570            
571                            exchange_first_end_insert = time.time()            
572                            exchange_first_insert += (exchange_first_end_insert-exchange_first_start_insert)    
573                            if len(best_insert_route_r) > 0 :        
574                                remoeve_route_s = original_plan[car_s][:]
575                                remoeve_route_s.remove(j)
576                                remoeve_route_s.remove(-j) 
577                                exchange_second_start_insert = time.time()
578                                best_insert_route_s = []
579                                for m in range(1,len(remoeve_route_s)+1):
580                                    for n in range(m+1,len(remoeve_route_s)+1):
581                                        insert_route_s = remoeve_route_s[:]
582                                        insert_route_s.insert(m,i)
583                                        insert_route_s.insert(n,-i)                
584                                        if check_feasible_route(insert_route_s,car_s) == 0:
585                #                            print "-------------------"
586                                            if len(best_insert_route_s) == 0:
587                                                best_insert_route_s = insert_route_s
588                                            else:
589                                                if total_distant(insert_route_s) < total_distant(best_insert_route_s):
590                                                    best_insert_route_s = insert_route_s
591                                exchange_second_end_insert = time.time()
592                                exchange_second_insert += (exchange_second_end_insert-exchange_second_start_insert)
593                                if len(best_insert_route_s) > 0:
594                                    if (total_distant(original_plan[car_r])+total_distant(original_plan[car_s]))-(total_distant(best_insert_route_r)+total_distant(best_insert_route_s))>0:
595#                                        print (total_distant(original_plan[car_r])+total_distant(original_plan[car_s]))-(total_distant(best_insert_route_r)+total_distant(best_insert_route_s))
596                                        original_plan[car_r] = best_insert_route_r                 
597                                        original_plan[car_s] = best_insert_route_s
598                                        all_reinsert_info[i] = car_s
599                                        all_reinsert_info[j] = car_r  
600                                        if len(best_insert_route_r) == 0 or len(best_insert_route_s) == 0 :
601                                            print "need to cut car"
602        return original_plan   
603
604
605    def check_service_time(feasible_route,out_type = None):
606#        print feasible_route
607        debug_time = Day_order[feasible_route[0]][2]
608#        print debug_time
609        debug_service_time = []   
610        for i in range(len(feasible_route)):
611            pre_node = Day_order[feasible_route[i-1]][1]            
612            now_node = Day_order[feasible_route[i]][1]
613
614            e_time = Day_order[feasible_route[i]][2]
615#            l_time = Day_order[feasible_route[i]][3]
616            if i == 0:
617                debug_service_time.append(debug_time)
618            elif i == len(feasible_route)-1:        
619                debug_time = debug_time+t[pre_node,now_node]
620                debug_service_time.append(debug_time)
621            else:
622                debug_time = max([debug_time+t[pre_node,now_node],e_time])
623                debug_service_time.append(debug_time)
624                if now_node > 0:
625                    debug_time += service_time
626#                print "afterser:",debug_time
627        ri_time = 0
628        test_n = 0                    
629        for i in range(len(feasible_route)):
630    #        print i,test[i],test[i+1],t[Day_order[test[i]][1],Day_order[test[i+1]][1]]
631            if type(feasible_route[i]) == int:
632                test_n += feasible_route[i]
633                if feasible_route[i] > 0:
634                    test_target = feasible_route.index(-feasible_route[i])
635                    
636                    ride_time =  debug_service_time[test_target] - debug_service_time[i]   
637                    ri_time += ride_time
638        if out_type == "list":
639            return debug_service_time
640        else:
641            return ri_time         
642
643    def check_arrive_time(feasible_route,out_type = None):
644#        print feasible_route
645        debug_time = Day_order[feasible_route[0]][2]
646#        print debug_time
647        debug_arrive_time = []   
648        for i in range(len(feasible_route)):
649            pre_node = Day_order[feasible_route[i-1]][1]            
650            now_node = Day_order[feasible_route[i]][1]
651
652            e_time = Day_order[feasible_route[i]][2]
653#            l_time = Day_order[feasible_route[i]][3]
654            if i == 0:
655                debug_arrive_time.append(debug_time)
656            elif i == len(feasible_route)-1:        
657                debug_time = debug_time+t[pre_node,now_node]
658                debug_arrive_time.append(debug_time)
659            else:
660                debug_arrive_time.append(debug_time+t[pre_node,now_node])
661                debug_time = max([debug_time+t[pre_node,now_node],e_time])
662                
663                if now_node > 0:
664                    debug_time += service_time
665#                print "afterser:",debug_time
666        ri_time = 0
667        test_n = 0  
668                          
669        for i in range(len(feasible_route)):
670    #        print i,test[i],test[i+1],t[Day_order[test[i]][1],Day_order[test[i+1]][1]]
671            if type(feasible_route[i]) == int:
672                test_n += feasible_route[i]
673                if feasible_route[i] > 0:
674                    test_target = feasible_route.index(-feasible_route[i])
675                    ride_time =  debug_arrive_time[test_target] - debug_arrive_time[i]   
676                    ri_time += ride_time
677#        print debug_arrive_time                
678        if out_type == "list":
679            return debug_arrive_time
680        else:
681            return ri_time                     
682    def ride_counter(feasible_route,out_type = None):
683#        print "    ",feasible_route
684#        print "debug_time",debug_time
685        node_service_time = check_service_time(feasible_route,"list")
686        node_arrive_time = check_arrive_time(feasible_route,"list")
687        ##########################
688        test = feasible_route
689        
690        e_time_list = [Day_order[i][2] for i in feasible_route]
691        l_time_list = [Day_order[i][3] for i in feasible_route]
692#        print len(l_time_list)
693        cuttime_list = []
694        for i,j in zip(node_service_time,node_arrive_time):
695            if j < i:
696                cuttime_list.append(i-j)
697            else:
698                cuttime_list.append(0)
699#        print cuttime_list                
700#        print len(cuttime_list)
701        ri_time = 0
702#        route_arrive_time = check_service_time(test)
703        test_n = 0
704        test_ancher = 0
705        if test[0] == 0:
706            for i in range(len(test)-1):
707                test_n += test[i]
708                if test_n == 0:
709                    if test[i] != 0:
710
711                        for j in range(test_ancher,i+1):
712                            
713                            if cuttime_list[j] > 0:
714                                if j == test_ancher:
715                                    node_arrive_time[test_ancher] = e_time_list[test_ancher] 
716                                else:
717                                    
718                                    change_new_timesign = 0
719#                                    print "1   ",change_new_timesign
720                                    for l in range(test_ancher,j):
721                                        new_service_time = node_service_time[l] + cuttime_list[j]
722                                        
723                                        if new_service_time >= e_time_list[l] and new_service_time <= l_time_list[l]:
724                                            continue
725                                        else:
726                                            change_new_timesign += 1
727#                                    print "2   ",change_new_timesign
728                                            
729                                    if change_new_timesign == 0:
730#                                        print test_ancher,j
731                                        for l in range(test_ancher,j):
732                                            node_service_time[l] = node_service_time[l] + cuttime_list[j]   
733                                            node_arrive_time[l] = node_arrive_time[l] + cuttime_list[j]   
734                                            
735                                        node_arrive_time[j] = e_time_list[j] 
736                                    else:
737#                                        print "NOOOO",test[j],cuttime_list[j]   
738                                        left_time_list = [l_time_list[l]-node_arrive_time[l]for l in range(test_ancher,j)]
739                                     
740                                        min_left_time = min(left_time_list)
741                                        for l in range(test_ancher,j):
742#                                            print test[l],left_time_list[l-test_ancher]
743                                            node_service_time[l] = node_service_time[l] + min_left_time
744                                            node_arrive_time[l] = node_arrive_time[l] + min_left_time
745                                        node_arrive_time[j] = node_arrive_time[j] + min_left_time                                               
746                        
747                    test_ancher = i+1
748#        print "    ",node_service_time            
749#        print "    ",node_arrive_time 
750        cuttime_list = []
751        for i,j in zip(node_service_time,node_arrive_time):
752            if j < i:
753                cuttime_list.append(i-j)
754            else:
755                cuttime_list.append(0)    
756#        print cuttime_list                
757        for i in range(len(test)):
758    #        print i,test[i],test[i+1],t[Day_order[test[i]][1],Day_order[test[i+1]][1]]
759            if type(test[i]) == int:
760                test_n += test[i]
761                if test[i] > 0:
762                    test_target = test.index(-test[i])
763    #                print test[i],-test[i]
764                    ride_time =  node_service_time[test_target] - node_service_time[i]   
765                    ri_time += ride_time
766#        print node_service_time
767        if out_type == "list":
768            return node_service_time
769        elif out_type == "arrive":
770            return node_arrive_time
771        else:
772            return ri_time               
773#%% sql cost
774    ## make the time & distant cost matrix
775    cost_info = {}
776    dist_info = {}   
777    for temp_cost in cost:
778        cost_info[temp_cost[2],temp_cost[3]] = temp_cost[4]
779        cost_info[temp_cost[3],temp_cost[2]] = temp_cost[4]
780        cost_info[temp_cost[2],temp_cost[2]] = 0
781        cost_info[temp_cost[3],temp_cost[3]] = 0
782        dist_info[temp_cost[2],temp_cost[3]] = temp_cost[5]
783        dist_info[temp_cost[3],temp_cost[2]] = temp_cost[5]
784        dist_info[temp_cost[2],temp_cost[2]] = 0
785        dist_info[temp_cost[3],temp_cost[3]] = 0
786    ## time cost matrix
787    t = copy.deepcopy(cost_info)
788    ## distant cost matrix
789    d = copy.deepcopy(dist_info)
790#%% sql request
791    
792    request_info = {} 
793    unservable_requests = {}
794    village_key = [request[0][1]]
795
796    ## the dictionary includes every request in a day 
797    Day_request_info = {}   
798    Day_request_info[village_key[0]] = {}
799    ## the dictionary of the information of every request 
800    ## Day_order = {request_number:[request number,pick place, EPT, LPT, passenger number, deliver place, EDT, LDT]}
801    ## Day_order[request_number] = [request number,pick place, EPT, LPT, passenger number, deliver place, EDT, LDT]
802    Day_order = {}
803    
804    ## frame the time window
805    for i in request:
806        SENDORDER = i[3]
807        ## if there are no pick windows        
808#        if i[8] == None or i[9] == None:
809        if True:
810            Pp,Dp,n_C= i[5],i[6],i[7]
811            
812            LT = (time_form(i[10])+time_form(i[11]))/2.0
813            
814            EPT = LT - constant_a*t[Pp,Dp] - constant_b  
815            EDT = LT -            t[Pp,Dp] - constant_b         
816            LPT = time_form(i[10])
817            LDT = time_form(i[11])
818            
819            Day_order[SENDORDER] = [SENDORDER]+[Pp,EPT,EDT,n_C,Dp,LPT,LDT]
820            Day_order[-SENDORDER] = [SENDORDER]+[Dp,LPT,LDT,n_C]            
821            temp_one = [str(i[0]),i[1],i[4],i[5],i[6],i[7],EPT,EDT,LPT,LDT]
822#        ## if there are no deliver windows 
823#        elif i[10] == None or i[11] == None:
824#            
825#            Pp,Dp,n_C= i[5],i[6],i[7]
826#
827#            EPT = time_form(i[8])
828#            EDT = time_form(i[9])
829#            LPT = EPT +            t[Pp,Dp] + constant_b
830#            LDT = EPT + constant_a*t[Pp,Dp] + constant_b
831#
832#            Day_order[SENDORDER] = [SENDORDER]+[Pp,EPT,EDT,n_C,Dp,LPT,LDT]
833#            Day_order[-SENDORDER] = [SENDORDER]+[Dp,LPT,LDT,n_C]            
834#            temp_one = [str(i[0]),i[1],i[4],i[5],i[6],i[7],EPT,EDT,LPT,LDT]   
835#        ## if both windows exist 
836#        else:
837#            Pp,Dp,n_C= i[5],i[6],i[7]
838# 
839#            EPT = time_form(i[8])
840#            EDT = time_form(i[9])          
841#            LPT = time_form(i[10])
842#            LDT = time_form(i[11]) 
843#            
844#            Day_order[SENDORDER] = [SENDORDER]+[Pp,EPT,EDT,n_C,Dp,LPT,LDT]
845#            Day_order[-SENDORDER] = [SENDORDER]+[Dp,LPT,LDT,n_C]             
846#            temp_one = [str(i[0]),i[1],i[4],i[5],i[6],i[7],EPT,EDT,LPT,LDT]
847
848        SENDORDER_date = "19000000"
849        SENDORDER_date = str(SENDORDER_date[:4])+"/"+str(SENDORDER_date[4:6])+"/"+str(SENDORDER_date[6:])
850        SENDORDER_ID = str(SENDORDER)
851    
852        for j in SENDORDER_ID:
853            if int(j) !=0:
854                SENDORDER_ID = int(SENDORDER_ID[SENDORDER_ID.index(j):])
855                break
856        ## build the day request dictionary 
857        ## let us know which requests should be matched in the specific day
858        request_info[SENDORDER_ID] = [SENDORDER_date]+temp_one[0:2]+[SENDORDER_ID]+temp_one[2:10]
859        request_info_now = request_info[SENDORDER_ID]
860#        if request_info_now[2] not in village_key:
861#            village_key.append(request_info_now[2])
862        
863        if request_info_now[0] not in Day_request_info[village_key[0]].keys():
864            Day_request_info[village_key[0]][request_info_now[0]] = {}
865            Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]] = [request_info_now[3]]
866        else:
867            if request_info_now[1] not in Day_request_info[request_info_now[2]][request_info_now[0]].keys():
868                Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]] = []
869                Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]] = [request_info_now[3]]
870            else:
871                Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]].append(request_info_now[3])
872#        print Day_request_info
873#%% sql resource              
874    resource_info = {}
875    
876    ## the dictionary of the car did not be used 
877    unuse_resource_info = {}
878    ## the dictionary of the car have been used 
879    useed_resource_info = {}
880    
881    for i in resource:
882        car_code = i[4]+'-'+str(resource.index(i)+1)
883        start_time = time_form(i[6])
884        close_time = time_form(i[7])   
885        temp_resource = [car_code,i[0],i[1],i[2].strftime('%Y/%m/%d'),i[3],i[4],i[5],time_form(i[6]),time_form(i[7]),i[8]]
886        ## pretend the driver's location as a day order 
887        ## but it does not include in day request
888        Day_order[car_code] = [car_code,i[9],start_time,close_time,0]
889#        temp_carnumber = temp_resource[4]
890#        
891#        temp_village = temp_resource[3]
892#        
893#        temp_date = temp_resource[0]
894        
895        temp_carnumber = temp_resource[0]
896        
897#        temp_village = village_key[0]
898        temp_village = temp_resource[4]
899     
900        temp_date = temp_resource[3]
901        
902        if temp_village not in unuse_resource_info.keys():
903            unuse_resource_info[temp_village] = {}
904            useed_resource_info[temp_village] = {}
905        if  temp_date not in unuse_resource_info[temp_village].keys():
906            unuse_resource_info[temp_village][temp_date] = [temp_carnumber]
907            useed_resource_info[temp_village][temp_date] = {}
908        else:
909            unuse_resource_info[temp_village][temp_date].append(temp_carnumber)
910        resource_info[temp_carnumber] = temp_resource      
911#    print unuse_resource_info
912#%% generate the initial route
913    Day_request = copy.copy(Day_request_info)
914    reserve_Plan = {}
915    for village in village_key:
916        Day_keys = sorted(Day_request[village].keys())
917        reserve_Plan[village] = {}
918        for day in Day_keys:
919            reserve_Plan[village][day] = {}
920            reser_Day_keys = sorted(Day_request[village][day].keys())
921    #        for reser_Day in reser_Day_keys[:1]:
922            for reser_Day in reser_Day_keys:
923                unroute_Day_requests = copy.copy(Day_request[village][day][reser_Day])
924#                print unroute_Day_requests
925                reserve_Plan_key = reserve_Plan[village][day].keys()
926                if reser_Day not in reserve_Plan_key:
927                    unroute_Day_requests = route_seed_initialer(unroute_Day_requests,village,reser_Day)
928#                    print "unroute_Day_requests",unroute_Day_requests
929                    final_route = regret_insert(unroute_Day_requests,village,reser_Day)
930#                    print final_route
931#                    reserve_Plan[village][day][reser_Day] = final_route
932                else:
933                    final_route = regret_insert(unroute_Day_requests,village,reser_Day)
934                reserve_Plan[village][day][reser_Day] = final_route
935#%% show the initial result               
936#    print "------initial result------"
937#    for i in useed_resource_info[village][reser_Day]:
938#        print useed_resource_info[village][reser_Day][i]                
939#%% improvement the initial route            
940    improvement = False
941
942    if improvement == True:
943#        print "+"
944        for village in village_key:
945            for reser_Day in useed_resource_info[village].keys(): 
946                relocation_sign = True
947                exchange_sign = True
948                while True:
949#                    
950                ############## Trip relocation ##############                   
951                    if relocation_sign == True:
952#                        print "---relocation_operator---"   
953                        old_plan = copy.copy(useed_resource_info[village][reser_Day])
954                        new_plan = relocation_operator(useed_resource_info[village][reser_Day])
955                        if old_plan != new_plan:
956                            useed_resource_info[village][reser_Day] = new_plan
957                        else:
958                            relocation_sign = False   
959#                        print "---relocation_operator---"                      
960#                    
961                ############## Trip exchange ##############                                       
962                    if exchange_sign == True:
963#                        print "---exchange_operator---"
964                        old_plan = copy.copy(useed_resource_info[village][reser_Day])
965                        new_plan = exchange_operator(useed_resource_info[village][reser_Day])
966                        if old_plan != new_plan:
967                            useed_resource_info[village][reser_Day] = new_plan
968                        else:
969                            exchange_sign = False  
970#                        
971                    if relocation_sign == False and exchange_sign ==  False:
972                        break
973
974#%% show the improved result                
975    print "------improved result------"
976    total_dist = 0
977    for i in useed_resource_info[village][reser_Day]:
978        print useed_resource_info[village][reser_Day][i],total_distant(useed_resource_info[village][reser_Day][i])
979        total_dist += total_distant(useed_resource_info[village][reser_Day][i])
980    print 'Total distance:', total_dist
981#%% show the unservable result         
982    print "------unservable result------"        
983    print unservable_requests        
984#%% waiting strategy & Fix TW      
985    for village in village_key:
986        for reser_Day in useed_resource_info[village].keys():  
987            for route in useed_resource_info[village][reser_Day]:
988#                    print useed_resource_info[village][reser_Day][route]
989                fix_route = useed_resource_info[village][reser_Day][route]
990#                if waiting_strategy == "drive_first":
991#                    nodeservice_time =  check_service_time(fix_route,"list")     
992#                elif waiting_strategy == "wait_first":
993                nodeservice_time =  ride_counter(fix_route,"list")
994                e_time_list = [Day_order[j][2] for j in fix_route]
995                l_time_list = [Day_order[j][3] for j in fix_route] 
996#                    print nodeservice_time
997#                    print e_time_list
998#                    print l_time_list
999                for j,k,l,m in zip(e_time_list,nodeservice_time,l_time_list,fix_route):
1000                    if m != 0:
1001#                        print
1002#                        print m,Day_order[m][2],Day_order[m][3]
1003                        if round(j,2)+service_time/2.0 > round(k,2):
1004#                                print round(j,2),round(k,2),round(l,2),"up"
1005                            Day_order[m][3] = j + new_tw
1006                        elif round(l,2)-service_time/2.0 < round(k,2):
1007#                                print round(j,2),round(k,2),round(l,2),"down"
1008                            Day_order[m][2] = l - new_tw
1009                        else:
1010#                                print round(j,2),round(k,2),round(l,2),"+5-5"
1011                            Day_order[m][2] = k - new_tw/2                          
1012                            Day_order[m][3] = k + new_tw/2
1013#                        print m,Day_order[m][2],Day_order[m][3]
1014#%% calculate the trip & format the data 
1015#    result_start_time = time.time()
1016    total_num = 0
1017    for i in useed_resource_info[village][reser_Day]:
1018#        print useed_resource_info[village][reser_Day][i] 
1019        total_num += (len(useed_resource_info[village][reser_Day][i])-2)/2.0
1020#    print total_num                      
1021    result = []
1022    trip_number = 0
1023    trip_dist = dict.fromkeys(useed_resource_info.keys())
1024    trip_time = dict.fromkeys(useed_resource_info.keys())
1025#    print useed_resource_info.keys()
1026    for i in useed_resource_info.keys(): 
1027        temp_trip_dist = dict.fromkeys(useed_resource_info[i].keys(),[])
1028        temp_trip_time = dict.fromkeys(useed_resource_info[i].keys(),[])
1029        for j in sorted(useed_resource_info[i].keys()):    
1030            temp_trip_dist_list = []
1031            temp_trip_time_list = []
1032            for k in useed_resource_info[i][j]:
1033                
1034                test_route = useed_resource_info[i][j][k]        
1035#                temp_store_list = [] 
1036                
1037#                customer_sign = 0
1038                cal_sign = 0
1039                cal_anchor = 1
1040                trip_list = []
1041                trip_dict ={}
1042#                print test_route
1043                for cus in test_route :
1044                    
1045                    if type(cus) == int:
1046
1047                        cal_sign += cus
1048                        if cal_sign == 0:
1049            #                print "     ---",temp_store_list[cal_anchor:feasible_route.index(i)+1]
1050                            cal_route = test_route[cal_anchor:test_route.index(cus)+1]
1051#                            print "cal_route",cal_route
1052                            trip_list.append(cal_route)
1053                            cal_anchor = test_route.index(cus)+1 
1054                run_sign = True
1055                start_sign = 0
1056                while run_sign == True:
1057                    if len(trip_list)>1:
1058                        take_time = (Day_order[trip_list[start_sign][-1]][3]+Day_order[trip_list[start_sign][-1]][2])/2
1059                        arive_time = (Day_order[trip_list[start_sign+1][0]][2]+Day_order[trip_list[start_sign+1][0]][3])/2                        
1060                        if arive_time - take_time > Max_trip_interval:
1061                            start_sign += 1
1062                        else:
1063                            test_trip = trip_list[start_sign] + trip_list[start_sign+1]
1064                            if total_distant(test_trip) > Max_mile:
1065                                start_sign += 1
1066                            else:
1067                                trip_list[start_sign] = test_trip
1068                                trip_list.remove(trip_list[start_sign+1])
1069                        if start_sign == len(trip_list)-1:
1070                            run_sign = False
1071                    else:
1072                        run_sign = False
1073#                print "---"                        
1074#                print trip_list      
1075#                print "---"
1076                p_new_trip = []
1077                up_order = {}
1078                down_order = {}   
1079                for m in trip_list:
1080                    
1081                    temp_trip_dist_list.append(total_distant(m))
1082                    temp_trip_time_list.append(total_time(m))
1083                    temp_p_new_trip = []
1084                    uporder = 0
1085                    downorder = 0                    
1086                    for l in m:
1087                        if l > 0:
1088
1089                            temp_p_new_trip.append(l)
1090                            uporder += 1                            
1091                            up_order[l] = uporder
1092                        else:
1093                            downorder += 1                            
1094                            down_order[l] = downorder                            
1095                    p_new_trip.append(temp_p_new_trip)
1096#                print p_new_trip
1097                for m in range(len(p_new_trip)):
1098#                    print p_new_trip
1099                    trip_number += 1
1100                    for l in range(len(p_new_trip[m])):
1101#                        if p_new_trip[m][l] > 0:
1102                        trip_dict[p_new_trip[m][l]] = trip_number
1103                        sin_req = p_new_trip[m][l]
1104                        UP_order = up_order[sin_req]
1105                        DOWN_order = down_order[-sin_req]
1106                        
1107                        TAKE_TIME = str(int((Day_order[sin_req][2]+Day_order[sin_req][3])/2//60))+":"+str(int((Day_order[sin_req][2]+Day_order[sin_req][3])/2%60))
1108                        AVR_TIME = str(int((Day_order[sin_req][6]+Day_order[sin_req][7])/2//60))+":"+str(int((Day_order[sin_req][6]+Day_order[sin_req][7])/2%60))
1109
1110                        TAKE_DATE = j[0:4]+"-"+j[5:7]+"-"+j[8:]
1111                        TAKE_DATE = datetime.datetime.strptime(TAKE_DATE, "%Y-%m-%d")
1112                        TAKE_TIME = datetime.datetime.strptime(TAKE_TIME, "%H:%M")
1113                        AVR_TIME = datetime.datetime.strptime(AVR_TIME, "%H:%M")
1114                        temp_result = [TAKE_DATE,i,sin_req,Day_order[sin_req][1],Day_order[sin_req][5],trip_number,"Vrp",UP_order,DOWN_order,resource_info[k][6],resource_info[k][5],TAKE_TIME,AVR_TIME]
1115#                        print "temp_result",temp_result
1116                        result.append(temp_result)    
1117
1118            temp_trip_dist[j] = temp_trip_dist_list
1119            temp_trip_time[j] = temp_trip_time_list
1120        trip_dist[i] = temp_trip_dist
1121        trip_time[i] = temp_trip_time
1122
1123    return useed_resource_info,result
1124
1125
1126#%% Data Input and Data Ouput
1127useed_resource,result = main_funtion(sql_request,sql_cost,sql_resource)
1128
1129for i in range(len(result)):
1130    cursor.execute("""INSERT INTO VRP_HAS_MATCHED (ENTERPRISEID,
1131                                               TAKE_DATE, 
1132                                                 GROUP_NAME, 
1133                                                 PASSENGER_ORDER_ID, 
1134                                                 START_PLACE, 
1135                                                 END_PLACE, 
1136                                                 SENDORDER_ID_VRP, 
1137                                                 TYPE, 
1138                                                 UP_ORDER,
1139                                                 DOWN_ORDER,
1140                                                 DRIVER_NAME, 
1141                                                 CAR_NUMBER, 
1142                                                 TAKE_TIME, 
1143                                                 AVR_TIME)
1144                                                 
1145                                                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""","None",result[i][0],result[i][1],result[i][2],result[i][3],result[i][4],result[i][5],result[i][6],result[i][7],result[i][8],result[i][9],result[i][10],result[i][11],result[i][12])
1146
1147cursor.execute('SELECT * from VRP_HAS_MATCHED')
1148VRP_HAS_MATCHED = datafit(cursor,"pandas") 
1149cnxn.commit()
1150=======
1151# -*- coding: utf-8 -*-
1152"""
1153Created on Thu Nov 29 15:35:08 2018
1154
1155@author: Kuan
1156"""
1157import math
1158import copy
1159import datetime
1160import pandas as pd
1161import pyodbc 
1162import time
1163#import pprint
1164#%% sql sever setting
1165#server = '' 
1166#database = '' 
1167#username = '' 
1168#password = '' 
1169#cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
1170server = '' 
1171database = '' 
1172username = '' 
1173password = ''
1174cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
1175#%% parameter setting
1176Max_mile = 20 # upper limit for a ride
1177service_time = 5 # service time when  arrive locstion 
1178down_service_time = 1
1179time_window = 30 # aditional time windows
1180constant_a = 3
1181constant_b = 5
1182Max_trip_interval = 15 #minutes
1183new_tw = 5
1184Large_cost = 99999
1185#%% input three sql data sheet
1186
1187## a funtion to transfer the form of data
1188## transfer into pandas or list 
1189def datafit(data,form):
1190    colList = []
1191    for colInfo in data.description:
1192        colList.append(colInfo[0])
1193    rowList = []
1194    while True:
1195        try:
1196            row = data.fetchone()
1197            if row:
1198                rowList.append(list(row))
1199            else:
1200                break
1201        except:   
1202            continue;
1203    if form == "pandas":
1204        sql_data = pd.DataFrame(rowList) 
1205        sql_data.columns = colList 
1206    elif form == "list":
1207        sql_data = rowList
1208    return sql_data
1209
1210
1211## delete the data has been create and recalculate 
1212cursor = cnxn.cursor()
1213cursor.execute('delete from VRP_HAS_MATCHED') 
1214cnxn.commit()
1215 
1216#print "---sql_resource---"
1217cursor.execute("SELECT * from VRP_CAR_USEABLE ")
1218sql_resource = datafit(cursor,"list") 
1219
1220#print ("---sql_cost---")
1221cursor.execute("SELECT * from VRP_TRAVEL_MATRIX_DATA ")
1222sql_cost = datafit(cursor,"list")
1223
1224#print ("---sql_request---")
1225cursor.execute("SELECT * from VRP_PRE_ORDER")
1226sql_request = datafit(cursor,"list")
1227
1228## if you want the data in a specific day
1229#cursor.execute("SELECT * from VRP_CAR_USEABLE where take_date ='2019/01/14'")
1230#cursor.execute("SELECT * from VRP_TRAVEL_MATRIX_DATA where take_date ='2019/01/14'")
1231#cursor.execute("SELECT * from VRP_PRE_ORDER where take_date ='2019/01/14'")
1232
1233## if you want the data in a specific period
1234#cursor.execute("SELECT * from VRP_CAR_USEABLE where take_date between '2019/01/14' and '2019/01/18'")
1235#cursor.execute("SELECT * from VRP_TRAVEL_MATRIX_DATA where take_date between '2019/01/14' and '2019/01/18'")
1236#cursor.execute("SELECT * from VRP_PRE_ORDER where take_date between '2019/01/14' and '2019/01/18'")
1237
1238#%% Main procedure 
1239def main_funtion(request,cost,resource): 
1240      
1241    ## a funtion to transfer the time format
1242    def time_form(intime):
1243        str_intime = str(intime)
1244        int_intime = int(str_intime[11])*10*60+int(str_intime[12])*60+int(str_intime[14])*10+int(str_intime[15])
1245        return int_intime 
1246    
1247    ## calculate the route time
1248    def total_time(route):
1249        tt_time = 0
1250        for c in range(len(route)-1):
1251            tt_time += t[Day_order[route[c]][1],Day_order[route[c+1]][1]]          
1252        return tt_time
1253    
1254    ## calculate the route distant
1255    def total_distant(route):
1256        tt_dist = 0
1257        for c in range(len(route)-1):
1258            tt_dist += d[Day_order[route[c]][1],Day_order[route[c+1]][1]]          
1259        return tt_dist
1260    
1261    ## give the route a start customer
1262    ## 
1263    def route_seed_initialer(unroute_list,village,Day):
1264        ## sort the unroute customers acordding to the pick up time
1265        now_unroute_list = []
1266        for i in unroute_list:
1267            now_unroute_list.append(Day_order[i])
1268        sort_now_unroute_list = sorted(now_unroute_list, key = lambda x : (x[2]))
1269        sort_unroute_list = []
1270        for i in sort_now_unroute_list:
1271            sort_unroute_list.append(i[0]) 
1272        ## sort the car drivers acordding to the starting service time    
1273        all_car_key_info = []
1274        for i in unuse_resource_info[village][Day]:
1275            all_car_key_info.append(resource_info[i])
1276        sort_all_car_key_info = sorted(all_car_key_info, key = lambda x : (x[-7]))
1277        sort_all_car_key = []
1278        for i in sort_all_car_key_info:
1279            sort_all_car_key.append(i[0])  
1280        ## give the route a start customer
1281        ## return the unroute list without the customerhave been matched
1282        new_unroute_list = copy.copy(sort_unroute_list)
1283        for j in sort_unroute_list:
1284            unservable_time = 0
1285            break_sign = 0
1286            for i in sort_all_car_key: #i就是車號
1287                current_routeA = [i,j,-j,i]
1288                if check_feasible_route(current_routeA,i) == 0: #輸入路徑與車號
1289                    break_sign += 1
1290                    useed_resource_info[village][Day][i] = [i,j,-j,i]   
1291                    new_unroute_list.remove(j)
1292                    unuse_resource_info[village][Day].remove(i)
1293                    break
1294                else:
1295                    unservable_time += 1
1296                    len(sort_all_car_key[sort_all_car_key.index(i):])
1297            if unservable_time == len(sort_all_car_key):
1298                if Day not in unservable_requests.keys():
1299                    unservable_requests[Day] = []
1300                    unservable_requests[Day].append(j)
1301                else:
1302                    unservable_requests[Day].append(j)
1303                new_unroute_list.remove(j)
1304            if break_sign>0:
1305                break
1306            #只要有一個人可以放進一台車就可以
1307#        print "in ",useed_resource_info[village][Day]
1308        return new_unroute_list    
1309    
1310    def route_seed_initialer2(unroute_list,village,Day):
1311#        print unroute_list,village,Day
1312        now_unroute_list = []
1313        for i in unroute_list:
1314            now_unroute_list.append(Day_order[i])
1315        sort_now_unroute_list = sorted(now_unroute_list, key = lambda x : (x[2]))
1316        sort_unroute_list = []
1317        for i in sort_now_unroute_list:
1318            sort_unroute_list.append(i[0])
1319        seed_list = copy.copy(sort_unroute_list)
1320        new_unroute_list = []
1321        for i in range(len(sort_unroute_list)-1):
1322            req_i = sort_unroute_list[i]
1323            req_i_1 = sort_unroute_list[i+1]
1324            LDTk = Day_order[req_i][7]
1325            TTDkPk_1 = t[Day_order[req_i][5],Day_order[req_i_1][1]]
1326            EPTk_1 = Day_order[req_i_1][2]
1327            if LDTk+TTDkPk_1<=EPTk_1:
1328                seed_list.remove(req_i_1)
1329                new_unroute_list.append(req_i_1)
1330        for i in unuse_resource_info[village][Day]:
1331            unservable_time = 0
1332            for j in seed_list: 
1333                current_routeA = [i,j,-j,i]
1334                if check_feasible_route(current_routeA,i) == 0:
1335                    useed_resource_info[village][Day][i] = [i,j,-j,i]
1336                    seed_list.remove(j)
1337                    break                  
1338                else:
1339                    unservable_time += 1
1340        for i in useed_resource_info[village][Day].keys():
1341            if i in unuse_resource_info[village][Day]:
1342                unuse_resource_info[village][Day].remove(i)
1343#        print "in ",useed_resource_info[village][Day]
1344        return new_unroute_list+seed_list  
1345   
1346    def check_feasible_route(feasible_route,car_number):
1347#        print feasible_route,car_number
1348        debug_time = Day_order[feasible_route[0]][2] ## first customer pick time 
1349        max_car_capacity = resource_info[car_number][-1] ## car capacity
1350  
1351        route_feasible_or_not = True
1352        ## check if the trip exceeds the max trip miles
1353        if route_feasible_or_not == True:
1354            temp_store_list = [] 
1355            cal_sign = 0
1356            cal_anchor = 0
1357            
1358            for i in feasible_route :
1359                if type(i) ==  int:
1360                    temp_store_list.append(i)
1361                    if i not in temp_store_list or -i not in temp_store_list:        
1362                        cal_sign += 1
1363                    elif i < 0 and -i in temp_store_list:
1364                        cal_sign -= 1
1365                    if cal_sign == 0:
1366                        cal_route = temp_store_list[cal_anchor:feasible_route.index(i)+1]
1367#                        print cal_anchor,feasible_route.index(i)+1
1368                        o_dist = total_distant(cal_route)
1369#                        for test_c in range(len(cal_route)-1):
1370#                            o_dist += d[Day_order[cal_route[test_c]][1],Day_order[cal_route[test_c+1]][1]]         
1371                        
1372                        if o_dist >= Max_mile:
1373                            route_feasible_or_not = False 
1374#                        else:
1375#                            print cal_route,car_number,total_distant(cal_route)
1376                            
1377                        cal_anchor = feasible_route.index(i)+1 
1378        ## check if the capacity exceeds the car limit               
1379        passenger_in_car = 0 
1380        if route_feasible_or_not == True: 
1381            for x in feasible_route:
1382                if x > 0 :
1383                    passenger_in_car += Day_order[x][4] 
1384                elif x <0:
1385                    passenger_in_car -= Day_order[x][4]
1386                if passenger_in_car > max_car_capacity:
1387
1388                    route_feasible_or_not = False
1389                    break
1390                
1391        ## check the route time window  
1392        debug_route_time = []
1393        debug_real_time = []    
1394        if route_feasible_or_not == True: 
1395            for i in range(len(feasible_route)):
1396                pre_node = Day_order[feasible_route[i-1]][1]            
1397                now_node = Day_order[feasible_route[i]][1]
1398    
1399                e_time = Day_order[feasible_route[i]][2] #early最早上車
1400                l_time = Day_order[feasible_route[i]][3] #latest 最晚上車
1401    
1402                if i == 0:
1403                    debug_route_time.append(debug_time)
1404                    debug_real_time.append(debug_time)
1405                    next_node = Day_order[feasible_route[i+1]][1]
1406                    if now_node == next_node:
1407                        continue
1408                    else:
1409                        if feasible_route[i] < 0:
1410#                            print feasible_route[i-1]
1411                            debug_time += down_service_time
1412#                            debug_time += service_time 
1413                        else:    
1414                            debug_time += service_time                   
1415                elif i == len(feasible_route)-1:    
1416                    debug_time = debug_time+t[pre_node,now_node]
1417                    debug_route_time.append(debug_time)
1418                    debug_real_time.append(l_time)
1419                elif i > 0:
1420#                    print pre_node,now_node
1421                    debug_time = max([debug_time+t[pre_node,now_node],e_time])
1422                    debug_route_time.append(debug_time)
1423                    debug_real_time.append(l_time)
1424                    next_node = Day_order[feasible_route[i+1]][1]
1425                    if now_node == next_node:
1426                        continue
1427                    else:
1428                        if feasible_route[i] < 0:
1429                            debug_time += down_service_time   
1430                        else:    
1431                            debug_time += service_time
1432            for i,j in zip(debug_route_time,debug_real_time):
1433                if  i > j:
1434#                    print i,j
1435#                    debug1 = 1
1436                    route_feasible_or_not = False                    
1437
1438        if route_feasible_or_not == True:  
1439            debug_signal = 0
1440        else:
1441            debug_signal = 1
1442#        if 14410 in feasible_route:
1443#            print feasible_route,car_number,route_feasible_or_not
1444           
1445        return debug_signal
1446
1447    def regret_insert(unroute_list,village,Day):
1448#        print "unroute_list",unroute_list,village,Day
1449#        for fadfad in range(10):
1450        while len(unroute_list) > 0:
1451#            print "unroute_list",unroute_list
1452            current_list = useed_resource_info[village][Day].values()
1453#            print useed_resource_info
1454#            print "current_list",current_list
1455            car_keys = useed_resource_info[village][Day].keys()        
1456            temp_route = copy.copy(current_list)
1457    #        print "temp_route:",temp_route
1458            c2_value = []
1459            c2_route = []
1460            c2_place = []
1461            c2_customer = []
1462#            print "----"
1463            for customer in unroute_list:
1464#                print customer
1465                min_c1_route = []
1466                min_c1_value = []
1467                min_c1_place = []
1468                customer_p = customer
1469                customer_d = -customer_p
1470                for o_route in temp_route: 
1471                    car_number = car_keys[current_list.index(o_route)]
1472                    o_route_tt_dist = 0
1473                    for test_c in range(len(o_route)-1):
1474                        o_route_tt_dist += d[Day_order[o_route[test_c]][1],Day_order[o_route[test_c+1]][1]]                      
1475                    c1_value = []
1476                    c1_place = []
1477                    for p_place in range(1,len(o_route)+1):         
1478                        test_p_route =  copy.copy(o_route)
1479                        test_p_route.insert(p_place,customer_p)
1480#                        print
1481#                        print "test_p_route-----------",test_p_route                        
1482#                        feasibility1 = check_feasible_route(test_p_route,car_number)
1483#                        print "-----------feasibility1",feasibility1
1484                        feasibility1 = 0
1485                        if feasibility1 == 0:
1486                            for d_place in range(p_place+1,len(test_p_route)):
1487                                #print d_place,"----"
1488                                test_d_route = copy.copy(test_p_route)
1489                                test_d_route.insert(d_place,customer_d)
1490#                                print"--"                                
1491                                feasibility2 = check_feasible_route(test_d_route,car_number)
1492#                                if (316 in test_d_route and 318 in test_d_route) or (317 in test_d_route and 318 in test_d_route):
1493#                                    print test_d_route,feasibility2
1494#                                    print "--"
1495#                                print"--"
1496                                if feasibility2 == 0:###############
1497                                    ##################################################################
1498#                                    tt_dist = total_distant(test_d_route)
1499#                                    print test_d_route
1500#                                    for test_c in range(len(test_d_route)-1):
1501##                                        print test_d_route[test_c],test_d_route[test_c+1],d[Day_order[test_d_route[test_c]][1],Day_order[test_d_route[test_c+1]][1]]
1502#                                        tt_dist += d[Day_order[test_d_route[test_c]][1],Day_order[test_d_route[test_c+1]][1]]
1503#                                    c1 = tt_dist-o_route_tt_dist
1504                                    c1 = total_distant(test_d_route)
1505#                                    print test_d_route,c1
1506                                    ##################################################################
1507                                    c1_value.append(c1)
1508                                    c1_place.append([p_place,d_place])
1509                                
1510                    min_c1_route.append(o_route)  
1511#                    print c1_value
1512                    if len(c1_value) > 0:
1513                        min_value = min(c1_value)
1514                        min_place = c1_place[c1_value.index(min_value)]                           
1515                        min_c1_value.append(min_value)
1516                        min_c1_place.append(min_place)
1517                    else:                
1518                        min_c1_value.append(Large_cost)
1519                        min_c1_place.append([-Large_cost,-Large_cost])     
1520#                print "min_c1_value",min_c1_value
1521                min_min_c1_value = min(min_c1_value)
1522                min_c1_index = min_c1_value.index(min_min_c1_value)
1523                min_min_c1_place = min_c1_place[min_c1_index]
1524                min_min_c1_route = min_c1_route[min_c1_index]
1525                c2_customer.append([customer,-customer])
1526#                print c2_customer
1527                c2 = 0
1528                if min_c1_value.count(Large_cost) != len(min_c1_value):
1529#                    print min_c1_value
1530                    for mmc in range(len(min_c1_value)):
1531#                        print min_c1_route[mmc],min_min_c1_route
1532#                        if min_c1_route[mmc] != min_min_c1_route:
1533                            
1534                        c2 += min_c1_value[mmc] - min_min_c1_value
1535#                        print "------------",c2
1536                else:
1537                    c2 = -Large_cost
1538                c2_value.append(c2)
1539                c2_route.append(min_min_c1_route)
1540                c2_place.append(min_min_c1_place)  
1541#                print c2_value,c2_route,c2_place
1542#            print c2_value  
1543            if c2_value.count(-Large_cost) != len(c2_value):
1544#                print "1111111111111"
1545                max_c2_value = max(c2_value)
1546#                print max_c2_value
1547                max_c2_index = c2_value.index(max_c2_value)
1548                max_c2_route = c2_route[max_c2_index]
1549                max_c2_place = c2_place[max_c2_index]
1550                max_c2_customer = c2_customer[max_c2_index]
1551                max_c2_index = current_list.index(max_c2_route)        
1552                for insert_p,insert_c in zip(max_c2_place,max_c2_customer):
1553                    max_c2_route.insert(insert_p,insert_c)
1554                current_list[max_c2_index] = max_c2_route
1555                unroute_list.remove(max_c2_customer[0])         
1556            else:
1557#                print "----",Day,unroute_list
1558#                unservable_requests[Day] = unroute_list ##route2
1559#                break
1560                unroute_list = route_seed_initialer(unroute_list,village,Day)
1561                
1562        return current_list
1563    
1564    def relocation_operator(original_plan):
1565        all_reinsert_info = {}
1566        for i in original_plan:
1567            for j in original_plan[i]:
1568                if j > 0 :
1569                    all_reinsert_info[j] = i 
1570        all_route = original_plan.keys()
1571        
1572        relocation_for_remove_time = 0
1573        relocation_for_insert_time = 0
1574        for relocate_time in range(1):
1575            for i in all_reinsert_info:
1576                
1577                relocation_for_remove_start_time = time.time()
1578                car_c = all_reinsert_info[i]
1579                remoeve_route_c = original_plan[car_c][:]
1580                if type(i) == int:
1581                    remoeve_route_c.remove(i)
1582                    remoeve_route_c.remove(-i)
1583                    relocation_for_remove_end_time = time.time()
1584                    relocation_for_remove_time += (relocation_for_remove_end_time-relocation_for_remove_start_time)
1585                    for l in all_route:
1586                        if l != car_c:
1587                            for m in range(1,len(original_plan[l])+1):
1588                                for n in range(m+1,len(original_plan[l])+1):
1589                                    if i in original_plan[car_c]:  
1590                                        relocation_for_insert_start_time = time.time()
1591                                        insert__route_c = original_plan[l][:]
1592                                        insert__route_c.insert(m,i)
1593                                        insert__route_c.insert(n,-i)
1594                                        relocation_for_insert_end_time = time.time()
1595                                        relocation_for_insert_time += (relocation_for_insert_end_time-relocation_for_insert_start_time)
1596        #                                print insert__route_c,check_feasible_route(insert__route_c,l)
1597                                        if check_feasible_route(insert__route_c,l) == 0:
1598        #                                    print insert__route_c,check_feasible_route(insert__route_c,l)
1599                                            if total_distant(original_plan[car_c])+total_distant(original_plan[l])-total_distant(remoeve_route_c)-total_distant(insert__route_c) > 0:
1600#                                                print total_distant(original_plan[car_c])+total_distant(original_plan[l])-total_distant(remoeve_route_c)-total_distant(insert__route_c) 
1601                                                original_plan[car_c] = remoeve_route_c
1602                                                original_plan[l] = insert__route_c
1603                                                all_reinsert_info[i] = l   
1604                                            if len(remoeve_route_c) == 0 or len(insert__route_c) == 0 :
1605                                                print "need to cut car"                                            
1606                                    else:
1607                                        break 
1608        return original_plan
1609    def exchange_operator(original_plan):
1610        all_reinsert_info = {}
1611        for i in original_plan:
1612#            print i,original_plan[i]
1613            for j in original_plan[i]:
1614#                print j
1615                if j > 0 and type(j) == int:
1616                    all_reinsert_info[j] = i
1617        exchange_first_insert = 0
1618        exchange_second_insert = 0
1619    #    exchange_start_time = time.time()
1620        for exchange_time in range(1):
1621            for i in all_reinsert_info:
1622                for j in all_reinsert_info:
1623                    car_r = all_reinsert_info[i]
1624                    car_s = all_reinsert_info[j]
1625                    if i != j and car_r != car_s:
1626            #            print 
1627            #            print Day_order[i],Day_order[j]
1628                        EPTi = Day_order[i][2]
1629                        LPTi = Day_order[i][3]
1630                        EDTi = Day_order[i][6]
1631                        LDTi = Day_order[i][7]       
1632                        EPTj = Day_order[j][2]
1633                        LPTj = Day_order[j][3]
1634                        EDTj = Day_order[j][6]
1635                        LDTj = Day_order[j][7]           
1636                        if (EPTi <= LPTj and EPTj <= LPTi) or (EDTi <= LDTj and EDTj <= LDTi):                    
1637       
1638                            remoeve_route_r = original_plan[car_r][:]
1639                            remoeve_route_r.remove(i)
1640                            remoeve_route_r.remove(-i)
1641                            
1642                            best_insert_route_r = []
1643                            exchange_first_start_insert = time.time()
1644                            for m in range(1,len(remoeve_route_r)+1):
1645                                for n in range(m+1,len(remoeve_route_r)+1):
1646    #                                print m,n
1647                                    insert_route_r = remoeve_route_r[:]
1648    #                                insert_route_r = copy.deepcopy(remoeve_route_r)
1649                                    insert_route_r.insert(m,j)
1650                                    insert_route_r.insert(n,-j)
1651    #                                print insert_route_r,check_feasible_route(insert_route_r,car_r)
1652                                    if check_feasible_route(insert_route_r,car_r) == 0:
1653                                        if len(best_insert_route_r) == 0:
1654                                            best_insert_route_r = insert_route_r
1655                                        else:
1656                                            if total_distant(insert_route_r) < total_distant(best_insert_route_r):
1657                                                best_insert_route_r = insert_route_r
1658            
1659                            exchange_first_end_insert = time.time()            
1660                            exchange_first_insert += (exchange_first_end_insert-exchange_first_start_insert)    
1661                            if len(best_insert_route_r) > 0 :        
1662                                remoeve_route_s = original_plan[car_s][:]
1663                                remoeve_route_s.remove(j)
1664                                remoeve_route_s.remove(-j) 
1665                                exchange_second_start_insert = time.time()
1666                                best_insert_route_s = []
1667                                for m in range(1,len(remoeve_route_s)+1):
1668                                    for n in range(m+1,len(remoeve_route_s)+1):
1669                                        insert_route_s = remoeve_route_s[:]
1670                                        insert_route_s.insert(m,i)
1671                                        insert_route_s.insert(n,-i)                
1672                                        if check_feasible_route(insert_route_s,car_s) == 0:
1673                #                            print "-------------------"
1674                                            if len(best_insert_route_s) == 0:
1675                                                best_insert_route_s = insert_route_s
1676                                            else:
1677                                                if total_distant(insert_route_s) < total_distant(best_insert_route_s):
1678                                                    best_insert_route_s = insert_route_s
1679                                exchange_second_end_insert = time.time()
1680                                exchange_second_insert += (exchange_second_end_insert-exchange_second_start_insert)
1681                                if len(best_insert_route_s) > 0:
1682                                    if (total_distant(original_plan[car_r])+total_distant(original_plan[car_s]))-(total_distant(best_insert_route_r)+total_distant(best_insert_route_s))>0:
1683#                                        print (total_distant(original_plan[car_r])+total_distant(original_plan[car_s]))-(total_distant(best_insert_route_r)+total_distant(best_insert_route_s))
1684                                        original_plan[car_r] = best_insert_route_r                 
1685                                        original_plan[car_s] = best_insert_route_s
1686                                        all_reinsert_info[i] = car_s
1687                                        all_reinsert_info[j] = car_r  
1688                                        if len(best_insert_route_r) == 0 or len(best_insert_route_s) == 0 :
1689                                            print "need to cut car"
1690        return original_plan   
1691
1692
1693    def check_service_time(feasible_route,out_type = None):
1694#        print feasible_route
1695        debug_time = Day_order[feasible_route[0]][2]
1696#        print debug_time
1697        debug_service_time = []   
1698        for i in range(len(feasible_route)):
1699            pre_node = Day_order[feasible_route[i-1]][1]            
1700            now_node = Day_order[feasible_route[i]][1]
1701
1702            e_time = Day_order[feasible_route[i]][2]
1703#            l_time = Day_order[feasible_route[i]][3]
1704            if i == 0:
1705                debug_service_time.append(debug_time)
1706            elif i == len(feasible_route)-1:        
1707                debug_time = debug_time+t[pre_node,now_node]
1708                debug_service_time.append(debug_time)
1709            else:
1710                debug_time = max([debug_time+t[pre_node,now_node],e_time])
1711                debug_service_time.append(debug_time)
1712                if now_node > 0:
1713                    debug_time += service_time
1714#                print "afterser:",debug_time
1715        ri_time = 0
1716        test_n = 0                    
1717        for i in range(len(feasible_route)):
1718    #        print i,test[i],test[i+1],t[Day_order[test[i]][1],Day_order[test[i+1]][1]]
1719            if type(feasible_route[i]) == int:
1720                test_n += feasible_route[i]
1721                if feasible_route[i] > 0:
1722                    test_target = feasible_route.index(-feasible_route[i])
1723                    
1724                    ride_time =  debug_service_time[test_target] - debug_service_time[i]   
1725                    ri_time += ride_time
1726        if out_type == "list":
1727            return debug_service_time
1728        else:
1729            return ri_time         
1730
1731    def check_arrive_time(feasible_route,out_type = None):
1732#        print feasible_route
1733        debug_time = Day_order[feasible_route[0]][2]
1734#        print debug_time
1735        debug_arrive_time = []   
1736        for i in range(len(feasible_route)):
1737            pre_node = Day_order[feasible_route[i-1]][1]            
1738            now_node = Day_order[feasible_route[i]][1]
1739
1740            e_time = Day_order[feasible_route[i]][2]
1741#            l_time = Day_order[feasible_route[i]][3]
1742            if i == 0:
1743                debug_arrive_time.append(debug_time)
1744            elif i == len(feasible_route)-1:        
1745                debug_time = debug_time+t[pre_node,now_node]
1746                debug_arrive_time.append(debug_time)
1747            else:
1748                debug_arrive_time.append(debug_time+t[pre_node,now_node])
1749                debug_time = max([debug_time+t[pre_node,now_node],e_time])
1750                
1751                if now_node > 0:
1752                    debug_time += service_time
1753#                print "afterser:",debug_time
1754        ri_time = 0
1755        test_n = 0  
1756                          
1757        for i in range(len(feasible_route)):
1758    #        print i,test[i],test[i+1],t[Day_order[test[i]][1],Day_order[test[i+1]][1]]
1759            if type(feasible_route[i]) == int:
1760                test_n += feasible_route[i]
1761                if feasible_route[i] > 0:
1762                    test_target = feasible_route.index(-feasible_route[i])
1763                    ride_time =  debug_arrive_time[test_target] - debug_arrive_time[i]   
1764                    ri_time += ride_time
1765#        print debug_arrive_time                
1766        if out_type == "list":
1767            return debug_arrive_time
1768        else:
1769            return ri_time                     
1770    def ride_counter(feasible_route,out_type = None):
1771#        print "    ",feasible_route
1772#        print "debug_time",debug_time
1773        node_service_time = check_service_time(feasible_route,"list")
1774        node_arrive_time = check_arrive_time(feasible_route,"list")
1775        ##########################
1776        test = feasible_route
1777        
1778        e_time_list = [Day_order[i][2] for i in feasible_route]
1779        l_time_list = [Day_order[i][3] for i in feasible_route]
1780#        print len(l_time_list)
1781        cuttime_list = []
1782        for i,j in zip(node_service_time,node_arrive_time):
1783            if j < i:
1784                cuttime_list.append(i-j)
1785            else:
1786                cuttime_list.append(0)
1787#        print cuttime_list                
1788#        print len(cuttime_list)
1789        ri_time = 0
1790#        route_arrive_time = check_service_time(test)
1791        test_n = 0
1792        test_ancher = 0
1793        if test[0] == 0:
1794            for i in range(len(test)-1):
1795                test_n += test[i]
1796                if test_n == 0:
1797                    if test[i] != 0:
1798
1799                        for j in range(test_ancher,i+1):
1800                            
1801                            if cuttime_list[j] > 0:
1802                                if j == test_ancher:
1803                                    node_arrive_time[test_ancher] = e_time_list[test_ancher] 
1804                                else:
1805                                    
1806                                    change_new_timesign = 0
1807#                                    print "1   ",change_new_timesign
1808                                    for l in range(test_ancher,j):
1809                                        new_service_time = node_service_time[l] + cuttime_list[j]
1810                                        
1811                                        if new_service_time >= e_time_list[l] and new_service_time <= l_time_list[l]:
1812                                            continue
1813                                        else:
1814                                            change_new_timesign += 1
1815#                                    print "2   ",change_new_timesign
1816                                            
1817                                    if change_new_timesign == 0:
1818#                                        print test_ancher,j
1819                                        for l in range(test_ancher,j):
1820                                            node_service_time[l] = node_service_time[l] + cuttime_list[j]   
1821                                            node_arrive_time[l] = node_arrive_time[l] + cuttime_list[j]   
1822                                            
1823                                        node_arrive_time[j] = e_time_list[j] 
1824                                    else:
1825#                                        print "NOOOO",test[j],cuttime_list[j]   
1826                                        left_time_list = [l_time_list[l]-node_arrive_time[l]for l in range(test_ancher,j)]
1827                                     
1828                                        min_left_time = min(left_time_list)
1829                                        for l in range(test_ancher,j):
1830#                                            print test[l],left_time_list[l-test_ancher]
1831                                            node_service_time[l] = node_service_time[l] + min_left_time
1832                                            node_arrive_time[l] = node_arrive_time[l] + min_left_time
1833                                        node_arrive_time[j] = node_arrive_time[j] + min_left_time                                               
1834                        
1835                    test_ancher = i+1
1836#        print "    ",node_service_time            
1837#        print "    ",node_arrive_time 
1838        cuttime_list = []
1839        for i,j in zip(node_service_time,node_arrive_time):
1840            if j < i:
1841                cuttime_list.append(i-j)
1842            else:
1843                cuttime_list.append(0)    
1844#        print cuttime_list                
1845        for i in range(len(test)):
1846    #        print i,test[i],test[i+1],t[Day_order[test[i]][1],Day_order[test[i+1]][1]]
1847            if type(test[i]) == int:
1848                test_n += test[i]
1849                if test[i] > 0:
1850                    test_target = test.index(-test[i])
1851    #                print test[i],-test[i]
1852                    ride_time =  node_service_time[test_target] - node_service_time[i]   
1853                    ri_time += ride_time
1854#        print node_service_time
1855        if out_type == "list":
1856            return node_service_time
1857        elif out_type == "arrive":
1858            return node_arrive_time
1859        else:
1860            return ri_time               
1861#%% sql cost
1862    ## make the time & distant cost matrix
1863    cost_info = {}
1864    dist_info = {}   
1865    for temp_cost in cost:
1866        cost_info[temp_cost[2],temp_cost[3]] = temp_cost[4]
1867        cost_info[temp_cost[3],temp_cost[2]] = temp_cost[4]
1868        cost_info[temp_cost[2],temp_cost[2]] = 0
1869        cost_info[temp_cost[3],temp_cost[3]] = 0
1870        dist_info[temp_cost[2],temp_cost[3]] = temp_cost[5]
1871        dist_info[temp_cost[3],temp_cost[2]] = temp_cost[5]
1872        dist_info[temp_cost[2],temp_cost[2]] = 0
1873        dist_info[temp_cost[3],temp_cost[3]] = 0
1874    ## time cost matrix
1875    t = copy.deepcopy(cost_info)
1876    ## distant cost matrix
1877    d = copy.deepcopy(dist_info)
1878#%% sql request
1879    
1880    request_info = {} 
1881    unservable_requests = {}
1882    village_key = [request[0][1]]
1883
1884    ## the dictionary includes every request in a day 
1885    Day_request_info = {}   
1886    Day_request_info[village_key[0]] = {}
1887    ## the dictionary of the information of every request 
1888    ## Day_order = {request_number:[request number,pick place, EPT, LPT, passenger number, deliver place, EDT, LDT]}
1889    ## Day_order[request_number] = [request number,pick place, EPT, LPT, passenger number, deliver place, EDT, LDT]
1890    Day_order = {}
1891    
1892    ## frame the time window
1893    for i in request:
1894        SENDORDER = i[3]
1895        ## if there are no pick windows        
1896#        if i[8] == None or i[9] == None:
1897        if True:
1898            Pp,Dp,n_C= i[5],i[6],i[7]
1899            
1900            LT = (time_form(i[10])+time_form(i[11]))/2.0
1901            
1902            EPT = LT - constant_a*t[Pp,Dp] - constant_b  
1903            EDT = LT -            t[Pp,Dp] - constant_b         
1904            LPT = time_form(i[10])
1905            LDT = time_form(i[11])
1906            
1907            Day_order[SENDORDER] = [SENDORDER]+[Pp,EPT,EDT,n_C,Dp,LPT,LDT]
1908            Day_order[-SENDORDER] = [SENDORDER]+[Dp,LPT,LDT,n_C]            
1909            temp_one = [str(i[0]),i[1],i[4],i[5],i[6],i[7],EPT,EDT,LPT,LDT]
1910#        ## if there are no deliver windows 
1911#        elif i[10] == None or i[11] == None:
1912#            
1913#            Pp,Dp,n_C= i[5],i[6],i[7]
1914#
1915#            EPT = time_form(i[8])
1916#            EDT = time_form(i[9])
1917#            LPT = EPT +            t[Pp,Dp] + constant_b
1918#            LDT = EPT + constant_a*t[Pp,Dp] + constant_b
1919#
1920#            Day_order[SENDORDER] = [SENDORDER]+[Pp,EPT,EDT,n_C,Dp,LPT,LDT]
1921#            Day_order[-SENDORDER] = [SENDORDER]+[Dp,LPT,LDT,n_C]            
1922#            temp_one = [str(i[0]),i[1],i[4],i[5],i[6],i[7],EPT,EDT,LPT,LDT]   
1923#        ## if both windows exist 
1924#        else:
1925#            Pp,Dp,n_C= i[5],i[6],i[7]
1926# 
1927#            EPT = time_form(i[8])
1928#            EDT = time_form(i[9])          
1929#            LPT = time_form(i[10])
1930#            LDT = time_form(i[11]) 
1931#            
1932#            Day_order[SENDORDER] = [SENDORDER]+[Pp,EPT,EDT,n_C,Dp,LPT,LDT]
1933#            Day_order[-SENDORDER] = [SENDORDER]+[Dp,LPT,LDT,n_C]             
1934#            temp_one = [str(i[0]),i[1],i[4],i[5],i[6],i[7],EPT,EDT,LPT,LDT]
1935
1936        SENDORDER_date = "19000000"
1937        SENDORDER_date = str(SENDORDER_date[:4])+"/"+str(SENDORDER_date[4:6])+"/"+str(SENDORDER_date[6:])
1938        SENDORDER_ID = str(SENDORDER)
1939    
1940        for j in SENDORDER_ID:
1941            if int(j) !=0:
1942                SENDORDER_ID = int(SENDORDER_ID[SENDORDER_ID.index(j):])
1943                break
1944        ## build the day request dictionary 
1945        ## let us know which requests should be matched in the specific day
1946        request_info[SENDORDER_ID] = [SENDORDER_date]+temp_one[0:2]+[SENDORDER_ID]+temp_one[2:10]
1947        request_info_now = request_info[SENDORDER_ID]
1948#        if request_info_now[2] not in village_key:
1949#            village_key.append(request_info_now[2])
1950        
1951        if request_info_now[0] not in Day_request_info[village_key[0]].keys():
1952            Day_request_info[village_key[0]][request_info_now[0]] = {}
1953            Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]] = [request_info_now[3]]
1954        else:
1955            if request_info_now[1] not in Day_request_info[request_info_now[2]][request_info_now[0]].keys():
1956                Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]] = []
1957                Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]] = [request_info_now[3]]
1958            else:
1959                Day_request_info[village_key[0]][request_info_now[0]][request_info_now[1]].append(request_info_now[3])
1960#        print Day_request_info
1961#%% sql resource              
1962    resource_info = {}
1963    
1964    ## the dictionary of the car did not be used 
1965    unuse_resource_info = {}
1966    ## the dictionary of the car have been used 
1967    useed_resource_info = {}
1968    
1969    for i in resource:
1970        car_code = i[4]+'-'+str(resource.index(i)+1)
1971        start_time = time_form(i[6])
1972        close_time = time_form(i[7])   
1973        temp_resource = [car_code,i[0],i[1],i[2].strftime('%Y/%m/%d'),i[3],i[4],i[5],time_form(i[6]),time_form(i[7]),i[8]]
1974        ## pretend the driver's location as a day order 
1975        ## but it does not include in day request
1976        Day_order[car_code] = [car_code,i[9],start_time,close_time,0]
1977#        temp_carnumber = temp_resource[4]
1978#        
1979#        temp_village = temp_resource[3]
1980#        
1981#        temp_date = temp_resource[0]
1982        
1983        temp_carnumber = temp_resource[0]
1984        
1985#        temp_village = village_key[0]
1986        temp_village = temp_resource[4]
1987     
1988        temp_date = temp_resource[3]
1989        
1990        if temp_village not in unuse_resource_info.keys():
1991            unuse_resource_info[temp_village] = {}
1992            useed_resource_info[temp_village] = {}
1993        if  temp_date not in unuse_resource_info[temp_village].keys():
1994            unuse_resource_info[temp_village][temp_date] = [temp_carnumber]
1995            useed_resource_info[temp_village][temp_date] = {}
1996        else:
1997            unuse_resource_info[temp_village][temp_date].append(temp_carnumber)
1998        resource_info[temp_carnumber] = temp_resource      
1999#    print unuse_resource_info
2000#%% generate the initial route
2001    Day_request = copy.copy(Day_request_info)
2002    reserve_Plan = {}
2003    for village in village_key:
2004        Day_keys = sorted(Day_request[village].keys())
2005        reserve_Plan[village] = {}
2006        for day in Day_keys:
2007            reserve_Plan[village][day] = {}
2008            reser_Day_keys = sorted(Day_request[village][day].keys())
2009    #        for reser_Day in reser_Day_keys[:1]:
2010            for reser_Day in reser_Day_keys:
2011                unroute_Day_requests = copy.copy(Day_request[village][day][reser_Day])
2012#                print unroute_Day_requests
2013                reserve_Plan_key = reserve_Plan[village][day].keys()
2014                if reser_Day not in reserve_Plan_key:
2015                    unroute_Day_requests = route_seed_initialer(unroute_Day_requests,village,reser_Day)
2016#                    print "unroute_Day_requests",unroute_Day_requests
2017                    final_route = regret_insert(unroute_Day_requests,village,reser_Day)
2018#                    print final_route
2019#                    reserve_Plan[village][day][reser_Day] = final_route
2020                else:
2021                    final_route = regret_insert(unroute_Day_requests,village,reser_Day)
2022                reserve_Plan[village][day][reser_Day] = final_route
2023#%% show the initial result               
2024#    print "------initial result------"
2025#    for i in useed_resource_info[village][reser_Day]:
2026#        print useed_resource_info[village][reser_Day][i]                
2027#%% improvement the initial route            
2028    improvement = False
2029
2030    if improvement == True:
2031#        print "+"
2032        for village in village_key:
2033            for reser_Day in useed_resource_info[village].keys(): 
2034                relocation_sign = True
2035                exchange_sign = True
2036                while True:
2037#                    
2038                ############## Trip relocation ##############                   
2039                    if relocation_sign == True:
2040#                        print "---relocation_operator---"   
2041                        old_plan = copy.copy(useed_resource_info[village][reser_Day])
2042                        new_plan = relocation_operator(useed_resource_info[village][reser_Day])
2043                        if old_plan != new_plan:
2044                            useed_resource_info[village][reser_Day] = new_plan
2045                        else:
2046                            relocation_sign = False   
2047#                        print "---relocation_operator---"                      
2048#                    
2049                ############## Trip exchange ##############                                       
2050                    if exchange_sign == True:
2051#                        print "---exchange_operator---"
2052                        old_plan = copy.copy(useed_resource_info[village][reser_Day])
2053                        new_plan = exchange_operator(useed_resource_info[village][reser_Day])
2054                        if old_plan != new_plan:
2055                            useed_resource_info[village][reser_Day] = new_plan
2056                        else:
2057                            exchange_sign = False  
2058#                        
2059                    if relocation_sign == False and exchange_sign ==  False:
2060                        break
2061
2062#%% show the improved result                
2063    print "------improved result------"
2064    total_dist = 0
2065    for i in useed_resource_info[village][reser_Day]:
2066        print useed_resource_info[village][reser_Day][i],total_distant(useed_resource_info[village][reser_Day][i])
2067        total_dist += total_distant(useed_resource_info[village][reser_Day][i])
2068    print 'Total distance:', total_dist
2069#%% show the unservable result         
2070    print "------unservable result------"        
2071    print unservable_requests        
2072#%% waiting strategy & Fix TW      
2073    for village in village_key:
2074        for reser_Day in useed_resource_info[village].keys():  
2075            for route in useed_resource_info[village][reser_Day]:
2076#                    print useed_resource_info[village][reser_Day][route]
2077                fix_route = useed_resource_info[village][reser_Day][route]
2078#                if waiting_strategy == "drive_first":
2079#                    nodeservice_time =  check_service_time(fix_route,"list")     
2080#                elif waiting_strategy == "wait_first":
2081                nodeservice_time =  ride_counter(fix_route,"list")
2082                e_time_list = [Day_order[j][2] for j in fix_route]
2083                l_time_list = [Day_order[j][3] for j in fix_route] 
2084#                    print nodeservice_time
2085#                    print e_time_list
2086#                    print l_time_list
2087                for j,k,l,m in zip(e_time_list,nodeservice_time,l_time_list,fix_route):
2088                    if m != 0:
2089#                        print
2090#                        print m,Day_order[m][2],Day_order[m][3]
2091                        if round(j,2)+service_time/2.0 > round(k,2):
2092#                                print round(j,2),round(k,2),round(l,2),"up"
2093                            Day_order[m][3] = j + new_tw
2094                        elif round(l,2)-service_time/2.0 < round(k,2):
2095#                                print round(j,2),round(k,2),round(l,2),"down"
2096                            Day_order[m][2] = l - new_tw
2097                        else:
2098#                                print round(j,2),round(k,2),round(l,2),"+5-5"
2099                            Day_order[m][2] = k - new_tw/2                          
2100                            Day_order[m][3] = k + new_tw/2
2101#                        print m,Day_order[m][2],Day_order[m][3]
2102#%% calculate the trip & format the data 
2103#    result_start_time = time.time()
2104    total_num = 0
2105    for i in useed_resource_info[village][reser_Day]:
2106#        print useed_resource_info[village][reser_Day][i] 
2107        total_num += (len(useed_resource_info[village][reser_Day][i])-2)/2.0
2108#    print total_num                      
2109    result = []
2110    trip_number = 0
2111    trip_dist = dict.fromkeys(useed_resource_info.keys())
2112    trip_time = dict.fromkeys(useed_resource_info.keys())
2113#    print useed_resource_info.keys()
2114    for i in useed_resource_info.keys(): 
2115        temp_trip_dist = dict.fromkeys(useed_resource_info[i].keys(),[])
2116        temp_trip_time = dict.fromkeys(useed_resource_info[i].keys(),[])
2117        for j in sorted(useed_resource_info[i].keys()):    
2118            temp_trip_dist_list = []
2119            temp_trip_time_list = []
2120            for k in useed_resource_info[i][j]:
2121                
2122                test_route = useed_resource_info[i][j][k]        
2123#                temp_store_list = [] 
2124                
2125#                customer_sign = 0
2126                cal_sign = 0
2127                cal_anchor = 1
2128                trip_list = []
2129                trip_dict ={}
2130#                print test_route
2131                for cus in test_route :
2132                    
2133                    if type(cus) == int:
2134
2135                        cal_sign += cus
2136                        if cal_sign == 0:
2137            #                print "     ---",temp_store_list[cal_anchor:feasible_route.index(i)+1]
2138                            cal_route = test_route[cal_anchor:test_route.index(cus)+1]
2139#                            print "cal_route",cal_route
2140                            trip_list.append(cal_route)
2141                            cal_anchor = test_route.index(cus)+1 
2142                run_sign = True
2143                start_sign = 0
2144                while run_sign == True:
2145                    if len(trip_list)>1:
2146                        take_time = (Day_order[trip_list[start_sign][-1]][3]+Day_order[trip_list[start_sign][-1]][2])/2
2147                        arive_time = (Day_order[trip_list[start_sign+1][0]][2]+Day_order[trip_list[start_sign+1][0]][3])/2                        
2148                        if arive_time - take_time > Max_trip_interval:
2149                            start_sign += 1
2150                        else:
2151                            test_trip = trip_list[start_sign] + trip_list[start_sign+1]
2152                            if total_distant(test_trip) > Max_mile:
2153                                start_sign += 1
2154                            else:
2155                                trip_list[start_sign] = test_trip
2156                                trip_list.remove(trip_list[start_sign+1])
2157                        if start_sign == len(trip_list)-1:
2158                            run_sign = False
2159                    else:
2160                        run_sign = False
2161#                print "---"                        
2162#                print trip_list      
2163#                print "---"
2164                p_new_trip = []
2165                up_order = {}
2166                down_order = {}   
2167                for m in trip_list:
2168                    
2169                    temp_trip_dist_list.append(total_distant(m))
2170                    temp_trip_time_list.append(total_time(m))
2171                    temp_p_new_trip = []
2172                    uporder = 0
2173                    downorder = 0                    
2174                    for l in m:
2175                        if l > 0:
2176
2177                            temp_p_new_trip.append(l)
2178                            uporder += 1                            
2179                            up_order[l] = uporder
2180                        else:
2181                            downorder += 1                            
2182                            down_order[l] = downorder                            
2183                    p_new_trip.append(temp_p_new_trip)
2184#                print p_new_trip
2185                for m in range(len(p_new_trip)):
2186#                    print p_new_trip
2187                    trip_number += 1
2188                    for l in range(len(p_new_trip[m])):
2189#                        if p_new_trip[m][l] > 0:
2190                        trip_dict[p_new_trip[m][l]] = trip_number
2191                        sin_req = p_new_trip[m][l]
2192                        UP_order = up_order[sin_req]
2193                        DOWN_order = down_order[-sin_req]
2194                        
2195                        TAKE_TIME = str(int((Day_order[sin_req][2]+Day_order[sin_req][3])/2//60))+":"+str(int((Day_order[sin_req][2]+Day_order[sin_req][3])/2%60))
2196                        AVR_TIME = str(int((Day_order[sin_req][6]+Day_order[sin_req][7])/2//60))+":"+str(int((Day_order[sin_req][6]+Day_order[sin_req][7])/2%60))
2197
2198                        TAKE_DATE = j[0:4]+"-"+j[5:7]+"-"+j[8:]
2199                        TAKE_DATE = datetime.datetime.strptime(TAKE_DATE, "%Y-%m-%d")
2200                        TAKE_TIME = datetime.datetime.strptime(TAKE_TIME, "%H:%M")
2201                        AVR_TIME = datetime.datetime.strptime(AVR_TIME, "%H:%M")
2202                        temp_result = [TAKE_DATE,i,sin_req,Day_order[sin_req][1],Day_order[sin_req][5],trip_number,"Vrp",UP_order,DOWN_order,resource_info[k][6],resource_info[k][5],TAKE_TIME,AVR_TIME]
2203#                        print "temp_result",temp_result
2204                        result.append(temp_result)    
2205
2206            temp_trip_dist[j] = temp_trip_dist_list
2207            temp_trip_time[j] = temp_trip_time_list
2208        trip_dist[i] = temp_trip_dist
2209        trip_time[i] = temp_trip_time
2210
2211    return useed_resource_info,result
2212
2213
2214#%% Data Input and Data Ouput
2215useed_resource,result = main_funtion(sql_request,sql_cost,sql_resource)
2216
2217for i in range(len(result)):
2218    cursor.execute("""INSERT INTO VRP_HAS_MATCHED (ENTERPRISEID,
2219                                               TAKE_DATE, 
2220                                                 GROUP_NAME, 
2221                                                 PASSENGER_ORDER_ID, 
2222                                                 START_PLACE, 
2223                                                 END_PLACE, 
2224                                                 SENDORDER_ID_VRP, 
2225                                                 TYPE, 
2226                                                 UP_ORDER,
2227                                                 DOWN_ORDER,
2228                                                 DRIVER_NAME, 
2229                                                 CAR_NUMBER, 
2230                                                 TAKE_TIME, 
2231                                                 AVR_TIME)
2232                                                 
2233                                                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""","None",result[i][0],result[i][1],result[i][2],result[i][3],result[i][4],result[i][5],result[i][6],result[i][7],result[i][8],result[i][9],result[i][10],result[i][11],result[i][12])
2234
2235cursor.execute('SELECT * from VRP_HAS_MATCHED')
2236VRP_HAS_MATCHED = datafit(cursor,"pandas") 
2237cnxn.commit()
2238>>>>>>> 7d8691cfa8529e4d1afe9dc681dedcadbe9f4fc3
2239
Full Screen