pypal.py 22.4 KB
Newer Older
Mohammad Imran Syed's avatar
Mohammad Imran Syed committed
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import math
import argparse
import time
import os

pd.options.mode.chained_assignment = None  # default='warn'

class PyPal:
    
    def UniqueFrames(self, trace1, trace2):
    
        directory = 'TXTTraces'
        if not os.path.exists(directory):
            os.makedirs(directory)
        os.chmod(directory, 0o777)
        
        
        # Extract unique frames (beacon and probe response) and write them to a pandas dataframe
                
        self.TRACE1=pd.read_csv(trace1, delimiter='\t')

        self.TRACE1=self.TRACE1.rename(columns={"frame.number":"Frame_number", "frame.time_epoch":"Frame_time_epoch", "wlan.fixed.timestamp":"Fixed_timestamp", "wlan_radio.signal_dbm":"RSSI_dBm", "wlan_radio.channel":"Channel", "wlan.fc.type":"Frame_type", "wlan.fc.type_subtype":"Frame_subtype", "wlan.fc.retry":"Retransmission", "wlan.fcs":"Checksum", "wlan.sa":"Source_MAC_address", "wlan.seq":"Sequence_number", "wlan.frag":"Fragment_number"})
        self.TRACE1['Source_MAC_address'] = self.TRACE1['Source_MAC_address'].fillna(0)
        self.TRACE1['Sequence_number'] = self.TRACE1['Sequence_number'].fillna(0)
        self.TRACE1['Checksum'] = self.TRACE1['Checksum'].fillna(0)
        self.TRACE1['Fragment_number'] = self.TRACE1['Fragment_number'].fillna(0)
        self.TRACE1['Fixed_timestamp'] = self.TRACE1['Fixed_timestamp'].fillna(0)
        
        uni_list=[]
        for row in self.TRACE1.itertuples():
            if (row.Frame_subtype==8 or row.Frame_subtype==5) and row.Retransmission==0:
                a=row
                uni_list.append(a)
        
        UniqueFrames1=pd.DataFrame(uni_list)
                
        self.TRACE2=pd.read_csv(trace2, delimiter='\t')
        
        self.TRACE2=self.TRACE2.rename(columns={"frame.number":"Frame_number", "frame.time_epoch":"Frame_time_epoch", "wlan.fixed.timestamp":"Fixed_timestamp", "wlan_radio.signal_dbm":"RSSI_dBm", "wlan_radio.channel":"Channel", "wlan.fc.type":"Frame_type", "wlan.fc.type_subtype":"Frame_subtype", "wlan.fc.retry":"Retransmission", "wlan.fcs":"Checksum", "wlan.sa":"Source_MAC_address", "wlan.seq":"Sequence_number", "wlan.frag":"Fragment_number"})
        self.TRACE2['Source_MAC_address'] = self.TRACE2['Source_MAC_address'].fillna(0)
        self.TRACE2['Sequence_number'] = self.TRACE2['Sequence_number'].fillna(0)
        self.TRACE2['Checksum'] = self.TRACE2['Checksum'].fillna(0)
        self.TRACE2['Fragment_number'] = self.TRACE2['Fragment_number'].fillna(0)
        self.TRACE2['Fixed_timestamp'] = self.TRACE2['Fixed_timestamp'].fillna(0)

        uni_list=[]        
        for row in self.TRACE2.itertuples():
            if (row.Frame_subtype==8 or row.Frame_subtype==5) and row.Retransmission==0:
                a=row
                uni_list.append(a)
        
        UniqueFrames2=pd.DataFrame(uni_list)
        
        # save the formatted traces
        self.TRACE1.to_csv(directory+'/'+self.trace1_name, index=False, header=True, sep='\t')
        self.TRACE2.to_csv(directory+'/'+self.trace2_name, index=False, header=True, sep='\t')

        
        # exits the code here after writing unique frames to txt files if this option is passed as an input argument
        if self.U:
            directory = 'UniqueFrames'
            if not os.path.exists(directory):
                os.makedirs(directory)
            os.chmod(directory, 0o777)
        
            file=open(directory+'/UniqueFrames_'+self.trace1_name, 'w')
            UniqueFrames1.to_csv(file, index=False, header=True, sep='\t')
            file.close()
            
            file=open(directory+'/UniqueFrames_'+self.trace2_name, 'w')
            UniqueFrames2.to_csv(file, index=False, header=True, sep='\t')
            file.close()
            
            print('--------------------------------------------------------------------------------------------')
            print('--------------------------------------------------------------------------------------------')
            print('Unique frames have been extracted to txt files and saved in UniqueFrames directory')
            print('--------------------------------------------------------------------------------------------')
            print('--------------------------------------------------------------------------------------------')
            
            return
                
        self.ExtractReferenceFrames(UniqueFrames1, UniqueFrames2)

    def ExtractReferenceFrames(self, UniqueFrames1, UniqueFrames2):
        
        # Extracts reference frames from unique frames
        
        h1={}
        h2={}
        
        # using a combination of MAC address, sequence number, frame subtype, 
        # checksum, and fragment number as key of the dictionary. This helps in finding
        # unique frames those are present in both the traces i.e. reference frames
        
        i=0
        for row in UniqueFrames1.itertuples():
            k=str(row.Source_MAC_address)+str(row.Sequence_number)+str(row.Frame_subtype)+str(row.Checksum)+str(row.Fragment_number)+str(row.Fixed_timestamp)
            if k not in h1:
                h1[k]=UniqueFrames1.iloc[i]
            i+=1
        
        i=0
        for row in UniqueFrames2.itertuples():
            k=str(row.Source_MAC_address)+str(row.Sequence_number)+str(row.Frame_subtype)+str(row.Checksum)+str(row.Fragment_number)+str(row.Fixed_timestamp)
            if k not in h2:
                h2[k]=UniqueFrames2.iloc[i]
            i+=1
            
        
        REFERENCE_FRAMES=list()
        REF_T1=[]
        REF_T2=[]
        h2_keys=list(h2.keys())
        
        for i in range(len(h2)):
            val = h2_keys[i]
            if val in h1:
                u1=h1[val]['Frame_number']
                u2=h2[val]['Frame_number']
                REFERENCE_FRAMES.append([u1,u2])
                
                ts1=h1[val]['Frame_time_epoch']
                ts2=h2[val]['Frame_time_epoch']
                REF_T1.append(ts1)
                REF_T2.append(ts2)
        
        
        # exits the code here after saving reference frames to a txt file if this option is passed as an input argument
        if self.R:
            directory = 'ReferenceFrames'
            if not os.path.exists(directory):
                os.makedirs(directory)
            os.chmod(directory, 0o777)
            file = open(directory+'/REFERENCE_FRAMES.txt', 'w')
            for i in range(len(REFERENCE_FRAMES)):
                file.write(str(REFERENCE_FRAMES[i][0]) + '\t' + str(REFERENCE_FRAMES[i][1]) + '\n')
            
            file.close()
            print('------------------------------------------------------------------------------------------------------')
            print('------------------------------------------------------------------------------------------------------')
            print('Unique reference frames have been extracted to txt files and saved in ReferenceFrames directory')
            print('------------------------------------------------------------------------------------------------------')
            print('------------------------------------------------------------------------------------------------------')

            return
        
        self.SynchronizeReferenceFrames(REFERENCE_FRAMES, REF_T1, REF_T2)

    def SynchronizeReferenceFrames(self, REFERENCE_FRAMES, REF_T1, REF_T2):
        
        # Synchronizes reference frames using linear regression and saves them to a txt file
        
        model = LinearRegression()
        window=3
        end=len(REF_T1)
        q=dict()
        a0=list()
        b0=list()
        directory = 'SynchronizedReferenceFrames'
        if not os.path.exists(directory):
            os.makedirs(directory)
        os.chmod(directory, 0o777)
        file = open(directory+'/Synchronized_Reference_Frames.txt', 'w+')
        file.write('a' + '\t' + 'b' + '\t' + 'frame1' + '\t' + 'frame2' + '\t' + 'time1' + '\t' + 'time2' + '\t' + 'error' + '\n')
        for i in range(end):
            if i==0:
                x=REF_T1[i:window]
                y=REF_T2[i:window]
                t1=REF_T1[i]    # timestamp of 1st trace which has to be synchronized
                s=REF_T2[i]     # timestamp of 2nd trace for finding error between timestamps after synchronization
            elif i==end-1:
                x=REF_T1[i-window+1:end]
                y=REF_T2[i-window+1:end]
                t1=REF_T1[i]
                s=REF_T2[i]
            else:
                x=REF_T1[i-math.floor(window/2):i+math.ceil(window/2)]
                y=REF_T2[i-math.floor(window/2):i+math.ceil(window/2)]
                t1=REF_T1[i]
                s=REF_T2[i]
            
            x=np.array(x).reshape((-1,1))
            y=np.array(y)
            model.fit(x,y)
            
            a=model.coef_
            b=model.intercept_
            
            t2=a[0]*t1+b #new timestamp of Trace 1
            err=t2-s
            if abs(err)<=106/1000000:
                a0.append(a[0])
                b0.append(b)
                q[REFERENCE_FRAMES[i][0]]=t2
                file.write(str(a[0]) + '\t' + str(b) + '\t' + str(REFERENCE_FRAMES[i][0]) + '\t' + str(REFERENCE_FRAMES[i][1]) + '\t' + str(t2) + '\t' + str(s) + '\t' + str(err) + '\n')
                
        file.close()
        
        # exits the code here after writing synchronized reference frames to a txt file if this option is passed as an input argument
        if self.SR:
            print('---------------------------------------------------------------------------------------------------------------------------------')
            print('---------------------------------------------------------------------------------------------------------------------------------')
            print('Unique reference frames have been synchronized and saved in txt files and saved in SynchronizedReferenceFrames directory')
            print('---------------------------------------------------------------------------------------------------------------------------------')
            print('---------------------------------------------------------------------------------------------------------------------------------')
            return
 
        # to make sure the values of linear regression are in order
        df = pd.read_csv(directory+'/Synchronized_Reference_Frames.txt', delimiter='\t', squeeze=True)
        df = df.sort_values(by=['frame1','frame2'])
        df.to_csv(directory+'/Synchronized_Reference_Frames.txt', index=False, header=True, sep='\t')
        a0 = df['a'].tolist()
        b0 = df['b'].tolist()
        
        self.SynchronizeTrace(a0, b0, q)
    
    def SynchronizeTrace(self, a0, b0, q):
        
        directory = 'SynchronizedTraces'
        if not os.path.exists(directory):
            os.makedirs(directory)
        os.chmod(directory, 0o777)
        
        # Syncronizes the whole first trace in accordance with 2nd trace and saves in a txt file

        k = 0
        a = a0[k]
        b = b0[k]
        sync_file=open(directory+'/Synchronized_Trace_'+self.trace1_name, 'w')
        first = list(q.keys())[0]
        i=0
        for row in self.TRACE1.itertuples():
            val = row.Frame_number          
            if val in q:
                self.TRACE1['Frame_time_epoch'][i]=q[val]
                if k<len(a0)-1 and val > first:
                    k += 1
                    a = a0[k]
                    b = b0[k]
            else:
                ts= row.Frame_time_epoch
                new_ts = a*ts+b
                self.TRACE1['Frame_time_epoch'][i]=new_ts
        
            i+=1
        
        self.TRACE1.to_csv(sync_file, index=False, header=True, sep='\t')
        
        sync_file.close()
        
        self.TRACE2.to_csv(directory+'/Synchronized_Trace_'+self.trace2_name, index=False, header=True, sep='\t')
        
        if self.S:
            print('----------------------------------------------------------------------------------------------------------')
            print('----------------------------------------------------------------------------------------------------------')
            print('Traces have been synchronized and saved in txt files and saved in SynchronizedTraces directory')
            print('----------------------------------------------------------------------------------------------------------')
            print('----------------------------------------------------------------------------------------------------------')
            return
        
        self.MergeTraces()
        
    def MergeTraces(self):
        
        if self.C:
            directory = 'ConcatenatedTraces'
            if not os.path.exists(directory):
                os.makedirs(directory)
            os.chmod(directory, 0o777)
        
            # Add trace name to each frame
            add_trace_name=[str(self.trace1_name[0:len(self.trace1_name)-4])]*len(self.TRACE1)
            self.TRACE1['Trace_Name']=add_trace_name
            add_trace_name=[str(self.trace2_name[0:len(self.trace2_name)-4])]*len(self.TRACE2)
            self.TRACE2['Trace_Name']=add_trace_name

            traces = [self.TRACE1, self.TRACE2]
	    
            self.TRACE1=pd.concat(traces)
            self.TRACE1=self.TRACE1.sort_values(by=['Frame_time_epoch'])
            new_frame_no=list(range(1,len(self.TRACE1)+1))
            self.TRACE1['Frame_number']=new_frame_no
            f = open(directory+'/ConcatenatedTrace.txt','w')
            self.TRACE1.to_csv(f, index=False, header=True, sep='\t')
            f.close()
            
            # extracting per user traces
            unique_MAC = self.TRACE1['Source_MAC_address'].unique()
            direct_UserTraces = directory + '/PerUserTraces'
            if not os.path.exists(direct_UserTraces):
                os.makedirs(direct_UserTraces)
            os.chmod(direct_UserTraces, 0o777)
            
            for i in range(len(unique_MAC)):
                per_user_trace = self.TRACE1[self.TRACE1.Source_MAC_address == unique_MAC[i]]
                f = open(direct_UserTraces+'/User_' + str (i+1) + '.txt','w')
                per_user_trace.to_csv(f, index=False, header=True, sep='\t')
            
            print('-----------------------------------------------------------------------------------------')
            print('-----------------------------------------------------------------------------------------')
            print('*****CONCATENATION COMPLETED, file saved in ConcatenatedTraces directory*****')
            print('-----------------------------------------------------------------------------------------')
            print('-----------------------------------------------------------------------------------------')
            return
        
        directory = 'MergedTraces'
        if not os.path.exists(directory):
            os.makedirs(directory)
        os.chmod(directory, 0o777)
        
        # create unique keys using source mac address, sequence number, frame subtype,
        # checksum, fragment number, and fixed timestamp for the ease of detecting
        # duplicate frames
        # this key ensures that unique packets are not otherwise considered duplicate
        # for example sequence numbers are repeated, capturing device migth drop
        # the framecheck sequence values, and so on
        
        unique_key=list()
        for row in self.TRACE1.itertuples():
            k=str(row.Source_MAC_address)+str(row.Sequence_number)+str(row.Frame_subtype)+str(row.Checksum)+str(row.Fragment_number)+str(row.Fixed_timestamp)
            unique_key.append(k)
        self.TRACE1['Unique_key']=unique_key
        
        unique_key=list()
        for row in self.TRACE2.itertuples():
            k=str(row.Source_MAC_address)+str(row.Sequence_number)+str(row.Frame_subtype)+str(row.Checksum)+str(row.Fragment_number)+str(row.Fixed_timestamp)
            unique_key.append(k)
        self.TRACE2['Unique_key']=unique_key
        
        # use the pandas dataframe merge option (which is a sort of a concatenation)
        # sort values by timestamp and unique key to make sure duplicate frames are well placed to be detected
        self.TRACE1=self.TRACE1.merge(self.TRACE2, on=['Frame_number', 'Frame_time_epoch', 'Fixed_timestamp', 'RSSI_dBm', 'Channel', 'Frame_type', 'Frame_subtype', 'Retransmission', 'Checksum', 'Source_MAC_address', 'Sequence_number', 'Fragment_number', 'Unique_key'], how='outer')
        self.TRACE1=self.TRACE1.sort_values(by=['Frame_time_epoch','Unique_key'])
 
        diff=list()
        
        # shifting timestamp, unique key and rssi values to facilitate
        # the comparisons and eventually identify the duplicate frames
        self.TRACE1['next_ts']=self.TRACE1['Frame_time_epoch'].shift(-1)
        self.TRACE1['next_key']=self.TRACE1['Unique_key'].shift(-1)
        self.TRACE1['next_rssi']=self.TRACE1['RSSI_dBm'].shift(-1)
        
        # labelling unique and duplicate frames so that frames with best RSSI values are kept
        dup = 0
        for row in self.TRACE1.itertuples():
            if dup == 1:
                diff.append('Unique')
                dup = 0
            elif dup == 2:
                diff.append('Duplicate')
                dup = 0
            elif row.next_key == row.Unique_key:
                k = row.next_ts - row.Frame_time_epoch
                if abs(k) < 106/1000000:
                    if row.next_rssi > row.RSSI_dBm:
                        diff.append('Duplicate')
                        dup = 1
                    else:
                        diff.append('Unique')
                        dup = 2
                else:
                    diff.append('Unique')
            else:
                diff.append('Unique')
        
        if len(diff) < len(self.TRACE1):
            diff.append('Unique')
        self.TRACE1['Unique_or_Duplicate']=diff
        
        # remove the shifted values as their purposed is served
        self.TRACE1 = self.TRACE1.drop(columns=['next_key'])
        self.TRACE1 = self.TRACE1.drop(columns=['next_ts'])
        self.TRACE1 = self.TRACE1.drop(columns=['next_rssi'])
        
        # save the trace with containing unique and duplicate labels for frames
        f = open(directory+'/Merged_Trace_with_Unique-Duplicate_Label.txt','w')
        self.TRACE1.to_csv(f, index=False, header=True, sep='\t')
        f.close()
        
        # drop the duplicate frames from the merged trace
        #self.TRACE1 = self.TRACE1.loc[(self.TRACE1['Unique_or_Duplicate'] == 'Unique') | ~self.TRACE1['Unique_key'].duplicated()]
        self.TRACE1 = self.TRACE1[self.TRACE1.Unique_or_Duplicate != 'Duplicate']
        
        # sort the trace by timestamps
        # remove the "unique" labels
        # re-number the frame numbers
        self.TRACE1 = self.TRACE1.sort_values(by=['Frame_time_epoch'])
        self.TRACE1 = self.TRACE1.drop(columns=['Unique_or_Duplicate'])
        new_frame_no=list(range(1,len(self.TRACE1)+1))
        self.TRACE1['Frame_number']=new_frame_no
        
        # save the final (duplicate frame free) merged trace
        f = open(directory+'/Merged_Trace.txt','w')
        self.TRACE1.to_csv(f, index=False, header=True, sep='\t')
        f.close()
        
        # extracting per user traces
        unique_MAC = self.TRACE1['Source_MAC_address'].unique()
        direct_UserTraces = directory + '/PerUserTraces'
        if not os.path.exists(direct_UserTraces):
            os.makedirs(direct_UserTraces)
        os.chmod(direct_UserTraces, 0o777)
        
        for i in range(len(unique_MAC)):
            per_user_trace = self.TRACE1[self.TRACE1.Source_MAC_address == unique_MAC[i]]
            f = open(direct_UserTraces+'/User_' + str (i+1) + '.txt','w')
            per_user_trace.to_csv(f, index=False, header=True, sep='\t')
        
        print('----------------------------------------------------------------------------------------------')
        print('----------------------------------------------------------------------------------------------')
        print('*****MERGING without duplicates COMPLETED, trace saved in MergedTraces directory*****')
        print('----------------------------------------------------------------------------------------------')
        print('----------------------------------------------------------------------------------------------')
        
        
