-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMain-fs.py
525 lines (388 loc) · 19.3 KB
/
Main-fs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 13:52:40 2017
@author: mario
"""
import numpy as np
import fs_MainOptimYpakaraiLakeTSPGAWithAlgaeImprovementRate3 as OptimGA
import fs_Algae_Sampled_grid_creator_project2 as AB_est
import fs_CalculoCoberturaTemporal as AB_sampled
import parameters_opt_ga as param
#import parameters_fullstrategy as param2
import time
import csv
EXPERIMENT = 'TEST'
MAX_TIME_FRAMES = 1
GROUP_EST_SIZE = 5 # AB Squares separated by more than 5 squares form a
# different AB group
FITNESS_FUNC_EXPL = 3
FITNESS_FUNC_INT = 5
PHASE_SIZE_THR = 0.75
EXPL_PH = 0
INT_PH = 1
HYB_PH = 2
def find_samp_coord(samp_grid):
"Halla las coordenadas de los cuadros con algas muestreados"
samp_grid_coord = []
for idx,element in enumerate(samp_grid):
for idx2, element2 in enumerate(element):
if element2:
samp_grid_coord.append([idx,idx2])
return samp_grid_coord
def find_ab_groups(samp_grid_coord):
ab_groups = [[samp_grid_coord[0]]]
ab_id = 0
for idx2, elements in enumerate(samp_grid_coord):
if idx2 > 0:
diff_flag = 0
for idx3,elements2 in enumerate(ab_groups[ab_id]):
#==============================================================================
# print 'Samp grid', elements
# print 'AB groups', elements2, ab_groups
# print elements[0], elements2[0], elements[1],elements2[1]
#==============================================================================
if (abs(elements[0]-elements2[0]))< GROUP_EST_SIZE and (
abs(elements[1]-elements2[1]))<GROUP_EST_SIZE:
ab_groups[ab_id].append(elements)
break
if idx3 == (len(ab_groups[ab_id])-1):
diff_flag = 1
if diff_flag ==1:
ab_groups.append([elements])
ab_id += 1
# else:
# ab_groups.append(elements)
# idx += 1
# print 'Len ab_groups', len(ab_groups)
ab_groups_sizes = []
for elements in ab_groups:
ab_groups_sizes.append(len(elements))
return ab_groups, ab_groups_sizes
def select_beacons_subgroup(ab_groups):
"Select a group of beacons based on the AB localization"
subgroup_beacons = set()
for idx,ab_elements in enumerate(ab_groups):
ab_side = 0
x_min, y_min = np.min(ab_elements, axis = 0)*param.GRID_SIZE
x_max, y_max = np.max(ab_elements, axis = 0)*param.GRID_SIZE
x_max += param.GRID_SIZE
y_max += param.GRID_SIZE
ab_side = y_max - y_min
for idx2,beacon_elements in enumerate(param.list_coord):
# print beacon_elements
if y_min - ab_side <= int(beacon_elements[1]) <= y_max + ab_side:
subgroup_beacons.add(idx2)
return list(subgroup_beacons)
def ab_evaluation(samp_grid_loc, ab_groups_sizes_loc, prev_ab_groups_sizes_loc,
arr_beacons_loc,ab_flag_loc,samp_grid_coord_loc,
fitness_function_loc, hybrid_count_loc, strategy_phase_loc,
time_frames_loc):
"Evaluate the conditions of the AB and selects the next phase accordingly"
# global hybrid_count
# global strategy_phase
# global time_frame
# print strategy_phase
ab_increase_flag_loc = 0
ab_groups,ab_groups_sizes = find_ab_groups(samp_grid_coord_loc)
if np.sum(samp_grid_loc) != 0:
for idx in range(len(ab_groups_sizes)-len(prev_ab_groups_sizes_loc)):
prev_ab_groups_sizes_loc.append(0) # Para comparar listas con igual longitud
print 'ab_groups size', ab_groups_sizes
print 'prev_ab_groups_sizes', prev_ab_groups_sizes_loc
for idx, ab_size in enumerate(ab_groups_sizes):
print '== ab_size, prev_groups_sizes[idx]', ab_size, prev_ab_groups_sizes_loc[idx]
if ab_size>prev_ab_groups_sizes_loc[idx]:
ab_increase_flag_loc = 1
break
if ab_increase_flag_loc == 1:
if strategy_phase_loc == INT_PH:
print 'Remain in Intensification Phase'
else:
print 'Moving to Intensification Phase'
strategy_phase_loc = INT_PH
# print 'strategy', strategy_phase
fitness_function_loc = FITNESS_FUNC_INT#Cambiar de posicion
hybrid_count_loc = 0
print 'Before', arr_beacons_loc, len(arr_beacons_loc)
arr_beacons_loc = np.array(select_beacons_subgroup(ab_groups))
print 'After', arr_beacons_loc, len(arr_beacons_loc)
else:
if strategy_phase_loc == HYB_PH:
print 'Remain in Hybrid Phase'
else:
print 'Moving to Hybrid Phase'
strategy_phase_loc = HYB_PH
fitness_function_loc = FITNESS_FUNC_INT
hybrid_count_loc += 1
#==============================================================================
# ab_flag_loc == 1
#
# for idx in range(len(ab_groups_sizes)-len(prev_ab_groups_sizes_loc)):
# prev_ab_groups_sizes_loc.append(0) # Para comparar listas con igual longitud
#
# print 'ab_groups size', ab_groups_sizes
# print 'prev_ab_groups_sizes', prev_ab_groups_sizes_loc
#
# for idx, ab_size in enumerate(ab_groups_sizes):
# print 'ab_size, prev_groups_sizes[idx]', ab_size, prev_ab_groups_sizes[idx]
#
#
# if ab_flag_loc == 0:
# print 'Moving to Intensification Phase'
# else:
# print 'Remain in Intensification Phase'
#
#
#
# if ab_flag_loc == 0:
#
#
# ab_increase_flag_loc = 1
#
# print 'Before', arr_beacons_loc, len(arr_beacons_loc)
# arr_beacons_loc = np.array(select_beacons_subgroup(ab_groups))
# fitness_function_loc = FITNESS_FUNC_INT
# print 'After', arr_beacons_loc, len(arr_beacons_loc)
#
# else:
# print 'Remain in Intensification Phase'
#
# for idx in range(len(ab_groups_sizes)-len(prev_ab_groups_sizes_loc)):
# prev_ab_groups_sizes_loc.append(0) # Para comparar listas con igual longitud
#
# print 'ab_groups size', ab_groups_sizes
# print 'prev_ab_groups_sizes', prev_ab_groups_sizes_loc
#
# for idx, ab_size in enumerate(ab_groups_sizes):
# print 'ab_size, prev_groups_sizes[idx]', ab_size, prev_ab_groups_sizes[idx]
#
# if ab_size<=PHASE_SIZE_THR*prev_ab_groups_sizes_loc[idx]:
#
# print 'Moving to Exploratory Phase'
# ab_increase_flag_loc = 0
# fitness_function_loc = FITNESS_FUNC_EXPL
# arr_beacons_loc = np.arange(60,dtype='uint8')
#
# break # Evaluar
#
#
#
# print 'Remain in intensification Phase'
# ab_increase_flag_loc = 1
# fitness_function_loc = FITNESS_FUNC_INT
#
# print 'Before', arr_beacons_loc, len(arr_beacons_loc)
# arr_beacons_loc = np.array(select_beacons_subgroup(ab_groups))
# print 'After', arr_beacons_loc, len(arr_beacons_loc)
#==============================================================================
else:
if strategy_phase_loc == EXPL_PH:
print 'Remain in Exploratory Phase'
else:
print 'Moving to Exploratory Phase'
ab_flag_loc = 0
# ab_increase_flag_loc = 0
fitness_function_loc = FITNESS_FUNC_EXPL #Cambiar de POSICION!!
arr_beacons_loc = np.arange(60,dtype='uint8')
np.savetxt('Results/sub_group_beacons_exp'+str(EXPERIMENT)+'_'+str(
time_frames_loc)+'.csv', arr_beacons_loc, fmt = '%i', delimiter=",")
prev_ab_groups_sizes_loc = ab_groups_sizes
print 'Prev_ab_group_sizes', prev_ab_groups_sizes_loc, ab_groups_sizes
return (ab_flag_loc,ab_increase_flag_loc, arr_beacons_loc, fitness_function_loc,
prev_ab_groups_sizes_loc, hybrid_count_loc, strategy_phase_loc)
def main():
####Initial Parameters Definition
print '=====START MAIN ROUTINE====='
print time.ctime()
'''
Fitness Function Options
------------------------
1 - Death Penalty + Penalty Factor -- km2
2 - Penalty Factor -- coverage %
3 - Exponential Penalty Factor -- coverage %
4 - Penalty Factor -- size km2
5 - Penalty Factor -- ROI exponential
6 - Death Penalty -- ROI
7 - Death Penalty -- coefficient of variation
8 - Penalty Factor -- coefficient of variation
9 - Penalty Factor -- ROI dstributed
'''
ab_flag = 0
ab_increase_flag = 0
strategy_phase = EXPL_PH
print 'strategy', strategy_phase
hybrid_count = 0
time_frames = 0 # number of time frames executed
arr_beacons = np.arange(60,dtype='uint8')
ab_conditions_coord = []
ab_groups_sizes = []
prev_ab_groups_sizes = []
fitness_function = FITNESS_FUNC_EXPL
OptimGA.print_parameters() # Impresion de parametros del algoritmo genetico
####Creacion de comportamiento dinamico de AB en max_time_frames
for idx in range(MAX_TIME_FRAMES):
ab_conditions_coord.append(np.loadtxt('Data/ab_conditions'+str(idx)+'_coord.csv',
dtype = 'uint8', delimiter =','))
#####Creacion de samp grid sin datos
samp_grid = np.zeros((param.GRID_X_DIV,param.GRID_Y_DIV),
dtype = 'uint16')
arr_routes_AB_est_intersec= np.zeros((param.N_BEACON,param.N_BEACON),
dtype = 'uint16')
####Print parameters
print "MAIN PROGRAM PARAMETERS"
print 'Experiment No. = ', EXPERIMENT
print 'Max Time Frames = ', MAX_TIME_FRAMES
print 'Bloom Margin Distance (No. of Squares Side) =', GROUP_EST_SIZE
print 'Fitness Function Exploration =',FITNESS_FUNC_EXPL
print 'Fitness Function Intensification =', FITNESS_FUNC_INT
print '========================================================================'
while time_frames < MAX_TIME_FRAMES:
real_AB = np.loadtxt('Data/ab_conditions'+str(time_frames)+'_pattern.csv',
dtype = 'uint8', delimiter =',')
print '\n'
print 'TIME FRAME ', time_frames
print '=============='
print 'strategy', strategy_phase
if strategy_phase == EXPL_PH:
print 'EXPLORATORY PHASE'
print '------Reset Route-AB Intersec Matrix'
print '\n'
arr_routes_AB_est_intersec = np.zeros((param.N_BEACON,param.N_BEACON),
dtype = 'uint16')
dict_routes_AB_est_intersec = {}
best_indiv = OptimGA.main(fitness_function, arr_beacons,
arr_routes_AB_est_intersec,
dict_routes_AB_est_intersec)
else:
print '-------Find Route-AB Intersec Matrix'
arr_routes_AB_est_intersec, dict_routes_AB_est_intersec = AB_est.main(samp_grid) # Routes between
# beacons and Estimated
# (sampled) AB intersections
# matrix
print 'INTENSIFICATION PHASE'
print '\n'
best_indiv = OptimGA.main(fitness_function, arr_beacons,
arr_routes_AB_est_intersec,
dict_routes_AB_est_intersec)
# =================TO BE USED WITH MULTIOBJECTIVE ==============================
#
#
# if strategy_phase == HYB_PH:
# print 'HYBRID PHASE'
# print '\n'
#
# best_indiv = OptimGA.main(fitness_function, arr_beacons,
# arr_routes_AB_est_intersec,
# dict_routes_AB_est_intersec)#REPLACE BY MOGA LATER!!
#
# else:
# print 'INTENSIFICATION PHASE'
# print '\n'
#
# best_indiv = OptimGA.main(fitness_function, arr_beacons,
# arr_routes_AB_est_intersec,
# dict_routes_AB_est_intersec)
#
# =============================================================================
print 'strategy', strategy_phase
with open('Results/dict_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv', 'wb') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict_routes_AB_est_intersec.items():
writer.writerow([key, value])
np.savetxt('Results/arr_routes_AB_est_intersec_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv',
arr_routes_AB_est_intersec, fmt = '%i', delimiter=",")
np.savetxt('Results/best_indiv_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv',
best_indiv, fmt = '%i', delimiter=",")
#==============================================================================
# if ab_flag:
# print 'INTENSIFICATION PHASE'
# print '------Find Route-AB Intersec Matrix'
# print '\n'
# arr_routes_AB_est_intersec, dict_routes_AB_est_intersec = AB_est.main(samp_grid) # Routes between
# # beacons and Estimated
# # (sampled) AB intersections
# # matrix
# with open('Results/dict_exp'+str(EXPERIMENT)+str(time_frames)+'.csv', 'wb') as csv_file:
# writer = csv.writer(csv_file)
# for key, value in dict_routes_AB_est_intersec.items():
# writer.writerow([key, value])
#
# else:
# print 'EXPLORATORY PHASE'
# print '------Reset Route-AB Intersec Matrix'
# print '\n'
# arr_routes_AB_est_intersec = np.zeros((param.N_BEACON,param.N_BEACON),
# dtype = 'uint16')
# dict_routes_AB_est_intersec = {}
#
#
# np.savetxt('Results/arr_routes_AB_est_intersec_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv',
# arr_routes_AB_est_intersec, fmt = '%i', delimiter=",")
# # Used in intensification phase
# print '------ Genetic Algorithm'
# # print arr_routes_AB_est_intersec
#
# best_indiv = OptimGA.main(
# fitness_function, arr_beacons, arr_routes_AB_est_intersec,
# dict_routes_AB_est_intersec)
#
# np.savetxt('Results/best_indiv_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv',
# best_indiv, fmt = '%i', delimiter=",")
#==============================================================================
print '------ Path Execution and Sampling Evaluation'
samp_grid = AB_sampled.main(best_indiv, ab_conditions_coord[time_frames])
np.savetxt('Results/samp_grid_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv', samp_grid,
fmt = '%i', delimiter=",")
for idx,element_x in enumerate(samp_grid):
for idx2,element_y in enumerate(element_x):
# print idx, idx2, element_y
if element_y != 0:
param.samp_pattern[idx][idx2] = 1
# print 'This'
else:
param.samp_pattern[idx][idx2] = 0
np.savetxt('Results/samp_pattern_exp'+str(EXPERIMENT)+'_'+str(time_frames)+'.csv', param.samp_pattern,
fmt = '%i', delimiter=",")
# FIND SAMP COORDINATES
# SEPARATE IN GROUPS
samp_grid_coord = find_samp_coord(samp_grid)
# print samp_grid_coord
# print "AB groups", ab_groups
print 'strategy', strategy_phase
print 'Sum samp_grid', np.sum(samp_grid)
print 'Non zero sampling', np.count_nonzero(samp_grid)
print 'Non zero real AB', np.count_nonzero(real_AB)
print 'strategy', strategy_phase
(ab_flag, ab_increase_flag, arr_beacons, fitness_function,
prev_ab_groups_sizes,hybrid_count,strategy_phase) = ab_evaluation(
samp_grid, ab_groups_sizes, prev_ab_groups_sizes, arr_beacons,
ab_flag,samp_grid_coord,fitness_function, hybrid_count,
strategy_phase,time_frames)
print 'strategy', strategy_phase
# if np.sump(samp_grid) != 0 and np.sum(samp_grid) > ab_size:
# ab_size = np.sum(samp_grid)
# fitness_function ==2
# arr_subgroup = select_subgroup()
# np.savetxt('', samp_grid, fmt = '%i', delimiter=",")
#
#==============================================================================
time_frames += 1
print '=====END MAIN ROUTINE====='
print time.ctime()
if __name__ == '__main__':
main()
#==============================================================================
# samp_grid = np.loadtxt(
# 'Results/samp_grid_exp15_0.csv', dtype = 'uint8', delimiter =',')
#
# for idx,element_x in enumerate(samp_grid):
# for idx2,element_y in enumerate(element_x):
# # print idx, idx2, element_y
# if element_y != 0:
# param.samp_pattern[idx][idx2]=1
#
# arr_routes_AB_est_intersec, dict_routes_AB_est_intersec = AB_est.main(
# samp_grid)
#
#==============================================================================