Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / networklocation / wps_harvest / src / quality.rs

quality.rs286 lines · 11.3 KiBRaw
1//! Turning many observations of a beacon into at most one store record.
2//!
3//! This is where "accuracy first" is actually earned. Coverage comes from the crawl; what
4//! decides whether a fix is any good is which observations are kept and which are thrown away.
5//!
6//! Three rules, in order of how much they matter:
7//!
8//! 1. **Movers are dropped entirely.** A BSSID seen in two places kilometres apart is a phone
9//! hotspot, a travel router, or an AP on a bus or train. Recording either position is worse
10//! than recording none: a device that sees it gets confidently placed somewhere it is not,
11//! and the solver has no way to tell. This is also the standard privacy mitigation for a
12//! dataset of this shape, since a moving AP's history is a person's history.
13//! 2. **Unusable identifiers are dropped**: randomized or multicast MACs, cell identities that
14//! do not fit the key layout, coordinates outside the representable range.
15//! 3. **Among what is left, the most precise observation wins**, and its accuracy is carried
16//! into the store rather than being replaced by a constant.
17
18use crate::keys;
19use crate::record::{Record, ACC_UNKNOWN};
20
21/// Metres per degree of latitude, near enough for a threshold comparison.
22const M_PER_DEG_LAT: f64 = 111_320.0;
23
24/// How the merge should treat a group of observations.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct Policy {
27 /// Observations of one beacon further apart than this mean it moves, so it is dropped.
28 pub mover_threshold_m: u32,
29 /// Drop observations whose reported accuracy is worse than this. `None` keeps everything,
30 /// which is the default: a coarse fix still helps the solver, because the solver is told
31 /// how coarse it is.
32 pub max_accuracy_m: Option<u16>,
33 /// Whether keys are WiFi MACs, which enables the randomized-address filter.
34 pub wifi: bool,
35}
36
37impl Policy {
38 /// Defaults for a WiFi store.
39 pub fn wifi() -> Policy {
40 Policy { mover_threshold_m: 1_000, max_accuracy_m: None, wifi: true }
41 }
42
43 /// Defaults for a cell store.
44 ///
45 /// The mover threshold is far looser than WiFi's: a cell's reported position is the centre
46 /// of a sector that can be kilometres across, and two datasets can put the same tower a
47 /// long way apart without either being wrong about which tower it is.
48 pub fn cell() -> Policy {
49 Policy { mover_threshold_m: 20_000, max_accuracy_m: None, wifi: false }
50 }
51}
52
53/// Why a group produced no record. Counted so a build reports what it discarded rather than
54/// silently shrinking.
55#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
56pub struct Rejects {
57 /// Randomized, locally-administered or multicast MACs.
58 pub randomized_mac: u64,
59 /// Coordinates outside the store's representable range.
60 pub out_of_range: u64,
61 /// Observations too far apart to be one fixed beacon.
62 pub mover: u64,
63 /// Every observation was less precise than the policy allows.
64 pub too_coarse: u64,
65}
66
67impl Rejects {
68 /// Total groups discarded.
69 pub fn total(&self) -> u64 {
70 self.randomized_mac + self.out_of_range + self.mover + self.too_coarse
71 }
72}
73
74/// Approximate distance in metres. Equirectangular, which is accurate to well under a percent
75/// at the scales the thresholds sit at and does not need trigonometry per pair beyond one
76/// cosine.
77pub fn distance_m(lat_a_e8: i64, lon_a_e8: i64, lat_b_e8: i64, lon_b_e8: i64) -> f64 {
78 let lat_a = lat_a_e8 as f64 / 1e8;
79 let lat_b = lat_b_e8 as f64 / 1e8;
80 let dlat = (lat_a - lat_b) * M_PER_DEG_LAT;
81 let mid = ((lat_a + lat_b) / 2.0).to_radians();
82 let dlon = (lon_a_e8 - lon_b_e8) as f64 / 1e8 * M_PER_DEG_LAT * mid.cos();
83 (dlat * dlat + dlon * dlon).sqrt()
84}
85
86/// Reduce every observation of one beacon to at most one record.
87///
88/// `group` must be non-empty and all entries must share a key. Returns `None` when the beacon
89/// is rejected, recording why in `rejects`.
90pub fn reduce(group: &[Record], policy: &Policy, rejects: &mut Rejects) -> Option<Record> {
91 let first = *group.first()?;
92
93 if policy.wifi && keys::is_randomized_mac(first.key as u64) {
94 rejects.randomized_mac += 1;
95 return None;
96 }
97
98 // Anything unrepresentable is dropped rather than clamped: a clamped coordinate is a
99 // confident claim about the wrong place.
100 let mut usable: Vec<&Record> = group.iter().filter(|r| r.in_range()).collect();
101 if usable.is_empty() {
102 rejects.out_of_range += 1;
103 return None;
104 }
105
106 // Movers are judged before the accuracy filter, so a beacon is not rescued from the mover
107 // test by having its outlying observations filtered out first.
108 let threshold = policy.mover_threshold_m as f64;
109 for (i, a) in usable.iter().enumerate() {
110 for b in usable.iter().skip(i + 1) {
111 if distance_m(a.lat_e8, a.lon_e8, b.lat_e8, b.lon_e8) > threshold {
112 rejects.mover += 1;
113 return None;
114 }
115 }
116 }
117
118 if let Some(max) = policy.max_accuracy_m {
119 usable.retain(|r| r.accuracy_m != ACC_UNKNOWN && r.accuracy_m <= max);
120 if usable.is_empty() {
121 rejects.too_coarse += 1;
122 return None;
123 }
124 }
125
126 // Most precise wins; an unreported accuracy loses to any reported one. `sort` in `sort.rs`
127 // already orders a group this way, but reduce must not depend on that to stay correct.
128 let best = usable.into_iter().min_by_key(|r| {
129 (r.accuracy_m == ACC_UNKNOWN, r.accuracy_m, r.source, r.lat_e8, r.lon_e8)
130 })?;
131 Some(*best)
132}
133
134/// Clamp a source-reported accuracy into the store's 16-bit field.
135///
136/// Saturates rather than dropping: 65 km is already useless for positioning, but the solver
137/// weights by accuracy, so a saturated value is correctly ignored rather than absent.
138pub fn clamp_accuracy(meters: i32) -> u16 {
139 if meters < 0 {
140 ACC_UNKNOWN
141 } else {
142 meters.min(ACC_UNKNOWN as i32 - 1) as u16
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149 use crate::record::{Source, ALT_UNKNOWN};
150
151 const SF_LAT: i64 = 37_77493000;
152 const SF_LON: i64 = -122_41942000;
153
154 fn rec(key: u128, lat: i64, lon: i64, acc: u16, source: Source) -> Record {
155 Record { key, lat_e8: lat, lon_e8: lon, accuracy_m: acc, altitude_m: ALT_UNKNOWN, source }
156 }
157
158 fn wifi(lat: i64, lon: i64, acc: u16) -> Record {
159 rec(0x001122334455, lat, lon, acc, Source::Gsloc)
160 }
161
162 #[test]
163 fn distance_is_about_right() {
164 // One degree of latitude.
165 let d = distance_m(0, 0, 1_00000000, 0);
166 assert!((d - M_PER_DEG_LAT).abs() < 1.0, "got {d}");
167 // A degree of longitude shrinks with latitude.
168 let equator = distance_m(0, 0, 0, 1_00000000);
169 let high = distance_m(60_00000000, 0, 60_00000000, 1_00000000);
170 assert!(high < equator * 0.55, "{high} vs {equator}");
171 assert_eq!(distance_m(SF_LAT, SF_LON, SF_LAT, SF_LON), 0.0);
172 }
173
174 #[test]
175 fn the_most_precise_observation_wins_and_keeps_its_accuracy() {
176 let mut rj = Rejects::default();
177 let group = vec![
178 wifi(SF_LAT, SF_LON, 200),
179 wifi(SF_LAT + 100, SF_LON, 15),
180 wifi(SF_LAT - 50, SF_LON, 90),
181 ];
182 let got = reduce(&group, &Policy::wifi(), &mut rj).unwrap();
183 assert_eq!(got.accuracy_m, 15);
184 assert_eq!(got.lat_e8, SF_LAT + 100);
185 assert_eq!(rj.total(), 0);
186 }
187
188 #[test]
189 fn a_reported_accuracy_beats_an_unreported_one() {
190 let mut rj = Rejects::default();
191 let group = vec![wifi(SF_LAT, SF_LON, ACC_UNKNOWN), wifi(SF_LAT, SF_LON, 900)];
192 assert_eq!(reduce(&group, &Policy::wifi(), &mut rj).unwrap().accuracy_m, 900);
193 }
194
195 #[test]
196 fn an_only_unreported_accuracy_still_produces_a_record() {
197 let mut rj = Rejects::default();
198 let group = vec![wifi(SF_LAT, SF_LON, ACC_UNKNOWN)];
199 assert_eq!(reduce(&group, &Policy::wifi(), &mut rj).unwrap().accuracy_m, ACC_UNKNOWN);
200 }
201
202 #[test]
203 fn a_beacon_seen_in_two_places_is_dropped_not_averaged() {
204 let mut rj = Rejects::default();
205 // San Francisco and New York.
206 let group = vec![wifi(SF_LAT, SF_LON, 20), wifi(40_71278000, -74_00594000, 20)];
207 assert_eq!(reduce(&group, &Policy::wifi(), &mut rj), None);
208 assert_eq!(rj.mover, 1);
209 }
210
211 #[test]
212 fn small_disagreements_between_sources_are_tolerated() {
213 let mut rj = Rejects::default();
214 // ~55 m apart: two datasets describing the same AP.
215 let group = vec![
216 rec(0x001122334455, SF_LAT, SF_LON, 40, Source::Beacondb),
217 rec(0x001122334455, SF_LAT + 50000, SF_LON, 25, Source::Gsloc),
218 ];
219 assert!(reduce(&group, &Policy::wifi(), &mut rj).is_some());
220 assert_eq!(rj.mover, 0);
221 }
222
223 #[test]
224 fn the_accuracy_filter_cannot_rescue_a_mover() {
225 let mut rj = Rejects::default();
226 let policy = Policy { max_accuracy_m: Some(50), ..Policy::wifi() };
227 // The far-away observation would be filtered out by max_accuracy, but the beacon still
228 // moves and must not be kept on the strength of the surviving one.
229 let group = vec![wifi(SF_LAT, SF_LON, 20), wifi(40_71278000, -74_00594000, 5000)];
230 assert_eq!(reduce(&group, &policy, &mut rj), None);
231 assert_eq!(rj.mover, 1);
232 assert_eq!(rj.too_coarse, 0);
233 }
234
235 #[test]
236 fn randomized_macs_are_dropped_for_wifi_but_the_filter_is_off_for_cells() {
237 let mut rj = Rejects::default();
238 // 0xAA first octet: locally administered.
239 let group = vec![rec(0xAABBCCDDEEFF, SF_LAT, SF_LON, 20, Source::Gsloc)];
240 assert_eq!(reduce(&group, &Policy::wifi(), &mut rj), None);
241 assert_eq!(rj.randomized_mac, 1);
242
243 // The same bit pattern as a cell key means nothing; the filter must not fire.
244 let mut rj2 = Rejects::default();
245 assert!(reduce(&group, &Policy::cell(), &mut rj2).is_some());
246 assert_eq!(rj2.randomized_mac, 0);
247 }
248
249 #[test]
250 fn out_of_range_coordinates_are_dropped() {
251 let mut rj = Rejects::default();
252 let group = vec![wifi(91_00000000, SF_LON, 20)];
253 assert_eq!(reduce(&group, &Policy::wifi(), &mut rj), None);
254 assert_eq!(rj.out_of_range, 1);
255 }
256
257 #[test]
258 fn a_partly_out_of_range_group_keeps_the_usable_observation() {
259 let mut rj = Rejects::default();
260 let group = vec![wifi(91_00000000, SF_LON, 5), wifi(SF_LAT, SF_LON, 30)];
261 let got = reduce(&group, &Policy::wifi(), &mut rj).unwrap();
262 assert_eq!(got.lat_e8, SF_LAT);
263 assert_eq!(rj.total(), 0);
264 }
265
266 #[test]
267 fn max_accuracy_drops_a_group_with_nothing_precise_enough() {
268 let mut rj = Rejects::default();
269 let policy = Policy { max_accuracy_m: Some(50), ..Policy::wifi() };
270 let group = vec![wifi(SF_LAT, SF_LON, 300), wifi(SF_LAT, SF_LON, ACC_UNKNOWN)];
271 assert_eq!(reduce(&group, &policy, &mut rj), None);
272 assert_eq!(rj.too_coarse, 1);
273 }
274
275 #[test]
276 fn accuracy_clamps_into_the_field_rather_than_wrapping() {
277 assert_eq!(clamp_accuracy(0), 0);
278 assert_eq!(clamp_accuracy(35), 35);
279 assert_eq!(clamp_accuracy(-1), ACC_UNKNOWN);
280 assert_eq!(clamp_accuracy(i32::MIN), ACC_UNKNOWN);
281 assert_eq!(clamp_accuracy(999_999), 65534);
282 assert_eq!(clamp_accuracy(65534), 65534);
283 // Never produces the sentinel from a real measurement.
284 assert_ne!(clamp_accuracy(65535), ACC_UNKNOWN);
285 }
286}