def main():
    
    start = time.time()
    pypal = PyPal()
    
    parser = argparse.ArgumentParser(description = 'PyPal 1.0 Trace Merging Tool _ *NOTE: Please use only one optional argument at a time*')
    parser.add_argument('trace1', type = str, help='1st trace file name: TRACE TO BE SYNCHRONIZED')
    parser.add_argument('trace2', type = str, help='2nd trace file name: REFERENCE TRACE')
    parser.add_argument('-U', help='Extract unique frames', required = False, nargs='?', const='True')
    parser.add_argument('-R', help='Extract unique reference frames', required = False, nargs='?', const='True')
    parser.add_argument('-SR', help='Synchronize unique reference frames', required = False, nargs='?', const='True')
    parser.add_argument('-S', help='Synchronize traces', required = False, nargs='?', const='True')
    parser.add_argument('-C', help='Concatenate traces (and keep the duplicate frames)', required = False, nargs='?', const='True')
    parser.add_argument('-M', help='Merge traces and remove the duplicate frames within a time difference of 106us', required = False, nargs='?', const='True')
    
    args = parser.parse_args()
    
    if not (args.U or args.R or args.SR or args.S or args.C or args.M):
        parser.error('No action requested, please choose one operation. Please check help for more details')
    
    trace1 = args.trace1
    trace2 = args.trace2
    pypal.U = args.U
    pypal.R = args.R
    pypal.SR = args.SR
    pypal.S = args.S
    pypal.C = args.C

    pypal.trace1_name = str(trace1[0:len(trace1)-4])+".txt"
    pypal.trace2_name = str(trace2[0:len(trace2)-4])+".txt"
    
    pypal.UniqueFrames(trace1, trace2)
    
    print("Time Taken: ", str(time.time()-start))


if __name__ == '__main__':
    main()