-
Notifications
You must be signed in to change notification settings - Fork 23
/
darp.py
executable file
·408 lines (327 loc) · 16.4 KB
/
darp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import numpy as np
import copy
import sys
import cv2
from Visualization import darp_area_visualization
import time
import random
import os
from numba import njit
np.set_printoptions(threshold=sys.maxsize)
random.seed(1)
os.environ['PYTHONHASHSEED'] = str(1)
np.random.seed(1)
@njit(fastmath=True)
def assign(droneNo, rows, cols, GridEnv, MetricMatrix, A):
ArrayOfElements = np.zeros(droneNo)
for i in range(rows):
for j in range(cols):
if GridEnv[i, j] == -1:
minV = MetricMatrix[0, i, j]
indMin = 0
for r in range(droneNo):
if MetricMatrix[r, i, j] < minV:
minV = MetricMatrix[r, i, j]
indMin = r
A[i, j] = indMin
ArrayOfElements[indMin] += 1
elif GridEnv[i, j] == -2:
A[i, j] = droneNo
return A, ArrayOfElements
@njit(fastmath=True)
def inverse_binary_map_as_uint8(BinaryMap):
# cv2.distanceTransform needs input of dtype unit8 (8bit)
return np.logical_not(BinaryMap).astype(np.uint8)
@njit(fastmath=True)
def euclidian_distance_points2d(array1: np.array, array2: np.array) -> np.float_:
# this runs much faster than the (numba) np.linalg.norm and is totally enough for our purpose
return (
((array1[0] - array2[0]) ** 2) +
((array1[1] - array2[1]) ** 2)
) ** 0.5
@njit(fastmath=True)
def constructBinaryImages(A, robo_start_point, rows, cols):
BinaryRobot = np.copy(A)
BinaryNonRobot = np.copy(A)
for i in range(rows):
for j in range(cols):
if A[i, j] == A[robo_start_point]:
BinaryRobot[i, j] = 1
BinaryNonRobot[i, j] = 0
elif A[i, j] != 0:
BinaryRobot[i, j] = 0
BinaryNonRobot[i, j] = 1
return BinaryRobot, BinaryNonRobot
@njit(fastmath=True)
def CalcConnectedMultiplier(rows, cols, dist1, dist2, CCvariation):
returnM = np.zeros((rows, cols))
MaxV = 0
MinV = 2**30
for i in range(rows):
for j in range(cols):
returnM[i, j] = dist1[i, j] - dist2[i, j]
if MaxV < returnM[i, j]:
MaxV = returnM[i, j]
if MinV > returnM[i, j]:
MinV = returnM[i, j]
for i in range(rows):
for j in range(cols):
returnM[i, j] = (returnM[i, j]-MinV)*((2*CCvariation)/(MaxV - MinV)) + (1-CCvariation)
return returnM
class DARP:
def __init__(self, nx, ny, notEqualPortions, given_initial_positions, given_portions, obstacles_positions,
visualization, MaxIter=80000, CCvariation=0.01,
randomLevel=0.0001, dcells=2,
importance=False):
self.rows = nx
self.cols = ny
self.initial_positions, self.obstacles_positions, self.portions = self.sanity_check(given_initial_positions, given_portions, obstacles_positions, notEqualPortions)
self.visualization = visualization
self.MaxIter = MaxIter
self.CCvariation = CCvariation
self.randomLevel = randomLevel
self.dcells = dcells
self.importance = importance
self.notEqualPortions = notEqualPortions
print("\nInitial Conditions Defined:")
print("Grid Dimensions:", nx, ny)
print("Number of Robots:", len(self.initial_positions))
print("Initial Robots' positions", self.initial_positions)
print("Portions for each Robot:", self.portions, "\n")
self.empty_space = []
if self.rows > self.cols:
for j in range(self.cols, self.rows):
for i in range(self.rows):
self.empty_space.append((i, j))
self.cols = self.rows
elif self.cols > self.rows:
for j in range(self.rows, self.cols):
for i in range(self.cols):
self.empty_space.append((j, i))
self.rows = self.cols
self.droneNo = len(self.initial_positions)
self.A = np.zeros((self.rows, self.cols))
self.defineGridEnv()
self.connectivity = np.zeros((self.droneNo, self.rows, self.cols))
self.BinaryRobotRegions = np.zeros((self.droneNo, self.rows, self.cols), dtype=bool)
self.AllDistances, self.termThr, self.Notiles, self.DesireableAssign, self.TilesImportance, self.MinimumImportance, self.MaximumImportance= self.construct_Assignment_Matrix()
self.MetricMatrix = copy.deepcopy(self.AllDistances)
self.ArrayOfElements = np.zeros(self.droneNo)
self.color = []
for r in range(self.droneNo):
np.random.seed(r)
self.color.append(list(np.random.choice(range(256), size=3)))
np.random.seed(1)
if self.visualization:
self.assignment_matrix_visualization = darp_area_visualization(self.A, self.droneNo, self.color, self.initial_positions)
def sanity_check(self, given_initial_positions, given_portions, obs_pos, notEqualPortions):
initial_positions = []
for position in given_initial_positions:
if position < 0 or position >= self.rows * self.cols:
print("Initial positions should be inside the Grid.")
sys.exit(1)
initial_positions.append((position // self.cols, position % self.cols))
obstacles_positions = []
for obstacle in obs_pos:
if obstacle < 0 or obstacle >= self.rows * self.cols:
print("Obstacles should be inside the Grid.")
sys.exit(2)
obstacles_positions.append((obstacle // self.cols, obstacle % self.cols))
portions = []
if notEqualPortions:
portions = given_portions
else:
for drone in range(len(initial_positions)):
portions.append(1 / len(initial_positions))
if len(initial_positions) != len(portions):
print("Portions should be defined for each drone")
sys.exit(3)
s = sum(portions)
if abs(s - 1) >= 0.0001:
print("Sum of portions should be equal to 1.")
sys.exit(4)
for position in initial_positions:
for obstacle in obstacles_positions:
if position[0] == obstacle[0] and position[1] == obstacle[1]:
print("Initial positions should not be on obstacles")
sys.exit(5)
return initial_positions, obstacles_positions, portions
def defineGridEnv(self):
self.GridEnv = np.full(shape=(self.rows, self.cols), fill_value=-1) # create non obstacle map with value -1
# obstacle tiles value is -2
for idx, obstacle_pos in enumerate(self.obstacles_positions):
self.GridEnv[obstacle_pos[0], obstacle_pos[1]] = -2
for idx, es_pos in enumerate(self.empty_space):
self.GridEnv[es_pos] = -2
connectivity = np.zeros((self.rows, self.cols))
mask = np.where(self.GridEnv == -1)
connectivity[mask[0], mask[1]] = 255
image = np.uint8(connectivity)
num_labels, labels_im = cv2.connectedComponents(image, connectivity=4)
if num_labels > 2:
print("The environment grid MUST not have unreachable and/or closed shape regions")
sys.exit(6)
# initial robot tiles will have their array.index as value
for idx, robot in enumerate(self.initial_positions):
self.GridEnv[robot] = idx
self.A[robot] = idx
return
def divideRegions(self):
success = False
cancelled = False
criterionMatrix = np.zeros((self.rows, self.cols))
iteration = 0
while self.termThr <= self.dcells and not success and not cancelled:
downThres = (self.Notiles - self.termThr*(self.droneNo-1))/(self.Notiles*self.droneNo)
upperThres = (self.Notiles + self.termThr)/(self.Notiles*self.droneNo)
success = True
# Main optimization loop
while iteration <= self.MaxIter and not cancelled:
self.A, self.ArrayOfElements = assign(self.droneNo,
self.rows,
self.cols,
self.GridEnv,
self.MetricMatrix,
self.A)
ConnectedMultiplierList = np.ones((self.droneNo, self.rows, self.cols))
ConnectedRobotRegions = np.zeros(self.droneNo)
plainErrors = np.zeros((self.droneNo))
divFairError = np.zeros((self.droneNo))
for r in range(self.droneNo):
ConnectedMultiplier = np.ones((self.rows, self.cols))
ConnectedRobotRegions[r] = True
self.update_connectivity()
image = np.uint8(self.connectivity[r, :, :])
num_labels, labels_im = cv2.connectedComponents(image, connectivity=4)
if num_labels > 2:
ConnectedRobotRegions[r] = False
BinaryRobot, BinaryNonRobot = constructBinaryImages(labels_im, self.initial_positions[r], self.rows, self.cols)
ConnectedMultiplier = CalcConnectedMultiplier(self.rows, self.cols,
self.NormalizedEuclideanDistanceBinary(True, BinaryRobot, BinaryNonRobot),
self.NormalizedEuclideanDistanceBinary(False, BinaryRobot, BinaryNonRobot),self.CCvariation)
ConnectedMultiplierList[r, :, :] = ConnectedMultiplier
plainErrors[r] = self.ArrayOfElements[r]/(self.DesireableAssign[r]*self.droneNo)
if plainErrors[r] < downThres:
divFairError[r] = downThres - plainErrors[r]
elif plainErrors[r] > upperThres:
divFairError[r] = upperThres - plainErrors[r]
if self.IsThisAGoalState(self.termThr, ConnectedRobotRegions):
break
TotalNegPerc = 0
totalNegPlainErrors = 0
correctionMult = np.zeros(self.droneNo)
for r in range(self.droneNo):
if divFairError[r] < 0:
TotalNegPerc += np.absolute(divFairError[r])
totalNegPlainErrors += plainErrors[r]
correctionMult[r] = 1
for r in range(self.droneNo):
if totalNegPlainErrors != 0:
if divFairError[r] < 0:
correctionMult[r] = 1 + (plainErrors[r]/totalNegPlainErrors)*(TotalNegPerc/2)
else:
correctionMult[r] = 1 - (plainErrors[r]/totalNegPlainErrors)*(TotalNegPerc/2)
criterionMatrix = self.calculateCriterionMatrix(
self.TilesImportance[r],
self.MinimumImportance[r],
self.MaximumImportance[r],
correctionMult[r],
divFairError[r] < 0)
self.MetricMatrix[r] = self.FinalUpdateOnMetricMatrix(
criterionMatrix,
self.generateRandomMatrix(),
self.MetricMatrix[r],
ConnectedMultiplierList[r, :, :])
iteration += 1
if self.visualization:
self.assignment_matrix_visualization.placeCells(self.A, iteration_number=iteration)
time.sleep(0.2)
if iteration >= self.MaxIter:
self.MaxIter = self.MaxIter/2
success = False
self.termThr += 1
self.getBinaryRobotRegions()
return success, iteration
def getBinaryRobotRegions(self):
ind = np.where(self.A < self.droneNo)
temp = (self.A[ind].astype(int),)+ind
self.BinaryRobotRegions[temp] = True
def generateRandomMatrix(self):
RandomMatrix = np.zeros((self.rows, self.cols))
RandomMatrix = 2*self.randomLevel*np.random.uniform(0, 1,size=RandomMatrix.shape) + (1 - self.randomLevel)
return RandomMatrix
def FinalUpdateOnMetricMatrix(self, CM, RM, currentOne, CC):
MMnew = np.zeros((self.rows, self.cols))
MMnew = currentOne*CM*RM*CC
return MMnew
def IsThisAGoalState(self, thresh, connectedRobotRegions):
for r in range(self.droneNo):
if np.absolute(self.DesireableAssign[r] - self.ArrayOfElements[r]) > thresh or not connectedRobotRegions[r]:
return False
return True
def update_connectivity(self):
self.connectivity = np.zeros((self.droneNo, self.rows, self.cols))
for i in range(self.droneNo):
mask = np.where(self.A == i)
self.connectivity[i, mask[0], mask[1]] = 255
# Construct Assignment Matrix
def construct_Assignment_Matrix(self):
Notiles = self.rows*self.cols
fair_division = 1/self.droneNo
effectiveSize = Notiles - self.droneNo - len(self.obstacles_positions) - len(self.empty_space)
termThr = 0
if effectiveSize % self.droneNo != 0:
termThr = 1
DesireableAssign = np.zeros(self.droneNo)
MaximunDist = np.zeros(self.droneNo)
MaximumImportance = np.zeros(self.droneNo)
MinimumImportance = np.zeros(self.droneNo)
for i in range(self.droneNo):
DesireableAssign[i] = effectiveSize * self.portions[i]
MinimumImportance[i] = sys.float_info.max
if (DesireableAssign[i] != int(DesireableAssign[i]) and termThr != 1):
termThr = 1
AllDistances = np.zeros((self.droneNo, self.rows, self.cols))
TilesImportance = np.zeros((self.droneNo, self.rows, self.cols))
for x in range(self.rows):
for y in range(self.cols):
tempSum = 0
for r in range(self.droneNo):
AllDistances[r, x, y] = euclidian_distance_points2d(np.array(self.initial_positions[r]), np.array((x, y))) # E!
if AllDistances[r, x, y] > MaximunDist[r]:
MaximunDist[r] = AllDistances[r, x, y]
tempSum += AllDistances[r, x, y]
for r in range(self.droneNo):
if tempSum - AllDistances[r, x, y] != 0:
TilesImportance[r, x, y] = 1/(tempSum - AllDistances[r, x, y])
else:
TilesImportance[r, x, y] = 1
# Todo FixMe!
if TilesImportance[r, x, y] > MaximumImportance[r]:
MaximumImportance[r] = TilesImportance[r, x, y]
if TilesImportance[r, x, y] < MinimumImportance[r]:
MinimumImportance[r] = TilesImportance[r, x, y]
return AllDistances, termThr, Notiles, DesireableAssign, TilesImportance, MinimumImportance, MaximumImportance
def calculateCriterionMatrix(self, TilesImportance, MinimumImportance, MaximumImportance, correctionMult, smallerthan_zero,):
returnCrit = np.zeros((self.rows, self.cols))
if self.importance:
if smallerthan_zero:
returnCrit = (TilesImportance- MinimumImportance)*((correctionMult-1)/(MaximumImportance-MinimumImportance)) + 1
else:
returnCrit = (TilesImportance- MinimumImportance)*((1-correctionMult)/(MaximumImportance-MinimumImportance)) + correctionMult
else:
returnCrit[:, :] = correctionMult
return returnCrit
def NormalizedEuclideanDistanceBinary(self, RobotR, BinaryRobot, BinaryNonRobot):
if RobotR:
distRobot = cv2.distanceTransform(inverse_binary_map_as_uint8(BinaryRobot), distanceType=2, maskSize=0, dstType=5)
else:
distRobot = cv2.distanceTransform(inverse_binary_map_as_uint8(BinaryNonRobot), distanceType=2, maskSize=0, dstType=5)
MaxV = np.max(distRobot)
MinV = np.min(distRobot)
#Normalization
if RobotR:
distRobot = (distRobot - MinV)*(1/(MaxV-MinV)) + 1
else:
distRobot = (distRobot - MinV)*(1/(MaxV-MinV))
return distRobot