Repository navigation
Expand file tree
/
Copy pathsolution_current.py
More file actions
425 lines (392 loc) · 15.1 KB
/
Copy pathsolution_current.py
File metadata and controls
425 lines (392 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import json
import sys
import math
import itertools
input_data = json.loads(sys.stdin.read())
map_size = input_data['map_size']
warehouse = [map_size[0] / 2, map_size[1] / 2]
drones = input_data['drones']
deliveries = input_data['deliveries']
no_fly_zones = input_data.get('no_fly_zones', [])
charging_stations = input_data.get('charging_stations', [])
def solve(warehouse, drones, deliveries, no_fly_zones, charging_stations):
EPS = 1e-6
NFZ_SAFETY = 0.05
BATTERY_MAX = 500.0
CHARGE_RATE = 2.0
WH = (warehouse[0], warehouse[1])
# ---------- geometry ----------
def dist(a, b):
return math.hypot(a[0] - b[0], a[1] - b[1])
def circle_intersection(p1, p2, c, r):
x1, y1 = p1; x2, y2 = p2
cx, cy = c
dx, dy = x2 - x1, y2 - y1
fx, fy = x1 - cx, y1 - cy
a = dx * dx + dy * dy
if a < EPS:
return (0.0, 0.0) if (fx * fx + fy * fy <= r * r) else None
b = 2 * (fx * dx + fy * dy)
c2 = fx * fx + fy * fy - r * r
disc = b * b - 4 * a * c2
if disc < 0:
return None
sd = math.sqrt(disc)
s1 = (-b - sd) / (2 * a)
s2 = (-b + sd) / (2 * a)
lo = max(0.0, s1); hi = min(1.0, s2)
return (lo, hi) if lo <= hi else None
def rect_intersection(p1, p2, corners):
x1, y1 = p1; x2, y2 = p2
(cx1, cy1), (cx2, cy2) = corners
xmin, xmax = min(cx1, cx2), max(cx1, cx2)
ymin, ymax = min(cy1, cy2), max(cy1, cy2)
te, tx = 0.0, 1.0
# Liang-Barsky
for p, q in ((-(x2 - x1), x1 - xmin),
(x2 - x1, xmax - x1),
(-(y2 - y1), y1 - ymin),
(y2 - y1, ymax - y1)):
if abs(p) < EPS:
if q < 0:
return None
continue
t = q / p
if p < 0:
if t > te: te = t
else:
if t < tx: tx = t
if te > tx:
return None
return (max(0.0, te), min(1.0, tx))
seg_cache = {}
def segment_nfz(p1, p2):
key = (p1, p2)
c = seg_cache.get(key)
if c is not None:
return c
d = dist(p1, p2)
if d < EPS:
seg_cache[key] = (0.0, [])
return seg_cache[key]
segs = []
for nfz in no_fly_zones:
if nfz['shape'] == 'circle':
iv = circle_intersection(p1, p2, tuple(nfz['center']), nfz['radius'])
else:
corners = (tuple(nfz['corners'][0]), tuple(nfz['corners'][1]))
iv = rect_intersection(p1, p2, corners)
if iv:
segs.append((iv[0] * d, iv[1] * d, nfz['T_start'], nfz['T_end']))
seg_cache[key] = (d, segs)
return seg_cache[key]
def compute_wait(p1, p2, t_start):
d, segs = segment_nfz(p1, p2)
if d < EPS or not segs:
return 0.0
wait = 0.0
for _ in range(len(segs) * 4 + 6):
t_dep = t_start + wait
need = 0.0
safe = True
for t0, t1d, T_s, T_e in segs:
t_enter = t_dep + t0
t_exit = t_dep + t1d
if t_exit <= T_s - NFZ_SAFETY:
continue
if t_enter >= T_e + NFZ_SAFETY:
continue
safe = False
req = (T_e + NFZ_SAFETY) - t_enter
if req > need:
need = req
if safe:
return wait
if need <= EPS:
return float('inf')
wait += need
if wait > 1e7:
return float('inf')
return float('inf')
# ---------- trip simulation ----------
def simulate(start_pos, start_time, start_battery,
ordered, max_payload, return_pos):
total_w = sum(d['weight'] for d in ordered)
if total_w > max_payload + EPS:
return None
pos = start_pos
t = start_time
bat = start_battery
payload = total_w
energy = 0.0
events = []
for d in ordered:
tgt = (d['x'], d['y'])
seg_d, _ = segment_nfz(pos, tgt)
w = compute_wait(pos, tgt, t)
if w == float('inf'):
return None
if w > EPS:
events.append(('WAIT', pos, t, w))
t += w
e = seg_d * (1 + payload)
if bat < e - EPS:
return None
bat -= e
energy += e
t += seg_d
if t > d['deadline'] + EPS:
return None
events.append(('DELIVER', d, t))
pos = tgt
payload -= d['weight']
# Return leg, optionally via charging station
dwh, _ = segment_nfz(pos, return_pos)
ewh = dwh * (1 + payload)
w_home = compute_wait(pos, return_pos, t)
if w_home != float('inf') and bat >= ewh - EPS:
if w_home > EPS:
events.append(('WAIT', pos, t, w_home))
t_end = t + w_home + dwh
return {
'events': events + [('RETURN_LEG', pos, return_pos, t + w_home)],
'end_time': t_end, 'energy': energy + ewh,
'used_station': None,
}
best = None
for st in charging_stations:
sp = (st['x'], st['y'])
ds, _ = segment_nfz(pos, sp)
es = ds * (1 + payload)
if bat < es - EPS:
continue
w1 = compute_wait(pos, sp, t)
if w1 == float('inf'):
continue
t_at = t + w1 + ds
bat_at = bat - es
dwh2, _ = segment_nfz(sp, return_pos)
ewh2 = dwh2 * (1 + payload)
need = max(0.0, ewh2 - bat_at)
ct = math.ceil(need / CHARGE_RATE) if need > EPS else 0
bat_after = min(BATTERY_MAX, bat_at + ct * CHARGE_RATE)
if bat_after < ewh2 - EPS:
continue
w2 = compute_wait(sp, return_pos, t_at + ct)
if w2 == float('inf'):
continue
te = t_at + ct + w2 + dwh2
tot_e = energy + es + ewh2
if best is None or te < best[0]:
best = (te, sp, w1, ds, es, ct, w2, dwh2, ewh2, bat_at, tot_e)
if best is None:
return None
te, sp, w1, ds, es, ct, w2, dwh2, ewh2, bat_at, tot_e = best
ev2 = events[:]
if w1 > EPS:
ev2.append(('WAIT', pos, t, w1))
ev2.append(('GO', pos, sp, t + w1))
ev2.append(('CHARGE', sp, t + w1 + ds))
ev2.append(('CHARGE_COMPLETE', sp, t + w1 + ds + ct))
if w2 > EPS:
ev2.append(('WAIT', sp, t + w1 + ds + ct, w2))
ev2.append(('RETURN_LEG', sp, return_pos, t + w1 + ds + ct + w2))
return {
'events': ev2, 'end_time': te, 'energy': tot_e,
'used_station': sp,
}
# ---------- ordering heuristics ----------
def order_nn(start, items):
rem = items[:]
out = []
cur = start
while rem:
i = min(range(len(rem)), key=lambda k: dist(cur, (rem[k]['x'], rem[k]['y'])))
out.append(rem.pop(i))
cur = (out[-1]['x'], out[-1]['y'])
return out
def two_opt(start, route, end, max_passes=3):
if len(route) < 3:
return route
r = route[:]
n = len(r)
for _ in range(max_passes):
improved = False
pts = [start] + [(d['x'], d['y']) for d in r] + [end]
for i in range(n - 1):
for j in range(i + 1, n):
a, b = pts[i], pts[i + 1]
c, d_ = pts[j + 1], pts[j + 2]
d_old = dist(a, b) + dist(c, d_)
# after reverse [i..j]: edges a-pts[j+1?] ... actually swap
new_b = pts[j + 1] if False else (r[j]['x'], r[j]['y']) if j < n else end
# Use straightforward reversal cost: edges become a-pts[j+1] and pts[i+1]-c
pts_after_b = (r[j]['x'], r[j]['y'])
pts_after_c = (r[i]['x'], r[i]['y'])
d_new = dist(a, pts_after_b) + dist(pts_after_c, d_)
if d_new + EPS < d_old:
r = r[:i] + r[i:j + 1][::-1] + r[j + 1:]
pts = [start] + [(x['x'], x['y']) for x in r] + [end]
improved = True
if not improved:
break
return r
def gen_orderings(start, items, end):
"""Generate a few candidate orderings."""
cands = []
# 1) Nearest-neighbor + 2opt
nn = order_nn(start, items)
cands.append(two_opt(start, nn, end))
# 2) Heaviest-first then NN
hw = sorted(items, key=lambda d: -d['weight'])
cands.append(two_opt(start, hw, end))
# 3) Tightest-deadline first
dl = sorted(items, key=lambda d: d['deadline'])
cands.append(two_opt(start, dl, end))
# 4) For tiny sets, brute force all permutations
if len(items) <= 5:
for perm in itertools.permutations(items):
cands.append(list(perm))
# Dedupe
seen = set()
uniq = []
for c in cands:
key = tuple(d['id'] for d in c)
if key not in seen:
seen.add(key)
uniq.append(c)
return uniq
# ---------- trip planner ----------
def plan_trip(start_pos, start_time, start_battery, candidates,
max_payload, return_pos):
"""
Try many subsets/orderings of candidates; return best (events, end_time,
energy, deliveries) by trip-score:
score = n*100 - energy*0.1 - (end_time - start_time)*0.05
"""
if not candidates:
return None
best = None
def consider(items):
nonlocal best
if not items:
return
for ordered in gen_orderings(start_pos, items, return_pos):
res = simulate(start_pos, start_time, start_battery,
ordered, max_payload, return_pos)
if res is None:
continue
n = len(ordered)
duration = res['end_time'] - start_time
score = n * 100 - res['energy'] * 0.1 - duration * 0.05
if best is None or score > best['score']:
best = {
'score': score,
'events': res['events'],
'end_time': res['end_time'],
'energy': res['energy'],
'deliveries': ordered,
}
# Sort candidates by closeness + deadline urgency
cand_sorted = sorted(candidates,
key=lambda d: dist(start_pos, (d['x'], d['y'])) + 0.001 * d['deadline'])
# Try shrinking trips: take top-K nearest, fitting payload
# plus subsets of small candidate pools
K = min(len(cand_sorted), 8)
pool = cand_sorted[:K]
# Greedy max-fit by weight
fit = []
wsum = 0.0
for d in pool:
if wsum + d['weight'] <= max_payload + EPS:
fit.append(d)
wsum += d['weight']
# Try the greedy fit and progressively shrink
cur = fit[:]
while cur:
consider(cur)
cur.pop() # drop farthest/last
# Also try just the closest single delivery (very common winner for
# large grids with tight deadlines)
for d in pool[:3]:
consider([d])
# Try all small subsets (up to size 3) of the closest pool
if len(pool) <= 6:
for size in range(1, min(len(pool), 4) + 1):
for combo in itertools.combinations(pool, size):
if sum(x['weight'] for x in combo) <= max_payload + EPS:
consider(list(combo))
return best
# ---------- emit JSON entries ----------
def emit_path(drone_id, trip, drone_state, picked_ids):
path = drone_state['path']
t0 = drone_state['t']
path.append({"x": WH[0], "y": WH[1], "t": round(t0, 4),
"action": "PICKUP",
"delivery_ids": picked_ids})
for ev in trip['events']:
kind = ev[0]
if kind == 'WAIT':
_, pos, t, dur = ev
path.append({"x": pos[0], "y": pos[1], "t": round(t, 4), "action": "WAIT"})
path.append({"x": pos[0], "y": pos[1], "t": round(t + dur, 4),
"action": "WAYPOINT"})
elif kind == 'DELIVER':
_, d, t = ev
path.append({"x": d['x'], "y": d['y'], "t": round(t, 4),
"action": "DELIVER", "delivery_id": d['id']})
elif kind == 'GO':
_, _src, _dst, _t = ev
# No explicit waypoint needed; CHARGE entry will follow.
elif kind == 'CHARGE':
_, pos, t = ev
path.append({"x": pos[0], "y": pos[1], "t": round(t, 4), "action": "CHARGE"})
elif kind == 'CHARGE_COMPLETE':
_, pos, t = ev
path.append({"x": pos[0], "y": pos[1], "t": round(t, 4),
"action": "CHARGE_COMPLETE"})
elif kind == 'RETURN_LEG':
# The actual RETURN waypoint is appended below.
pass
path.append({"x": WH[0], "y": WH[1], "t": round(trip['end_time'], 4),
"action": "RETURN"})
drone_state['t'] = trip['end_time']
# ---------- main scheduling loop ----------
drone_state = {d['id']: {'t': 0.0, 'path': [], 'max_payload': d['max_payload']}
for d in drones}
unassigned = {d['id']: d for d in deliveries}
MAX_TRIPS = 500
dead_drones = set()
for _ in range(MAX_TRIPS):
if not unassigned:
break
# Pick drone with smallest free time among non-dead drones
live = [d for d in drones if d['id'] not in dead_drones]
if not live:
break
drone = min(live, key=lambda d: drone_state[d['id']]['t'])
st = drone_state[drone['id']]
cands = list(unassigned.values())
# Filter by payload feasibility
cands = [d for d in cands if d['weight'] <= drone['max_payload'] + EPS]
if not cands:
dead_drones.add(drone['id'])
continue
trip = plan_trip(WH, st['t'], BATTERY_MAX, cands,
drone['max_payload'], WH)
if trip is None:
dead_drones.add(drone['id'])
continue
picked_ids = [d['id'] for d in trip['deliveries']]
emit_path(drone['id'], trip, st, picked_ids)
for did in picked_ids:
unassigned.pop(did, None)
flight_manifest = []
for d in drones:
st = drone_state[d['id']]
if st['path']:
flight_manifest.append({"drone_id": d['id'], "path": st['path']})
return flight_manifest
result = solve(warehouse, drones, deliveries, no_fly_zones, charging_stations)
output = {"flight_manifest": result}
print(json.dumps(output))