-
Notifications
You must be signed in to change notification settings - Fork 6
/
heraldrisk.R
1173 lines (979 loc) · 56.3 KB
/
heraldrisk.R
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
# Apache 2.0 licensed
#
# Copyright (c) 2021 Herald Project Contributors
#
# Author Adam Fowler <adam@adamfowler.org>
# This file holds the Herald Risk calibration and scoring library for R
library(ggplot2)
library(parsedate)
library(stringr)
library(moments) # For skewness calculation
library(zoo) # rolling mean
library(lubridate) # working with time durations
library(fitdistrplus) # gamma distribution fitting
library(slider) # sliding time window
library(scales) # date format in charts
generateDefaultHeraldLibrarySettings <- function() {
data.frame(
filterTimeMin <- NA,
filterTimeMax <- NA,
filterWithoutTxPower <- TRUE,
outputFolder <- ".",
outputFilePrefix <- "", # E.g. phonedir plus hyphen
groupText <- "", # differentiating text when running the same output function multiple times
chartWidth <- 400,
chartHeight <- 300,
ignoreHeraldDevices <- TRUE,
heraldCsvDateFormat <- "%Y-%m-%d %H:%M:%S" # PRE v2.1.0-beta3 - integer seconds
#heraldCsvDateFormat <- "%Y-%m-%d %H:%M:%OS3%z" # v2.1.0-beta3 onwards - 3 decimal places of seconds with timezone as E.g. -0800
)
}
getmode <- function(v) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
initialDataPrepAndFilter <- function(settings, dataFrame) {
# We only care about measures (and their RSSI and TxPower values)
# i.e. the didMeasure calls (for ALL nearby devices, prefiltering)
measures <- dplyr::filter(dataFrame,measure==3)
#head(measures)
measures <- dplyr::select(measures,c("time","id","data"))
##measures <- dplyr::distinct(measures) # DO NOT DO THIS - reduces RSSI data
names(measures) <- c("time","macuuid","data")
#head(measures)
if (settings$ignoreHeraldDevices[1]) {
# Collect macuuids for devices with Herald payloads
# We will use our two known contacts to test the final risk score algorithm
print(" - Filtering out Herald devices from dataset")
heraldcontacts <- dplyr::filter(dataFrame,read==2)
measures <- dplyr::filter(measures, !(macuuid %in% heraldcontacts$id) )
}
# Filter by time
measures$t <- as.POSIXct(measures$time, format=settings$heraldCsvDateFormat[1])
measures <- dplyr::filter(measures,t>=settings$filterTimeMin[1])
measures <- dplyr::filter(measures,t<=settings$filterTimeMax[1])
#head(measures)
# Now extract RSSI and txPower (if present)
# Example $data value: RSSI:-97.0[BLETransmitPower:8.0]
rssiAndTxPowerPattern <- "RSSI:(-[0-9]+\\.0)(.BLETransmitPower:([0-9.]+).)?"
matches <- stringr::str_match(measures$data,rssiAndTxPowerPattern)
#head(matches)
measures$rssi <- stringr::str_match(measures$data,rssiAndTxPowerPattern)[,2]
measures$txpower <- stringr::str_match(measures$data,rssiAndTxPowerPattern)[,4]
# if (settings$filterWithoutTxPower[1]) {
# #head(measures)
# } else {
# measures$txpower <- NA
# }
# Filter out those without RSSI
measures <- dplyr::filter(measures,!is.na(rssi))
measures$rssiint <- as.numeric(measures$rssi)
#head(measures)
measures
}
## IMPORTANT filter nonsense RSSI readings before proceeding
# Contrary to popular believe, RSSI is NOT -127->128 on phones
# It's only valid -1 to -98
# -99 Is used by some bluetooth chip manufacturers to indicate "valid packet but extreme range"
# -100 to -106 are used as error flags for some manufacturers
# Removes error values. Does not attempt to remove any data based on situation/calibration
filterRawData <- function(dataFrame) {
dplyr::filter(dataFrame,rssiint > -99 & rssiint < 0)
}
calcCEStats <- function(dataFrame) {
#cestats <- dataFrame %>%
# dplyr::group_by(macuuid) %>%
# dplyr::summarise(n=dplyr::n(), mint=min(t), maxt=max(t), difft=maxt-mint, sdrssi=sd(rssiint), meanrssi=mean(rssiint), moderssi=getmode(rssiint), minrssi=min(rssiint), maxrssi=max(rssiint), rangerssi=max(rssiint)-min(rssiint)) %>%
# dplyr::arrange(dplyr::desc(n))
#cestats$durmin <- as.numeric(as.POSIXct(cestats$difft)$seconds) / 60 #assume seconds conversion
#head(cestats)
cestats <- dataFrame %>%
dplyr::group_by(macuuid) %>%
dplyr::summarise(n=dplyr::n(), mint=min(t), maxt=max(t), difft=as.numeric(maxt)-as.numeric(mint), sdrssi=sd(rssiint), meanrssi=mean(rssiint), moderssi=getmode(rssiint), minrssi=min(rssiint), maxrssi=max(rssiint), rangerssi=max(rssiint)-min(rssiint)) %>%
dplyr::arrange(dplyr::desc(n))
cestats$durmin <- cestats$difft / 60 # seconds to minutes
cestats
}
chartCEStats <- function(settings,dataFrameCE) {
print(" - chartCEStats")
if (settings$generateCharts[1]) {
p <- ggplot(dataFrameCE, aes(x=meanrssi,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
labs(x="Mean RSSI",
y="Relative Frequency",
title="Mean RSSI Chart",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-meanrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=moderssi,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
labs(x="Mode RSSI",
y="Relative Frequency",
title="Mode RSSI Chart",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-moderssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=sdrssi,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
labs(x="SD RSSI",
y="Relative Frequency",
title="SD RSSI Chart",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-sdrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=minrssi,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
labs(x="Minimum RSSI",
y="Relative Frequency",
title="Minimum RSSI Chart",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-minrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=maxrssi,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
labs(x="Maximum RSSI",
y="Relative Frequency",
title="Maximum RSSI Chart",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-maxrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
# Show maxrssi by meanrssi and similar scatter plots
p <- ggplot(dataFrameCE, aes(x=meanrssi, y=maxrssi,color=1, fill=1)) +
geom_point(alpha=0.5, show.legend = F) +
labs(x="Mean RSSI",
y="Max RSSI",
title="Mean vs Max RSSI",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-meanvsmaxrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=meanrssi, y=minrssi,color=1, fill=1)) +
geom_point(alpha=0.5, show.legend = F) +
labs(x="Mean RSSI",
y="Min RSSI",
title="Mean vs Min RSSI",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-meanvsminrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=meanrssi, y=rangerssi,color=1, fill=1)) +
geom_point(alpha=0.5, show.legend = F) +
labs(x="Mean RSSI",
y="Range RSSI",
title="Mean vs Range RSSI",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-meanvsrangerssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=meanrssi, y=sdrssi,color=1, fill=1)) +
geom_point(alpha=0.5, show.legend = F) +
labs(x="Mean RSSI",
y="SD RSSI",
title="Mean vs SD RSSI",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-meanvssdrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
p <- ggplot(dataFrameCE, aes(x=maxrssi, y=minrssi,color=1, fill=1)) +
geom_point(alpha=0.5, show.legend = F) +
labs(x="Max RSSI",
y="Min RSSI",
title="Max vs Min RSSI",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-maxvsminrssi.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
print(" - Done")
} else {
print(" - Skipping")
}
}
chartCEDuration <- function(settings, dataFrameCE, durationLimitMins) {
print(" - chartCEDuration")
if (settings$generateCharts[1]) {
cestatslim <- dataFrameCE
cestatslim$durmin[cestatslim$durmin > durationLimitMins] <- durationLimitMins
p <- ggplot(cestatslim, aes(x=durmin,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
labs(x="Duration (minutes)",
y="Relative Frequency",
title="Contact Event Duration Frequency",
subtitle=paste("Across all interactions (max of ",durationLimitMins," minutes)",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-duration.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
print(" - Done")
} else {
print(" - Skipping")
}
}
chartCEReadingsCount <- function(settings, dataFrameCE, readingCountLimit) {
print(" - chartCEReadingsCount")
if (settings$generateCharts[1]) {
# Also show a chart of number of readings for each contact event, in the tens of readings
cestatscntlim <- dataFrameCE
cestatscntlim$n[cestatscntlim$n > readingCountLimit] <- readingCountLimit
p <- ggplot(cestatscntlim, aes(x=n,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=5, show.legend = F, aes( y=..density.. )) +
labs(x="Readings (count)",
y="Relative Frequency",
title="Contact Event Reading Count Frequency",
subtitle=paste("Across ",settings$groupText[1]," interactions (limited to n=",readingCountLimit,")",sep=""))
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"ce-",settings$groupText[1],"-readingcount.png", sep=""),
width = settings$chartWidth[1], height = settings$chartHeight[1], units = "mm")
print(" - Done")
} else {
print(" - Skipping")
}
}
# Corrects for TxPower, which implies filtering raw data for TxPower
#filterAndCorrectForTxPower <- function(dataFrame) {
# # Filter data for those with TxPower
# withTx <- dplyr::filter(dataFrame,!is.na(txpower))
# # Create txpowerint
# withTx$txpowerint <- as.numeric(withTx$txpower)
# # Correct data
# withTx$rssicor <- withTx$rssiint - withTx$txpowerint
# withTx
#}
# This function corrects for TxPower too, and reverses the order. Centred around txPower per phone (0dBm) rather than overall
txAndReverse <- function(dataFrame) {
# Filter data for those with TxPower
withTx <- dplyr::filter(dataFrame,!is.na(txpower))
# Create txpowerint
withTx$txpowerint <- as.numeric(withTx$txpower)
# Correct data
withTx$rssicor <- withTx$txpowerint - withTx$rssiint
withTx
}
# TODO function to infer TxPower from each contact event's individual distribution
## Smooth each contact event's rssi value over time
#smooth <- function(dataFrame, smoothingWidth) {
# # Order data by ascending time (should be by default)
# # For each macuuid (contact event), smooth over up to given number of readings (smoothingWidth)
#
#}
# TODO a version of the above that is sensitive to time between readings
# TODO function that assigns contact event id so that repeated mac addresses from different devices do not interfere with long lived data
# SECTION - Single data column functions
# No longer used
#justReverse <- function(dataFrame) {
# mydf <- dataFrame
# maxValue <- max(mydf$rssiint)
# mydf$rssicor <- maxValue - mydf$rssiint + 1.0
# mydf
#}
# Doesn't really use a 'reference tx power' yet, simple hardcoding reverse
# Not currently used, but left for when we allow inclusion of non txpower corrected data
referenceTxAndReverse <- function(dataFrame) {
mydf <- dataFrame
mydf$rssicor <- 1.0 - mydf$rssiint
mydf
}
chartProximity <- function(settings, dataFrame) {
print(paste("chartProximity for ",settings$groupText[1],sep=""))
print(" - Charting prox values")
if (settings$generateCharts[1]) {
# Graph 1a&b - Show RSSI frequencies by macuuid across whole time period
# Note: As devices rotate mac address, some devices will be the same but
# appear as different mac addresses
p <- ggplot(dataFrame, aes(x=rssicor, color=macuuid, fill=macuuid)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend=F) +
labs(x=paste(settings$groupText[1]," proximity",sep=""),
y="Count of each proximity value",
title="Proximity histogram for each phone detected",
subtitle="Some phones may be duplicates") +
theme(legend.position = "bottom")
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],settings$groupText[1],"-proximity-values.png", sep=""),
width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
print(" - Done")
} else {
print(" - Skipped")
}
print(" - Charting prox density")
if (settings$generateCharts[1]) {
p <- ggplot(dataFrame, aes(x=rssicor, y=..density.. , color=macuuid, fill=macuuid)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend=F) +
geom_density(alpha=0.3, fill=NA, show.legend = F) +
labs(x=paste(settings$groupText[1]," proximity",sep=""),
y="Relative Density",
title="Proximity histogram for each phone detected",
subtitle="Some phones may be duplicates") +
theme(legend.position = "bottom")
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"",settings$groupText[1],"-proximity-density.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
# Graph 2 - Smoothed line of rssi over time (3 degrees of freedom)
print(" - Charting prox over time")
if (settings$generateCharts[1]) {
p <- ggplot(dataFrame, aes(x=t,y=rssicor,color=macuuid)) +
geom_point(show.legend = F) +
labs(x="Time",
y=paste(settings$groupText[1]," proximity",sep=""),
title="Proximity detected over time",
subtitle="Some phones may be duplicates") +
scale_x_datetime(date_breaks = "10 min", date_minor_breaks = "2 min")
# scale_x_datetime(date_breaks = "60 min", date_minor_breaks = "10 min")
# + geom_smooth(method="lm", formula=y ~ poly(x,3), show.legend = F)
# geom_smooth(method="loess")
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"",settings$groupText[1],"-proximity-over-time.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
print(" - Calculating most CE and longest CE")
mostdatacontactevents <- dataFrame %>%
dplyr::group_by(macuuid) %>%
dplyr::summarise(n=dplyr::n(), mint=min(t), maxt=max(t), difft=maxt-mint) %>%
dplyr::arrange(dplyr::desc(n))
mostdatacontactevents <- dplyr::slice_head(mostdatacontactevents, n=50)
head(mostdatacontactevents)
NROW(mostdatacontactevents)
measuresinrangewithmostdata <- dplyr::filter(dataFrame, macuuid %in% mostdatacontactevents$macuuid)
head(measuresinrangewithmostdata)
measuresinrangewithmostdatanomean <- measuresinrangewithmostdata
## Note: Pre-v2.1.0-beta3 workaround for multiple readings at same integer second point in time (as it skews running mean line otherwise)
measuresinrangewithmostdata <- measuresinrangewithmostdata %>%
dplyr::group_by(macuuid,t) %>%
dplyr::summarise(rssicor=mean(rssicor))
head(measuresinrangewithmostdata)
longestcontactevents <- mostdatacontactevents %>%
dplyr::arrange(dplyr::desc(difft))
longestcontactevents <- dplyr::slice_head(longestcontactevents, n=20)
head(longestcontactevents)
NROW(longestcontactevents)
measuresinrangewithlongestduration <- dplyr::filter(dataFrame, macuuid %in% longestcontactevents$macuuid)
head(measuresinrangewithlongestduration)
## Note: Pre-v2.1.0-beta3 workaround for multiple readings at same integer second point in time (as it skews running mean line otherwise)
measuresinrangewithlongestduration <- measuresinrangewithlongestduration %>%
dplyr::group_by(macuuid,t) %>%
dplyr::summarise(rssicor=mean(rssicor))
head(measuresinrangewithlongestduration)
print(" - Charting top50 ce by data quantity")
if (settings$generateCharts[1]) {
p <- ggplot(measuresinrangewithmostdata, aes(x=t,y=rssicor,color=macuuid)) +
geom_point(show.legend = F) +
labs(x="Time",
y=paste(settings$groupText[1]," Proximity",sep=""),
title="Proximity detected over time",
subtitle="50 Contact Events with most in range data only") +
geom_line(aes(y=zoo::rollmean(rssicor, 5, na.pad=TRUE))) +
scale_x_datetime(date_breaks = "5 min", date_minor_breaks = "1 min") +
facet_wrap(~macuuid, ncol=5, nrow=10, scales="free") +
theme(legend.position = "none")
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"",settings$groupText[1],"-proximity-over-time-top50.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
print(" - Charting top20 ce by duration")
if (settings$generateCharts[1]) {
p <- ggplot(measuresinrangewithlongestduration, aes(x=t,y=rssicor,color=macuuid)) +
geom_point(show.legend = F) +
labs(x="Time",
y=paste(settings$groupText[1]," Proximity",sep=""),
title="Proximity detected over time",
subtitle="20 Contact Events withlongest duration") +
geom_line(aes(y=zoo::rollmean(rssicor, 5, na.pad=TRUE))) +
scale_x_datetime(date_breaks = "5 min", date_minor_breaks = "1 min") +
facet_wrap(~macuuid, ncol=4, nrow=5, scales="free") +
theme(legend.position = "none")
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"",settings$groupText[1],"-proximity-over-time-longest20.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
# Density of ones with most data, above
print(" - Charting density of top50 ce by duration")
if (settings$generateCharts[1]) {
p <- ggplot(measuresinrangewithmostdata, aes(x=rssicor, y=..density.. , color=macuuid, fill=macuuid)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend=F) +
geom_density(alpha=0.3, fill=NA, show.legend = F) +
labs(x=paste(settings$groupText[1]," Proximity",sep=""),
y="Relative Density",
title="Proximity histogram for each phone detected",
subtitle="Top 50 events with most data") +
facet_wrap(~macuuid, ncol=5, nrow=10, scales="free") +
theme(legend.position = "bottom")
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"",settings$groupText[1],"-proximity-density-top50.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
}
printSummary <- function(settings,dataFrame) {
ce <- dataFrame %>%
dplyr::group_by(macuuid) %>%
dplyr::summarise(mean=mean(rssicor), sd=sd(rssicor), min=min(rssicor), max=max(rssicor), range=max-min, n=dplyr::n())
totalces <- NROW(ce)
meanRange <- mean(ce$range)
sdRange <- sd(ce$range)
# Print number of readings total
print(
paste("Summary of ",settings$groupText[1],
": Readings=",NROW(dataFrame$rssicor),
", Contact Events=",totalces,
", Mean range=",meanRange,
", SD range=",sdRange,
sep=""
)
)
}
# DUplicate/no longer used
#filterForCERange <- function(dataFrame, minRange) {
# ce <- dataFrame %>%
# dplyr::group_by(macuuid) %>%
# dplyr::summarise(mean=mean(rssicor), sd=sd(rssicor), min=min(rssicor), max=max(rssicor), range=max-min, n=dplyr::n())
# ce <- dplyr::filter(ce, range >= minRange)
# filtered <- dplyr::filter(dataFrame, macuuid %in% ce$macuuid)
#}
filterContactEvents <- function (dataFrame, statsData, configuration) {
res <- dataFrame
# count lower and higher than 25 mins
#celong <- dplyr::filter(statsData, durmin >= 60)
#cemiddle <- dplyr::filter(statsData, durmin >= 26 & durmin < 60)
ceshort <- dplyr::filter(statsData, durmin < 26)
#NROW(celong)
#NROW(cemiddle)
NROW(ceshort)
# Filter remaining data by those likely as phones (with BL E Privacy enabled)
NROW(res)
res <- dplyr::filter(res, macuuid %in% ceshort$macuuid)
NROW(res)
# Filter out contact events with less than 35 readings
cestatscntenough <- dplyr::filter(statsData, n > 35)
res <- dplyr::filter(res, macuuid %in% cestatscntenough$macuuid)
NROW(res)
# Filter for maxrssi
cestatsmaxrssi <- statsData
cestatsmaxrssi <- dplyr::filter(cestatsmaxrssi, maxrssi > -90)
res <- dplyr::filter(res, macuuid %in% cestatsmaxrssi$macuuid)
NROW(res)
# Filter for meanrssi
cestatsmeanrssi <- statsData
cestatsmeanrssi <- dplyr::filter(cestatsmeanrssi, meanrssi > -80)
res <- dplyr::filter(res, macuuid %in% cestatsmeanrssi$macuuid)
NROW(res)
# Filter for rangerssi > 5 NOTE SUPERCEDED BY LATER FILTER
#cestatsrangerssi <- statsData
#cestatsrangerssi <- dplyr::filter(cestatsrangerssi, rangerssi > 5)
#res <- dplyr::filter(res, macuuid %in% cestatsrangerssi$macuuid)
#NROW(res)
# Filter for cerange > 10
cerangegte10 <- statsData
cerangegte10 <- dplyr::filter(cerangegte10, rangerssi >= 10)
res <- dplyr::filter(res, macuuid %in% cerangegte10$macuuid)
NROW(res)
res
}
calculateCentralAndUpperPeak <- function(settings, dataFrame) {
meanrssitxcor <- mean(dataFrame$rssicor)
sdrssitxcor <- sd(dataFrame$rssicor)
countrssitxcor <- NROW(dataFrame)
minrssitxcor <- min(dataFrame$rssicor)
maxrssitxcor <- max(dataFrame$rssicor)
skewrssitxcor <- moments::skewness(dataFrame$rssicor, na.rm = TRUE)
kurtosisrssitxcor <- moments::kurtosis(dataFrame$rssicor, na.rm = TRUE)
weakmintxcor <- min(meanrssitxcor + (3 * sdrssitxcor), max(dataFrame$rssicor))# -98 is the boundary value for bluetooth chips to receive data, so ignore
weakmaxtxcor <- (meanrssitxcor + (2 * sdrssitxcor))
strongmintxcor <- (meanrssitxcor - (2 * sdrssitxcor))
strongmaxtxcor <- max(meanrssitxcor - (4 * sdrssitxcor), 0)
# Filter those so we're left with those between 2 and 3 SD only
dataExtremeties <- dataFrame %>%
dplyr::filter(
(rssicor >= strongmaxtxcor & rssicor < strongmintxcor)
|
(rssicor <= weakmintxcor & rssicor > weakmaxtxcor )
)
# - Second, for each RSSI, find local proportion above the curve (local maxima) beyond 1 SD
rssicountstxcor <- dataExtremeties %>%
dplyr::group_by(rssicor) %>%
dplyr::summarise(cnt=dplyr::n())
rssicountstxcor$probrssi <- countrssitxcor *
(pnorm(rssicountstxcor$rssicor - 0.5, mean = meanrssitxcor, sd = sdrssitxcor, lower.tail=FALSE) -
pnorm(rssicountstxcor$rssicor + 0.5, mean = meanrssitxcor, sd = sdrssitxcor, lower.tail=FALSE)
)
# rssicountstxcor$probrssi <- countrssitxcor *
# (pgamma(rssicountstxcor$rssicor - 0.5, shape = gammashape, rate = gammarate, lower.tail=FALSE) -
# pgamma(rssicountstxcor$rssicor + 0.5, shape = gammashape, rate = gammarate, lower.tail=FALSE)
# )
rssicountstxcor$abovecurve <- rssicountstxcor$cnt - rssicountstxcor$probrssi
head(rssicountstxcor)
#rssicountstxcor <- dplyr::filter(rssicountstxcor, abovecurve > 0) # ignore so we still get the nearest to norm/gamma curve too
rssicountstxcor$abovefrac <- rssicountstxcor$abovecurve / rssicountstxcor$cnt # Larger is better (more above the curve)
rssicountstxcor$lowerarea <- rssicountstxcor$rssicor > meanrssitxcor
head(rssicountstxcor)
rssicountssummarytxcor <- rssicountstxcor %>%
dplyr::group_by(lowerarea) %>%
dplyr::slice(which.max(abovefrac))
head(rssicountssummarytxcor)
rssicountssummarytxcor$sdpos <- (rssicountssummarytxcor$rssicor - meanrssitxcor) / sdrssitxcor
write.csv(rssicountssummarytxcor,paste(settings$outputFolder[1] , "/", settings$outputFilePrefix[1],settings$groupText[1],"rssi-peaks.csv",sep=""))
lowerpeaktxcor <- as.integer(rssicountssummarytxcor[2:2,"sdpos"]) # WARNING ASSUMES A SINGLE PEAK
lowerpeaktxcor
upperpeaktxcor <- as.integer(rssicountssummarytxcor[1:1,"sdpos"]) # WARNING ASSUMES A SINGLE PEAK
upperpeaktxcor
#print(paste("Lower peak RSSI:",lowerpeak,"Upper Peak RSSI:", upperpeak)," ")
# Calculate peak positions relative to mean by number of RSSI SD positions
#lowersdpostxcor <- (lowerpeaktxcor - meanrssitxcor) / sdrssitxcor
#uppersdpostxcor <- (upperpeaktxcor - meanrssitxcor) / sdrssitxcor
#lowersdpostxcor <- meanrssitxcor + (lowerpeaktxcor * sdrssitxcor)
#uppersdpostxcor <- meanrssitxcor + (upperpeaktxcor * sdrssitxcor)
lowersdpostxcor <- as.integer(rssicountssummarytxcor[2:2,"rssicor"])
uppersdpostxcor <- as.integer(rssicountssummarytxcor[1:1,"rssicor"])
lowersdpostxcor
uppersdpostxcor
# Find the central (largest y value) peak
peakData <- dataFrame
peakData$rssicorGroup <- round(peakData$rssicor)
peakGroups <- peakData %>%
dplyr::group_by(rssicorGroup) %>%
dplyr::summarise(n=dplyr::n()) %>%
dplyr::ungroup() %>%
dplyr::arrange(dplyr::desc(n)) #,dplyr::desc(rssicorGroup))
centralPeakValue <- peakGroups$rssicorGroup[1]
centralPeakCount <- peakGroups$n[1]
print(paste(" - Central value is ",centralPeakValue," with count of ",centralPeakCount,sep=""))
# if lower (farthest) point missing, use +3 * SD
# if upper (nearest) point missing, use -3 * SD
#if (lowersdpostxcor == meanrssitxcor) {
# lowersdpostxcor <- meanrssitxcor + (3 * sdrssitxcor)
#}
#if (uppersdpostxcor == meanrssitxcor) {
# uppersdpostxcor <- meanrssitxcor - (3 * sdrssitxcor)
#}
data.frame(
farPeakValue = lowersdpostxcor, # 'Farther'
nearPeakValue = uppersdpostxcor, # 'Nearer'
centralPeakValue = centralPeakValue,
centralPeakCount = centralPeakCount,
meanValue = meanrssitxcor,
sdValue = sdrssitxcor,
countValues = countrssitxcor,
minValue = minrssitxcor,
maxValue = maxrssitxcor,
nearAreaMin = strongmaxtxcor,
nearAreaMax = strongmintxcor,
farAreaMin = weakmaxtxcor, # original variables were flipped, hence the confusing names within this function
farAreaMax = weakmintxcor
)
}
chartAndFit <- function(settings, dataFrame, fitData) {
print(paste("chartAndFit - ",settings$groupText[1],sep=""))
#meanrssitx <- mean(dataFrame$rssiint)
#sdrssitx <- sd(dataFrame$rssiint)
#countrssitx <- NROW(dataFrame)
#minrssitx <- min(dataFrame$rssiint)
#maxrssitx <- max(dataFrame$rssiint)
#skewrssitx <- moments::skewness(dataFrame$rssiint, na.rm = TRUE)
#kurtosisrssitx <- moments::kurtosis(dataFrame$rssiint, na.rm = TRUE)
#meanrssitxcor <- mean(dataFrame$rssicor)
#sdrssitxcor <- sd(dataFrame$rssicor)
#countrssitxcor <- NROW(dataFrame)
#minrssitxcor <- min(dataFrame$rssicor)
#maxrssitxcor <- max(dataFrame$rssicor)
skewrssitxcor <- moments::skewness(dataFrame$rssicor, na.rm = TRUE)
kurtosisrssitxcor <- moments::kurtosis(dataFrame$rssicor, na.rm = TRUE)
# # NOW CREATE NORMALISED (scaled) DATASET
# # Now alter rssi values to the idealised normal distribution
# # NOTE: Not actually to a N(0,1) as yet - not got the scale factors right...
# # Calculate fitness
# scaledtxcor <- dataFrame
# # Filter beyond the two peaks
# #scaledtxcor <- dplyr::filter(scaledtxcor, rssicor >= lowerpeaktxcor & rssicor <= upperpeaktxcor)
# #scaledtxcor$rssicorrected <- 0
# #scaledtxcor$rssicorrected[scaledtxcor$rssicor < meanrssitxcor] <- (scaledtxcor$rssicor[scaledtxcor$rssicor < meanrssitxcor] - meanrssitxcor) / abs(lowersdpostxcor)
# #scaledtxcor$rssicorrected[scaledtxcor$rssicor > meanrssitxcor] <- (scaledtxcor$rssicor[scaledtxcor$rssicor > meanrssitxcor] - meanrssitxcor) / abs(uppersdpostxcor)
# head(scaledtxcor)
# meancortxcor <- mean(scaledtxcor$rssicor)
# sdcortxcor <- sd(scaledtxcor$rssicor)
# skewcortxcor <- moments::skewness(scaledtxcor$rssicor, na.rm = TRUE)
# kurtosiscortxcor <- moments::kurtosis(scaledtxcor$rssicor, na.rm = TRUE)
print(" - Calculating scaled fit")
myfit <- fitdist(dataFrame$rssicor, distr = "gamma", method = "mle")
summary(myfit)
gammashape <- myfit$estimate[1] # shape
gammarate <- myfit$estimate[2] # rate
myfitnorm <- fitdist(dataFrame$rssicor, distr = "norm", method = "mle")
summary(myfitnorm)
myfitnorm$sd[2]
# Now plot the same but after txpower correction of rssi
print(paste(" - Stats: mean=",fitData$meanValue[1]," sd=",fitData$sdValue[1]," n=",fitData$countValues[1], sep=""))
# if (settings$generateCharts[1]) {
# p <- ggplot(dataFrame, aes(x=rssicor,color=1, fill=1)) +
# geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor), color="blue", linetype="dashed", size=1, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=maxrssitxcor), color="black", linetype="solid", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=minrssitxcor), color="black", linetype="solid", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor + sdrssitxcor), color="grey", linetype="dashed", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor - sdrssitxcor), color="grey", linetype="dashed", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor + 2*sdrssitxcor), color="grey", linetype="dashed", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor - 2*sdrssitxcor), color="grey", linetype="dashed", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor + 3*sdrssitxcor), color="grey", linetype="dashed", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=meanrssitxcor - 3*sdrssitxcor), color="grey", linetype="dashed", size=0.5, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=lowersdpostxcor), color="blue", linetype="dashed", size=1, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=uppersdpostxcor), color="blue", linetype="dashed", size=1, show.legend = F) +
# geom_vline(data=dataFrame, aes(xintercept=centralPeakValue), color="blue", linetype="dashed", size=1, show.legend = F) +
# geom_text(aes(x=lowersdpostxcor, label=paste("Lower peak = ",lowersdpostxcor,sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
# geom_text(aes(x=uppersdpostxcor, label=paste("Upper peak = ",uppersdpostxcor,sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
# geom_text(aes(x=centralPeakValue, label=paste("Central peak = ",centralPeakValue,sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
# geom_text(aes(x=meanrssitxcor, label=paste("N = ",countrssitxcor,"\nMean = ",meanrssitxcor,"\nSD = ",sdrssitxcor,"\nSkewness = ",skewrssitxcor,"\nKurtosis = ",kurtosisrssitxcor,sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
# labs(x="RSSI corrected for TxPower",
# y="Relative Frequency",
# title="Corrected RSSI Frequency",
# subtitle="Across all interactions") +
# stat_function(fun = dnorm, args = list(mean = meanrssitxcor, sd = sdrssitxcor), show.legend = F)
# p
# ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],"",settings$groupText[1],"-fitting-01-input-distribution.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
# } else {
# print(" - Skipped");
# }
print(" - Calculating bounds for scaling")
# A2 Try to normalise these values - by using the mean and local maxima peaks based on human behaviour
# - First, Filter for only those rssiint between -3 (or -97) and -1 SD and 1 and 3 SD (or minrssi if smaller)
#weakmintxcor <- max(meanrssitxcor - (3 * sdrssitxcor), -120)# -98 is the boundary value for bluetooth chips to receive data, so ignore
#weakmaxtxcor <- meanrssitxcor - (2 * sdrssitxcor)
#strongmintxcor <- meanrssitxcor + (2 * sdrssitxcor)
#strongmaxtxcor <- min(meanrssitxcor + (4 * sdrssitxcor), maxrssitxcor, 0)
sdmeasurestxcor <- dplyr::filter(dataFrame,
(rssicor > fitData$farAreaMin[1] & rssicor <= fitData$farAreaMax[1]) |
(rssicor >= fitData$nearAreaMin[1] & rssicor <= fitData$nearAreaMax[1])
)
# Chart these as a debug step
if (settings$generateCharts[1]) {
p <- ggplot(sdmeasurestxcor, aes(x=rssicor)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend=F, aes( y=..density.. )) +
labs(x="Proximity values",
y="Count",
title="Proximity Values in range of local maxima") +
theme(legend.position = "bottom") +
stat_function(fun = dnorm, args = list(mean = fitData$meanValue[1], sd = fitData$sdValue[1]), show.legend = F)
p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],settings$groupText[1],"-fitting-02-maxima-areas.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
print(" - Calculating scaling summaries")
# Now chart it
xlimmin <- fitData$maxValue[1]
if (xlimmin < 255) {
xlimmin <- 255
}
xlimmax <- fitData$minValue[1]
if (xlimmax > 0) {
xlimmax <- 0
}
print(" - Charting scaled fit")
if (settings$generateCharts[1]) {
# Now reversed and fitted to gamma and normal(gaussian) distributions
p <- ggplot(dataFrame, aes(x=rssicor,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=10, show.legend = F, aes( y=..density.. )) +
geom_text(aes(x=fitData$meanValue[1] - 2*fitData$sdValue[1], label=paste(
"Gamma:-\nShape = ",myfit$estimate[1]," (SE = ",myfit$sd[1],")\nRate = ",myfit$estimate[2]," (SE = ",myfit$sd[2],")",
"\nNorm:-\nMean = ",myfitnorm$estimate[1]," (SE = ",myfitnorm$sd[1],")\nSD = ",myfitnorm$estimate[2]," (SE = ",myfitnorm$sd[2],")",
sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$maxValue[1]), color="black", linetype="solid", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$minValue[1]), color="black", linetype="solid", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + 2*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - 2*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + 3*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - 3*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$farPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$nearPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$centralPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_text(aes(x=fitData$maxValue[1], label=paste("Max = ",fitData$maxValue[1],sep=""), y=0.01), colour="black", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$minValue[1], label=paste("Min = ",fitData$minValue[1],sep=""), y=0.01), colour="black", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$farPeakValue[1], label=paste("Lower peak = ",fitData$farPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$nearPeakValue[1], label=paste("Upper peak = ",fitData$nearPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$centralPeakValue[1], label=paste("Central peak = ",fitData$centralPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$meanValue[1] + 2*fitData$sdValue[1], label=paste("N = ",fitData$countValues[1],"\nMean = ",fitData$meanValue[1],"\nSD = ",
fitData$sdValue[1],"\nSkewness = ",skewrssitxcor,"\nKurtosis = ",kurtosisrssitxcor,sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
labs(x="Calibrated proximity",
y="Relative Frequency",
title="Proximity Frequency fitting",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep="")) +
stat_function(fun = dgamma, args = list(shape = myfit$estimate[1], rate = myfit$estimate[2]), show.legend = F, colour="orange") +
stat_function(fun = dnorm, args = list(mean = myfitnorm$estimate[1], sd = myfitnorm$estimate[2]), show.legend = F) +
xlim(xlimmax,xlimmin) + ylim(0,0.025)
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],settings$groupText[1],"-fitting-03-complete.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
# Now reversed and fitted to gamma and normal(gaussian) distributions
p <- ggplot(dataFrame, aes(x=rssicor,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=3, show.legend = F, aes( y=..density.. )) +
geom_text(aes(x=fitData$meanValue[1] - 2*fitData$sdValue[1], label=paste(
"Gamma:-\nShape = ",myfit$estimate[1]," (SE = ",myfit$sd[1],")\nRate = ",myfit$estimate[2]," (SE = ",myfit$sd[2],")",
"\nNorm:-\nMean = ",myfitnorm$estimate[1]," (SE = ",myfitnorm$sd[1],")\nSD = ",myfitnorm$estimate[2]," (SE = ",myfitnorm$sd[2],")",
sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$maxValue[1]), color="black", linetype="solid", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$minValue[1]), color="black", linetype="solid", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + 2*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - 2*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + 3*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - 3*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$farPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$nearPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$centralPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_text(aes(x=fitData$maxValue[1], label=paste("Max = ",fitData$maxValue[1],sep=""), y=0.01), colour="black", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$minValue[1], label=paste("Min = ",fitData$minValue[1],sep=""), y=0.01), colour="black", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$farPeakValue[1], label=paste("Lower peak = ",fitData$farPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$nearPeakValue[1], label=paste("Upper peak = ",fitData$nearPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$centralPeakValue[1], label=paste("Central peak = ",fitData$centralPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$meanValue[1] + 2*fitData$sdValue[1], label=paste("N = ",fitData$countValues[1],"\nMean = ",fitData$meanValue[1],"\nSD = ",
fitData$sdValue[1],"\nSkewness = ",skewrssitxcor,"\nKurtosis = ",kurtosisrssitxcor,sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
labs(x="Calibrated proximity",
y="Relative Frequency",
title="Proximity Frequency fitting",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep="")) +
stat_function(fun = dgamma, args = list(shape = myfit$estimate[1], rate = myfit$estimate[2]), show.legend = F, colour="orange") +
stat_function(fun = dnorm, args = list(mean = myfitnorm$estimate[1], sd = myfitnorm$estimate[2]), show.legend = F) +
xlim(xlimmax,xlimmin) + ylim(0,0.025)
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],settings$groupText[1],"-fitting-03-complete-3.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
# Now with binwidth=1
# Now reversed and fitted to gamma and normal(gaussian) distributions
p <- ggplot(dataFrame, aes(x=rssicor,color=1, fill=1)) +
geom_histogram(alpha=0.5, binwidth=1, show.legend = F, aes( y=..density.. )) +
geom_text(aes(x=fitData$meanValue[1] - 2*fitData$sdValue[1], label=paste(
"Gamma:-\nShape = ",myfit$estimate[1]," (SE = ",myfit$sd[1],")\nRate = ",myfit$estimate[2]," (SE = ",myfit$sd[2],")",
"\nNorm:-\nMean = ",myfitnorm$estimate[1]," (SE = ",myfitnorm$sd[1],")\nSD = ",myfitnorm$estimate[2]," (SE = ",myfitnorm$sd[2],")",
sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$maxValue[1]), color="black", linetype="solid", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$minValue[1]), color="black", linetype="solid", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + 2*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - 2*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] + 3*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$meanValue[1] - 3*fitData$sdValue[1]), color="grey", linetype="dashed", size=0.5, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$farPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$nearPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_vline(data=dataFrame, aes(xintercept=fitData$centralPeakValue[1]), color="blue", linetype="dashed", size=1, show.legend = F) +
geom_text(aes(x=fitData$maxValue[1], label=paste("Max = ",fitData$maxValue[1],sep=""), y=0.01), colour="black", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$minValue[1], label=paste("Min = ",fitData$minValue[1],sep=""), y=0.01), colour="black", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$farPeakValue[1], label=paste("Lower peak = ",fitData$farPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$nearPeakValue[1], label=paste("Upper peak = ",fitData$nearPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$centralPeakValue[1], label=paste("Central peak = ",fitData$centralPeakValue[1],sep=""), y=0.01), colour="blue", angle=90, vjust = -1, text=element_text(size=11)) +
geom_text(aes(x=fitData$meanValue[1] + 2*fitData$sdValue[1], label=paste("N = ",fitData$countValues[1],"\nMean = ",fitData$meanValue[1],"\nSD = ",
fitData$sdValue[1],"\nSkewness = ",skewrssitxcor,"\nKurtosis = ",kurtosisrssitxcor,sep=""), y=0.02), colour="blue", vjust = -1, text=element_text(size=11)) +
labs(x="Calibrated proximity",
y="Relative Frequency",
title="Proximity Frequency fitting",
subtitle=paste("Across ",settings$groupText[1]," interactions",sep="")) +
stat_function(fun = dgamma, args = list(shape = myfit$estimate[1], rate = myfit$estimate[2]), show.legend = F, colour="orange") +
stat_function(fun = dnorm, args = list(mean = myfitnorm$estimate[1], sd = myfitnorm$estimate[2]), show.legend = F) +
xlim(xlimmax,xlimmin) + ylim(0,0.025)
#p
ggsave(paste(settings$outputFolder[1],"/",settings$outputFilePrefix[1],settings$groupText[1],"-fitting-03-complete-thin.png", sep=""), width =settings$chartWidth[1], height =settings$chartHeight[1], units = "mm")
} else {
print(" - Skipped");
}
print(" - Done")
}
applyStandardisedWindow <- function(dataFrame, stdWindowSeconds, windowSizeSeconds) {
res <- dataFrame %>%
dplyr::group_by(macuuid) %>%
dplyr::summarise( t=seq(from=min(t) + stdWindowSeconds,to=max(t) + stdWindowSeconds,by=paste(stdWindowSeconds,"secs",sep=" ")) ) %>%
dplyr::ungroup()
head(res)
res <- res %>%
dplyr::group_by(macuuid,t) %>%
dplyr::mutate(
rssicorrected=mean(dataFrame$rssicor[
dataFrame$macuuid==macuuid &
dataFrame$t < t &
dataFrame$t >= (t - windowSizeSeconds)
]),
txpowerint=head(c(tail(dataFrame$txpowerint[
dataFrame$macuuid==macuuid &
dataFrame$t < t &
dataFrame$t >= (t - windowSizeSeconds)
],n=1), NA),n=1)
) %>%
dplyr::ungroup()
res <- as.data.frame(res)
res <- dplyr::filter(res,!is.na(rssicorrected) & !is.na(txpowerint) & rssicorrected>=0)
res
}
calculateScale <- function(fitData, minPeakTargetValue, centralPeakTargetValue) {
central <- fitData$centralPeakValue[1]
upperpeakvalue <- fitData$nearPeakValue[1]
minPeakRisk <- minPeakTargetValue
centralRisk <- centralPeakTargetValue
scaleFactor <- (centralRisk - minPeakRisk) / (central - upperpeakvalue)
data.frame(
scaleFactor=scaleFactor,
srcIndexValue=upperpeakvalue,
srcCentralValue=central,
targetIndexValue=minPeakRisk,
targetCentralValue=centralRisk
)
}
applyScale <- function(dataFrame, scaleFactorData, applyZeroLimit = TRUE) {
scaledData <- dataFrame
scaledData$rssicor <- scaledData$rssicor - scaleFactorData$srcIndexValue[1]
scaledData$rssicor <- scaledData$rssicor * scaleFactorData$scaleFactor[1]
scaledData$rssicor <- scaledData$rssicor + scaleFactorData$targetIndexValue[1]
min(scaledData$rssicor)
max(scaledData$rssicor)