-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathRadioMap.scala
975 lines (926 loc) · 34.2 KB
/
RadioMap.scala
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
/*
* Anyplace: A free and open Indoor Navigation Service with superb accuracy!
*
* Anyplace is a first-of-a-kind indoor information service offering GPS-less
* localization, navigation and search inside buildings using ordinary smartphones.
*
* Author(s): Nikolas Neofytou, Constantinos Costa, Kyriakos Georgiou, Lambros Petrou
*
* Co-Supervisor: Paschalis Mpeis
* Supervisor: Demetrios Zeinalipour-Yazti
*
* URL: https://anyplace.cs.ucy.ac.cy
* Contact: [email protected]
*
* Copyright (c) 2016, Data Management Systems Lab (DMSL), University of Cyprus.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the “Software”), to deal in the
* Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package modules.radiomapserver
import java.io._
import java.text.DecimalFormat
import java.util
import java.util.{ArrayList, HashMap, LinkedList}
import Jama.Matrix
import utils.LOG
import scala.jdk.CollectionConverters.{CollectionHasAsScala, MapHasAsScala}
object RadioMap {
val RBF_ENABLED = false
/**
* Verifies rss-log file and returns a map of buid:list of floors.
* Weird: The list always contains one floor
*
* @param inFile
* @return
*/
def verifyRssLogAndGetBuildingFloors(inFile: File): HashMap[String, LinkedList[String]] = {
var line_num = 0
var reader: BufferedReader = null
val buildingsFloors = new HashMap[String, LinkedList[String]]()
try {
var line: String = null
val fr = new FileReader(inFile)
reader = new BufferedReader(fr)
while ( {
line = reader.readLine
line != null
}) {
line_num += 1
if (!(line.startsWith("#") || line.trim().isEmpty)) {
line = line.replace(", ", " ")
val temp = line.split(" ")
if (temp.length != 8) {
throw new Exception("Line " + line_num + " length is not equal to 8.")
}
java.lang.Float.parseFloat(temp(1))
java.lang.Float.parseFloat(temp(2))
java.lang.Float.parseFloat(temp(3))
if (!temp(4).matches(
"[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}")) {
throw new Exception("Line " + line_num + " MAC Address is not valid.")
}
java.lang.Integer.parseInt(temp(5))
val sfloor = temp(6)
val sbuid = temp(7)
java.lang.Integer.parseInt(sfloor)
if (!buildingsFloors.containsKey(sbuid)) {
val tempList = new LinkedList[String]()
tempList.add(sfloor)
buildingsFloors.put(sbuid, tempList)
}
}
}
fr.close()
reader.close()
} catch {
case nfe: NumberFormatException => {
LOG.E("Error while authenticating RSS log file " + inFile.getAbsolutePath +
": Line " + line_num, nfe)
return null
}
case e: Exception => {
LOG.E("Error while authenticating RSS log file " + inFile.getAbsolutePath, e)
return null
}
}
buildingsFloors
}
class RadioMap(private val rss_folder: File,
private val radiomap_filename: String,
private val radiomap_AP: String,
private val defaultNaNValue: Int) {
private val RadioMap = new HashMap[String, HashMap[String, ArrayList[Integer]]]()
private val NewRadioMap: HashMap[String, HashMap[Integer, ArrayList[Any]]] =
new HashMap[String, HashMap[Integer, ArrayList[Any]]]()
private var orientationLists: HashMap[Integer, ArrayList[Any]] = _
private val isIndoor = this.radiomap_filename.contains("indoor")
private val radiomap_mean_filename = radiomap_filename.replace(".", "-mean.")
private val radiomap_rbf_weights_filename = radiomap_filename.replace(".", "-weights.")
private val radiomap_parameters_filename = radiomap_filename.replace(".", "-parameters.")
private var S_RBF: Float = -1f
private var MIN_RSS: Int = java.lang.Integer.MAX_VALUE
private var MAX_RSS: Int = java.lang.Integer.MIN_VALUE
/**
* Creates radiomap files
*
* @return error message otherwise null on success
*/
def createRadioMap(): String = {
if (!rss_folder.exists() || !rss_folder.isDirectory) {
return "createRadioMap: Folder does not exist."
}
try {
RadioMap.clear()
createRadioMapFromPath(rss_folder)
writeRadioMap()
} catch {
case e: Exception => return "ERROR: " + e.getClass + ": " + e.getMessage
}
null
}
private def createRadioMapFromPath(inFile: File): Unit = {
if (inFile.exists()) {
// how is this if working... ??
if (inFile.canExecute() && inFile.isDirectory) {
val list = inFile.list()
if (list != null) {
for (i <- 0 until list.length) {
createRadioMapFromPath(new File(inFile, list(i)))
}
}
} else if (inFile.canRead() && inFile.isFile) {
parseLogFileToRadioMap(inFile)
}
}
}
def parseLogFileToRadioMap(inFile: File): Unit = {
var MACAddressMap: HashMap[String, ArrayList[Integer]] = null
var RSS_Values: ArrayList[Integer] = null
val MAG_Values: ArrayList[ArrayList[Float]] = null
var orientationList: ArrayList[Any] = null
val f = inFile
var reader: BufferedReader = null
if (!verifyFloorRawRss(f)) {
return
}
var group = 0
var line_num = 0
try {
var line: String = null
var key = ""
val degrees = 360
val num_orientations = 4
val range = degrees / num_orientations
val deviation = range / 2
var RSS_Value = 0
val fr = new FileReader(f)
reader = new BufferedReader(fr)
while ( {
line = reader.readLine;
line != null
}) {
line_num += 1
if (!(line.startsWith("#") || line.trim().isEmpty)) {
line = line.replace(", ", " ")
val temp = line.split(" ")
RSS_Value = java.lang.Integer.parseInt(temp(5))
key = temp(1) + ", " + temp(2)
group = (((Math.round((java.lang.Float.parseFloat(temp(3))) + deviation) %
degrees) /
range) %
num_orientations).toInt
orientationLists = NewRadioMap.get(key)
if (orientationLists == null) {
orientationLists = new HashMap[Integer, ArrayList[Any]](Math.round(num_orientations.toFloat))
orientationList = new ArrayList[Any](2)
orientationLists.put(group, orientationList)
MACAddressMap = new HashMap[String, ArrayList[Integer]]()
RSS_Values = new ArrayList[Integer]()
RSS_Values.add(RSS_Value)
MACAddressMap.put(temp(4).toLowerCase(), RSS_Values)
orientationList.add(MACAddressMap)
orientationList.add(0)
NewRadioMap.put(key, orientationLists)
} else if (orientationLists.get(group) == null) {
orientationList = new ArrayList[Any](2)
orientationLists.put(group, orientationList)
MACAddressMap = new HashMap[String, ArrayList[Integer]]()
RSS_Values = new ArrayList[Integer]()
RSS_Values.add(RSS_Value)
MACAddressMap.put(temp(4).toLowerCase(), RSS_Values)
orientationList.add(MACAddressMap)
orientationList.add(0)
NewRadioMap.put(key, orientationLists)
} else {
MACAddressMap = orientationLists.get(group).get(0).asInstanceOf[HashMap[String, ArrayList[Integer]]]
RSS_Values = MACAddressMap.get(temp(4).toLowerCase())
var position = orientationLists.get(group).get(1).asInstanceOf[java.lang.Integer]
if (RSS_Values == null) {
RSS_Values = new ArrayList[Integer]()
}
if (position == RSS_Values.size) {
position = position + 1
orientationLists.get(group).set(1, position)
RSS_Values.add(RSS_Value)
MACAddressMap.put(temp(4).toLowerCase(), RSS_Values)
} else {
for (i <- RSS_Values.size until position - 1) {
RSS_Values.add(this.defaultNaNValue)
}
RSS_Values.add(RSS_Value)
MACAddressMap.put(temp(4).toLowerCase(), RSS_Values)
}
}
}
}
fr.close()
reader.close()
} catch {
case e: Exception => LOG.E("Error while parsing RSS log file " + f.getAbsolutePath +
": " +
e.getMessage)
}
}
def verifyFloorRawRss(inFile: File): Boolean = {
var line_num = 0
var reader: BufferedReader = null
try {
var line: String = null
val fr = new FileReader(inFile)
reader = new BufferedReader(fr)
while ( {
line = reader.readLine
line != null
}) {
line_num += 1
// Check X, Y or Latitude, Longitude
if (!(line.startsWith("#") || line.trim().isEmpty)) {
// Remove commas
line = line.replace(", ", " ")
val temp = line.split(" ")
java.lang.Float.parseFloat(temp(1))
java.lang.Float.parseFloat(temp(2))
java.lang.Float.parseFloat(temp(3))
if (!temp(4).matches("[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}")) {
throw new Exception("Line " + line_num + " MAC Address is not valid.")
}
java.lang.Integer.parseInt(temp(5))
java.lang.Integer.parseInt(temp(6))
}
}
fr.close()
reader.close()
} catch {
case nfe: NumberFormatException => {
LOG.E("Error while authenticating RSS log file " + inFile.getAbsolutePath +
": Line " +
line_num +
" " +
nfe.getMessage)
return false
}
case e: Exception => {
LOG.E("Error while authenticating RSS log file " + inFile.getAbsolutePath +
": " +
e.getMessage)
return false
}
}
true
}
def writeParameters(orientations: Int): String = {
for (i <- 0 until orientations) {
val group = i * 360 / orientations
var fos: FileOutputStream = null
val RM = new RadioMapMean(this.isIndoor, this.defaultNaNValue)
if (!RM.ConstructRadioMap(new File(radiomap_mean_filename))) return "writeParameters: Failed to ConstructRadioMap"
if (!find_MIN_MAX_Values(group)) return "writeParameters: Failed to find_MIN_MAX_Values"
if (!(RM.getOrderList().size >= 2)) return "writeParameters: RBF: RM orderList is small: " + RM.getOrderList().size
LOG.D("Calculating RBF parameter...")
S_RBF = calculateSGreek(RM, group)
if (S_RBF == -1) return "writeParameters: S_RBF == -1"
LOG.D("RBF calculation Done!")
val radiomap_parameters_file = new File(radiomap_parameters_filename)
try {
fos = if (i == 0) new FileOutputStream(radiomap_parameters_file, false) else new FileOutputStream(radiomap_parameters_file,
true)
} catch {
case e: Exception => {
radiomap_parameters_file.delete()
return "writeParameters: " + e.getClass + ": " + "Error while writing parameters: " + e.getMessage
}
}
try {
if (i != 0) {
fos.write("\n".getBytes)
} else {
fos.write(("NaN, " + this.defaultNaNValue + "\n").getBytes)
}
fos.write(("RBF, " + group + ", " + this.S_RBF).getBytes)
fos.close()
} catch {
case e: Exception => {
radiomap_parameters_file.delete()
return "writeParameters: " + e.getClass + ": " + "Error while writing RBF parameters: " + e.getMessage
}
}
}
LOG.D("Written Parameters!")
null
}
private def find_MIN_MAX_Values(group: Int): Boolean = {
var frRadiomap: FileReader = null
var readerRadiomap: BufferedReader = null
try {
var radiomapLine: String = null
var temp: Array[String] = null
frRadiomap = new FileReader(radiomap_filename)
readerRadiomap = new BufferedReader(frRadiomap)
while ( {
radiomapLine = readerRadiomap.readLine;
radiomapLine != null
}) {
if (!(radiomapLine.startsWith("#") || radiomapLine.trim().isEmpty)) {
radiomapLine = radiomapLine.replace(", ", " ")
temp = radiomapLine.split(" ")
if (temp(0).trim().equals("#")) {
if (!temp(1).trim().equals("NaN")) {
// Must have more than 3 fields
if (temp.length < 5) {
return false
} else if (this.isIndoor &&
(!temp(1).trim().equalsIgnoreCase("X") || !temp(2).trim().equalsIgnoreCase("Y"))) {
return false
}
}
} else {
if (temp.length < 4) {
return false
}
if (java.lang.Integer.parseInt(temp(2)) == group) {
for (i <- 3 until temp.length) {
set_MIN_MAX_RSS(java.lang.Integer.parseInt(temp(i)))
}
}
}
}
}
frRadiomap.close()
readerRadiomap.close()
}
catch {
case e: Exception => {
LOG.E("Error while finding min and max RSS values: " + e.getMessage)
return false
}
}
true
}
private def set_MIN_MAX_RSS(RSS_Value: Int) : Unit = {
if (MIN_RSS > RSS_Value && RSS_Value != this.defaultNaNValue) {
MIN_RSS = RSS_Value
}
if (MAX_RSS < RSS_Value) {
MAX_RSS = RSS_Value
}
}
private def calculateSGreek(RM: RadioMapMean, group: Int): java.lang.Float = {
if (RM == null) return -1f
var maximumDistance = 0.0f
val allDistances = new util.ArrayList[Float]()
var result: Float = 0.0f
// must have size >= 2
for (i <- 0 until RM.getOrderList().size; j <- i + 1 until RM.getOrderList().size) {
val RadioMapFile = RM.getLocationRSS_HashMap(group)
if (RadioMapFile != null && RadioMapFile.get(RM.getOrderList().get(i)) != null &&
RadioMapFile.get(RM.getOrderList().get(j)) != null) {
result = calculateEuclideanDistance(RadioMapFile.get(RM.getOrderList().get(i)), RadioMapFile.get(RM.getOrderList().get(j)))
if (result == java.lang.Float.NEGATIVE_INFINITY) {
return -1f
}
allDistances.add(result)
}
}
maximumDistance = allDistances.asScala.max
java.lang.Float.valueOf((maximumDistance / Math.sqrt(2 * RM.getOrderList().size())).toFloat)
}
private def calculateEuclideanDistance(real: String, estimate: String): Double
= {
var pos_error: Double = 0.0
var temp_real: Array[String] = null
var temp_estimate: Array[String] = null
var x1: Double = 0.0
var x2: Double = 0.0
temp_real = real.split(" ")
temp_estimate = estimate.split(" ")
try {
x1 = Math.pow(java.lang.Double.parseDouble(temp_real(0)) - java.lang.Double.parseDouble(temp_estimate(0)),
2)
x2 = Math.pow(java.lang.Double.parseDouble(temp_real(1)) - java.lang.Double.parseDouble(temp_estimate(1)),
2)
} catch {
case e: Exception => {
LOG.E("Error while calculating Euclidean distance: " + e.getMessage)
return -1
}
}
pos_error = Math.sqrt((x1 + x2))
pos_error
}
/**
* Stores the following radiomap frozen files:
* - indoor-radiomap.txt
* - indoor-radiomap-mean.txt
* - indoor-radiomap-parameters.txt
* - indoor-radiomap-weights.txt
*
* @return
*/
private def writeRadioMap(): String = {
LOG.D("writing radio map to files")
val AP = new ArrayList[String]()
val orientations = 4
val radiomap_file = new File(radiomap_filename)
val radiomap_mean_file = new File(radiomap_mean_filename)
if (NewRadioMap.isEmpty) return "writeRadioMap: NewRadioMap is empty"
val f = new File(radiomap_AP)
var reader: BufferedReader = null
if (f.exists()) {
try {
var line: String = null
val fr = new FileReader(f)
reader = new BufferedReader(fr)
while ( {line = reader.readLine; line != null }) {
AP.add(line.toLowerCase())
}
fr.close()
reader.close()
} catch {
case e: Exception => return "Error while parsing AP txt file " + f.getAbsolutePath +
": " + e.getMessage
}
}
try {
var res: String = null
res = createRadioMapFrozenAndMean(radiomap_file, radiomap_mean_file, AP, orientations)
if (res != null) return res
// BUG:DZ BUG:PM BUG:NN below methods fail
if (RBF_ENABLED == true) {
LOG.D1("BUG: writeParameters, writeRBFWeights")
res = writeParameters(orientations)
if (res != null) return res
res = writeRBFWeights(orientations)
if (res != null) return res
}
} catch {
case e: Exception =>
e.printStackTrace()
return "writeRadioMap:" + e.getClass + ": " + e.getMessage
}
LOG.D("Finished writing radio map to files!")
null
}
/**
* Populates these two files:
* - indoor-radiomap.txt
* - indoor-radiomap-mean.txt
*
* @param radiomap_file
* @param radiomap_mean_file
* @param AP
* @param orientations
* @return error message otherwise null
*/
def createRadioMapFrozenAndMean(radiomap_file: File, radiomap_mean_file: File, AP: ArrayList[String],
orientations: Int): String = {
try {
val dec = new DecimalFormat("###.#")
var MACAddressMap: HashMap[String, ArrayList[Integer]] = null
val fos = new FileOutputStream(radiomap_file, false)
val fos_mean = new FileOutputStream(radiomap_mean_file, false)
var count = 0
var max_values = 0
var first = 0
val NaNValue = "# NaN " + this.defaultNaNValue + "\n"
val header = "# X, Y, HEADING, "
fos.write(NaNValue.getBytes)
fos_mean.write(NaNValue.getBytes)
fos.write(header.getBytes)
fos_mean.write(header.getBytes)
val MACKeys = new ArrayList[String]()
var MRSS_Values: Array[Int] = null
var heading = 0
var x_y = ""
var group = 0
for ((key, value) <- NewRadioMap.asScala) {
val degrees = 360
for ((key, value) <- value.asScala) {
MACAddressMap = value.get(0).asInstanceOf[HashMap[String, ArrayList[Integer]]]
for ((key, value) <- MACAddressMap.asScala) {
val MACAddress = key
if (!MACKeys.contains(MACAddress.toLowerCase())) {
if (AP.size == 0 || AP.contains(MACAddress.toLowerCase())) {
MACKeys.add(MACAddress.toLowerCase())
if (first == 0) {
fos.write((MACAddress.toLowerCase()).getBytes)
fos_mean.write((MACAddress.toLowerCase()).getBytes)
} else {
fos.write((", " + MACAddress.toLowerCase()).getBytes)
fos_mean.write((", " + MACAddress.toLowerCase()).getBytes)
}
first += 1
}
}
}
}
}
for ((key, value) <- NewRadioMap.asScala) {
val degrees = 360
group = degrees / orientations
x_y = key
for ((key, value) <- value.asScala) {
max_values = 0
heading = key * group
MACAddressMap = value.get(0).asInstanceOf[HashMap[String, ArrayList[Integer]]]
for ((key, value) <- MACAddressMap.asScala) {
val wifi_rss_values = value
if (wifi_rss_values.size > max_values) {
max_values = wifi_rss_values.size
}
}
if (count == 0) {
fos.write(("\n").getBytes)
fos_mean.write(("\n").getBytes)
}
MRSS_Values = new Array[Int](MACKeys.size)
for (v <- 0 until max_values) {
fos.write((x_y + ", " + heading).getBytes)
for (i <- 0 until MACKeys.size) {
var rss_value = 0
if (MACAddressMap.containsKey(MACKeys.get(i).toLowerCase())) {
if (v >=
MACAddressMap.get(MACKeys.get(i).toLowerCase()).size &&
MACAddressMap.get(MACKeys.get(i).toLowerCase()).size <
max_values) {
MRSS_Values(i) += this.defaultNaNValue
rss_value = this.defaultNaNValue
} else {
rss_value = MACAddressMap.get(MACKeys.get(i).toLowerCase()).get(v)
MRSS_Values(i) += rss_value
}
} else {
rss_value = this.defaultNaNValue
MRSS_Values(i) += this.defaultNaNValue
}
fos.write((", " + dec.format(rss_value)).getBytes)
}
fos.write("\n".getBytes)
}
fos_mean.write((x_y + ", " + heading).getBytes)
for (i <- MRSS_Values.indices) {
fos_mean.write((", " + dec.format(MRSS_Values(i).toFloat / max_values))
.getBytes)
}
fos_mean.write("\n".getBytes)
count += 1
}
}
fos_mean.close()
fos.close()
} catch {
case e: FileNotFoundException => {
radiomap_file.delete()
radiomap_mean_file.delete()
return "Error while writing radio map: " + e.getMessage
}
case e: Exception =>{
e.printStackTrace()
return "writeRadioMap:" + e.getClass + ": " + e.getMessage
}
}
null
}
def writeRBFWeights(orientation: Int): String = {
val start = System.currentTimeMillis()
LOG.D("Writing RBF weights!")
for (x <- 0 until orientation) {
val group = x * 360 / orientation
val MatrixU = create_U_matrix(group)
if (MatrixU == null) return "writeRBFWeights: MatrixU is null"
LOG.D("created U matrix! time[ " + (System.currentTimeMillis() - start) +
"] ms")
val Matrixd = create_d_matrix(MatrixU.getRowDimension, group)
if (Matrixd == null) return "writeRBFWeights: Matrixd is null"
LOG.D("created matrix d! time[ " + (System.currentTimeMillis() - start) + "] ms")
val UPlus = computeUPlusMatrix(MatrixU)
if (UPlus == null) return "writeRBFWeights: UPlus is null"
LOG.D("computed Plus matrix! time[ " + (System.currentTimeMillis() - start) +
"] ms")
val w = computeWMatrix(UPlus, Matrixd)
if (w == null) return "writeRBFWeights: w is null"
LOG.D("computed W matrix! time[ " + (System.currentTimeMillis() - start) + "] ms")
val dec = new DecimalFormat("###.########")
var fos: FileOutputStream = null
val radiomap_rbf_weights_file = new File(radiomap_rbf_weights_filename)
try {
fos = if (x == 0) new FileOutputStream(radiomap_rbf_weights_file, false) else new FileOutputStream(radiomap_rbf_weights_file,
true)
} catch {
case e: FileNotFoundException => {
radiomap_rbf_weights_file.delete()
return "writeRBFWeights: Error RBF weights" + e.getClass + ": " + e.getMessage
}
}
try {
if (x == 0) fos.write("# Heading wx, wy\n".getBytes)
for (i <- 0 until w.getRowDimension) {
fos.write((s"$group").getBytes)
for (j <- 0 until w.getColumnDimension) {
fos.write(dec.format(w.get(i, j)).getBytes)
if (j != w.getColumnDimension - 1) {
fos.write(", ".getBytes)
}
}
fos.write("\n".getBytes)
}
fos.close()
} catch {
case e: Exception => {
radiomap_rbf_weights_file.delete()
return "writeRBFWeights: Error RBF weights" + e.getClass + ": " + e.getMessage
}
}
}
LOG.D("Written RBF weights! time[ " + (System.currentTimeMillis() - start) +
"] ms")
null
}
private def create_U_matrix(orientation: Int): Matrix
= {
var UArray: ArrayList[ArrayList[Double]] = null
var CArray: ArrayList[ArrayList[Double]] = null
var Urow: ArrayList[Double] = null
CArray = fillCArray(orientation)
if (CArray == null) {
return null
}
UArray = fillUArray(CArray, orientation)
if (UArray == null) {
return null
}
val row = UArray.size
val column = CArray.size
val UArrayMatrix = Array.ofDim[Double](row, column)
for (i <- 0 until row) {
Urow = UArray.get(i)
for (j <- 0 until column) {
UArrayMatrix(i)(j) = Urow.get(j)
}
}
new Matrix(UArrayMatrix)
}
private def fillCArray(orientation: Int): ArrayList[ArrayList[Double]]
= {
var CArray = new ArrayList[ArrayList[Double]]()
var CArrayLine: ArrayList[Double] = null
var temp: Array[String] = null
var frRadiomapMean: FileReader = null
var readerRadiomapMean: BufferedReader = null
try {
frRadiomapMean = new FileReader(radiomap_mean_filename)
readerRadiomapMean = new BufferedReader(frRadiomapMean)
var line: String = null
while ( {
line = readerRadiomapMean.readLine;
line != null
}) {
if (!line.trim().isEmpty) {
line = line.replace(", ", " ")
temp = line.split(" ")
if (temp(0).trim().equals("#")) {
if (!temp(1).trim().equals("NaN")) {
if (temp.length < 5) {
return null
} else if (this.isIndoor &&
(!temp(1).trim().equalsIgnoreCase("X") || !temp(2).trim().equalsIgnoreCase("Y"))) {
return null
}
}
} else {
if (temp.length < 4) {
return null
}
CArrayLine = new ArrayList[Double]()
if (java.lang.Integer.parseInt(temp(2)) == orientation) {
for (i <- 3 until temp.length) {
CArrayLine.add(java.lang.Double.parseDouble(temp(i)))
}
CArray.add(CArrayLine)
}
}
}
}
frRadiomapMean.close()
readerRadiomapMean.close()
}
catch {
case e: Exception => {
LOG.E("Error while populating C array of RBF: " + e.getMessage)
CArray = null
}
}
CArray
}
private def fillUArray(CArray: ArrayList[ArrayList[Double]], orientation: Int): ArrayList[ArrayList[Double]]
= {
val UArray = new ArrayList[ArrayList[Double]]()
var frRadiomap: FileReader = null
var readerRadiomap: BufferedReader = null
var Srow: ArrayList[Double] = null
var Crow: ArrayList[Double] = null
var Urow: ArrayList[Double] = null
var temp: Array[String] = null
try {
var radiomapLine: String = null
frRadiomap = new FileReader(radiomap_filename)
readerRadiomap = new BufferedReader(frRadiomap)
while ( {
radiomapLine = readerRadiomap.readLine;
radiomapLine != null
}) {
if (!radiomapLine.trim().isEmpty) {
radiomapLine = radiomapLine.replace(", ", " ")
temp = radiomapLine.split(" ")
if (temp(0).trim().equals("#")) {
if (!temp(1).trim().equals("NaN")) {
if (temp.length < 5) {
return null
} else if (this.isIndoor &&
(!temp(1).trim().equalsIgnoreCase("X") || !temp(2).trim().equalsIgnoreCase("Y"))) {
return null
}
}
}
else {
if (temp.length < 4) {
return null
}
if (java.lang.Integer.parseInt(temp(2)) == orientation) {
Srow = new ArrayList[Double]()
for (i <- 3 until temp.length) {
Srow.add(java.lang.Double.parseDouble(temp(i)))
set_MIN_MAX_RSS(java.lang.Integer.parseInt(temp(i)))
}
Urow = new ArrayList[Double]()
for (i <- 0 until CArray.size) {
Crow = CArray.get(i)
val numerator = computeNumerator(Srow, Crow)
val denominator = computeDenominator(Srow, CArray)
Urow.add(numerator / denominator)
}
UArray.add(Urow)
}
}
}
}
frRadiomap.close()
readerRadiomap.close()
} catch {
case e: Exception => {
LOG.E("Error while populating U array of RBF: " + e.getMessage)
return null
}
}
UArray
}
private def computeNumerator(Srow: ArrayList[Double], Crow: ArrayList[Double]): java.lang.Double
= {
var Si: java.lang.Double = null
var Cj: java.lang.Double = null
val firstParameter = -1 / (2 * Math.pow(S_RBF, 2))
var secondParameter = 0.0d
for (i <- 0 until Srow.size) {
Si = Srow.get(i)
Cj = Crow.get(i)
secondParameter += Math.pow(Si - Cj, 2)
}
Math.exp(firstParameter * secondParameter)
}
private def computeDenominator(Srow: ArrayList[Double], C: ArrayList[ArrayList[Double]]): java.lang.Double
= {
var Crow: ArrayList[Double] = null
var sum = 0.0d
for (i <- 0 until C.size) {
Crow = C.get(i)
sum += computeNumerator(Srow, Crow)
}
sum
}
private def create_d_matrix(rowDimension: Int, orientation: Int): Matrix
= {
var frRadiomap: FileReader = null
var readerRadiomap: BufferedReader = null
var temp: Array[String] = null
val row = rowDimension
val column = 2
val dArrayMatrix = Array.ofDim[Double](row, column)
var i = 0
try {
var radiomapLine: String = null
frRadiomap = new FileReader(radiomap_filename)
readerRadiomap = new BufferedReader(frRadiomap)
while ( {
radiomapLine = readerRadiomap.readLine;
radiomapLine != null
}) {
if (radiomapLine.trim().isEmpty) {
radiomapLine = radiomapLine.replace(", ", " ")
temp = radiomapLine.split(" ")
if (temp(0).trim().equals("#")) {
if (!temp(1).trim().equals("NaN")) {
if (temp.length < 5) {
return null
} else if (this.isIndoor &&
(!temp(1).trim().equalsIgnoreCase("X") || !temp(2).trim().equalsIgnoreCase("Y"))) {
return null
}
}
} else {
if (temp.length < 4) {
return null
}
if (java.lang.Integer.parseInt(temp(2)) == orientation) {
for (k <- 0 until 2) {
dArrayMatrix(i)(k) = java.lang.Double.parseDouble(temp(k))
}
i
}
}
}
}
frRadiomap.close()
readerRadiomap.close()
} catch {
case e: Exception => {
LOG.E("Error while creating d matrix of RBF: " + e.getMessage)
return null
}
}
new Matrix(dArrayMatrix)
}
private def computeUPlusMatrix(MatrixU: Matrix): Matrix
= {
try {
val Utranspose = MatrixU.transpose()
val UtransposeU = Utranspose.times(MatrixU)
val UtransposeUInverse = UtransposeU.inverse()
UtransposeUInverse.times(Utranspose)
} catch {
case e: Exception => {
LOG.E("Error while computing U+ matrix of RBF: " + e.getMessage)
null
}
}
}
private def computeWMatrix(UPlus: Matrix, Matrixd: Matrix): Matrix
= {
var w: Matrix = null
try {
w = UPlus.times(Matrixd)
w
} catch {
case e: Exception => {
LOG.E("Error while computing w matrix of RBF: " + e.getMessage)
null
}
}
}
private def calculateEuclideanDistance(l1: ArrayList[String], l2: ArrayList[String]): Float = {
var finalResult = 0.0f
var v1: Float = 0.0f
var v2: Float = 0.0f
var temp: Float = 0.0f
var str: String = null
for (i <- 0 until l1.size) {
try {
str = l1.get(i)
v1 = java.lang.Float.valueOf(str.trim()).floatValue()
str = l2.get(i)
v2 = java.lang.Float.valueOf(str.trim()).floatValue()
} catch {
case e: Exception => return java.lang.Float.NEGATIVE_INFINITY
}
temp = v1 - v2
temp *= temp
finalResult += temp
}
Math.sqrt(finalResult).toFloat
}
private def printMatrix(m: Matrix): Unit = {
for (i <- 0 until m.getRowDimension) {
for (j <- 0 until m.getColumnDimension()) {
System.out.print(s"$m.get(i, j)")
}
println()
}
}
}
}