networklocation: port GrapheneOS EM multilateration position estimator (Rust JNI)
- Commit
34472ab99e38711f77fefafabb28d79608619a0f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-09 22:42 UTC (3 months ago)
- Parents
7089da9
Diff
networklocation/src/main/rust/Cargo.toml
diff --git a/networklocation/src/main/rust/Cargo.toml b/networklocation/src/main/rust/Cargo.tomlindex 4a1e798595..80b5d2e6a0 100644--- a/networklocation/src/main/rust/Cargo.toml+++ b/networklocation/src/main/rust/Cargo.toml@@ -1,16 +1,21 @@ [package]-name = "networklocation"+name = "network_location_position_estimation_rust" version = "0.1.0" edition = "2021"-description = "Native device-position estimation (weighted-centroid / inverse-variance least squares over Apple gs-loc beacon fixes) for the network location provider, via JNI"-license = "GPL-2.0-only"+description = "Robust device-position estimation (RANSAC + Expectation-Maximization multilateration) for the network location provider, via JNI. Ported from GrapheneOS NetworkLocation (MIT)."+license = "MIT" [lib]-name = "networklocation"+name = "network_location_position_estimation_rust" crate-type = ["cdylib", "rlib"] [dependencies] jni.workspace = true+log.workspace = true+itertools = "0.14"++[dev-dependencies]+rand = { version = "0.8", features = ["small_rng"] } [profile.release] opt-level = 3
networklocation/src/main/rust/LICENSE-GrapheneOS
diff --git a/networklocation/src/main/rust/LICENSE-GrapheneOS b/networklocation/src/main/rust/LICENSE-GrapheneOSnew file mode 100644index 0000000000..334b247077--- /dev/null+++ b/networklocation/src/main/rust/LICENSE-GrapheneOS@@ -0,0 +1,31 @@+The device-position estimation algorithm in this directory+(coordinate.rs, measurement.rs, multilateration.rs, position.rs, and the+RANSAC driver in lib.rs) is ported from GrapheneOS's NetworkLocation app:++ https://github.com/GrapheneOS/platform_packages_apps_NetworkLocation++which is distributed under the MIT License, reproduced below. This file is+retained to satisfy that license's requirement that the copyright notice and+permission notice accompany the ported code.++MIT License++Copyright (c) 2024-2025 GrapheneOS++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.
networklocation/src/main/rust/src/coordinate.rs
diff --git a/networklocation/src/main/rust/src/coordinate.rs b/networklocation/src/main/rust/src/coordinate.rsnew file mode 100644index 0000000000..1a95b6edd3--- /dev/null+++ b/networklocation/src/main/rust/src/coordinate.rs@@ -0,0 +1,36 @@+// Ported from GrapheneOS NetworkLocation+// (github.com/GrapheneOS/platform_packages_apps_NetworkLocation),+// MIT-licensed, Copyright (c) 2024-2025 GrapheneOS. See LICENSE-GrapheneOS.++//! Documentation for coordinate module.++/// Coordinate.+#[derive(Clone, Copy, Debug)]+pub struct Coordinate {+ /// whether the value is real (not estimated based on other data)+ pub real: bool,+ /// coordinate value+ pub value: f64,+ /// 6-sigma²+ pub six_sigma_squared: f64,+}++impl Coordinate {+ /// new real coordinate+ pub fn new_real(value: f64, six_sigma_squared: f64) -> Self {+ Coordinate {+ real: true,+ value,+ six_sigma_squared,+ }+ }++ /// new fake coordinate+ pub fn new_fake() -> Self {+ Coordinate {+ real: false,+ value: 0.0,+ six_sigma_squared: 0.0,+ }+ }+}
networklocation/src/main/rust/src/estimate.rs
diff --git a/networklocation/src/main/rust/src/estimate.rs b/networklocation/src/main/rust/src/estimate.rsdeleted file mode 100644index 6fd59f5c24..0000000000--- a/networklocation/src/main/rust/src/estimate.rs+++ /dev/null@@ -1,190 +0,0 @@-//! Device-position estimation from a set of beacon fixes.-//!-//! Each beacon (a cell tower or WiFi AP whose coordinates the Apple `gs-loc`-//! proxy returned, then cached locally) is a self-reported position with an-//! accuracy radius in metres. The device is somewhere among them; we want a-//! single lat/lon plus an accuracy estimate.-//!-//! Treating each beacon as a noisy observation of the device position with-//! Gaussian error `sigma_i` (its accuracy radius), the maximum-likelihood /-//! least-squares estimate that minimises `sum_i (1/sigma_i^2) * |p - b_i|^2`-//! is the inverse-variance-weighted centroid `p* = (sum w_i b_i) / (sum w_i)`-//! with `w_i = 1/sigma_i^2`. So the "weighted centroid" and the "least-squares-//! fit" are the same closed-form solution here — no iteration required.-//!-//! Math is done on a local east/north tangent plane (equirectangular-//! projection about the first beacon) so the averaging is metric and does not-//! misbehave with raw degrees; beacons in one fix are always within a few km.--/// Metres per degree of latitude (WGS-84 mean). Longitude scales this by-/// `cos(lat)`.-const M_PER_DEG_LAT: f64 = 111_320.0;--/// Accuracy radii below this (metres) are clamped up, so a single beacon-/// reporting an implausibly tiny radius cannot completely dominate the fit or-/// blow up `1/sigma^2`.-const MIN_ACCURACY_M: f64 = 1.0;--/// Estimate the device position from beacon fixes.-///-/// `beacons` is interleaved `[lat0, lon0, acc0, lat1, lon1, acc1, ...]` where-/// lat/lon are degrees and `acc` is the beacon's accuracy radius in metres.-///-/// Returns `[lat, lon, accuracy_m]`. `accuracy_m` is the inverse-variance-/// standard error of the estimate, floored by the weighted RMS spread of the-/// beacons about the estimate so that mutually disagreeing beacons widen (never-/// falsely shrink) the reported accuracy.-///-/// Returns `None` if there are no beacons or the slice length is not a-/// multiple of three.-pub fn estimate_position(beacons: &[f64]) -> Option<[f64; 3]> {- if beacons.is_empty() || beacons.len() % 3 != 0 {- return None;- }-- // Reference the tangent plane on the first *finite* beacon; a leading NaN- // beacon must not poison lat0/lon0 (and thus every projected coordinate).- let reference = beacons.chunks_exact(3).find(|b| {- b[0].is_finite() && b[1].is_finite() && b[2].is_finite()- })?;- let lat0 = reference[0];- let lon0 = reference[1];- let cos_lat0 = lat0.to_radians().cos();- // Guard the pole singularity; cos(lat) -> 0 makes the east scale explode.- let east_scale = (M_PER_DEG_LAT * cos_lat0).max(1e-6);-- let mut sum_w = 0.0f64;- let mut sum_we = 0.0f64;- let mut sum_wn = 0.0f64;-- // Reduce to a local tangent plane in metres about (lat0, lon0).- let to_en = |lat: f64, lon: f64| {- let north = (lat - lat0) * M_PER_DEG_LAT;- let east = (lon - lon0) * east_scale;- (east, north)- };-- for b in beacons.chunks_exact(3) {- let (lat, lon, acc) = (b[0], b[1], b[2]);- if !lat.is_finite() || !lon.is_finite() || !acc.is_finite() {- continue;- }- let sigma = acc.max(MIN_ACCURACY_M);- let w = 1.0 / (sigma * sigma);- let (east, north) = to_en(lat, lon);- sum_w += w;- sum_we += w * east;- sum_wn += w * north;- }-- if sum_w <= 0.0 {- return None;- }-- let e_mean = sum_we / sum_w;- let n_mean = sum_wn / sum_w;-- // Weighted variance of the beacons about the estimate (spread), and the- // inverse-variance standard error of the mean. Report the larger.- let mut sum_w_sq_dist = 0.0f64;- for b in beacons.chunks_exact(3) {- let (lat, lon, acc) = (b[0], b[1], b[2]);- if !lat.is_finite() || !lon.is_finite() || !acc.is_finite() {- continue;- }- let sigma = acc.max(MIN_ACCURACY_M);- let w = 1.0 / (sigma * sigma);- let (east, north) = to_en(lat, lon);- let de = east - e_mean;- let dn = north - n_mean;- sum_w_sq_dist += w * (de * de + dn * dn);- }- let spread = (sum_w_sq_dist / sum_w).sqrt();- let std_err = (1.0 / sum_w).sqrt();- let accuracy = spread.max(std_err);-- let lat = lat0 + n_mean / M_PER_DEG_LAT;- let lon = lon0 + e_mean / east_scale;-- Some([lat, lon, accuracy])-}--#[cfg(test)]-mod tests {- use super::*;-- fn approx(a: f64, b: f64, tol: f64, what: &str) {- assert!((a - b).abs() < tol, "{what}: {a} vs {b} (tol {tol})");- }-- #[test]- fn none_on_empty_or_ragged() {- assert!(estimate_position(&[]).is_none());- assert!(estimate_position(&[1.0, 2.0]).is_none());- assert!(estimate_position(&[1.0, 2.0, 3.0, 4.0]).is_none());- }-- #[test]- fn single_beacon_returns_itself() {- let out = estimate_position(&[37.4, -122.1, 25.0]).unwrap();- approx(out[0], 37.4, 1e-9, "lat");- approx(out[1], -122.1, 1e-9, "lon");- // Spread is zero, so accuracy is the inverse-variance std error == sigma.- approx(out[2], 25.0, 1e-6, "acc");- }-- #[test]- fn two_equal_beacons_midpoint() {- let out = estimate_position(&[37.0, -122.0, 30.0, 37.002, -122.0, 30.0]).unwrap();- approx(out[0], 37.001, 1e-6, "lat midpoint");- approx(out[1], -122.0, 1e-6, "lon");- }-- #[test]- fn more_accurate_beacon_dominates() {- // Beacon A far but very accurate, beacon B near but very inaccurate.- // Result should sit much closer to A.- let a_lat = 37.000;- let b_lat = 37.010;- let out = estimate_position(&[a_lat, -122.0, 5.0, b_lat, -122.0, 500.0]).unwrap();- let d_a = (out[0] - a_lat).abs();- let d_b = (out[0] - b_lat).abs();- assert!(d_a < d_b, "estimate should be closer to the accurate beacon");- // 1/25 vs 1/250000 weighting => essentially on A.- approx(out[0], a_lat, 1e-4, "lat near A");- }-- #[test]- fn accuracy_shrinks_with_agreeing_beacons() {- let one = estimate_position(&[37.0, -122.0, 40.0]).unwrap();- let many = estimate_position(&[- 37.0, -122.0, 40.0, //- 37.0, -122.0, 40.0, //- 37.0, -122.0, 40.0, //- 37.0, -122.0, 40.0,- ])- .unwrap();- // Four identical, agreeing observations halve the standard error (sqrt(4)).- assert!(many[2] < one[2], "more agreeing beacons -> tighter accuracy");- approx(many[2], one[2] / 2.0, 1e-3, "std error scales 1/sqrt(n)");- }-- #[test]- fn disagreeing_beacons_widen_accuracy() {- // Two equally-weighted beacons ~1 km apart: the reported accuracy must- // reflect the spread, not the (smaller) inverse-variance std error.- let out = estimate_position(&[37.0, -122.0, 50.0, 37.009, -122.0, 50.0]).unwrap();- assert!(out[2] > 200.0, "spread should dominate, got {}", out[2]);- }-- #[test]- fn skips_non_finite_beacons() {- let out = estimate_position(&[- f64::NAN, -122.0, 10.0, // dropped- 37.5, -122.5, 20.0, // kept- ])- .unwrap();- approx(out[0], 37.5, 1e-9, "lat");- approx(out[1], -122.5, 1e-9, "lon");- }-}
networklocation/src/main/rust/src/jni.rs
diff --git a/networklocation/src/main/rust/src/jni.rs b/networklocation/src/main/rust/src/jni.rsnew file mode 100644index 0000000000..443b7ee59e--- /dev/null+++ b/networklocation/src/main/rust/src/jni.rs@@ -0,0 +1,120 @@+// Ported from GrapheneOS NetworkLocation+// (github.com/GrapheneOS/platform_packages_apps_NetworkLocation),+// MIT-licensed, Copyright (c) 2024-2025 GrapheneOS. See LICENSE-GrapheneOS.++//! Thin JNI marshalling layer bridging the Kotlin `NetworkLocationNative`+//! object to the host-testable [`estimate_position`](crate::estimate_position)+//! solver. This file contains no estimation math; it only converts between the+//! Kotlin `DoubleArray` contract and the solver's [`Measurement`] domain.++use crate::coordinate::Coordinate;+use crate::estimate_position;+use crate::measurement::Measurement;+use crate::position::Position;++use jni::objects::{JClass, JDoubleArray};+use jni::sys::jdoubleArray;+use jni::JNIEnv;++/// Metres per degree of latitude (WGS-84 mean). Longitude scales this by+/// `cos(lat)`.+const M_PER_DEG_LAT: f64 = 111_320.0;++/// Accuracy radii below this (metres) are clamped up, so a single beacon+/// reporting an implausibly tiny radius cannot dominate the fit.+const MIN_ACCURACY_M: f64 = 1.0;++/// Estimate the device position from interleaved beacon fixes.+///+/// `beacons` is `[lat0, lon0, acc0, lat1, lon1, acc1, ...]` (degrees, degrees,+/// metres). Returns `[lat, lon, accuracy_m]`, or `None` when there are no+/// usable beacons or the slice length is not a multiple of three.+///+/// Beacon fixes carry a self-reported position and an accuracy radius but no+/// ranging, so each is modelled as a [`Measurement`] whose beacon location is+/// the observed position (on a local east/north tangent plane in metres) with+/// per-axis `six_sigma_squared = sigma^2`, and `distance = 0` — i.e. the device+/// is a priori co-located with the beacon. The robust EM/RANSAC solver in+/// [`estimate_position`] then resolves the single position most consistent with+/// all beacons and rejects outliers.+fn estimate_lat_lon(beacons: &[f64]) -> Option<[f64; 3]> {+ if beacons.is_empty() || beacons.len() % 3 != 0 {+ return None;+ }++ // Reference the tangent plane on the first *finite* beacon; a leading NaN+ // beacon must not poison lat0/lon0 (and thus every projected coordinate).+ let reference = beacons+ .chunks_exact(3)+ .find(|b| b[0].is_finite() && b[1].is_finite() && b[2].is_finite())?;+ let lat0 = reference[0];+ let lon0 = reference[1];+ let cos_lat0 = lat0.to_radians().cos();+ // Guard the pole singularity; cos(lat) -> 0 makes the east scale explode.+ let east_scale = (M_PER_DEG_LAT * cos_lat0).max(1e-6);++ let mut measurements = Vec::with_capacity(beacons.len() / 3);+ for b in beacons.chunks_exact(3) {+ let (lat, lon, acc) = (b[0], b[1], b[2]);+ if !lat.is_finite() || !lon.is_finite() || !acc.is_finite() {+ continue;+ }+ let sigma = acc.max(MIN_ACCURACY_M);+ let six_sigma_squared = sigma * sigma;+ let east = (lon - lon0) * east_scale;+ let north = (lat - lat0) * M_PER_DEG_LAT;++ measurements.push(Measurement {+ position: Position {+ x: Coordinate::new_real(east, six_sigma_squared),+ y: Coordinate::new_real(north, six_sigma_squared),+ // Altitude is unknown for a network beacon fix: latent.+ z: Coordinate::new_fake(),+ },+ distance: 0.0,+ weight: 0.0,+ });+ }++ let estimated = estimate_position(&measurements)?;+ let position = estimated.position;++ let lat = lat0 + position.y.value / M_PER_DEG_LAT;+ let lon = lon0 + position.x.value / east_scale;+ let accuracy = (position.x.six_sigma_squared + position.y.six_sigma_squared).sqrt();++ Some([lat, lon, accuracy])+}++/// `estimatePosition(beacons)`. `beacons` is interleaved+/// `[lat0,lon0,acc0,lat1,lon1,acc1,...]` (degrees, degrees, metres); returns a+/// 3-element `[lat, lon, accuracyMeters]` array, or null when there are no+/// usable beacons / on error.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_networklocation_NetworkLocationNative_estimatePosition<+ 'l,+>(+ env: JNIEnv<'l>,+ _class: JClass<'l>,+ beacons: JDoubleArray<'l>,+) -> jdoubleArray {+ let len = env.get_array_length(&beacons).unwrap_or(0) as usize;+ let mut buf = vec![0f64; len];+ if env.get_double_array_region(&beacons, 0, &mut buf).is_err() {+ return std::ptr::null_mut();+ }++ let result = match estimate_lat_lon(&buf) {+ Some(r) => r,+ None => return std::ptr::null_mut(),+ };++ let out = match env.new_double_array(result.len() as i32) {+ Ok(a) => a,+ Err(_) => return std::ptr::null_mut(),+ };+ if env.set_double_array_region(&out, 0, &result).is_err() {+ return std::ptr::null_mut();+ }+ out.into_raw()+}
networklocation/src/main/rust/src/lib.rs
diff --git a/networklocation/src/main/rust/src/lib.rs b/networklocation/src/main/rust/src/lib.rsindex 510a82a425..6dbcd66ff6 100644--- a/networklocation/src/main/rust/src/lib.rs+++ b/networklocation/src/main/rust/src/lib.rs@@ -1,54 +1,371 @@-//! Network-location native library: device-position estimation from the set of-//! beacon fixes returned by the Apple `gs-loc` proxy (and cached locally),-//! exposed to Kotlin via JNI.-//!-//! The estimation math lives in the dependency-free [`estimate`] module so it is-//! testable on the host; this file is only the thin JNI marshalling layer.+// Ported from GrapheneOS NetworkLocation+// (github.com/GrapheneOS/platform_packages_apps_NetworkLocation),+// MIT-licensed, Copyright (c) 2024-2025 GrapheneOS. See LICENSE-GrapheneOS.+//+// Adaptation note: the upstream Android build depends on AOSP's `liblogger`+// crate for on-device logging. That crate is not available on crates.io, so the+// `logger::init(...)` calls are dropped; the algorithm is otherwise unchanged. -mod estimate;+//! Position estimation using robust algorithms. -pub use estimate::estimate_position;+use std::ops::{Add, Div};++use crate::multilateration::multilateration;+use itertools::Itertools;+use measurement::Measurement;+use position::Position;++pub mod coordinate;+mod jni;+pub mod measurement;+pub mod multilateration;+pub mod position;++/// Estimated position.+pub struct EstimatedPosition {+ /// estimated position+ position: Position,+ /// inliers size+ inliers_size: usize,+}++struct Candidate {+ inliers_indices: Vec<usize>,+ position: Position,+}++/**+ * Estimate a position using robust methods.+ */+pub fn estimate_position(measurements: &[Measurement]) -> Option<EstimatedPosition> {+ if measurements.is_empty() {+ return None;+ }++ // only applies to measurements used for combos, all measurements+ // are still used when checking for inliers+ let max_measurements_for_combos = measurements.len().min(10);++ let sample_size = measurements.len().min(4);+ let min_inliers = measurements.len().min(4);+ let mut candidate_inliers_indices = Vec::with_capacity(measurements.len());++ let mut candidates: Vec<Candidate> = vec![];++ let mut measurements_indices: Vec<usize> = (0..measurements.len()).collect();+ measurements_indices = measurements_indices+ .iter()+ .sorted_by(|m1, m2| {+ let m1 = measurements[**m1];+ let m1_standard_deviation = (m1.position.x.six_sigma_squared+ + m1.position.y.six_sigma_squared+ + m1.position.z.six_sigma_squared)+ .sqrt();+ let m2 = measurements[**m2];+ let m2_standard_deviation = (m2.position.x.six_sigma_squared+ + m2.position.y.six_sigma_squared+ + m2.position.z.six_sigma_squared)+ .sqrt();++ m1_standard_deviation.total_cmp(&m2_standard_deviation)+ })+ .take(max_measurements_for_combos)+ .cloned()+ .collect();+ let top_measurements_indices = &measurements_indices[0..max_measurements_for_combos];++ for combo in top_measurements_indices.iter().combinations(sample_size) {+ let mut sample: Vec<Measurement> =+ combo.iter().map(|index| measurements[**index]).collect();++ let initial_guess = Position::average(&sample.iter().map(|m| m.position).collect_vec());++ let candidate_position = multilateration(&mut sample, Some(initial_guess), 50);++ candidate_inliers_indices.clear();+ for (index, measurement) in measurements.iter().enumerate() {+ let dx = candidate_position.x.value - measurement.position.x.value;+ let dy = candidate_position.y.value - measurement.position.y.value;+ let dz = candidate_position.z.value - measurement.position.z.value;++ let estimated_distance = (dx.powi(2) + dy.powi(2) + dz.powi(2)).sqrt();+ let residual = (estimated_distance - measurement.distance).abs();+ let standard_deviation = (measurement.position.x.six_sigma_squared+ + measurement.position.y.six_sigma_squared+ + measurement.position.z.six_sigma_squared)+ .sqrt()+ // Prevent division by zero.+ .max(f64::MIN_POSITIVE);+ let standardized_residual = residual / standard_deviation;+ // within 2 standard deviations+ let threshold = 2.0;++ if standardized_residual <= threshold {+ candidate_inliers_indices.push(index);+ }+ }++ candidates.push(Candidate {+ inliers_indices: candidate_inliers_indices.clone(),+ position: candidate_position,+ });+ }++ let target_inlier_count = measurements_indices.len().div(2).add(1).max(min_inliers);+ let best_candidate = candidates.iter().reduce(|best, candidate| {+ let compare_inlier_count = !(candidate.inliers_indices.len() >= target_inlier_count+ && best.inliers_indices.len() >= target_inlier_count);+ if compare_inlier_count && candidate.inliers_indices.len() > best.inliers_indices.len() {+ candidate+ } else if compare_inlier_count+ && candidate.inliers_indices.len() < best.inliers_indices.len()+ {+ best+ } else if candidate.position.number_of_real() > best.position.number_of_real()+ || (((candidate.position.is_all_real() && best.position.is_all_real())+ || candidate.position.number_of_real() == best.position.number_of_real())+ && candidate.position.x.six_sigma_squared+ + candidate.position.y.six_sigma_squared+ + candidate.position.z.six_sigma_squared+ < best.position.x.six_sigma_squared+ + best.position.y.six_sigma_squared+ + best.position.z.six_sigma_squared)+ {+ candidate+ } else {+ best+ }+ });++ if let Some(best_candidate) = best_candidate {+ if best_candidate.inliers_indices.len() >= min_inliers {+ let final_estimated_position = multilateration(+ &mut best_candidate+ .inliers_indices+ .iter()+ .map(|index| measurements[*index])+ .collect_vec(),+ Some(best_candidate.position),+ 1000.div(best_candidate.inliers_indices.len()).max(3),+ );++ Some(EstimatedPosition {+ position: final_estimated_position,+ inliers_size: best_candidate.inliers_indices.len(),+ })+ } else {+ None+ }+ } else {+ None+ }+}++#[cfg(test)]+mod tests {+ use log::info;+ use rand::rngs::SmallRng;+ use rand::{Rng, SeedableRng};+ use std::ops::Range;++ use crate::coordinate::Coordinate; -#[cfg(not(test))]-mod jni_bindings { use super::*;- use jni::objects::{JClass, JDoubleArray};- use jni::sys::jdoubleArray;- use jni::JNIEnv;-- /// `estimatePosition(beacons)`. `beacons` is interleaved- /// `[lat0,lon0,acc0,lat1,lon1,acc1,...]` (degrees, degrees, metres); returns- /// a 3-element `[lat, lon, accuracyMeters]` array, or null when there are no- /// usable beacons / on error.- #[no_mangle]- pub extern "system" fn Java_com_vayunmathur_networklocation_NetworkLocationNative_estimatePosition<- 'l,- >(- env: JNIEnv<'l>,- _class: JClass<'l>,- beacons: JDoubleArray<'l>,- ) -> jdoubleArray {- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- let len = env.get_array_length(&beacons).unwrap_or(0) as usize;- let mut buf = vec![0f64; len];- if env.get_double_array_region(&beacons, 0, &mut buf).is_err() {- return None;++ fn generate_random_measurement(+ x_range: Range<f64>,+ y_range: Range<f64>,+ z_range: Range<f64>,+ real_position: Position,+ random: &mut SmallRng,+ ) -> Measurement {+ let x = random.gen_range(x_range);+ let y = random.gen_range(y_range);+ let z = random.gen_range(z_range);+ let x_six_sigma_squared: f64 = random.gen_range(3000.0..5000.0);+ let y_six_sigma_squared: f64 = random.gen_range(3000.0..5000.0);+ let z_six_sigma_squared: f64 = random.gen_range(50.0..100.0);+ let distance = ((x - real_position.x.value).powi(2)+ + (y - real_position.y.value).powi(2)+ + (z - real_position.z.value).powi(2))+ .sqrt()+ + random.gen_range(10.0..100.0);++ Measurement {+ position: Position {+ x: Coordinate::new_real(x, x_six_sigma_squared),+ y: Coordinate::new_real(y, y_six_sigma_squared),+ z: Coordinate::new_real(z, z_six_sigma_squared),+ },+ distance,+ weight: 0.0,+ }+ }++ /// checks that position estimation fails due to not having enough inliers+ #[test]+ fn not_enough_inliers() {+ let mut results = vec![];+ let iterations = 100;++ for s in 0..iterations {+ let mut random = SmallRng::seed_from_u64(s);++ let real_position = Position {+ x: Coordinate::new_real(random.gen_range(-10000.0..10000.0), 0.0),+ y: Coordinate::new_real(random.gen_range(-10000.0..10000.0), 0.0),+ z: Coordinate::new_real(random.gen_range(-10000.0..10000.0), 0.0),+ };++ let mut measurements = vec![];++ for i in 0..9 {+ let mut measurement = generate_random_measurement(+ real_position.x.value - random.gen_range(0.0..1000.0)+ ..real_position.x.value + random.gen_range(0.0..1000.0),+ real_position.y.value - random.gen_range(0.0..1000.0)+ ..real_position.y.value + random.gen_range(0.0..1000.0),+ real_position.z.value - random.gen_range(0.0..1000.0)+ ..real_position.z.value + random.gen_range(0.0..1000.0),+ real_position,+ &mut random,+ );++ // make 6 of them outliers, meaning we only have 3 inliers which is not+ // enough (minimum inliers is currently 4)+ if i < 6 {+ measurement.position.x.value *= 100.0;+ measurement.position.y.value *= 100.0;+ measurement.position.z.value *= 100.0;+ }++ measurements.push(measurement);+ }++ let estimated_position = estimate_position(&measurements);++ results.push((real_position, estimated_position));+ }++ let position_deltas = results.iter().map(|p| {+ p.1.as_ref().map(|result| {+ let result = result.position;+ Position {+ x: Coordinate::new_real(+ (p.0.x.value - result.x.value).abs(),+ result.x.six_sigma_squared,+ ),+ y: Coordinate::new_real(+ (p.0.y.value - result.y.value).abs(),+ result.y.six_sigma_squared,+ ),+ z: Coordinate::new_real(+ (p.0.z.value - result.z.value).abs(),+ result.z.six_sigma_squared,+ ),+ }+ })+ });++ let successful_results_deltas = position_deltas.flatten().collect::<Vec<Position>>();+ let success_results_deltas_count = successful_results_deltas.len();++ let average_delta = Position::average(&successful_results_deltas);++ info!(+ "\nreal position: {:#?},\naverage delta: {:#?},\nratio of success: {}/{iterations}",+ Position::average(&results.iter().map(|p| p.0).collect_vec()),+ average_delta,+ success_results_deltas_count,+ );++ assert_eq!(success_results_deltas_count, 0);+ }++ /// checks that we can estimate a position successfully despite convincing outliers,+ /// as long as the majority of measurements are inliers+ #[test]+ fn majority_wins() {+ let mut results = vec![];+ let iterations = 100;++ for s in 0..iterations {+ let mut random = SmallRng::seed_from_u64(s);++ let real_position = Position {+ x: Coordinate::new_real(random.gen_range(0.0..10000.0), 0.0),+ y: Coordinate::new_real(random.gen_range(0.0..10000.0), 0.0),+ z: Coordinate::new_real(random.gen_range(0.0..10000.0), 0.0),+ };++ let mut measurements = vec![];++ for i in 0..9 {+ let mut measurement = generate_random_measurement(+ real_position.x.value - random.gen_range(0.0..1000.0)+ ..real_position.x.value + random.gen_range(0.0..1000.0),+ real_position.y.value - random.gen_range(0.0..1000.0)+ ..real_position.y.value + random.gen_range(0.0..1000.0),+ real_position.z.value - random.gen_range(0.0..1000.0)+ ..real_position.z.value + random.gen_range(0.0..1000.0),+ real_position,+ &mut random,+ );++ // make 4 of them convincing outliers by just inversing their coordinates,+ // meaning they still seem valid+ if i < 4 {+ measurement.position.x.value *= -1.0;+ measurement.position.y.value *= -1.0;+ measurement.position.z.value *= -1.0;+ }++ measurements.push(measurement); }- estimate_position(&buf)- }))- .unwrap_or(None);-- let result = match result {- Some(r) => r,- None => return std::ptr::null_mut(),- };- let out = match env.new_double_array(result.len() as i32) {- Ok(a) => a,- Err(_) => return std::ptr::null_mut(),- };- if env.set_double_array_region(&out, 0, &result).is_err() {- return std::ptr::null_mut();++ let estimated_position = estimate_position(&measurements);++ results.push((real_position, estimated_position)); }- out.into_raw()++ let position_deltas = results.iter().map(|p| {+ p.1.as_ref().map(|result| {+ let result = result.position;+ Position {+ x: Coordinate::new_real(+ (p.0.x.value - result.x.value).abs(),+ result.x.six_sigma_squared,+ ),+ y: Coordinate::new_real(+ (p.0.y.value - result.y.value).abs(),+ result.y.six_sigma_squared,+ ),+ z: Coordinate::new_real(+ (p.0.z.value - result.z.value).abs(),+ result.z.six_sigma_squared,+ ),+ }+ })+ });++ let successful_results_deltas = position_deltas.flatten().collect::<Vec<Position>>();+ let success_results_deltas_count = successful_results_deltas.len();++ let average_delta = Position::average(&successful_results_deltas);++ info!(+ "\nreal position: {:#?},\naverage delta: {:#?},\nratio of success: {}/{iterations}",+ Position::average(&results.iter().map(|p| p.0).collect_vec()),+ average_delta,+ success_results_deltas_count,+ );++ assert!(average_delta.x.value < 101.0);+ assert!(average_delta.y.value < 100.0);+ assert!(average_delta.z.value < 100.0);++ assert!(average_delta.x.six_sigma_squared < 5000.0);+ assert!(average_delta.y.six_sigma_squared < 5000.0);+ assert!(average_delta.z.six_sigma_squared < 100.0); } }
networklocation/src/main/rust/src/measurement.rs
diff --git a/networklocation/src/main/rust/src/measurement.rs b/networklocation/src/main/rust/src/measurement.rsnew file mode 100644index 0000000000..6317ce36bb--- /dev/null+++ b/networklocation/src/main/rust/src/measurement.rs@@ -0,0 +1,18 @@+// Ported from GrapheneOS NetworkLocation+// (github.com/GrapheneOS/platform_packages_apps_NetworkLocation),+// MIT-licensed, Copyright (c) 2024-2025 GrapheneOS. See LICENSE-GrapheneOS.++//! Documentation for measurement module.++use crate::position::Position;++/// Measurement.+#[derive(Clone, Copy)]+pub struct Measurement {+ /// position of measurement+ pub position: Position,+ /// estimated distance away from device+ pub distance: f64,+ /// weight of measurement+ pub weight: f64,+}
networklocation/src/main/rust/src/multilateration.rs
diff --git a/networklocation/src/main/rust/src/multilateration.rs b/networklocation/src/main/rust/src/multilateration.rsnew file mode 100644index 0000000000..92d489cb0f--- /dev/null+++ b/networklocation/src/main/rust/src/multilateration.rs@@ -0,0 +1,411 @@+// Ported from GrapheneOS NetworkLocation+// (github.com/GrapheneOS/platform_packages_apps_NetworkLocation),+// MIT-licensed, Copyright (c) 2024-2025 GrapheneOS. See LICENSE-GrapheneOS.++//! Documentation for multilateration module.++use core::f64;+use std::ops::{Div, Sub};++use crate::{measurement::Measurement, position::Position};+use itertools::Itertools;++/**+ * Multilateration using an algorithm based on Expectation-Maximization.+ */+pub fn multilateration(+ measurements: &mut [Measurement],+ initial_guess: Option<Position>,+ iterations: usize,+) -> Position {+ // Also used for six_sigma_squared estimation iterations.+ let mut estimated_position = initial_guess.unwrap_or_default();+ let mut actual_estimated_position = estimated_position;+ let six_sigma_squared_estimation_iterations_per_point = 6;+ // 2 points for each dimension.+ let mut six_sigma_squared_estimation_points = [Position::default(); 6];+ let six_sigma_squared_estimation_iterations = six_sigma_squared_estimation_points.len()+ * six_sigma_squared_estimation_iterations_per_point;+ let mut previous_estimated_position = estimated_position;++ let iterations_per_phase = iterations / 3;+ // Make sure we don't have any extra iterations.+ let iterations = (iterations_per_phase * 3) + six_sigma_squared_estimation_iterations;++ for iter_index in 0..iterations {+ let is_last_phases_iter = iter_index == (iterations_per_phase * 3) - 1;++ let only_use_measurements_with_no_latent_variables = iter_index < iterations_per_phase;+ let only_update_position_with_fully_real_measurements =+ (iterations_per_phase..(iterations_per_phase * 2)).contains(&iter_index);+ let can_use_measurement_for_position_update = |measurement: Measurement| {+ measurement.position.is_all_real() || !only_update_position_with_fully_real_measurements+ };+ let is_in_final_six_sigma_squared_estimation =+ (iterations.sub(six_sigma_squared_estimation_iterations)..iterations)+ .contains(&iter_index);+ let learning_rate = if iter_index < iterations - six_sigma_squared_estimation_iterations {+ iter_index as f64 / iterations_per_phase as f64+ } else {+ 1.0+ };+ let learning_rate = 1.0 - learning_rate.fract();+ let mut measurements_to_work_on = None;++ let six_sigma_squared_estimation_iter_index =+ iter_index.wrapping_sub(iterations - six_sigma_squared_estimation_iterations);+ let six_sigma_squared_estimation_point_index = six_sigma_squared_estimation_iter_index+ / six_sigma_squared_estimation_iterations_per_point;+ if is_in_final_six_sigma_squared_estimation+ && six_sigma_squared_estimation_iter_index+ % six_sigma_squared_estimation_iterations_per_point+ == 0+ {+ estimated_position = actual_estimated_position;+ match six_sigma_squared_estimation_point_index {+ 0 => estimated_position.x.value -= estimated_position.x.six_sigma_squared.sqrt(),+ 1 => estimated_position.x.value += estimated_position.x.six_sigma_squared.sqrt(),+ 2 => estimated_position.y.value -= estimated_position.y.six_sigma_squared.sqrt(),+ 3 => estimated_position.y.value += estimated_position.y.six_sigma_squared.sqrt(),+ 4 => estimated_position.z.value -= estimated_position.z.six_sigma_squared.sqrt(),+ 5 => estimated_position.z.value += estimated_position.z.six_sigma_squared.sqrt(),+ 6.. => panic!(+ "There shouldn't be more than 6 six_sigma_squared estimation points (2 for each dimension)!"+ ),+ }+ };++ if only_use_measurements_with_no_latent_variables {+ let measurements_with_no_latent_variables = measurements+ .iter_mut()+ .enumerate()+ .filter(|measurement| {+ let position = measurement.1.position;+ position.x.real && position.y.real && position.z.real+ })+ .map(|measurement| measurement.0)+ .collect_vec();++ if !measurements_with_no_latent_variables.is_empty() {+ measurements_to_work_on = Some(measurements_with_no_latent_variables);+ }+ }++ let measurements_to_work_on = match measurements_to_work_on {+ None => measurements+ .iter()+ .enumerate()+ .map(|measurement| measurement.0)+ .collect_vec(),+ Some(measurements) => measurements,+ };++ let mut update = Position::default();++ let mut total_weighted_six_sigma_x = 0.0;+ let mut total_weighted_six_sigma_y = 0.0;+ let mut total_weighted_six_sigma_z = 0.0;++ for measurement_index in &measurements_to_work_on {+ let mut measurement = measurements[*measurement_index];++ let mut x_delta = estimated_position.x.value - measurement.position.x.value;+ let mut y_delta = estimated_position.y.value - measurement.position.y.value;+ let mut z_delta = estimated_position.z.value - measurement.position.z.value;++ if x_delta.abs() <= measurement.position.x.six_sigma_squared.sqrt() {+ x_delta = 0.0+ }+ if y_delta.abs() <= measurement.position.y.six_sigma_squared.sqrt() {+ y_delta = 0.0+ }+ if z_delta.abs() <= measurement.position.z.six_sigma_squared.sqrt() {+ z_delta = 0.0+ }++ let x_delta_squared = x_delta.powi(2);+ let y_delta_squared = y_delta.powi(2);+ let z_delta_squared = z_delta.powi(2);++ let space_diagonal_length_squared = x_delta_squared + y_delta_squared + z_delta_squared;+ let estimated_distance = space_diagonal_length_squared.sqrt();++ let is_x_real = measurement.position.x.real;+ let is_y_real = measurement.position.y.real;+ let is_z_real = measurement.position.z.real;++ let x_six_sigma_squared = measurement.position.x.six_sigma_squared;+ let y_six_sigma_squared = measurement.position.y.six_sigma_squared;+ let z_six_sigma_squared = measurement.position.z.six_sigma_squared;++ let measurement_distance_std_dev = (measurement.position.x.six_sigma_squared+ + measurement.position.y.six_sigma_squared+ + measurement.position.z.six_sigma_squared)+ .sqrt();+ measurement.weight = if (measurement.distance - estimated_distance).abs()+ > measurement_distance_std_dev+ && estimated_distance > 0.0+ {+ (measurement.distance+ - (measurement_distance_std_dev+ * (measurement.distance - estimated_distance).signum()))+ / estimated_distance+ - 1.0+ } else {+ 0.0+ };++ let update_x = ((x_delta_squared * measurement.weight).abs().sqrt()+ * (x_delta * measurement.weight).signum())+ * learning_rate;+ let update_y = ((y_delta_squared * measurement.weight).abs().sqrt()+ * (y_delta * measurement.weight).signum())+ * learning_rate;+ let update_z = ((z_delta_squared * measurement.weight).abs().sqrt()+ * (z_delta * measurement.weight).signum())+ * learning_rate;++ if !is_x_real {+ measurement.position.x.value -= update_x;+ }+ if !is_y_real {+ measurement.position.y.value -= update_y;+ }+ if !is_z_real {+ measurement.position.z.value -= update_z;+ }++ if can_use_measurement_for_position_update(measurement) {+ if is_x_real {+ update.x.value += update_x;+ }+ if is_y_real {+ update.y.value += update_y;+ }+ if is_z_real {+ update.z.value += update_z;+ }+ }++ if is_last_phases_iter && can_use_measurement_for_position_update(measurement) {+ let weight = ((estimated_distance+ + (measurement_distance_std_dev+ * (measurement.distance - estimated_distance).signum()))+ - measurement.distance)+ / measurement_distance_std_dev;+ let weight = weight.max(1.0);+ if is_x_real {+ total_weighted_six_sigma_x += x_six_sigma_squared.sqrt() * weight;+ }+ if is_y_real {+ total_weighted_six_sigma_y += y_six_sigma_squared.sqrt() * weight;+ }+ if is_z_real {+ total_weighted_six_sigma_z += z_six_sigma_squared.sqrt() * weight;+ }+ }+ }++ let real_measurements_to_work_on_lens =+ measurements_to_work_on+ .iter()+ .fold((0.0, 0.0, 0.0), |acc, measurement_index| {+ let measurement = measurements[*measurement_index];++ if can_use_measurement_for_position_update(measurement) {+ (+ acc.0+ + if measurement.position.x.real {+ 1.0+ } else {+ 0.0+ },+ acc.1+ + if measurement.position.y.real {+ 1.0+ } else {+ 0.0+ },+ acc.2+ + if measurement.position.z.real {+ 1.0+ } else {+ 0.0+ },+ )+ } else {+ acc+ }+ });+ if real_measurements_to_work_on_lens.0 == 0.0 {+ update.x.value = 0.0+ } else {+ update.x.value /= real_measurements_to_work_on_lens.0+ }+ if real_measurements_to_work_on_lens.1 == 0.0 {+ update.y.value = 0.0+ } else {+ update.y.value /= real_measurements_to_work_on_lens.1+ }+ if real_measurements_to_work_on_lens.2 == 0.0 {+ update.z.value = 0.0+ } else {+ update.z.value /= real_measurements_to_work_on_lens.2+ }++ estimated_position.x.value += update.x.value;+ estimated_position.y.value += update.y.value;+ estimated_position.z.value += update.z.value;++ if is_last_phases_iter {+ estimated_position.x.six_sigma_squared = if real_measurements_to_work_on_lens.0 == 0.0 {+ estimated_position.x.real = false;+ 0.0+ } else {+ (total_weighted_six_sigma_x / real_measurements_to_work_on_lens.0).powi(2)+ };+ estimated_position.y.six_sigma_squared = if real_measurements_to_work_on_lens.1 == 0.0 {+ estimated_position.y.real = false;+ 0.0+ } else {+ (total_weighted_six_sigma_y / real_measurements_to_work_on_lens.1).powi(2)+ };+ estimated_position.z.six_sigma_squared = if real_measurements_to_work_on_lens.2 == 0.0 {+ estimated_position.z.real = false;+ 0.0+ } else {+ (total_weighted_six_sigma_z / real_measurements_to_work_on_lens.2).powi(2)+ };++ actual_estimated_position = estimated_position;+ }++ if is_in_final_six_sigma_squared_estimation {+ let mut six_sigma_squared_estimation_point = estimated_position;+ // If even, we use the lowest and if odd we use the highest since even estimated points had+ // lower initial guesses and odd ones had higher guesses. This way, we are protected against+ // oscillating position estimates since we will always choose the one that yields less+ // reported accuracy.+ let most_general_point = |v1: f64, v2: f64| -> f64 {+ if six_sigma_squared_estimation_point_index % 2 == 0 {+ v1.min(v2)+ } else {+ v1.max(v2)+ }+ };+ six_sigma_squared_estimation_point.x.value = most_general_point(+ estimated_position.x.value,+ previous_estimated_position.x.value,+ );+ six_sigma_squared_estimation_point.y.value = most_general_point(+ estimated_position.y.value,+ previous_estimated_position.y.value,+ );+ six_sigma_squared_estimation_point.z.value = most_general_point(+ estimated_position.z.value,+ previous_estimated_position.z.value,+ );++ six_sigma_squared_estimation_points[six_sigma_squared_estimation_point_index] =+ six_sigma_squared_estimation_point;++ if iter_index == iterations - 1 {+ let first_x = six_sigma_squared_estimation_points[0].x;+ let second_x = six_sigma_squared_estimation_points[1].x;+ let first_y = six_sigma_squared_estimation_points[2].y;+ let second_y = six_sigma_squared_estimation_points[3].y;+ let first_z = six_sigma_squared_estimation_points[4].z;+ let second_z = six_sigma_squared_estimation_points[5].z;++ let final_x = (first_x.value + second_x.value) / 2.0;+ let final_x_six_sigma_squared = (first_x.value - second_x.value).div(2.0).powi(2);+ let final_y = (first_y.value + second_y.value) / 2.0;+ let final_y_six_sigma_squared = (first_y.value - second_y.value).div(2.0).powi(2);+ let final_z = (first_z.value + second_z.value) / 2.0;+ let final_z_six_sigma_squared = (first_z.value - second_z.value).div(2.0).powi(2);++ actual_estimated_position.x.value = final_x;+ actual_estimated_position.x.six_sigma_squared = final_x_six_sigma_squared;+ actual_estimated_position.y.value = final_y;+ actual_estimated_position.y.six_sigma_squared = final_y_six_sigma_squared;+ actual_estimated_position.z.value = final_z;+ actual_estimated_position.z.six_sigma_squared = final_z_six_sigma_squared;+ }+ }++ previous_estimated_position = estimated_position;+ }++ actual_estimated_position+}++#[cfg(test)]+mod tests {+ use crate::{+ coordinate::Coordinate, measurement::Measurement, multilateration::multilateration,+ position::Position,+ };++ #[test]+ fn basic() {+ let mut measurements = vec![];++ measurements.push(Measurement {+ position: Position {+ x: Coordinate::new_real(1.5, 1.0_f64.powi(2)),+ ..Default::default()+ },+ distance: 4.0,+ weight: 0.0,+ });+ measurements.push(Measurement {+ position: Position {+ x: Coordinate::new_real(12.0, 1.5_f64.powi(2)),+ ..Default::default()+ },+ distance: 5.5,+ weight: 0.0,+ });++ let expected = Position {+ // Most accurate result would be value: 5.75, six_sigma_squared: 0.75_f64.powi(2).+ x: Coordinate::new_real(5.868107855175952, 0.3015669990124259_f64.powi(2)),+ ..Default::default()+ };++ let result = multilateration(&mut measurements, None, 50);++ assert_eq!(expected.x.value, result.x.value);+ assert_eq!(expected.x.six_sigma_squared, result.x.six_sigma_squared);++ let mut measurements = vec![];++ measurements.push(Measurement {+ position: Position {+ x: Coordinate::new_real(9.5, 1.0_f64.powi(2)),+ ..Default::default()+ },+ distance: 4.0,+ weight: 0.0,+ });+ measurements.push(Measurement {+ position: Position {+ x: Coordinate::new_real(12.0, 1.5_f64.powi(2)),+ ..Default::default()+ },+ distance: 5.5,+ weight: 0.0,+ });++ let expected = Position {+ // Most accurate result would be value: 5.75, six_sigma_squared: 0.75_f64.powi(2).+ x: Coordinate::new_real(5.756402373747081, 0.6326516952769938_f64.powi(2)),+ ..Default::default()+ };++ let result = multilateration(&mut measurements, None, 50);++ assert_eq!(expected.x.value, result.x.value);+ assert_eq!(expected.x.six_sigma_squared, result.x.six_sigma_squared)+ }+}
networklocation/src/main/rust/src/position.rs
diff --git a/networklocation/src/main/rust/src/position.rs b/networklocation/src/main/rust/src/position.rsnew file mode 100644index 0000000000..2a106d52a1--- /dev/null+++ b/networklocation/src/main/rust/src/position.rs@@ -0,0 +1,60 @@+// Ported from GrapheneOS NetworkLocation+// (github.com/GrapheneOS/platform_packages_apps_NetworkLocation),+// MIT-licensed, Copyright (c) 2024-2025 GrapheneOS. See LICENSE-GrapheneOS.++//! Documentation for position module.++use crate::coordinate::Coordinate;++/// Position.+#[derive(Clone, Copy, Debug)]+pub struct Position {+ /// x coordinate+ pub x: Coordinate,+ /// y coordinate+ pub y: Coordinate,+ /// z coordinate+ pub z: Coordinate,+}++impl Default for Position {+ fn default() -> Self {+ Self {+ x: Coordinate::new_fake(),+ y: Coordinate::new_fake(),+ z: Coordinate::new_fake(),+ }+ }+}++impl Position {+ /// Gets the average position.+ pub fn average(positions: &[Position]) -> Self {+ let positions_len = positions.len() as f64;++ Position {+ x: Coordinate::new_real(+ positions.iter().map(|p| p.x.value).sum::<f64>() / positions_len,+ positions.iter().map(|p| p.x.six_sigma_squared).sum::<f64>() / positions_len,+ ),+ y: Coordinate::new_real(+ positions.iter().map(|p| p.y.value).sum::<f64>() / positions_len,+ positions.iter().map(|p| p.y.six_sigma_squared).sum::<f64>() / positions_len,+ ),+ z: Coordinate::new_real(+ positions.iter().map(|p| p.z.value).sum::<f64>() / positions_len,+ positions.iter().map(|p| p.z.six_sigma_squared).sum::<f64>() / positions_len,+ ),+ }+ }++ /// Whether all coordinates are real.+ pub fn is_all_real(self) -> bool {+ self.x.real && self.y.real && self.z.real+ }++ /// Returns the number of coordinates which are real.+ pub fn number_of_real(self) -> u8 {+ u8::from(self.x.real) + u8::from(self.y.real) + u8::from(self.z.real)+ }+}