-
Notifications
You must be signed in to change notification settings - Fork 0
/
MLE_attack.py
403 lines (305 loc) · 12.7 KB
/
MLE_attack.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
from __future__ import print_function
from localize.localize import *
import os
import numpy as np
from matplotlib import pyplot as plt
import theano
import theano.tensor as T
import random
import matplotlib.pyplot as plt
import matplotlib.mlab as ml
import math
import scipy
from scipy.interpolate import griddata
### Notations
# true_... = the ground truth
# ..._false = the falsely reported values
# ...true = the adversary's guess of true locations
#
def estimate_rss(receivers, x, y):
rss_list = []
for i in range(len(x)):
rss = 0.0
total_weight = 0.0
for j in range(len(receivers)):
dist = edist(receivers[j][0], receivers[j][1], x[i], y[i])
rss += (1/(dist **2)) * receivers[j][2]
total_weight += 1/(dist **2)
rss_list.append(rss/total_weight)
return rss_list
NUM_REC = 44
TRANSMITTER_NUMBER = 26
loc, rss = read_dataset()
recv_list, trans_list = get_receiver_snapshots(loc, rss, NUM_REC)
receivers = recv_list[TRANSMITTER_NUMBER]
transmitter_loc = trans_list[TRANSMITTER_NUMBER]
# extract true locations
true_x = [x[0] for x in receivers]
true_y = [x[1] for x in receivers]
true_rss = [x[2] for x in receivers]
# ### Convert true RSS to Watts
# true_rss_watt = []
# for val in true_rss:
# true_rss_watt.append(10**(val/ 10))
# true_rss = true_rss_watt[:]
# #also do in the receiver list
# for i in range(len(receivers)):
# receivers[i][-1] = 10**(receivers[i][-1]/ 10)
print(true_x)
print(true_y)
print(true_rss)
# set up false locations to report
x_false = [random.uniform(-5, 10) for i in range(len(receivers))]
y_false = [random.uniform(-1, 15) for i in range(len(receivers))]
# estimate the RSS at the false location
rss_false = estimate_rss(receivers, x_false, y_false)
# test the estimated RSS by localizing the transmitter (Gives you a rough idea if everything is in place till now)
grid_centers = calculate_grid_centers(10, 13, -5, -5, 1.0)
noisy_recv_list = []
for i in range(len(x_false)):
noisy_recv_list.append([x_false[i], y_false[i], rss_false[i]])
transmitter_localized = localize(noisy_recv_list, grid_centers, rss_dbm=True)[0]
print("the error with localize: ", edist(transmitter_localized[0], transmitter_localized[1], transmitter_loc[0], transmitter_loc[1]))
# START MOUNTING THE MLE ATTACK
def MLE_attack(receivers, x_false, y_false):
# make gueses for true locations and RSS
x_true = [random.uniform(-5, 10) for i in range(len(receivers))]
y_true = [random.uniform(-5, 15) for i in range(len(receivers))]
rss_true = [random.uniform(-60, 1) for i in range(len(receivers))] # Random Initialization
# fill RSS up with closest point in the estimate (Intellifgent RSS Initialization)
rss_true = []
for i in range(len(x_true)):
distance = float('inf')
index = None
for j in range(len(x_false)):
if edist(x_false[j], y_false[j], x_true[i], y_true[i]) < distance:
index = j
distance = edist(x_false[j], y_false[j], x_true[i], y_true[i])
rss_true.append(rss_false[index])
# Define elements in graph
x = T.dmatrix('x') # the x coordinates of the true location to guess
y = T.dmatrix('y') # the y coordinates of the true location to guess
f = T.dmatrix('f') # the RSS values at the these locations
vx = T.dscalar('vx') # falsely reported location x coordinate
vy = T.dscalar('vy') # falsely reported location y coordinate
p = T.dscalar('p') # adjusted RSS reported for false location reported
def function(x, y, vx, vy, f):
'''
Takes Theno tensors as input and calculates the RSS at falsely reported
locations based on true location guesses
'''
d = (x - vx)**2 + (y - vy)**2
d = d ** -1
predicted = T.sum((d / T.sum(d)) * f)
return predicted
def loss(x, y, vx, vy, f, p):
'''
Calculated the loss for single instance of falsely reported location
'''
return (function(x, y, vx, vy, f) - p)**2
# set for partial gradients
gx = T.grad(loss(x, y, vx, vy, f, p), x)
gy = T.grad(loss(x, y, vx, vy, f, p), y)
gf = T.grad(loss(x, y, vx, vy, f, p), f)
# convert in Theano function for calculations
f1 = theano.function([x,y,vx,vy,f,p], gx)
f2 = theano.function([x,y,vx,vy,f,p], gy)
f3 = theano.function([x,y,vx,vy,f,p], gf)
# factor out the loss function to calculate values for plotting
f_loss = theano.function([x,y,vx,vy,f,p], (function(x, y, vx, vy, f) - p)**2)
#loss_function = theano.function([x,y,vx,vy,f,p], loss)
EPOCH = 4
for m in range(EPOCH):
delta = 0.01 # incremental update size
num_trials = 1000 # number of iterations for MLE
# loop through and find the gradient for all the vjs; update guesses and repeat
loss_list = []
counter = 1
for k in range(num_trials):
sumf1 = [0.0] * len(x_true)
sumf2 = [0.0] * len(x_true)
sumf3 = [0.0] * len(x_true)
cumm_loss = 0.0
for i in range(len(x_false)):
cumm_loss += math.sqrt(f_loss([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i]))
sumf1 += f1([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i])
sumf2 += f2([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i])
sumf3 += f3([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i])
loss_list.append(cumm_loss/len(x_false))
#print("loss for interation", k, loss([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i]))
# update the true location and rss guesses
for i in range(len(x_true)):
x_true[i] -= delta * sumf1[0][i]
y_true[i] -= delta * sumf2[0][i]
rss_true[i] -= delta * sumf3[0][i]
delta = 0.01 / math.sqrt(counter)
counter += 1
# fix the guesses close to the false locations
for i in range(len(x_true)):
min_index = None
mdist = float('inf')
# pick the nearest false reported location
for j in range(len(x_false)):
if edist(x_true[i], y_true[i], x_false[j], y_false[j]) < mdist:
mdist = edist(x_true[i], y_true[i], x_false[j], y_false[j])
min_index = j
if mdist < 1.5: # close to some falsely reported location by 1.5m
# initialize to random
x_true[i] = random.uniform(-5, 10)
y_true[i] = random.uniform(-5, 15)
return x_true, y_true, rss_true, loss_list
# # make gueses for true locations and RSS
# x_true = [random.uniform(-5, 10) for i in range(len(receivers))]
# y_true = [random.uniform(-5, 15) for i in range(len(receivers))]
# rss_true = [random.uniform(-60, 1) for i in range(len(receivers))] # Random Initialization
# # fill RSS up with closest point in the estimate (Intellifgent RSS Initialization)
# rss_true = []
# for i in range(len(x_true)):
# distance = 1000.0
# index = None
# for j in range(len(x_false)):
# if edist(x_false[j], y_false[j], x_true[i], y_true[i]) < distance:
# index = j
# distance = edist(x_false[j], y_false[j], x_true[i], y_true[i])
# rss_true.append(rss_false[index])
# # This is an initialization for quick sanity check for the Theano graph for MLE gradient updates
# # With ground truth the loss should be almost 0 and should stay around that
# # x_true = true_x[:]
# # y_true = true_y[:]
# # rss_true = true_rss[:]
# # Define elements in graph
# x = T.dmatrix('x') # the x coordinates of the true location to guess
# y = T.dmatrix('y') # the y coordinates of the true location to guess
# f = T.dmatrix('f') # the RSS values at the these locations
# vx = T.dscalar('vx') # falsely reported location x coordinate
# vy = T.dscalar('vy') # falsely reported location y coordinate
# p = T.dscalar('p') # adjusted RSS reported for false location reported
# def function(x, y, vx, vy, f):
# '''
# Takes Theno tensors as input and calculates the RSS at falsely reported
# locations based on true location guesses
# '''
# d = (x - vx)**2 + (y - vy)**2
# d = d ** -1
# predicted = T.sum((d / T.sum(d)) * f)
# return predicted
# def loss(x, y, vx, vy, f, p):
# '''
# Calculated the loss for single instance of falsely reported location
# '''
# return (function(x, y, vx, vy, f) - p)**2
# # set for partial gradients
# gx = T.grad(loss(x, y, vx, vy, f, p), x)
# gy = T.grad(loss(x, y, vx, vy, f, p), y)
# gf = T.grad(loss(x, y, vx, vy, f, p), f)
# # convert in Theano function for calculations
# f1 = theano.function([x,y,vx,vy,f,p], gx)
# f2 = theano.function([x,y,vx,vy,f,p], gy)
# f3 = theano.function([x,y,vx,vy,f,p], gf)
# # factor out the loss function to calculate values for plotting
# f_loss = theano.function([x,y,vx,vy,f,p], (function(x, y, vx, vy, f) - p)**2)
# #loss_function = theano.function([x,y,vx,vy,f,p], loss)
# delta = 0.01 # incremental update size
# num_trials = 4000 # number of iterations for MLE
# # loop through and find the gradient for all the vjs; update guesses and repeat
# loss_list = []
# counter = 1
# for k in range(num_trials):
# sumf1 = [0.0] * len(x_true)
# sumf2 = [0.0] * len(x_true)
# sumf3 = [0.0] * len(x_true)
# cumm_loss = 0.0
# for i in range(len(x_false)):
# cumm_loss += math.sqrt(f_loss([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i]))
# sumf1 += f1([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i])
# sumf2 += f2([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i])
# sumf3 += f3([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i])
# loss_list.append(cumm_loss/len(x_false))
# #print("loss for interation", k, loss([x_true], [y_true], x_false[i], y_false[i], [rss_true], rss_false[i]))
# # update the true location and rss guesses
# for i in range(len(x_true)):
# x_true[i] -= delta * sumf1[0][i]
# y_true[i] -= delta * sumf2[0][i]
# rss_true[i] -= delta * sumf3[0][i]
# delta = 0.01 / math.sqrt(counter)
# counter += 1
x_true, y_true, rss_true, loss_list = MLE_attack(receivers, x_false, y_false)
# Out of curiosity, let's test how well the guessed RSS field does
grid_centers = calculate_grid_centers(10, 13, -5, -5, 1.0)
noisy_recv_list = []
for i in range(len(x_true)):
noisy_recv_list.append([x_true[i], y_true[i], rss_true[i]])
transmitter_localized = localize(noisy_recv_list, grid_centers, rss_dbm=True)[0]
print ("locating transmitter again: ", edist(transmitter_localized[0], transmitter_localized[1], transmitter_loc[0], transmitter_loc[1]))
# let's give adversary the best evaluation metric, he cannot do better
error_list = []
for i in range(len(x_true)):
err = float('inf')
index = None
for j in range(len(x_true)):
if edist(x_true[i], y_true[i], true_x[j], true_y[j]) < err:
index = j
err = edist(x_true[i], y_true[i], true_x[j], true_y[j])
error_list.append(err)
print("Metric for adversary's guess: ", np.mean(error_list), min(error_list), max(error_list)) # some stats
# how rss values relate to localization error
# prepare a list of rss vs error
rss_error_list = []
for i in range(len(x_true)):
rss_error_list.append([error_list[i], rss_true[i]])
print("RSS error list (with predicted RSS): ")
rss_error_list.sort(key=lambda x: x[-1])
print(rss_error_list)
plt.figure()
rss_error_list = np.array(rss_error_list)
plt.plot(rss_error_list[:, [0]], rss_error_list[:, [1]])
#plt.show()
rss_error_list = []
for i in range(len(x_true)):
rss_error_list.append([error_list[i], rss_false[i]])
print("RSS error list (with false reported RSS): ")
sorted(rss_error_list, key=lambda x: x[-1])
print(rss_error_list)
# Time for visualization
# The loss function
plt.figure()
plt.plot(loss_list)
plt.title("Loss Function")
plt.xlabel("Iteration number")
plt.ylabel("Loss calculated on RSS dBm")
# how well do guesses true locations fair against the ground truth for true locations
#plt.figure()
fig, ax = plt.subplots()
ax.scatter(x_true, y_true, label="Guesses true locations (by adversary)")
ax.scatter(true_x, true_y, label="Actual true locations (ground truth)")
ax.scatter(x_false, y_false, label="false locations")
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1))
plt.xlabel("X-coordinate (m)")
plt.ylabel("Y-coordinate (m)")
ax.grid(True)
# Lets the RSS field from falsely reported data to server
plt.figure()
print(len(loc))
loc = loc.drop(loc.index[[TRANSMITTER_NUMBER]])
print (len(loc), len(true_rss))
yi = np.linspace(int(min(loc[1])), int(max(loc[1]))-1 , 19*3)
xi = np.linspace(int(min(loc[0]))+1, int(max(loc[0])) , 16*3)
zi = griddata((x_false, y_false), rss_false, (xi[None,:], yi[:,None]), method='linear')
plt.contour(xi, yi, zi, colors='k')
plt.contourf(xi, yi, zi, cmap=plt.cm.jet)
plt.xlabel("X-coordinate (m)")
plt.ylabel("Y-coordinate (m)")
plt.title("Variation of RSS in an Area(from falsely reported locations)")
cb = plt.colorbar()
cb.set_label('RSS values in dBm')
# let's see the RSS field from the guesses made the adversary
plt.figure()
zi = griddata((x_true, y_true), rss_true, (xi[None,:], yi[:,None]), method='linear')
plt.contour(xi, yi, zi, colors='k')
plt.contourf(xi, yi, zi, cmap=plt.cm.jet)
plt.xlabel("X-coordinate (m)")
plt.ylabel("Y-coordinate (m)")
plt.title("Variation of RSS in an Area(from Adversary Guesses)")
cb = plt.colorbar()
cb.set_label('RSS values in dBm')
plt.show()