forked from chjose/wellbeing-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no_group_by_gen_wellbeing_stats.py
executable file
·2846 lines (2358 loc) · 102 KB
/
no_group_by_gen_wellbeing_stats.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
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
#!/usr/bin/python
__author__ = 'Christin'
from collections import defaultdict
import utils
import glob
from time import localtime, strftime
import datetime
from datetime import date
import sqlite3 as lite
import string
import time
import csv
import math
from collections import Counter
from collections import OrderedDict
import optparse
import json
import numpy
from itertools import groupby
from operator import itemgetter
from geopy.distance import vincenty
import numpy as np
#from matplotlib import pyplot as plt
#from nitime import utils
from nitime import algorithms as alg
#from nitime.timeseries import TimeSeries
#from nitime.viz import plot_tseries
start_time = 0
end_time = 1432176252
parser = optparse.OptionParser("usage %prog "+"-p <path> -f <file> --start <epoch-time> --end <epoch-time> Ex: 'python %prog -p ~ -f my_test'")
parser.add_option('-p', dest='path', type='string', help='Please give the database path(all_data.db) excluding the file name.')
parser.add_option('-f', dest='file', type='string', help='This name will be prepended to the output csv`s generated')
parser.add_option('-i', dest='ignore', type='string', help='Put values as "true" to change the date range ')
parser.add_option('--start', dest='start', type='string', help='Start date for the wellbeing value calculation')
parser.add_option('--end', dest='end', type='string', help='End date for the wellbeing value calculation')
(options, args) = parser.parse_args()
if options.path == None:
f = glob.glob("/net/garms/users/cj279/alldata/New version app/new/*.db")
#f = glob.glob("/net/garms/users/cj279/alldata/New version app/test/*.db")
else:
input_path = options.path + "/*.db"
f = glob.glob(input_path)
file = ""
if options.file != None:
file = options.file
if options.start != None and options.end != None:
start_time = int(options.start)
end_time = int(options.end)
print "Start time and End time"
print start_time
print end_time
if len(f) == 0:
print("Enter a path where there is 'all_data.db' files")
exit()
print(f)
print("WELLBEING INDEX... STATISTICS GENERATION IN PROGRESS...")
files_csv = {}
ar_values = {}
shannons_entropy_stats = {}
shannons_entropy_sms = {}
shannons_entropy_stats_disc = {}
shannons_entropy_sms_disc = {}
shannons_location = {}
shannons_location_update = {}
day_night_location_ratio = {}
weekday_weekend_location_ratio = {}
weekday_weekend_call_ratio = {}
weekday_weekend_sms_ratio = {}
device_imei = {}
location_stats = {}
location_stats_interval = {}
call_type_csv = []
sms_type_csv = []
eligible_days_call = {}
eligible_days_sms = {}
imei_timestamp = {}
imei_num_timestamp = {}
imei_smstimestamp = {}
imei_num_smstimestamp = {}
#New attributes
distinct_contacts = defaultdict(list)
distinct_contacts_sms = defaultdict(list)
call_duration_total = {}
incoming_call_count = {}
outgoing_call_count = {}
missed_call_count = {}
incoming_sms_count = {}
outgoing_sms_count = {}
day_night_call_ratio = {}
day_night_sms_ratio = {}
first_contacts_call = {}
second_contacts_call = {}
new_contacts_call = {}
first_contacts_call_disc = {}
second_contacts_call_disc = {}
new_contacts_call_disc = {}
new_contacts_call_outgoing = {}
first_contacts_call_outgoing = {}
second_contacts_call_outgoing = {}
first_contacts_sms = {}
second_contacts_sms = {}
new_contacts_sms = {}
first_contacts_sms_disc = {}
second_contacts_sms_disc = {}
new_contacts_sms_disc = {}
first_location = {}
second_location = {}
new_location = {}
location_list = {}
duration_call = {}
most_freq_contact_call = {}
response_params_call = {}
response_rate_count = {}
response_latency = {}
response_params_sms = {}
response_rate_count_sms = {}
response_latency_sms = {}
longest_call = {}
distinct_calls_outgoing = {}
first_location_discretionary = {}
second_location_discretionary = {}
new_location_discretionary = {}
shannons_location_discretionary = {}
shannons_location_discretionary3 = {}
con = 0
def write_stats_to_csv():
d = defaultdict(list)
dd = defaultdict(list)
d_duration = defaultdict(list)
cur = con.cursor()
cur.execute("PRAGMA temp_store = 2")
data_imei = cur.execute("""select device, imei from data
where probe like '%Hardware%'""")
for x in data_imei:
imei_num = x[1]
if imei_num!=None:
device_imei[x[0]]=str(imei_num)
#for key, value in device_imei.iteritems():
# print key+" "+value
cur = con.cursor()
cur.execute("PRAGMA temp_store = 2")
data = cur.execute("""select device, timestamp, value from data
where probe like '%Call%'""")
distinct_calls = {}
call_duration = {}
imei_list = device_imei.values()
#print imei_list
for imei in imei_list:
date1 = datetime.date(2015, 2, 12)
date2 = datetime.date(2015, 4, 26)
day = datetime.timedelta(days=1)
while date1 <= date2:
std_mtime = date1.strftime('%Y-%m-%d')
try:
location_stats_interval[imei]
except KeyError:
location_stats_interval[imei] = {}
try:
location_stats_interval[imei][std_mtime]
except KeyError:
location_stats_interval[imei][std_mtime] = {}
location_stats_interval[imei][std_mtime]["00:00-01:00"] = 0
location_stats_interval[imei][std_mtime]["01:00-02:00"] = 0
location_stats_interval[imei][std_mtime]["02:00-03:00"] = 0
location_stats_interval[imei][std_mtime]["03:00-04:00"] = 0
location_stats_interval[imei][std_mtime]["04:00-05:00"] = 0
location_stats_interval[imei][std_mtime]["05:00-06:00"] = 0
location_stats_interval[imei][std_mtime]["06:00-07:00"] = 0
location_stats_interval[imei][std_mtime]["07:00-08:00"] = 0
location_stats_interval[imei][std_mtime]["08:00-09:00"] = 0
location_stats_interval[imei][std_mtime]["09:00-10:00"] = 0
location_stats_interval[imei][std_mtime]["10:00-11:00"] = 0
location_stats_interval[imei][std_mtime]["11:00-12:00"] = 0
location_stats_interval[imei][std_mtime]["12:00-13:00"] = 0
location_stats_interval[imei][std_mtime]["13:00-14:00"] = 0
location_stats_interval[imei][std_mtime]["14:00-15:00"] = 0
location_stats_interval[imei][std_mtime]["15:00-16:00"] = 0
location_stats_interval[imei][std_mtime]["16:00-17:00"] = 0
location_stats_interval[imei][std_mtime]["17:00-18:00"] = 0
location_stats_interval[imei][std_mtime]["18:00-19:00"] = 0
location_stats_interval[imei][std_mtime]["19:00-20:00"] = 0
location_stats_interval[imei][std_mtime]["20:00-21:00"] = 0
location_stats_interval[imei][std_mtime]["21:00-22:00"] = 0
location_stats_interval[imei][std_mtime]["22:00-23:00"] = 0
location_stats_interval[imei][std_mtime]["23:00-24:00"] = 0
date1 = date1 + day
print "CALL RECORDS"
for x in data:
std_mtime = time.strftime('%Y-%m-%d', time.localtime(x[1]))
record_time = int(x[1])
time_of_the_day = time.strftime('%H:%M', time.localtime(x[1]))
number_index = x[2].find('"number"')
last_index = x[2].find(',', number_index)
call_id = x[2][number_index:last_index-4]
# code below for the distinction between the type of call and recording it
if record_time>start_time and record_time<end_time:
formatted_call_record = x[2].replace('\\','').replace('"{','{').replace('}"','}')
#print formatted_call_record
json_call_record = json.loads(formatted_call_record)
#print json_call_record['type']
#print json_call_record['number']['ONE_WAY_HASH']
call_type = json_call_record['type']
call_type_csv_row = []
# outgoing calls
if call_type == 2:
if device_imei[x[0]] in response_params_call:
if 'incoming' in response_params_call[device_imei[x[0]]]:
if json_call_record['number']['ONE_WAY_HASH'] in response_params_call[device_imei[x[0]]]['incoming']:
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
else:
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']] = set()
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
else:
response_params_call[device_imei[x[0]]]['incoming'] = {}
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']] = set()
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
else:
response_params_call[device_imei[x[0]]] = {}
response_params_call[device_imei[x[0]]]['incoming'] = {}
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']] = set()
response_params_call[device_imei[x[0]]]['incoming'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
#Find distinct outgoing calls
# Get the first two weeks contact, comparison date is 3-20-2015
if record_time<1426824000:
if device_imei[x[0]] in first_contacts_call_outgoing:
first_contacts_call_outgoing[device_imei[x[0]]].add(json_call_record['number']['ONE_WAY_HASH'])
else:
first_contacts_call_outgoing[device_imei[x[0]]] = set()
first_contacts_call_outgoing[device_imei[x[0]]].add(json_call_record['number']['ONE_WAY_HASH'])
else:
if device_imei[x[0]] in second_contacts_call_outgoing:
second_contacts_call_outgoing[device_imei[x[0]]].add(json_call_record['number']['ONE_WAY_HASH'])
else:
second_contacts_call_outgoing[device_imei[x[0]]] = set()
second_contacts_call_outgoing[device_imei[x[0]]].add(json_call_record['number']['ONE_WAY_HASH'])
if call_type == 3:
if device_imei[x[0]] in response_params_call:
if 'missed' in response_params_call[device_imei[x[0]]]:
if json_call_record['number']['ONE_WAY_HASH'] in response_params_call[device_imei[x[0]]]['missed']:
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
else:
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']] = set()
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
else:
response_params_call[device_imei[x[0]]]['missed'] = {}
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']] = set()
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
else:
response_params_call[device_imei[x[0]]] = {}
response_params_call[device_imei[x[0]]]['missed'] = {}
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']] = set()
response_params_call[device_imei[x[0]]]['missed'][json_call_record['number']['ONE_WAY_HASH']].add(json_call_record['timestamp'])
try:
if call_type == 1:
#Incoming Call
call_type_csv_row.append(device_imei[x[0]])
call_type_csv_row.append(json_call_record['number']['ONE_WAY_HASH'])
call_type_csv_row.append(json_call_record['timestamp'])
call_type_csv_row.append("Incoming")
call_type_csv_row.append(json_call_record['duration'])
if incoming_call_count.has_key(device_imei[x[0]]):
incoming_call_count[device_imei[x[0]]] += 1
else:
incoming_call_count[device_imei[x[0]]] = 1
if call_type == 2:
#Outgoing Call
call_type_csv_row.append(json_call_record['number']['ONE_WAY_HASH'])
call_type_csv_row.append(device_imei[x[0]])
call_type_csv_row.append(json_call_record['timestamp'])
call_type_csv_row.append("Outgoing")
call_type_csv_row.append(json_call_record['duration'])
if outgoing_call_count.has_key(device_imei[x[0]]):
outgoing_call_count[device_imei[x[0]]] += 1
else:
outgoing_call_count[device_imei[x[0]]] = 1
if call_type == 3:
#Missed Call
call_type_csv_row.append(device_imei[x[0]])
call_type_csv_row.append(json_call_record['number']['ONE_WAY_HASH'])
call_type_csv_row.append(json_call_record['timestamp'])
call_type_csv_row.append("Missed")
call_type_csv_row.append(json_call_record['duration'])
if missed_call_count.has_key(device_imei[x[0]]):
missed_call_count[device_imei[x[0]]] += 1
else:
missed_call_count[device_imei[x[0]]] = 1
if len(call_type_csv_row)>0:
call_type_csv.append(call_type_csv_row)
else:
print "Find the mysterious call types"
print call_type
except KeyError:
pass
# code ends here
try:
distinct_calls[x[0]]
except KeyError:
distinct_calls[x[0]] = defaultdict(list)
distinct_calls[x[0]][std_mtime].append(call_id)
duration_index = x[2].find('"duration"')
duration_index = x[2].find(':', duration_index)
last_index = x[2].find(',', duration_index)
duration_str = x[2][duration_index+1:last_index]
try:
call_duration[x[0]]
except KeyError:
call_duration[x[0]] = {}
try:
call_duration[x[0]][std_mtime] += int(duration_str)
except KeyError:
call_duration[x[0]][std_mtime] = 0
call_duration[x[0]][std_mtime] += int(duration_str)
if record_time>start_time and record_time<end_time:
date_time = datetime.datetime.strptime(std_mtime,'%Y-%m-%d')
try:
device_imei[x[0]]
except KeyError:
device_imei[x[0]] = x[0]
print "imei: "+str(device_imei[x[0]])+"Date: "+str(std_mtime)
try:
shannons_entropy_stats[device_imei[x[0]]]
except KeyError:
call_duration_total[device_imei[x[0]]] = 0
shannons_entropy_stats[device_imei[x[0]]] = {}
day_night_call_ratio[device_imei[x[0]]] = {}
weekday_weekend_call_ratio[device_imei[x[0]]] = {}
first_contacts_call[device_imei[x[0]]] = set()
second_contacts_call[device_imei[x[0]]] = set()
new_contacts_call[device_imei[x[0]]] = set()
first_contacts_call_disc[device_imei[x[0]]] = set()
second_contacts_call_disc[device_imei[x[0]]] = set()
new_contacts_call_disc[device_imei[x[0]]] = set()
most_freq_contact_call[device_imei[x[0]]] = []
try:
shannons_entropy_stats[device_imei[x[0]]][call_id] += 1
except KeyError:
shannons_entropy_stats[device_imei[x[0]]][call_id] = 1
# Get the first two weeks contact, comparison date is 3-20-2015
if record_time<1426824000:
first_contacts_call[device_imei[x[0]]].add(call_id)
else:
second_contacts_call[device_imei[x[0]]].add(call_id)
# Avoid the first two weeks data. Divide the remaining data into two.
# Remove data before 2-26-2015 and split data at 3-26-2015
if record_time>1425010915 and record_time<1427342400:
first_contacts_call_disc[device_imei[x[0]]].add(call_id)
elif record_time>1427342400:
second_contacts_call_disc[device_imei[x[0]]].add(call_id)
if date_time.weekday()==5 or date_time.weekday()==6:
try:
weekday_weekend_call_ratio[device_imei[x[0]]]["weekend"] += 1
except KeyError:
weekday_weekend_call_ratio[device_imei[x[0]]]["weekend"] = 1
else:
try:
weekday_weekend_call_ratio[device_imei[x[0]]]["weekday"] += 1
except KeyError:
weekday_weekend_call_ratio[device_imei[x[0]]]["weekday"] = 1
#Distinct contacts
distinct_contacts[device_imei[x[0]]].append(call_id)
call_duration_total[device_imei[x[0]]] += int(duration_str)
if time_of_the_day>"18:00" and time_of_the_day<"6:00":
try:
day_night_call_ratio[device_imei[x[0]]]["NIGHT"] += 1
except:
day_night_call_ratio[device_imei[x[0]]]["NIGHT"] = 1
else:
try:
day_night_call_ratio[device_imei[x[0]]]["DAY"] += 1
except:
day_night_call_ratio[device_imei[x[0]]]["DAY"] = 1
if device_imei[x[0]] in duration_call:
if call_id in duration_call[device_imei[x[0]]]:
print duration_call[device_imei[x[0]]][call_id]
duration_call[device_imei[x[0]]][call_id]+=int(duration_str)
else:
duration_call[device_imei[x[0]]][call_id] = int(duration_str)
else:
duration_call[device_imei[x[0]]] = {}
duration_call[device_imei[x[0]]][call_id] = int(duration_str)
if device_imei[x[0]] in longest_call:
if longest_call[imei]<int(duration_str):
longest_call[imei] = int(duration_str)
else:
longest_call[imei] = int(duration_str)
#print d
#for row in data:
print "Number of calls for the all the devices on a day"
for imei, value in distinct_calls.iteritems():
for date, inner_list in value.iteritems():
print "\n"
print "Device ID: {}".format(imei)
print "==============================================="
distinct_cal = set(inner_list)
distinct_cal = list(distinct_cal)
distinct_cal.sort()
try:
files_csv[imei]
except KeyError:
files_csv[imei] = {}
if date>'2015-02-11' and date<'2015-04-27':
files_csv[imei][date] = {}
j = len(inner_list)
files_csv[imei][date]["Num of calls"] = j
files_csv[imei][date]["Total Duration"] = call_duration[imei][date]
files_csv[imei][date]["Number of SMS"] = 0
files_csv[imei][date]["Distinct users SMS"] = 0
files_csv[imei][date]["Distinct Locations"] = 0
print "Number of calls on {} is {}".format(imei,j)
print "Total call duration on {} is {} second(s)".format(date,call_duration[imei][date])
j = len(distinct_cal)
files_csv[imei][date]["Distinct Calls"] = j
print "Number of distinct users called on {} is {}".format(date,j)
#print "Call type CSV"
#print call_type_csv
# Response rate for call
for imei, call_type in response_params_call.iteritems():
for type, num_dict in call_type['missed'].iteritems():
for missed_ts in num_dict:
if type in response_params_call[imei]['incoming']:
for incoming in response_params_call[imei]['incoming'][type]:
if (missed_ts+3600)>=incoming and missed_ts<incoming:
if imei in response_rate_count:
response_rate_count[imei]+=1
response_latency[imei]+=(missed_ts+3600)-incoming
else:
response_rate_count[imei] = 1
response_latency[imei]=(missed_ts+3600)-incoming
break
# code ends here
# distinct outgoing calls
for imei, call_type in response_params_call.iteritems():
distinct_calls_outgoing[imei] = len(call_type['incoming'])
# code ends here
########################################
# Discretionary call stats
for imei, value in new_contacts_call_disc.iteritems():
new_contacts_call_disc[imei] = second_contacts_call_disc[imei] - first_contacts_call_disc[imei]
for call in new_contacts_call_disc[imei]:
if imei in shannons_entropy_stats_disc:
shannons_entropy_stats_disc[imei][call] = shannons_entropy_stats[imei][call]
else:
shannons_entropy_stats_disc[imei] = {}
shannons_entropy_stats_disc[imei][call] = shannons_entropy_stats[imei][call]
#print shannons_entropy_stats_disc
#######################################
d = defaultdict(list)
dd = defaultdict(list)
distinct_sms = {}
cur = con.cursor()
cur.execute("PRAGMA temp_store = 2")
data = cur.execute("""select device, timestamp, value from data
where probe like '%Sms%'""")
print "SMS data"
for x in data:
std_mtime = time.strftime('%Y-%m-%d', time.localtime(x[1]))
d[x[0]].append(std_mtime)
time_of_the_day = time.strftime('%H:%M', time.localtime(x[1]))
record_time = int(x[1])
number_index = x[2].find('"address"')
last_index = x[2].find(',', number_index)
call_id = x[2][number_index:last_index-4]
print "Device {} time {} date {} call_id {}".format(x[0],x[1],std_mtime,call_id)
# code below for the distinction between the type of call and recording it
if record_time>start_time and record_time<end_time:
formatted_sms_record = x[2].replace('\\','').replace('"{','{').replace('}"','}')
print formatted_sms_record
json_sms_record = json.loads(formatted_sms_record)
print json_sms_record['type']
print json_sms_record['address']['ONE_WAY_HASH']
sms_type = json_sms_record['type']
sms_type_csv_row = []
try:
device_imei[x[0]]
except KeyError:
device_imei[x[0]] = x[0]
if sms_type == 1:
if device_imei[x[0]] in response_params_sms:
if 'incoming' in response_params_sms[device_imei[x[0]]]:
if json_sms_record['address']['ONE_WAY_HASH'] in response_params_sms[device_imei[x[0]]]['incoming']:
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
else:
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']] = set()
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
else:
response_params_sms[device_imei[x[0]]]['incoming'] = {}
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']] = set()
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
else:
response_params_sms[device_imei[x[0]]] = {}
response_params_sms[device_imei[x[0]]]['incoming'] = {}
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']] = set()
response_params_sms[device_imei[x[0]]]['incoming'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
if sms_type == 2:
if device_imei[x[0]] in response_params_sms:
if 'outgoing' in response_params_sms[device_imei[x[0]]]:
if json_sms_record['address']['ONE_WAY_HASH'] in response_params_sms[device_imei[x[0]]]['outgoing']:
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
else:
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']] = set()
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
else:
response_params_sms[device_imei[x[0]]]['outgoing'] = {}
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']] = set()
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
else:
response_params_sms[device_imei[x[0]]] = {}
response_params_sms[device_imei[x[0]]]['outgoing'] = {}
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']] = set()
response_params_sms[device_imei[x[0]]]['outgoing'][json_sms_record['address']['ONE_WAY_HASH']].add(json_sms_record['timestamp'])
try:
if sms_type == 1:
#Incoming Sms
sms_type_csv_row.append(device_imei[x[0]])
sms_type_csv_row.append(json_sms_record['address']['ONE_WAY_HASH'])
sms_type_csv_row.append(json_sms_record['timestamp'])
sms_type_csv_row.append("Incoming")
if incoming_sms_count.has_key(device_imei[x[0]]):
incoming_sms_count[device_imei[x[0]]] += 1
else:
incoming_sms_count[device_imei[x[0]]] = 1
if sms_type == 2:
#Outgoing Sms
sms_type_csv_row.append(json_sms_record['address']['ONE_WAY_HASH'])
sms_type_csv_row.append(device_imei[x[0]])
sms_type_csv_row.append(json_sms_record['timestamp'])
sms_type_csv_row.append("Outgoing")
if outgoing_sms_count.has_key(device_imei[x[0]]):
outgoing_sms_count[device_imei[x[0]]] += 1
else:
outgoing_sms_count[device_imei[x[0]]] = 1
if len(sms_type_csv_row)>0:
sms_type_csv.append(sms_type_csv_row)
else:
print "DANGER"
print sms_type
except KeyError:
pass
# code ends here
try:
distinct_sms[x[0]]
except KeyError:
distinct_sms[x[0]] = defaultdict(list)
distinct_sms[x[0]][std_mtime].append(call_id)
if record_time>start_time and record_time<end_time:
date_time = datetime.datetime.strptime(std_mtime,'%Y-%m-%d')
try:
device_imei[x[0]]
except KeyError:
device_imei[x[0]] = x[0]
print "imei: "+str(device_imei[x[0]])+"Date: "+str(std_mtime)
try:
shannons_entropy_sms[device_imei[x[0]]]
except KeyError:
shannons_entropy_sms[device_imei[x[0]]] = {}
day_night_sms_ratio[device_imei[x[0]]] = {}
weekday_weekend_sms_ratio[device_imei[x[0]]] = {}
first_contacts_sms[device_imei[x[0]]] = set()
second_contacts_sms[device_imei[x[0]]] = set()
new_contacts_sms[device_imei[x[0]]] = set()
first_contacts_sms_disc[device_imei[x[0]]] = set()
second_contacts_sms_disc[device_imei[x[0]]] = set()
new_contacts_sms_disc[device_imei[x[0]]] = set()
try:
shannons_entropy_sms[device_imei[x[0]]][call_id] += 1
except KeyError:
shannons_entropy_sms[device_imei[x[0]]][call_id] = 1
#Distinct contacts
distinct_contacts_sms[device_imei[x[0]]].append(call_id)
# Get the first two weeks contact, comparison date is 3-20-2015
if record_time<1426824000:
first_contacts_sms[device_imei[x[0]]].add(call_id)
else:
second_contacts_sms[device_imei[x[0]]].add(call_id)
# Avoid the first two weeks data. Divide the remaining data into two.
# Remove data before 2-26-2015 and split data at 3-26-2015
if record_time>1425010915 and record_time<1427342400:
first_contacts_sms_disc[device_imei[x[0]]].add(call_id)
elif record_time>1427342400:
second_contacts_sms_disc[device_imei[x[0]]].add(call_id)
if date_time.weekday()==5 or date_time.weekday()==6:
try:
weekday_weekend_sms_ratio[device_imei[x[0]]]["weekend"] += 1
except KeyError:
weekday_weekend_sms_ratio[device_imei[x[0]]]["weekend"] = 1
else:
try:
weekday_weekend_sms_ratio[device_imei[x[0]]]["weekday"] += 1
except KeyError:
weekday_weekend_sms_ratio[device_imei[x[0]]]["weekday"] = 1
if time_of_the_day>"18:00" and time_of_the_day<"6:00":
try:
day_night_sms_ratio[device_imei[x[0]]]["NIGHT"] += 1
except:
day_night_sms_ratio[device_imei[x[0]]]["NIGHT"] = 1
else:
try:
day_night_sms_ratio[device_imei[x[0]]]["DAY"] += 1
except:
day_night_sms_ratio[device_imei[x[0]]]["DAY"] = 1
# Response rate for sms
for imei, sms_type in response_params_sms.iteritems():
for type, num_dict in sms_type['incoming'].iteritems():
for incoming_ts in num_dict:
if 'outgoing' in response_params_sms[imei]:
if type in response_params_sms[imei]['outgoing']:
for outgoing in response_params_sms[imei]['outgoing'][type]:
if (incoming_ts+3600)>=outgoing and missed_ts<outgoing:
if imei in response_rate_count_sms:
response_rate_count_sms[imei]+=1
response_latency_sms[imei]+=(missed_ts+3600)-outgoing
else:
response_rate_count_sms[imei] = 1
response_latency_sms[imei]=(missed_ts+3600)-outgoing
break
# code ends here
print "Number of SMS for all devices on a day"
for imei, value in distinct_sms.iteritems():
for date, inner_list in value.iteritems():
print "\n"
print "Device ID: {}".format(imei)
print "==============================================="
distinct_msg = set(inner_list)
distinct_msg = list(distinct_msg)
distinct_msg.sort()
try:
files_csv[imei]
except KeyError:
files_csv[imei] = {}
j = len(inner_list)
if date>'2015-02-11' and date<'2015-04-27':
try:
files_csv[imei][date]
except KeyError:
files_csv[imei][date] = {}
files_csv[imei][date]["Total Duration"] = 0
files_csv[imei][date]["Distinct Calls"] = 0
files_csv[imei][date]["Num of calls"] = 0
files_csv[imei][date]["Distinct Locations"] = 0
files_csv[imei][date]["Number of SMS"] = j
print "Number of sms on {} is {}".format(imei,j)
j = len(distinct_msg)
files_csv[imei][date]["Distinct users SMS"] = j
print "Number of distinct sms called on {} is {}".format(date,j)
########################################
# Discretionary sms stats
for imei, value in new_contacts_sms_disc.iteritems():
new_contacts_sms_disc[imei] = second_contacts_sms_disc[imei] - first_contacts_sms_disc[imei]
for call in new_contacts_sms_disc[imei]:
if imei in shannons_entropy_sms_disc:
shannons_entropy_sms_disc[imei][call] = shannons_entropy_sms[imei][call]
else:
shannons_entropy_sms_disc[imei] = {}
shannons_entropy_sms_disc[imei][call] = shannons_entropy_sms[imei][call]
#print shannons_entropy_sms_disc
#exit()
#######################################
cur = con.cursor()
times_list = []
devices = []
distinct_locations = {}
cur = con.cursor()
cur.execute("PRAGMA temp_store = 2")
data = cur.execute("""select device, value, timestamp from data
where probe like '%Location%'""")
old_str = 0
print "LOCATION DATA"
for x in data:
temp1 = x[1].find('"mTime"')
if temp1 > 0:
temp1 += 8
try:
new_str = int(x[1][temp1:temp1+13])/1000
std_mtime = time.strftime('%Y-%m-%d', time.localtime(new_str))
except ValueError:
print "UNIQUE STRING"
std_mtime = time.strftime('%Y-%m-%d', time.localtime(x[2]))
else:
new_str = x[2];
std_mtime = time.strftime('%Y-%m-%d', time.localtime(x[2]))
record_time = int(x[2])
long_index = x[1].find('"mLongitude"')
last_index = x[1].find(',', long_index)
cordinate = x[1][long_index+13:last_index]
fvalue_cordiante = float(cordinate)
long_int = float("{0:.4f}".format(fvalue_cordiante))
lat_index = x[1].find('"mLatitude"')
last_index = x[1].find(',', lat_index)
cordinate = x[1][lat_index+12:last_index]
fvalue_cordiante = float(cordinate)
lat_int = float("{0:.4f}".format(fvalue_cordiante))
location_str = str(long_int) + " " + str(lat_int)
try:
distinct_locations[x[0]]
except KeyError:
distinct_locations[x[0]] = defaultdict(list)
distinct_locations[x[0]][std_mtime].append(location_str)
# For shannon's entropy calculation
location_bin = str(long_int) + " " + str(lat_int)
# Location verbose and intervals
time_long_lat_list = [time.strftime('%H:%M', time.localtime(new_str)), str(long_int), str(lat_int), new_str]
print time_long_lat_list
if record_time>start_time and record_time<end_time:
try:
device_imei[x[0]]
except KeyError:
device_imei[x[0]] = x[0]
print "imei: "+str(device_imei[x[0]])+"Date: "+str(std_mtime)
try:
shannons_location[device_imei[x[0]]]
except KeyError:
shannons_location[device_imei[x[0]]] = {}
try:
shannons_location[device_imei[x[0]]][location_bin] += 1
except KeyError:
shannons_location[device_imei[x[0]]][location_bin] = 1
print "Entry made"
try:
device_imei[x[0]]
except KeyError:
device_imei[x[0]] = x[0]
try:
location_stats[device_imei[x[0]]]
except KeyError:
location_stats[device_imei[x[0]]] = {}
try:
location_stats[device_imei[x[0]]][std_mtime]
except KeyError:
location_stats[device_imei[x[0]]][std_mtime] = []
location_stats[device_imei[x[0]]][std_mtime].append(time_long_lat_list)
########################################
# Code to get only the first location of an hour.
list_of_lists = []
location_stats_interval_copy = location_stats_interval
first_lat_long_hour = {}
for imei, date in location_stats.iteritems():
for date_key, time_long_lat in date.iteritems():
for element in time_long_lat:
time_hour = element[0][:element[0].index(":")]
print(time_hour)
record_time = int(element[3])
plus_one = int(time_hour)+1
if plus_one<10:
plus_one = "0"+str(plus_one)
else:
plus_one = str(plus_one)
interval_string = time_hour+":00-"+str(plus_one)+":00"
print interval_string
try:
if location_stats_interval_copy[imei][date_key][interval_string] == 0 and int(element[3])>start_time and int(element[3])<end_time:
location_stats_interval_copy[imei][date_key][interval_string]+=1
ref = imei+date_key+interval_string
location_bin = str(element[1]) + " " + str(element[2])
try:
shannons_location_update[imei]
shannons_location_discretionary[imei]
day_night_location_ratio[imei]
except KeyError:
shannons_location_update[imei] = {}
shannons_location_discretionary[imei] = {}
day_night_location_ratio[imei] = {}
first_location[imei] = set()
second_location[imei] = set()
location_list[imei] = []
first_location_discretionary[imei] = set()
second_location_discretionary[imei] = set()
new_location_discretionary[imei] = set()
new_location[imei] = set()
lng = float("{0:.2f}".format(float(element[1])))
lat = float("{0:.2f}".format(float(element[2])))
lng3 = float("{0:.3f}".format(float(element[1])))
lat3 = float("{0:.3f}".format(float(element[2])))
location_bin3 = str(lng3) + " " + str(lat3)
# Get the first two weeks contact, comparison date is 3-20-2015
if record_time<1426824000:
first_location[imei].add(str(lng)+" "+str(lat))
else:
second_location[imei].add(str(lng)+" "+str(lat))
location_list[imei].append(str(lng)+" "+str(lat))
# Avoid the first two weeks data. Divide the remaining data into two.
# Remove data before 2-26-2015 and split data at 3-26-2015
if record_time>1425010915 and record_time<1427342400:
first_location_discretionary[imei].add(str(lng3)+" "+str(lat3))
elif record_time>1427342400:
second_location_discretionary[imei].add(str(lng3)+" "+str(lat3))
try:
shannons_location_update[imei][location_bin] += 1
shannons_location_discretionary[imei][location_bin3] += 1
except KeyError:
shannons_location_update[imei][location_bin] = 1
shannons_location_discretionary[imei][location_bin3] = 1
if element[0]>"18:00" and element[0]<"6:00":
try:
day_night_location_ratio[imei]["NIGHT"]
except:
day_night_location_ratio[imei]["NIGHT"] = {}
try:
day_night_location_ratio[imei]["NIGHT"][location_bin] += 1
except KeyError:
day_night_location_ratio[imei]["NIGHT"][location_bin] = 1
else:
try:
day_night_location_ratio[imei]["DAY"]
except:
day_night_location_ratio[imei]["DAY"] = {}
try:
day_night_location_ratio[imei]["DAY"][location_bin] += 1
except KeyError:
day_night_location_ratio[imei]["DAY"][location_bin] = 1
first_lat_long_hour[ref] = [element[1], element[2]]
except KeyError:
print "KeyError in location interval"
print imei
print "OUPUT!!!!!"
list_of_lists = []
for imei, date_1 in location_stats_interval_copy.iteritems():
for date_key, interval in date_1.iteritems():
for time_slot, freq in interval.iteritems():
if freq>0:
ref = imei+date_key+time_slot
row = [imei, date_key, time_slot, freq, first_lat_long_hour[ref][0], first_lat_long_hour[ref][1]]
else:
row = [imei, date_key, time_slot, freq, 0, 0]
#print row
list_of_lists.append(row)
list_of_lists.sort(key=lambda x:(x[0], x[1], x[2]))
if len(file) > 0:
resultFile = open(file + "_location_interval_first_location.csv",'wb')
else:
resultFile = open("output_location_interval_first_location.csv",'wb')
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(['IMEI','Day','Time_slot','Frequency','Longitude','Latitude'])
for x in list_of_lists:
row = [x[0],x[1],x[2],x[3],x[4],x[5]]
wr.writerow(row)
resultFile.close()
########################################
# Discretionary travel stats
for imei, value in new_location_discretionary.iteritems():
new_location_discretionary[imei] = second_location_discretionary[imei] - first_location_discretionary[imei]