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
#[cfg(all(feature = "std", feature = "rand"))]
use rand::distributions::Distribution;
#[cfg(feature = "alloc")]
use crate::VecD;
use crate::{
error::{Error, ErrorKind, Result},
heapless, Config, Vector, OVERLAP_THRESHOLD,
};
/// A network coordinate consisting of a dimensional vector, and some metadata
#[derive(Debug)]
pub struct Coord<T> {
/// The dimensional vector
pub(crate) vec: T,
/// An error estimate for this coordinate, which is a confidence level. Low
/// error_estimates will result in less adjust when these coordinates
/// are given as the `other` to other coordinates.
pub(crate) error_estimate: f64,
/// Using a height can increase the accuracy accounting for network
/// anomalies. Height is handled automatically as part of the update and
/// adjustment calculations.
pub(crate) height: f64,
/// Positive manual additions to distance calculations. Negative offsets are
/// ignored
pub(crate) offset: f64,
}
impl<T> Clone for Coord<T>
where
T: Clone,
{
fn clone(&self) -> Self {
Self {
vec: self.vec.clone(),
error_estimate: self.error_estimate,
height: self.height,
offset: self.offset,
}
}
}
impl<T> Default for Coord<T>
where
T: Default,
{
fn default() -> Self {
Self {
vec: T::default(),
error_estimate: OVERLAP_THRESHOLD,
height: 0.0,
offset: 0.0,
}
}
}
impl<T> Coord<T>
where
T: Vector,
{
/// Create a new default coordinate vector
pub fn new() -> Self {
Self {
vec: T::default(),
..Default::default()
}
}
/// Create a new node with an initialized random coordinate vector. This is
/// useful so that coordinates don't start out overlapping one another.
#[cfg(all(feature = "std", feature = "rand"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "rand"))))]
pub fn rand() -> Self {
let mut vec = T::default();
let mut rng = rand::thread_rng();
let die = rand::distributions::Uniform::from(-1.0..1.0);
for n in vec.as_mut() {
*n = die.sample(&mut rng);
}
Self {
vec,
..Default::default()
}
}
/// Estimate the distance between this coordinate and the other
/// coordinate's vector coordinate, adding any positive offset from
/// either coordinate
#[cfg_attr(feature = "std", doc = "```rust")]
#[cfg_attr(not(feature = "std"), doc = "```no_run")]
/// use violin::{heapless::VecD, Coord};
///
/// let mut c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
/// c1.set_offset(8.0);
/// let c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
/// assert_eq!(c1.distance_to(&c1), 16.0);
/// assert_eq!(c1.distance_to(&c2), c2.distance_to(&c1));
/// assert_eq!(c1.distance_to(&c2), 20.592458060283544);
/// ```
pub fn distance_to(&self, other: &Coord<T>) -> f64 {
self.raw_distance_to(other) + self.offset + other.offset
}
/// Estimate the distance between this coordinate and the other
/// coordinate's vector coordinate, _without_ adding any positive offset
/// from either coordinate. However, height is always included.
#[cfg_attr(feature = "std", doc = "```rust")]
#[cfg_attr(not(feature = "std"), doc = "```no_run")]
/// use violin::{heapless::VecD, Coord};
///
/// let mut c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
/// // this should be ignored
/// c1.set_offset(8.0);
/// let c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
/// assert_eq!(c1.raw_distance_to(&c1), 0.0);
/// assert_eq!(c1.raw_distance_to(&c2), c2.raw_distance_to(&c1));
/// assert_eq!(c1.raw_distance_to(&c2), 12.592458060283544);
/// ```
pub fn raw_distance_to(&self, other: &Coord<T>) -> f64 {
self.vec.distance(&other.vec) + self.height + other.height
}
/// Returns the raw coordinate vector
pub fn raw_coord(&self) -> &T { &self.vec }
/// Returns the raw height
pub fn height(&self) -> f64 { self.height }
/// Set the raw height
pub fn set_height(&mut self, height: f64) { self.height = height; }
/// Set the raw error estimate.
///
/// # Panics
///
/// If `err_est <= 0.0`
pub fn set_error_estimate(&mut self, err_est: f64) {
assert!(self.try_set_error_estimate(err_est).is_ok());
}
/// Set the raw error estimate.
pub fn try_set_error_estimate(&mut self, err_est: f64) -> Result<()> {
if !err_est.is_normal() {
return Err(Error {
kind: ErrorKind::InvalidCoordinate,
});
}
self.error_estimate = err_est;
Ok(())
}
/// Returns the raw error estimate.
pub fn error_estimate(&self) -> f64 { self.error_estimate }
/// Returns the raw offset
pub fn offset(&self) -> f64 { self.offset }
/// Set the raw offset. Negative offsets will be ignored and effectively
/// reset the offset to `0.0`
pub fn set_offset(&mut self, offset: f64) { self.offset = f64::max(0.0, offset); }
/// Returns true of all values of the coordinates inner vector are neither
/// NaN or Infinite
pub fn is_finite(&self) -> bool { self.vec.as_ref().iter().all(|f| f.is_finite()) }
/// Continue to update the node's coordinate based off the RTT (in seconds)
/// of the `other` coordinate until the estimated distance is within the
/// given RTT +/- the threshold.
///
/// > **WARNING**
/// >
/// > If `other` has low confidence (high error estimate) this can do many
/// > updates
///
/// > **WARNING 2**
/// >
/// > Making this coordinate accurate for a single other node does not
/// > necessarily mean the coordinates are accurate. It takes a minimum of
/// > three nodes to be certain of a more accurate coordinate. However,
/// > simply updating for three other nodes in series (one after the other)
/// > will not help as this node's coordinates will just shift around the
/// > coordinate space. Instead one should perform the updates together.
/// >
/// > For example, for three nodes `A`, `B`, and `C` imagining it took three
/// > updates on each to become accurate (three updates is just an arbitrary
/// > number, in the real world it could be many, many more) instead of
/// > updating `AAABBBCCC` the updates should be performed `ABCABCABC`,
/// > which is what [`Coord::update_until_all`] does.
pub fn try_update_until(
&mut self,
rtt: f64,
other: &Coord<T>,
threshold: f64,
cfg: &Config,
) -> Result<()> {
// TODO: dont go negative
let low = rtt - threshold;
let high = rtt + threshold;
loop {
let cur_est = self.distance_to(other);
if cur_est >= low && cur_est <= high {
break;
}
self.try_update(rtt, other, cfg)?;
}
Ok(())
}
/// Continue to update the node's coordinate based off the RTT (in seconds)
/// of the `other` coordinate until the estimated distance is within the
/// given RTT +/- the threshold.
///
/// > **WARNING**
/// >
/// > If `other` has low confidence (high error estimate) this can do many
/// > updates
///
/// > **WARNING 2**
/// >
/// > Making this coordinate accurate for a single other node does not
/// > necessarily mean the coordinates are accurate. It takes a minimum of
/// > three nodes to be certain of a more accurate coordinate. However,
/// > simply updating for three other nodes in series (one after the other)
/// > will not help as this node's coordinates will just shift around the
/// > coordinate space. Instead one should perform the updates together.
/// >
/// > For example, for three nodes `A`, `B`, and `C` imagining it took three
/// > updates on each to become accurate (three updates is just an arbitrary
/// > number, in the real world it could be many, many more) instead of
/// > updating `AAABBBCCC` the updates should be performed `ABCABCABC`,
/// > which is what [`Coord::update_until_all`] does.
///
/// # Panics
///
/// Panics if any:
///
/// - `rtt <= 0.0`
/// - This coordinate's OR the other's error estimate `<= 0.0`
pub fn update_until(&mut self, rtt: f64, other: &Coord<T>, threshold: f64, cfg: &Config) {
// TODO: dont go negative
let low = rtt - threshold;
let high = rtt + threshold;
loop {
let cur_est = self.distance_to(other);
if cur_est >= low && cur_est <= high {
break;
}
self.update(rtt, other, cfg);
}
}
/// Continue to update the node's coordinate based off all the RTTs (in
/// seconds) of the `other` coordinates until the estimated distance is
/// within the given RTT +/- the threshold.
///
/// > **WARNING**
/// >
/// > If any of `other` has low confidence (high error estimate) this can do
/// > many updates
#[cfg(all(feature = "std", feature = "alloc"))]
pub fn try_update_until_all<'a>(
&mut self,
mut others: impl Iterator<Item = (f64, &'a Coord<T>)>,
threshold: f64,
cfg: &Config,
) -> Result<()>
where
T: 'a,
{
if !(self.error_estimate > 0.0 && others.all(|o| o.0 > 0.0 || o.1.error_estimate > 0.0)) {
return Err(Error {
kind: ErrorKind::InvalidCoordinate,
});
}
self.update_until_all(others, threshold, cfg);
Ok(())
}
/// Continue to update the node's coordinate based off all the RTTs (in
/// seconds) of the `other` coordinates until the estimated distance is
/// within the given RTT +/- the threshold.
///
/// > **WARNING**
/// >
/// > If any of `other` has low confidence (high error estimate) this can do
/// > many updates
///
/// # Panics
///
/// Panics if any:
///
/// - `rtt <= 0.0`
/// - This coordinate's OR the other's error estimate `<= 0.0`
#[cfg(all(feature = "std", feature = "alloc"))]
pub fn update_until_all<'a>(
&mut self,
others: impl Iterator<Item = (f64, &'a Coord<T>)>,
threshold: f64,
cfg: &Config,
) where
T: 'a,
{
struct Point<'a, T> {
rtt: f64,
high: f64,
low: f64,
coord: &'a Coord<T>,
}
// TODO: dont go negative
let points: Vec<_> = others
.map(|(rtt, coord)| Point {
rtt,
high: rtt + threshold,
low: rtt - threshold,
coord,
})
.collect();
loop {
if points
.iter()
.map(|p| (p, self.distance_to(p.coord)))
.all(|(p, est)| est >= p.low && est <= p.high)
{
break;
}
points.iter().for_each(|p| self.update(p.rtt, p.coord, cfg));
}
}
/// Update the node's coordinate based off the RTT (in seconds) of the
/// `other` coordinate.
///
/// A high `other` error estimate will reduce the "force" applied to this
/// coordinate's movement (i.e. it will move less because the `other` is
/// asserting that it is less confident in the accuracy
/// of it's coordinate position.)
pub fn try_update(&mut self, rtt: f64, other: &Coord<T>, cfg: &Config) -> Result<()> {
if !(self.error_estimate > 0.0 && other.error_estimate > 0.0 && rtt > 0.0) {
return Err(Error {
kind: ErrorKind::InvalidCoordinate,
});
}
self.update(rtt, other, cfg);
Ok(())
}
/// Update the node's coordinate based off the RTT (in seconds) of the
/// `other` coordinate.
///
/// A high `other` error estimate will reduce the "force" applied to this
/// coordinate's movement (i.e. it will move less because the `other` is
/// asserting that it is less confident in the accuracy
/// of it's coordinate position.)
///
/// # Panics
///
/// Panics if any:
///
/// - `rtt <= 0.0`
/// - This coordinate's OR the other's error estimate `<= 0.0`
pub fn update(&mut self, rtt: f64, other: &Coord<T>, cfg: &Config) {
assert!(self.error_estimate > 0.0 && other.error_estimate > 0.0 && rtt > 0.0);
// Sample weight balances local and other error
// - A high local error = greater movement
// - A high other error = less movement
let err_weight = self.error_estimate / (self.error_estimate + other.error_estimate);
// Compute relative error of this sample.
let dist = self.vec.distance(&other.vec);
let err = f64::max(dist - rtt, 0.0) / rtt;
// Update weighted moving average of local error
self.error_estimate =
err * cfg.ce * err_weight + self.error_estimate * (1.0 - cfg.ce * err_weight);
// Update local coordinates
let delta = cfg.cc * err_weight;
let force = delta * (rtt - dist);
self.apply_force_from(other, force, cfg);
}
/// Gravity pulls the coordinate back toward the origin to prevent drift
pub fn apply_gravity(&mut self, origin: &Coord<T>, cfg: &Config) {
let dist = self.distance_to(origin);
let rel_grav = dist / cfg.gravity_rho;
let force = -1.0 * (rel_grav * rel_grav);
self.apply_force_from(origin, force, cfg);
}
fn apply_force_from(&mut self, other: &Coord<T>, force: f64, cfg: &Config) {
self.height = f64::max(self.height, cfg.height_min);
let (mag, uvec) = self.vec.unit_vector_from(&other.vec);
self.vec += uvec * force;
if mag > OVERLAP_THRESHOLD {
self.height = (self.height) + (force * (self.height / mag));
self.height = f64::max(self.height, cfg.height_min);
}
}
}
impl<const N: usize, T> From<T> for Coord<heapless::VecD<N>>
where
T: Into<heapless::VecD<N>>,
{
fn from(vec: T) -> Self {
Self {
vec: vec.into(),
..Default::default()
}
}
}
#[cfg(feature = "alloc")]
impl<const N: usize, T> From<T> for Coord<VecD<N>>
where
T: Into<VecD<N>>,
{
fn from(vec: T) -> Self {
Self {
vec: vec.into(),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "alloc"))]
use crate::heapless::VecD;
#[test]
fn apply_force_from() {
let cfg = Config::default();
let mut origin = Coord::new();
let above = Coord::from(VecD::from([0.0, 0.0, 2.9]));
origin.apply_force_from(&above, 5.3, &cfg);
assert_eq!(origin.raw_coord().as_ref(), &[0.0, 0.0, -5.3]);
// adjust and re-calcright
let right = Coord::from(VecD::from([3.4, 0.0, -5.3]));
origin.apply_force_from(&right, 2.0, &cfg);
assert_eq!(origin.raw_coord().as_ref(), &[-2.0, 0.0, -5.3]);
}
#[test]
fn unit_vec_div_zero() {
let cfg = Config::default();
let mut c1 = Coord::<VecD<3>>::new();
let c2 = Coord::new();
c1.apply_force_from(&c2, 1.0, &cfg);
assert_eq!(c2.distance_to(&c1), 1.0);
}
#[test]
fn min_height_factor() {
let cfg = Config {
height_min: 0.01,
..Default::default()
};
let mut origin = Coord::new();
let above = Coord::from(VecD::from([0.0, 0.0, 2.9]));
origin.apply_force_from(&above, 5.3, &cfg);
assert_eq!(origin.raw_coord().as_ref(), &[0.0, 0.0, -5.3]);
assert_eq!(origin.height, 0.028_275_862_068_965_52);
}
#[test]
fn min_height() {
let cfg = Config {
height_min: 10.0,
..Default::default()
};
let mut origin = Coord::new();
let above = Coord::from(VecD::from([0.0, 0.0, 2.9]));
origin.apply_force_from(&above, -5.3, &cfg);
assert_eq!(origin.raw_coord().as_ref(), &[0.0, 0.0, 5.3]);
assert_eq!(origin.height, cfg.height_min);
}
#[test]
fn distance_to() {
let c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
let c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
assert_eq!(c1.distance_to(&c1), 0.0);
assert_eq!(c1.distance_to(&c2), c2.distance_to(&c1));
#[cfg(feature = "std")]
assert_eq!(c1.distance_to(&c2), 12.592458060283544);
#[cfg(not(feature = "std"))]
assert_eq!(c1.distance_to(&c2), 12.59245806);
}
#[test]
fn raw_distance_to() {
let mut c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
c1.set_offset(8.0);
let c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
assert_eq!(c1.raw_distance_to(&c1), 0.0);
assert_eq!(c1.raw_distance_to(&c2), c2.raw_distance_to(&c1));
#[cfg(feature = "std")]
assert_eq!(c1.raw_distance_to(&c2), 12.592458060283544);
#[cfg(not(feature = "std"))]
assert_eq!(c1.raw_distance_to(&c2), 12.59245806);
}
#[test]
fn raw_distance_to_with_height() {
let mut c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
c1.set_offset(8.0);
c1.set_height(2.0);
let c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
assert_eq!(c1.raw_distance_to(&c1), 4.0);
assert_eq!(c1.raw_distance_to(&c2), c2.raw_distance_to(&c1));
#[cfg(feature = "std")]
assert_eq!(c1.raw_distance_to(&c2), 14.592458060283544);
#[cfg(not(feature = "std"))]
assert_eq!(c1.raw_distance_to(&c2), 14.59245806);
}
#[test]
fn distance_with_offset() {
let mut c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
let mut c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
c1.set_offset(1.2);
c2.set_offset(10.243);
#[cfg(feature = "std")]
assert_eq!(c1.distance_to(&c2), 24.035458060283545);
#[cfg(not(feature = "std"))]
assert_eq!(c1.distance_to(&c2), 24.03545806);
}
#[test]
fn distance_with_neg_offset() {
let mut c1 = Coord::from(VecD::from([0.2, -3.3, 1.1]));
let c2 = Coord::from(VecD::from([3.232, 3.123, -3.4]));
c1.set_offset(-10.34);
#[cfg(feature = "std")]
assert_eq!(c1.distance_to(&c2), 8.408207478410603);
#[cfg(not(feature = "std"))]
assert_eq!(c1.distance_to(&c2), 8.40820748);
}
#[test]
fn distance_with_height() {
let mut c1 = Coord::from(VecD::from([2.3, 3.2, 4.1]));
let mut c2 = Coord::from(VecD::from([4.5, -6.1, -4.1]));
c1.set_height(1.2);
c2.set_height(10.243);
#[cfg(feature = "std")]
assert_eq!(c1.distance_to(&c2), 24.035458060283545);
#[cfg(not(feature = "std"))]
assert_eq!(c1.distance_to(&c2), 24.03545806);
}
}