-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathselect_sensor.py
More file actions
2135 lines (1864 loc) · 95 KB
/
select_sensor.py
File metadata and controls
2135 lines (1864 loc) · 95 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Select sensor and detect transmitter
'''
import random
import math
import copy
import time
import os
import numpy as np
import pandas as pd
from numba import cuda
from scipy.spatial import distance
from scipy.stats import multivariate_normal, norm
from joblib import Parallel, delayed, dump, load
from sensor import Sensor
from transmitter import Transmitter
from utility import read_config, ordered_insert#, print_results
#from cuda_kernals import o_t_approx_kernal, o_t_kernal, o_t_approx_dist_kernal
import plots
class SelectSensor:
'''Near-optimal low-cost sensor selection
Attributes:
config (json): configurations - settings and parameters
sen_num (int): the number of sensors
grid_len (int): the length of the grid
grid_priori (np.ndarray): the element is priori probability of hypothesis - transmitter
grid_posterior (np.ndarray): the element is posterior probability of hypothesis - transmitter
transmitters (list): a list of Transmitter
sensors (dict): a dictionary of Sensor. less than 10% the # of transmitter
data (ndarray): a 2D array of observation data
covariance (np.ndarray): a 2D array of covariance. each data share a same covariance matrix
mean_stds (dict): assume sigal between a transmitter-sensor pair is normal distributed
subset (dict): a subset of all sensors
subset_index (list): the linear index of sensor in self.sensors
meanvec_array (np.ndarray): contains the mean vector of every transmitter, for CUDA
TPB (int): thread per block
'''
def __init__(self, filename):
self.config = read_config(filename)
self.sen_num = int(self.config["sensor_number"])
self.grid_len = int(self.config["grid_length"])
self.discre_x_file = self.config["discretized_x_file"]
self.grid_priori = np.zeros(0)
self.grid_posterior = np.zeros(0)
self.transmitters = []
self.sensors = []
self.data = np.zeros(0)
self.covariance = np.zeros(0)
self.init_transmitters()
self.set_priori()
self.means = np.zeros(0)
self.stds = np.zeros(0)
self.subset = {}
self.subset_index = []
self.meanvec_array = np.zeros(0)
self.TPB = 32
#@profile
def init_from_real_data(self, cov_file, sensor_file, hypothesis_file):
'''Init everything from collected real data
1. init covariance matrix
2. init sensors
3. init mean and std between every pair of transmitters and sensors
'''
cov = pd.read_csv(cov_file, header=None, delimiter=' ')
del cov[len(cov)]
self.covariance = cov.values
self.sensors = []
with open(sensor_file, 'r') as f:
max_gain = 0.5*len(self.transmitters)
index = 0
lines = f.readlines()
for line in lines:
line = line.split(' ')
x, y, std, cost = int(line[0]), int(line[1]), float(line[2]), float(line[3])
self.sensors.append(Sensor(x, y, std, cost, gain_up_bound=max_gain, index=index))
index += 1
self.means = np.zeros((self.grid_len * self.grid_len, len(self.sensors)))
self.stds = np.zeros((self.grid_len * self.grid_len, len(self.sensors)))
with open(hypothesis_file, 'r') as f:
lines = f.readlines()
count = 0
for line in lines:
line = line.split(' ')
tran_x, tran_y = int(line[0]), int(line[1])
#sen_x, sen_y = int(line[2]), int(line[3])
mean, std = float(line[4]), float(line[5])
self.means[tran_x*self.grid_len + tran_y, count] = mean # count equals to the index of the sensors
self.stds[tran_x*self.grid_len + tran_y, count] = std
count = (count + 1) % len(self.sensors)
for transmitter in self.transmitters:
tran_x, tran_y = transmitter.x, transmitter.y
mean_vec = [0] * len(self.sensors)
for sensor in self.sensors:
mean = self.means[self.grid_len*tran_x + tran_y, sensor.index]
mean_vec[sensor.index] = mean
transmitter.mean_vec = np.array(mean_vec)
#self.transmitters_to_array() # for GPU
#del self.means_stds # in 64*64 grid offline case, need to delete means_stds. otherwise exceed 4GB limit of joblib
print('init done!')
def set_priori(self):
'''Set priori distribution - uniform distribution
'''
uniform = 1./(self.grid_len * self.grid_len)
self.grid_priori = np.full((self.grid_len, self.grid_len), uniform)
self.grid_posterior = np.full((self.grid_len, self.grid_len), uniform)
def init_transmitters(self):
'''Initiate a transmitter at all locations
'''
self.transmitters = [0] * self.grid_len * self.grid_len
for i in range(self.grid_len):
for j in range(self.grid_len):
transmitter = Transmitter(i, j)
setattr(transmitter, 'hypothesis', i*self.grid_len + j)
self.transmitters[i*self.grid_len + j] = transmitter
def update_subset(self, subset_index):
'''Given a list of sensor indexes, which represents a subset of sensors, update self.subset
Args:
subset_index (list): a list of sensor indexes. guarantee sorted
'''
self.subset = []
self.subset_index = subset_index
for index in self.subset_index:
self.subset.append(self.sensors[index])
def update_transmitters(self):
'''Given a subset of sensors' index,
update each transmitter's mean vector sub and multivariate gaussian function
'''
for transmitter in self.transmitters:
transmitter.set_mean_vec_sub(self.subset_index)
new_cov = self.covariance[np.ix_(self.subset_index, self.subset_index)]
transmitter.multivariant_gaussian = multivariate_normal(mean=transmitter.mean_vec_sub, cov=new_cov)
def update_mean_vec_sub(self, subset_index):
'''Given a subset of sensors' index,
update each transmitter's mean vector sub
Args:
subset_index (list)
'''
for transmitter in self.transmitters:
transmitter.set_mean_vec_sub(subset_index)
def select_offline_random(self, number, cores):
'''Select a subset of sensors randomly
Args:
number (int): number of sensors to be randomly selected
cores (int): number of cores for parallelization
Return:
(list): results to be plotted. each element is (str, int, float),
where str is the list of selected sensors, int is # of sensor, float is O_T
'''
random.seed(0)
subset_index = []
plot_data = []
sequence = [i for i in range(self.sen_num)]
i = 1
subset_to_compute = []
while i <= number:
select = random.choice(sequence)
ordered_insert(subset_index, select)
subset_to_compute.append(copy.deepcopy(subset_index))
sequence.remove(select)
i += 1
subset_results = Parallel(n_jobs=cores)(delayed(self.inner_random)(subset_index) for subset_index in subset_to_compute)
for result in subset_results:
plot_data.append([str(result[0]), len(result[0]), result[1]])
return plot_data
def inner_random(self, subset_index):
'''Inner loop for random
'''
#o_t = self.o_t(subset_index)
o_t = self.o_t_host(subset_index)
return (subset_index, o_t)
def covariance_sub(self, subset_index):
'''Given a list of index of sensors, return the sub covariance matrix
Args:
subset_index (list): list of index of sensors. should be sorted.
Return:
(np.ndarray): a 2D sub covariance matrix
'''
sub_cov = self.covariance[np.ix_(subset_index, subset_index)]
return sub_cov
def o_t_p(self, subset_index, cores):
'''(Parallelized version of o_t function) Given a subset of sensors T, compute the O_T
Args:
subset_index (list): a subset of sensors T, guarantee sorted
cores (int): number of cores to do the parallel
Return O_T
'''
if not subset_index: # empty sequence are false
return 0
sub_cov = self.covariance_sub(subset_index)
sub_cov_inv = None
try:
sub_cov_inv = np.linalg.inv(sub_cov) # inverse
except Exception as e:
print(e)
prob = Parallel(n_jobs=cores)(delayed(self.inner_o_t)(subset_index, sub_cov_inv, transmitter_i) for transmitter_i in self.transmitters)
o_t = 0
for i in prob:
o_t += i
return o_t
def inner_o_t(self, subset_index, sub_cov_inv, transmitter_i):
'''The inner loop for o_t function (for parallelization)
'''
i_x, i_y = transmitter_i.x, transmitter_i.y
transmitter_i.set_mean_vec_sub(subset_index)
prob_i = []
for transmitter_j in self.transmitters:
j_x, j_y = transmitter_j.x, transmitter_j.y
if i_x == j_x and i_y == j_y:
continue
transmitter_j.set_mean_vec_sub(subset_index)
pj_pi = transmitter_j.mean_vec_sub - transmitter_i.mean_vec_sub
prob_i.append(1 - norm.sf(0.5 * math.sqrt(np.dot(np.dot(pj_pi, sub_cov_inv), pj_pi))))
product = 1
for i in prob_i:
product *= i
return product*self.grid_priori[i_x][i_y]
#@profile
def o_t(self, subset_index):
'''Given a subset of sensors T, compute the O_T
Args:
subset_index (list): a subset of sensors T, guarantee sorted
Return O_T
'''
if not subset_index: # empty sequence are false
return 0
sub_cov = self.covariance_sub(subset_index)
sub_cov_inv = np.linalg.inv(sub_cov) # inverse
o_t = 0
for transmitter_i in self.transmitters:
i_x, i_y = transmitter_i.x, transmitter_i.y
transmitter_i.set_mean_vec_sub(subset_index)
prob_i = 1
for transmitter_j in self.transmitters:
j_x, j_y = transmitter_j.x, transmitter_j.y
if i_x == j_x and i_y == j_y:
continue
transmitter_j.set_mean_vec_sub(subset_index)
pj_pi = transmitter_j.mean_vec_sub - transmitter_i.mean_vec_sub
prob_i *= (1 - norm.sf(0.5 * math.sqrt(np.dot(np.dot(pj_pi, sub_cov_inv), pj_pi))))
o_t += prob_i * self.grid_priori[i_x][i_y]
return o_t
def o_t_approximate(self, subset_index):
'''Not the accurate O_T, but apprioximating O_T. So that we have a good propertiy of submodular
Args:
subset_index (list): a subset of sensors T, needs guarantee sorted
'''
if not subset_index: # empty sequence are false
return -99999999999.
sub_cov = self.covariance_sub(subset_index)
sub_cov_inv = np.linalg.inv(sub_cov) # inverse
prob_error = 0 # around 3% speed up by replacing [] to float
for transmitter_i in self.transmitters:
i_x, i_y = transmitter_i.x, transmitter_i.y
transmitter_i.set_mean_vec_sub(subset_index)
prob_i = 0
for transmitter_j in self.transmitters:
j_x, j_y = transmitter_j.x, transmitter_j.y
if i_x == j_x and i_y == j_y:
continue
transmitter_j.set_mean_vec_sub(subset_index)
pj_pi = transmitter_j.mean_vec_sub - transmitter_i.mean_vec_sub
prob_i += norm.sf(0.5 * math.sqrt(np.dot(np.dot(pj_pi, sub_cov_inv), pj_pi)))
prob_error += prob_i * self.grid_priori[i_x][i_y]
return 1 - prob_error
def select_offline_greedy_p(self, budget, cores):
'''(Parallel version) Select a subset of sensors greedily. offline + homo version
Args:
budget (int): budget constraint
cores (int): number of cores for parallelzation
Return:
(list): an element is [str, int, float],
where str is the list of subset_index, int is # of sensors, float is O_T
'''
plot_data = []
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_index = [i for i in range(self.sen_num)] # S\T in the paper
subset_to_compute = []
while cost < budget and complement_index:
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy)(subset_index, candidate) for candidate in complement_index)
best_candidate = candidate_results[0][0] # an element of candidate_results is a tuple - (int, float, list)
maximum = candidate_results[0][1] # where int is the candidate, float is the O_T, list is the subset_list with new candidate
for candidate in candidate_results:
print(candidate[2], candidate[1])
if candidate[1] > maximum:
best_candidate = candidate[0]
maximum = candidate[1]
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
complement_index.remove(best_candidate)
cost += 1
subset_to_compute.append(copy.deepcopy(subset_index))
plot_data.append([len(subset_index), maximum, 0]) # don't compute real o_t now, delay to after all the subsets are selected
if maximum > 0.999:
break
subset_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy_real_ot)(subset_index) for subset_index in subset_to_compute)
for i in range(len(subset_results)):
plot_data[i][2] = subset_results[i]
return plot_data
def select_offline_greedy_p_lazy(self, budget, cores, cuda_kernal):
'''(Parallel + Lazy greedy) Select a subset of sensors greedily. offline + homo version using ** GPU **
Args:
budget (int): budget constraint
cores (int): number of cores for parallelzation
cuda_kernal (cuda_kernals.o_t_approx_kernal or o_t_approx_dist_kernal): the O_{aux} in the paper
Return:
(list): an element is [str, int, float],
where str is the list of subset_index, int is # of sensors, float is O_T
'''
counter = 0
base_ot_approx = 0
if cuda_kernal == o_t_approx_kernal:
base_ot_approx = 1 - 0.5*len(self.transmitters)
elif cuda_kernal == o_t_approx_dist_kernal:
largest_dist = (self.grid_len-1)*math.sqrt(2)
max_gain_up_bound = 0.5*len(self.transmitters)*largest_dist # the default bound is for non-distance
for sensor in self.sensors: # need to update the max gain upper bound for o_t_approx with distance
sensor.gain_up_bound = max_gain_up_bound
base_ot_approx = (1 - 0.5*len(self.transmitters))*largest_dist
plot_data = []
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_sensors = copy.deepcopy(self.sensors) # S\T in the paper
subset_to_compute = []
while cost < budget and complement_sensors:
best_candidate = complement_sensors[0].index # init as the first sensor
best_sensor = complement_sensors[0]
complement_sensors.sort() # sorting the gain descendingly
new_base_ot_approx = 0
#for sensor in complement_sensors:
# print((sensor.index, sensor.gain_up_bound), end=' ')
update, max_gain = 0, 0
while update < len(complement_sensors):
update_end = update+cores if update+cores <= len(complement_sensors) else len(complement_sensors)
candidiate_index = []
for i in range(update, update_end):
candidiate_index.append(complement_sensors[i].index)
counter += 1
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy)(subset_index, cuda_kernal, candidate) for candidate in candidiate_index)
# an element of candidate_results is a tuple - (index, o_t_approx, subsetlist)
for i, j in zip(range(update, update_end), range(0, cores)): # the two range might be different, if the case, follow the first range
complement_sensors[i].gain_up_bound = candidate_results[j][1] - base_ot_approx # update the upper bound of gain
#print(candidate_results[j][2], candidate_results[j][1], base_ot_approx, complement_sensors[i].gain_up_bound)
if complement_sensors[i].gain_up_bound > max_gain:
max_gain = complement_sensors[i].gain_up_bound
best_candidate = candidate_results[j][0]
best_sensor = complement_sensors[i]
new_base_ot_approx = candidate_results[j][1]
if update_end < len(complement_sensors) and max_gain > complement_sensors[update_end].gain_up_bound: # where the lazy happens
#print('\n***LAZY!***\n', cost, (update, update_end), len(complement_sensors), '\n')
break
update += cores
base_ot_approx = new_base_ot_approx # update the base o_t_approx for the next iteration
print(best_candidate, subset_index, base_ot_approx, '\n')
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
subset_to_compute.append(copy.deepcopy(subset_index))
plot_data.append([len(subset_index), base_ot_approx, 0]) # don't compute real o_t now, delay to after all the subsets are selected
complement_sensors.remove(best_sensor)
if base_ot_approx > 0.9999999999999:
break
cost += 1
print('number of o_t_approx', counter)
subset_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy_real_ot)(subset_index) for subset_index in subset_to_compute)
for i in range(len(subset_results)):
plot_data[i][2] = subset_results[i]
return plot_data
def select_offline_greedy_p_lazy_cpu(self, budget, cores):
'''(Parallel + Lazy greedy) Select a subset of sensors greedily. offline + homo version using ** CPU **
Attributes:
budget (int): budget constraint
cores (int): number of cores for parallelzation
Return:
(list): an element is [str, int, float],
where str is the list of subset_index, int is # of sensors, float is O_T
'''
counter = 0
base_ot_approx = 1 - 0.5*len(self.transmitters)
plot_data = []
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_sensors = copy.deepcopy(self.sensors) # S\T in the paper
subset_to_compute = []
while cost < budget and complement_sensors:
best_candidate = -1
best_sensor = None
complement_sensors.sort() # sorting the gain descendingly
new_base_ot_approx = 0
#for sensor in complement_sensors:
# print((sensor.index, sensor.gain_up_bound), end=' ')
update, max_gain = 0, 0
while update < len(complement_sensors):
update_end = update+cores if update+cores <= len(complement_sensors) else len(complement_sensors)
candidiate_index = []
for i in range(update, update_end):
candidiate_index.append(complement_sensors[i].index)
counter += 1
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy_cpu)(subset_index, candidate) for candidate in candidiate_index)
# an element of candidate_results is a tuple - (index, o_t_approx, subsetlist)
for i, j in zip(range(update, update_end), range(0, cores)): # the two range might be different, if the case, follow the first range
complement_sensors[i].gain_up_bound = candidate_results[j][1] - base_ot_approx # update the upper bound of gain
if complement_sensors[i].gain_up_bound > max_gain:
max_gain = complement_sensors[i].gain_up_bound
best_candidate = candidate_results[j][0]
best_sensor = complement_sensors[i]
new_base_ot_approx = candidate_results[j][1]
if update_end < len(complement_sensors) and max_gain > complement_sensors[update_end].gain_up_bound: # where the lazy happens
print('\n***LAZY!***\n', cost, (update, update_end), len(complement_sensors), '\n')
break
update += cores
base_ot_approx = new_base_ot_approx # update the base o_t_approx for the next iteration
print(best_candidate, base_ot_approx, '\n\n')
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
subset_to_compute.append(copy.deepcopy(subset_index))
plot_data.append([len(subset_index), base_ot_approx, 0]) # don't compute real o_t now, delay to after all the subsets are selected
complement_sensors.remove(best_sensor)
cost += 1
if base_ot_approx > 0.9999999999999:
break
print('number of o_t_approx', counter)
return # for scalability test, we don't need to compute the real Ot in the scalability test.
subset_results = Parallel(n_jobs=len(plot_data))(delayed(self.inner_greedy_real_ot_cpu)(subset_index) for subset_index in subset_to_compute)
for i in range(len(subset_results)):
plot_data[i][2] = subset_results[i]
return plot_data
def inner_greedy(self, subset_index, cuda_kernal, candidate):
'''Inner loop for selecting candidates
Args:
subset_index (list):
candidate (int):
Return:
(tuple): (index, o_t_approx, new subset_index)
'''
subset_index2 = copy.deepcopy(subset_index)
ordered_insert(subset_index2, candidate) # guarantee subset_index always be sorted here
o_t = self.o_t_approx_host(subset_index2, cuda_kernal)
return (candidate, o_t, subset_index2)
def inner_greedy_real_ot(self, subset_index):
'''Compute the real o_t (accruacy of prediction)
Args:
subset_index (list):
Return:
(tuple): (index, o_t_approx, new subset_index)
'''
o_t = self.o_t_host(subset_index)
return o_t
def inner_greedy_cpu(self, subset_index, candidate):
'''Inner loop for selecting candidates
Args:
subset_index (list):
candidate (int):
Return:
(tuple): (index, o_t_approx, new subset_index)
'''
subset_index2 = copy.deepcopy(subset_index)
ordered_insert(subset_index2, candidate) # guarantee subset_index always be sorted here
o_t = self.o_t_approximate(subset_index2)
return (candidate, o_t, subset_index2)
def inner_greedy_real_ot_cpu(self, subset_index):
'''Compute the real o_t (accruacy of prediction)
Args:
subset_index (list):
Return:
(tuple): (index, o_t_approx, new subset_index)
'''
o_t = self.o_t(subset_index)
return o_t
def select_offline_greedy(self, budget):
'''Select a subset of sensors greedily. offline + homo version
Args:
budget (int): budget constraint
Return:
(list): an element is [str, int, float],
where str is the list of subset_index, int is # of sensors, float is O_T
'''
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_index = [i for i in range(self.sen_num)] # S\T in the paper
plot_data = []
while cost < budget and complement_index:
maximum = self.o_t_approximate(subset_index) # L in the paper
best_candidate = complement_index[0] # init the best candidate as the first one
for candidate in complement_index:
ordered_insert(subset_index, candidate) # guarantee subset_index always be sorted here
temp = self.o_t_approximate(subset_index)
print(subset_index, temp)
if temp > maximum:
maximum = temp
best_candidate = candidate
subset_index.remove(candidate)
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
complement_index.remove(best_candidate)
plot_data.append([str(subset_index), len(subset_index), maximum])
cost += 1
return plot_data
def select_offline_random_hetero(self, budget, cores):
'''Offline selection when the sensors are heterogeneous
Args:
budget (int): budget we have for the heterogeneous sensors
cores (int): number of cores for parallelization
'''
'''
energy = pd.read_csv('data/energy.txt', header=None) # load the energy cost
size = energy[1].count()
i = 0
for sensor in self.sensors:
setattr(self.sensors.get(sensor), 'cost', energy[1][i%size])
i += 1
'''
random.seed(0) # though algorithm is random, the results are the same every time
self.subset = {}
subset_index = []
plot_data = []
sequence = [i for i in range(self.sen_num)]
cost = 0
cost_list = []
subset_to_compute = []
while cost < budget:
option = []
for index in sequence:
temp_cost = self.sensors[index].cost
if cost + temp_cost <= budget: # a sensor can be selected if adding its cost is under budget
option.append(index)
if not option: # if there are no sensors that can be selected, then break
break
select = random.choice(option)
ordered_insert(subset_index, select)
subset_to_compute.append(copy.deepcopy(subset_index))
sequence.remove(select)
cost += self.sensors[select].cost
cost_list.append(cost)
subset_results = Parallel(n_jobs=cores)(delayed(self.inner_random)(subset_index) for subset_index in subset_to_compute)
for cost, result in zip(cost_list, subset_results):
plot_data.append((str(result[0]), cost, result[1]))
return plot_data
def select_offline_greedy_hetero(self, budget, cores):
'''Offline selection when the sensors are heterogeneous
Two pass method: first do a homo pass, then do a hetero pass, choose the best of the two
Args:
budget (int): budget we have for the heterogeneous sensors
cores (int): number of cores for parallelization
cost_filename (str): file that has the cost of sensors
'''
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_index = [i for i in range(self.sen_num)] # S\T in the paper
maximum = 0
first_pass_plot_data = []
while cost < budget and complement_index:
option = []
for index in complement_index:
temp_cost = self.sensors[index].cost
if cost + temp_cost <= budget: # a sensor can be selected if adding its cost is under budget
option.append(index)
if not option: # if there are no sensors that can be selected, then break
break
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy)(subset_index, candidate) for candidate in option)
best_candidate = candidate_results[0][0] # an element of candidate_results is a tuple - (int, float, list)
maximum = candidate_results[0][1] # where int is the candidate, float is the O_T, list is the subset_list with new candidate
for candidate in candidate_results:
#print(candidate[2], candidate[1])
if candidate[1] > maximum:
best_candidate = candidate[0]
maximum = candidate[1]
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
complement_index.remove(best_candidate)
cost += self.sensors[best_candidate].cost
first_pass_plot_data.append([copy.deepcopy(subset_index), cost, 0]) # Y value is real o_t
print(subset_index, maximum, cost)
if maximum > 0.999:
break
print('end of the first homo pass and start of the second hetero pass')
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_index = [i for i in range(self.sen_num)] # S\T in the paper
base_ot = 1 - 0.5*len(self.transmitters) # O_T from the previous iteration
second_pass_plot_data = []
while cost < budget and complement_index:
option = []
for index in complement_index:
temp_cost = self.sensors[index].cost
if cost + temp_cost <= budget: # a sensor can be selected if adding its cost is under budget
option.append(index)
if not option:
break
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy)(subset_index, candidate) for candidate in option)
best_candidate = candidate_results[0][0] # an element of candidate_results is a tuple - (int, float, list)
cost_of_candiate = self.sensors[best_candidate].cost
new_base_ot = candidate_results[0][1]
maximum = (candidate_results[0][1]-base_ot)/cost_of_candiate # where int is the candidate, float is the O_T, list is the subset_list with new candidate
for candidate in candidate_results:
incre = candidate[1] - base_ot
cost_of_candiate = self.sensors[candidate[0]].cost
incre_cost = incre/cost_of_candiate # increment of O_T devided by cost
#print(candidate[2], candidate[1], incre, cost_of_candiate, incre_cost)
if incre_cost > maximum:
best_candidate = candidate[0]
maximum = incre_cost
new_base_ot = candidate[1]
base_ot = new_base_ot
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
complement_index.remove(best_candidate)
cost += self.sensors[best_candidate].cost
second_pass_plot_data.append([copy.deepcopy(subset_index), cost, 0]) # Y value is real o_t
print(subset_index, base_ot, cost)
first_pass = []
for data in first_pass_plot_data:
first_pass.append(data[0])
second_pass = []
for data in second_pass_plot_data:
second_pass.append(data[0])
first_pass_o_ts = Parallel(n_jobs=cores)(delayed(self.inner_greedy_real_ot)(subset_index) for subset_index in first_pass)
second_pass_o_ts = Parallel(n_jobs=cores)(delayed(self.inner_greedy_real_ot)(subset_index) for subset_index in second_pass)
for i in range(len(first_pass_o_ts)):
first_pass_plot_data[i][2] = first_pass_o_ts[i]
for i in range(len(second_pass_o_ts)):
second_pass_plot_data[i][2] = second_pass_o_ts[i]
first_final_o_t = first_pass_plot_data[len(first_pass_plot_data)-1][2]
second_final_o_t = second_pass_plot_data[len(second_pass_plot_data)-1][2]
if second_final_o_t > first_final_o_t:
print('second pass is selected')
return second_pass_plot_data
else:
print('first pass is selected')
return first_pass_plot_data
def select_offline_greedy_hetero_lazy(self, budget, cores):
'''(Lazy) Offline selection when the sensors are heterogeneous
Two pass method: first do a homo pass, then do a hetero pass, choose the best of the two
Args:
budget (int): budget we have for the heterogeneous sensors
cores (int): number of cores for parallelization
cost_filename (str): file that has the cost of sensors
'''
base_ot_approx = 1 - 0.5*len(self.transmitters)
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_sensors = copy.deepcopy(self.sensors) # S\T in the paper
first_pass_plot_data = []
while cost < budget and complement_sensors:
complement_sensors.sort() # sort the sensors by gain upper bound descendingly
option = []
for sensor in complement_sensors:
temp_cost = sensor.cost
if cost + temp_cost <= budget: # a sensor can be selected if adding its cost is under budget
option.append(sensor)
if not option: # if there are no sensors that can be selected, then break
break
best_candidate = -1
best_sensor = None
new_base_ot_approx = 0
update, max_gain = 0, 0
while update < len(option):
update_end = update+cores if update+cores <= len(option) else len(option)
candidiate_index = []
for i in range(update, update_end):
candidiate_index.append(option[i].index)
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy)(subset_index, candidate) for candidate in candidiate_index)
# an element of candidate_results is a tuple - (index, o_t_approx, subsetlist)
for i, j in zip(range(update, update_end), range(0, cores)): # the two range might be different, if the case, follow the first range
complement_sensors[i].gain_up_bound = candidate_results[j][1] - base_ot_approx # update the upper bound of gain
if complement_sensors[i].gain_up_bound > max_gain:
max_gain = complement_sensors[i].gain_up_bound
best_candidate = candidate_results[j][0]
best_sensor = complement_sensors[i]
new_base_ot_approx = candidate_results[j][1]
if update_end < len(complement_sensors) and max_gain > complement_sensors[update_end].gain_up_bound: # where the lazy happens
print('\n******LAZY!')
print(cost, (update, update_end), len(complement_sensors), '\n******\n')
break
update += cores
base_ot_approx = new_base_ot_approx
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
complement_sensors.remove(best_sensor)
cost += self.sensors[best_candidate].cost
first_pass_plot_data.append([copy.deepcopy(subset_index), cost, 0]) # Y value is real o_t
print(subset_index, base_ot_approx, cost)
print('end of the first homo pass and start of the second hetero pass')
i = 0
lowest_cost = 1
for sensor in self.sensors:
if sensor.cost < lowest_cost:
lowest_cost = sensor.cost
i += 1
max_gain_up_bound = 0.5*len(self.transmitters)/lowest_cost
for sensor in self.sensors:
sensor.gain_up_bound = max_gain_up_bound
cost = 0 # |T| in the paper
subset_index = [] # T in the paper
complement_sensors = copy.deepcopy(self.sensors) # S\T in the paper
base_ot_approx = 1 - 0.5*len(self.transmitters)
second_pass_plot_data = []
while cost < budget and complement_sensors:
complement_sensors.sort()
option = []
for sensor in complement_sensors:
temp_cost = sensor.cost
if cost + temp_cost <= budget: # a sensor can be selected if adding its cost is under budget
option.append(sensor)
if not option:
break
best_candidate = -1
best_sensor = None
new_base_ot_approx = 0
update, max_gain = 0, 0
while update < len(option):
update_end = update+cores if update+cores <= len(complement_sensors) else len(complement_sensors)
candidiate_index = []
for i in range(update, update_end):
candidiate_index.append(complement_sensors[i].index)
candidate_results = Parallel(n_jobs=cores)(delayed(self.inner_greedy)(subset_index, candidate) for candidate in candidiate_index)
# an element of candidate_results is a tuple - (index, o_t_approx, subsetlist)
for i, j in zip(range(update, update_end), range(0, cores)): # the two range might be different, if the case, follow the first range
complement_sensors[i].gain_up_bound = (candidate_results[j][1] - base_ot_approx)/complement_sensors[i].cost # update the upper bound of gain
if complement_sensors[i].gain_up_bound > max_gain:
max_gain = complement_sensors[i].gain_up_bound
best_candidate = candidate_results[j][0]
best_sensor = complement_sensors[i]
new_base_ot_approx = candidate_results[j][1]
if update_end < len(complement_sensors) and max_gain > complement_sensors[update_end].gain_up_bound: # where the lazy happens
print('\n******LAZY!')
print(cost, (update, update_end), len(complement_sensors), '\n******\n')
break
update += cores
base_ot_approx = new_base_ot_approx # update the base o_t_approx for the next iteration
ordered_insert(subset_index, best_candidate) # guarantee subset_index always be sorted here
complement_sensors.remove(best_sensor)
cost += self.sensors[best_candidate].cost
second_pass_plot_data.append([copy.deepcopy(subset_index), cost, 0]) # Y value is real o_t
print(subset_index, base_ot_approx, cost)
first_pass = []
for data in first_pass_plot_data:
first_pass.append(data[0])
second_pass = []
for data in second_pass_plot_data:
second_pass.append(data[0])
first_pass_o_ts = Parallel(n_jobs=cores)(delayed(self.inner_greedy_real_ot)(subset_index) for subset_index in first_pass)
second_pass_o_ts = Parallel(n_jobs=cores)(delayed(self.inner_greedy_real_ot)(subset_index) for subset_index in second_pass)
for i in range(len(first_pass_o_ts)):
first_pass_plot_data[i][2] = first_pass_o_ts[i]
for i in range(len(second_pass_o_ts)):
second_pass_plot_data[i][2] = second_pass_o_ts[i]
first_final_o_t = first_pass_plot_data[len(first_pass_plot_data)-1][2]
second_final_o_t = second_pass_plot_data[len(second_pass_plot_data)-1][2]
if second_final_o_t > first_final_o_t:
print('second pass is selected')
return second_pass_plot_data
else:
print('first pass is selected')
return first_pass_plot_data
def select_offline_coverage(self, budget, cores):
'''A coverage-based baseline algorithm
'''
random.seed(0)
center = (int(self.grid_len/2), int(self.grid_len/2))
min_dis = 99999
first_index, i = 0, 0
first_sensor = None
for sensor in self.sensors: # select the first sensor that is closest to the center of the grid
temp_dis = distance.euclidean([center[0], center[1]], [sensor.x, sensor.y])
if temp_dis < min_dis:
min_dis = temp_dis
first_index = i
first_sensor = sensor
i += 1
subset_index = [first_index]
subset_to_compute = [copy.deepcopy(subset_index)]
complement_index = [i for i in range(self.sen_num)]
complement_index.remove(first_index)
radius = self.compute_coverage_radius(first_sensor, subset_index) # compute the radius
print('radius', radius)
coverage = np.zeros((self.grid_len, self.grid_len), dtype=int)
self.add_coverage(coverage, first_sensor, radius)
cost = 1
while cost < budget and complement_index: # find the sensor that has the least overlap
least_overlap = 99999
best_candidate = []
best_sensor = []
for candidate in complement_index:
sensor = self.index_to_sensor(candidate)
overlap = self.compute_overlap(coverage, sensor, radius)
if overlap < least_overlap:
least_overlap = overlap
best_candidate = [candidate]
best_sensor = [sensor]
elif overlap == least_overlap:
best_candidate.append(candidate)
best_sensor.append(sensor)
choose = random.choice(range(len(best_candidate)))
ordered_insert(subset_index, best_candidate[choose])
complement_index.remove(best_candidate[choose])
self.add_coverage(coverage, best_sensor[choose], radius)
subset_to_compute.append(copy.deepcopy(subset_index))
cost += 1
subset_results = Parallel(n_jobs=cores)(delayed(self.inner_random)(subset_index) for subset_index in subset_to_compute)
plot_data = []
for result in subset_results:
plot_data.append((str(result[0]), len(result[0]), result[1]))
return plot_data
def select_offline_coverage_hetero(self, budget, cores):
'''A coverage-based baseline algorithm (heterogeneous version)
'''
random.seed(0)
center = (int(self.grid_len/2), int(self.grid_len/2))
min_dis = 99999
first_index, i = 0, 0
first_sensor = None
for sensor in self.sensors: # select the first sensor that is closest to the center of the grid
temp_dis = distance.euclidean([center[0], center[1]], [sensor.x, sensor.y])
if temp_dis < min_dis:
min_dis = temp_dis
first_index = i
first_sensor = sensor
i += 1
subset_index = [first_index]
subset_to_compute = [copy.deepcopy(subset_index)]
complement_index = [i for i in range(self.sen_num)]
complement_index.remove(first_index)
radius = self.compute_coverage_radius(first_sensor, subset_index) # compute the radius
print('radius', radius)
coverage = np.zeros((self.grid_len, self.grid_len), dtype=int)
self.add_coverage(coverage, first_sensor, radius)
cost = self.sensors[first_index].cost
cost_list = [cost]
while cost < budget and complement_index:
option = []
for index in complement_index:
temp_cost = self.sensors[index].cost
if cost + temp_cost <= budget: # a sensor can be selected if adding its cost is under budget
option.append(index)
if not option: # if there are no sensors that can be selected, then break
break
min_overlap_cost = 99999 # to minimize overlap*cost
best_candidate = []
best_sensor = []
for candidate in option:
sensor = self.index_to_sensor(candidate)
overlap = self.compute_overlap(coverage, sensor, radius)
temp_cost = self.sensors[candidate].cost
overlap_cost = (overlap+0.001)*temp_cost
if overlap_cost < min_overlap_cost:
min_overlap_cost = overlap_cost
best_candidate = [candidate]
best_sensor = [sensor]
elif overlap_cost == min_overlap_cost:
best_candidate.append(candidate)
best_sensor.append(sensor)
choose = random.choice(range(len(best_candidate)))
ordered_insert(subset_index, best_candidate[choose])
complement_index.remove(best_candidate[choose])
self.add_coverage(coverage, best_sensor[choose], radius)
subset_to_compute.append(copy.deepcopy(subset_index))
cost += self.sensors[best_candidate[choose]].cost
cost_list.append(cost)
print(len(subset_to_compute), subset_to_compute)
subset_results = Parallel(n_jobs=cores)(delayed(self.inner_random)(subset_index) for subset_index in subset_to_compute)
plot_data = []
for cost, result in zip(cost_list, subset_results):
plot_data.append((str(result[0]), cost, result[1]))
return plot_data
def compute_coverage_radius(self, first_sensor, subset_index):
'''Compute the coverage radius for the coverage-based selection algorithm
Args:
first_sensor (tuple): sensor that is closest to the center
subset_index (list):
'''
sub_cov = self.covariance_sub(subset_index)
sub_cov_inv = np.linalg.inv(sub_cov) # inverse
radius = 1
for i in range(1, int(self.grid_len/2)): # compute 'radius'
transmitter_i = self.transmitters[(first_sensor.x - i)*self.grid_len + first_sensor.y] # 2D index --> 1D index
i_x, i_y = transmitter_i.x, transmitter_i.y
if i_x < 0:
break
transmitter_i.set_mean_vec_sub(subset_index)
prob_i = []
for transmitter_j in self.transmitters:
j_x, j_y = transmitter_j.x, transmitter_j.y
if i_x == j_x and i_y == j_y:
continue
transmitter_j.set_mean_vec_sub(subset_index)
pj_pi = transmitter_j.mean_vec_sub - transmitter_i.mean_vec_sub