|
| 1 | +//! This module defines the [Vector2DOps] trait and implements it for the |
| 2 | +//! [Coord] struct. |
| 3 | +
|
| 4 | +use crate::{Coord, CoordFloat, CoordNum}; |
| 5 | + |
| 6 | +/// Defines vector operations for 2D coordinate types which implement CoordFloat |
| 7 | +/// |
| 8 | +/// This trait is intended for internal use within the geo crate as a way to |
| 9 | +/// bring together the various hand-crafted linear algebra operations used |
| 10 | +/// throughout other algorithms and attached to various structs. |
| 11 | +pub trait Vector2DOps<Rhs = Self> |
| 12 | +where |
| 13 | + Self: Sized, |
| 14 | +{ |
| 15 | + type Scalar: CoordNum + Send + Sync; |
| 16 | + |
| 17 | + /// The euclidean distance between this coordinate and the origin |
| 18 | + /// |
| 19 | + /// `sqrt(x² + y²)` |
| 20 | + /// |
| 21 | + fn magnitude(self) -> Self::Scalar; |
| 22 | + |
| 23 | + /// The squared distance between this coordinate and the origin. |
| 24 | + /// (Avoids the square root calculation when it is not needed) |
| 25 | + /// |
| 26 | + /// `x² + y²` |
| 27 | + /// |
| 28 | + fn magnitude_squared(self) -> Self::Scalar; |
| 29 | + |
| 30 | + /// Rotate this coordinate around the origin by 90 degrees clockwise. |
| 31 | + /// |
| 32 | + /// `a.left() => (-a.y, a.x)` |
| 33 | + /// |
| 34 | + /// Assumes a coordinate system where positive `y` is up and positive `x` is |
| 35 | + /// to the right. The described rotation direction is consistent with the |
| 36 | + /// documentation for [crate::algorithm::rotate::Rotate]. |
| 37 | + fn left(self) -> Self; |
| 38 | + |
| 39 | + /// Rotate this coordinate around the origin by 90 degrees anti-clockwise. |
| 40 | + /// |
| 41 | + /// `a.right() => (a.y, -a.x)` |
| 42 | + /// |
| 43 | + /// Assumes a coordinate system where positive `y` is up and positive `x` is |
| 44 | + /// to the right. The described rotation direction is consistent with the |
| 45 | + /// documentation for [crate::algorithm::rotate::Rotate]. |
| 46 | + fn right(self) -> Self; |
| 47 | + |
| 48 | + /// The inner product of the coordinate components |
| 49 | + /// |
| 50 | + /// `a · b = a.x * b.x + a.y * b.y` |
| 51 | + /// |
| 52 | + fn dot_product(self, other: Rhs) -> Self::Scalar; |
| 53 | + |
| 54 | + /// The calculates the `wedge product` between two vectors. |
| 55 | + /// |
| 56 | + /// `a ∧ b = a.x * b.y - a.y * b.x` |
| 57 | + /// |
| 58 | + /// Also known as: |
| 59 | + /// |
| 60 | + /// - `exterior product` |
| 61 | + /// - because the wedge product comes from 'Exterior Algebra' |
| 62 | + /// - `perpendicular product` |
| 63 | + /// - because it is equivalent to `a.dot(b.right())` |
| 64 | + /// - `2D cross product` |
| 65 | + /// - because it is equivalent to the signed magnitude of the |
| 66 | + /// conventional 3D cross product assuming `z` ordinates are zero |
| 67 | + /// - `determinant` |
| 68 | + /// - because it is equivalent to the `determinant` of the 2x2 matrix |
| 69 | + /// formed by the column-vector inputs. |
| 70 | + /// |
| 71 | + /// ## Examples |
| 72 | + /// |
| 73 | + /// The following list highlights some examples in geo which might be |
| 74 | + /// brought together to use this function: |
| 75 | + /// |
| 76 | + /// 1. [geo_types::Point::cross_prod()] is already defined on |
| 77 | + /// [geo_types::Point]... but that it seems to be some other |
| 78 | + /// operation on 3 points?? |
| 79 | + /// 2. [geo_types::Line] struct also has a [geo_types::Line::determinant()] |
| 80 | + /// function which is the same as `line.start.wedge_product(line.end)` |
| 81 | + /// 3. The [crate::algorithm::Kernel::orient2d()] trait default |
| 82 | + /// implementation uses cross product to compute orientation. It returns |
| 83 | + /// an enum, not the numeric value which is needed for line segment |
| 84 | + /// intersection. |
| 85 | + /// |
| 86 | + /// ## Properties |
| 87 | + /// |
| 88 | + /// - The absolute value of the cross product is the area of the |
| 89 | + /// parallelogram formed by the operands |
| 90 | + /// - Anti-commutative: The sign of the output is reversed if the operands |
| 91 | + /// are reversed |
| 92 | + /// - If the operands are colinear with the origin, the value is zero |
| 93 | + /// - The sign can be used to check if the operands are clockwise with |
| 94 | + /// respect to the origin, or phrased differently: |
| 95 | + /// "is a to the left of the line between the origin and b"? |
| 96 | + /// - If this is what you are using it for, then please use |
| 97 | + /// [crate::algorithm::Kernel::orient2d()] instead as this is more |
| 98 | + /// explicit and has a `RobustKernel` option for extra precision. |
| 99 | + fn wedge_product(self, other: Rhs) -> Self::Scalar; |
| 100 | + |
| 101 | + /// Try to find a vector of unit length in the same direction as this |
| 102 | + /// vector. |
| 103 | + /// |
| 104 | + /// Returns `None` if the result is not finite. This can happen when |
| 105 | + /// |
| 106 | + /// - the vector is really small (or zero length) and the `.magnitude()` |
| 107 | + /// calculation has rounded-down to `0.0` |
| 108 | + /// - the vector is really large and the `.magnitude()` has rounded-up |
| 109 | + /// or 'overflowed' to `f64::INFINITY` |
| 110 | + /// - Either x or y are `f64::NAN` or `f64::INFINITY` |
| 111 | + fn try_normalize(self) -> Option<Self>; |
| 112 | + |
| 113 | + /// Returns true if both the x and y components are finite |
| 114 | + // Annotation to disable bad clippy lint; It is not good to use |
| 115 | + // `&self` as clippy suggests since Coord is Copy |
| 116 | + #[allow(clippy::wrong_self_convention)] |
| 117 | + fn is_finite(self) -> bool; |
| 118 | +} |
| 119 | + |
| 120 | +impl<T> Vector2DOps for Coord<T> |
| 121 | +where |
| 122 | + T: CoordFloat + Send + Sync, |
| 123 | +{ |
| 124 | + type Scalar = T; |
| 125 | + |
| 126 | + fn wedge_product(self, right: Coord<T>) -> Self::Scalar { |
| 127 | + self.x * right.y - self.y * right.x |
| 128 | + } |
| 129 | + |
| 130 | + fn dot_product(self, other: Self) -> Self::Scalar { |
| 131 | + self.x * other.x + self.y * other.y |
| 132 | + } |
| 133 | + |
| 134 | + fn magnitude(self) -> Self::Scalar { |
| 135 | + (self.x * self.x + self.y * self.y).sqrt() |
| 136 | + } |
| 137 | + |
| 138 | + fn magnitude_squared(self) -> Self::Scalar { |
| 139 | + self.x * self.x + self.y * self.y |
| 140 | + } |
| 141 | + |
| 142 | + fn left(self) -> Self { |
| 143 | + Self { |
| 144 | + x: -self.y, |
| 145 | + y: self.x, |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + fn right(self) -> Self { |
| 150 | + Self { |
| 151 | + x: self.y, |
| 152 | + y: -self.x, |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + fn try_normalize(self) -> Option<Self> { |
| 157 | + let magnitude = self.magnitude(); |
| 158 | + let result = self / magnitude; |
| 159 | + // Both the result AND the magnitude must be finite they are finite |
| 160 | + // Otherwise very large vectors overflow magnitude to Infinity, |
| 161 | + // and the after the division the result would be coord!{x:0.0,y:0.0} |
| 162 | + // Note we don't need to check if magnitude is zero, because after the division |
| 163 | + // that would have made result non-finite or NaN anyway. |
| 164 | + if result.is_finite() && magnitude.is_finite() { |
| 165 | + Some(result) |
| 166 | + } else { |
| 167 | + None |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + fn is_finite(self) -> bool { |
| 172 | + self.x.is_finite() && self.y.is_finite() |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +#[cfg(test)] |
| 177 | +mod test { |
| 178 | + use super::Vector2DOps; |
| 179 | + use crate::coord; |
| 180 | + |
| 181 | + #[test] |
| 182 | + fn test_cross_product() { |
| 183 | + // perpendicular unit length |
| 184 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 185 | + let b = coord! { x: 0f64, y: 1f64 }; |
| 186 | + |
| 187 | + // expect the area of parallelogram |
| 188 | + assert_eq!(a.wedge_product(b), 1f64); |
| 189 | + // expect swapping will result in negative |
| 190 | + assert_eq!(b.wedge_product(a), -1f64); |
| 191 | + |
| 192 | + // Add skew; expect results should be the same |
| 193 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 194 | + let b = coord! { x: 1f64, y: 1f64 }; |
| 195 | + |
| 196 | + // expect the area of parallelogram |
| 197 | + assert_eq!(a.wedge_product(b), 1f64); |
| 198 | + // expect swapping will result in negative |
| 199 | + assert_eq!(b.wedge_product(a), -1f64); |
| 200 | + |
| 201 | + // Make Colinear; expect zero |
| 202 | + let a = coord! { x: 2f64, y: 2f64 }; |
| 203 | + let b = coord! { x: 1f64, y: 1f64 }; |
| 204 | + assert_eq!(a.wedge_product(b), 0f64); |
| 205 | + } |
| 206 | + |
| 207 | + #[test] |
| 208 | + fn test_dot_product() { |
| 209 | + // perpendicular unit length |
| 210 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 211 | + let b = coord! { x: 0f64, y: 1f64 }; |
| 212 | + // expect zero for perpendicular |
| 213 | + assert_eq!(a.dot_product(b), 0f64); |
| 214 | + |
| 215 | + // Parallel, same direction |
| 216 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 217 | + let b = coord! { x: 2f64, y: 0f64 }; |
| 218 | + // expect +ive product of magnitudes |
| 219 | + assert_eq!(a.dot_product(b), 2f64); |
| 220 | + // expect swapping will have same result |
| 221 | + assert_eq!(b.dot_product(a), 2f64); |
| 222 | + |
| 223 | + // Parallel, opposite direction |
| 224 | + let a = coord! { x: 3f64, y: 4f64 }; |
| 225 | + let b = coord! { x: -3f64, y: -4f64 }; |
| 226 | + // expect -ive product of magnitudes |
| 227 | + assert_eq!(a.dot_product(b), -25f64); |
| 228 | + // expect swapping will have same result |
| 229 | + assert_eq!(b.dot_product(a), -25f64); |
| 230 | + } |
| 231 | + |
| 232 | + #[test] |
| 233 | + fn test_magnitude() { |
| 234 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 235 | + assert_eq!(a.magnitude(), 1f64); |
| 236 | + |
| 237 | + let a = coord! { x: 0f64, y: 0f64 }; |
| 238 | + assert_eq!(a.magnitude(), 0f64); |
| 239 | + |
| 240 | + let a = coord! { x: -3f64, y: 4f64 }; |
| 241 | + assert_eq!(a.magnitude(), 5f64); |
| 242 | + } |
| 243 | + |
| 244 | + #[test] |
| 245 | + fn test_magnitude_squared() { |
| 246 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 247 | + assert_eq!(a.magnitude_squared(), 1f64); |
| 248 | + |
| 249 | + let a = coord! { x: 0f64, y: 0f64 }; |
| 250 | + assert_eq!(a.magnitude_squared(), 0f64); |
| 251 | + |
| 252 | + let a = coord! { x: -3f64, y: 4f64 }; |
| 253 | + assert_eq!(a.magnitude_squared(), 25f64); |
| 254 | + } |
| 255 | + |
| 256 | + #[test] |
| 257 | + fn test_left_right() { |
| 258 | + let a = coord! { x: 1f64, y: 0f64 }; |
| 259 | + let a_left = coord! { x: 0f64, y: 1f64 }; |
| 260 | + let a_right = coord! { x: 0f64, y: -1f64 }; |
| 261 | + |
| 262 | + assert_eq!(a.left(), a_left); |
| 263 | + assert_eq!(a.right(), a_right); |
| 264 | + assert_eq!(a.left(), -a.right()); |
| 265 | + } |
| 266 | + |
| 267 | + #[test] |
| 268 | + fn test_left_right_match_rotate() { |
| 269 | + use crate::algorithm::rotate::Rotate; |
| 270 | + use crate::Point; |
| 271 | + // The aim of this test is to confirm that wording in documentation is |
| 272 | + // consistent. |
| 273 | + |
| 274 | + // when the user is in a coordinate system where the y axis is flipped |
| 275 | + // (eg screen coordinates in a HTML canvas), then rotation directions |
| 276 | + // will be different to those described in the documentation. |
| 277 | + |
| 278 | + // The documentation for the Rotate trait says: 'Positive angles are |
| 279 | + // counter-clockwise, and negative angles are clockwise rotations' |
| 280 | + |
| 281 | + let counter_clockwise_rotation_degrees = 90.0; |
| 282 | + let clockwise_rotation_degrees = -counter_clockwise_rotation_degrees; |
| 283 | + |
| 284 | + let a: Point = coord! { x: 1.0, y: 0.0 }.into(); |
| 285 | + let origin: Point = coord! { x: 0.0, y: 0.0 }.into(); |
| 286 | + |
| 287 | + // left is anti-clockwise |
| 288 | + assert_relative_eq!( |
| 289 | + Point::from(a.0.left()), |
| 290 | + a.rotate_around_point(counter_clockwise_rotation_degrees, origin), |
| 291 | + ); |
| 292 | + // right is clockwise |
| 293 | + assert_relative_eq!( |
| 294 | + Point::from(a.0.right()), |
| 295 | + a.rotate_around_point(clockwise_rotation_degrees, origin), |
| 296 | + ); |
| 297 | + } |
| 298 | + |
| 299 | + #[test] |
| 300 | + fn test_try_normalize() { |
| 301 | + // Already Normalized |
| 302 | + let a = coord! { |
| 303 | + x: 1.0, |
| 304 | + y: 0.0 |
| 305 | + }; |
| 306 | + assert_relative_eq!(a.try_normalize().unwrap(), a); |
| 307 | + |
| 308 | + // Already Normalized |
| 309 | + let a = coord! { |
| 310 | + x: 1.0 / f64::sqrt(2.0), |
| 311 | + y: -1.0 / f64::sqrt(2.0) |
| 312 | + }; |
| 313 | + assert_relative_eq!(a.try_normalize().unwrap(), a); |
| 314 | + |
| 315 | + // Non trivial example |
| 316 | + let a = coord! { x: -10.0, y: 8.0 }; |
| 317 | + assert_relative_eq!( |
| 318 | + a.try_normalize().unwrap(), |
| 319 | + coord! { x: -10.0, y: 8.0 } / f64::sqrt(10.0 * 10.0 + 8.0 * 8.0) |
| 320 | + ); |
| 321 | + } |
| 322 | + |
| 323 | + #[test] |
| 324 | + fn test_try_normalize_edge_cases() { |
| 325 | + use float_next_after::NextAfter; |
| 326 | + |
| 327 | + // The following tests demonstrate some of the floating point |
| 328 | + // edge cases that can cause try_normalize to return None. |
| 329 | + |
| 330 | + // Zero vector - Normalize returns None |
| 331 | + let a = coord! { x: 0.0, y: 0.0 }; |
| 332 | + assert_eq!(a.try_normalize(), None); |
| 333 | + |
| 334 | + // Very Small Input - Normalize returns None because of |
| 335 | + // rounding-down to zero in the .magnitude() calculation |
| 336 | + let a = coord! { |
| 337 | + x: 0.0, |
| 338 | + y: 1e-301_f64 |
| 339 | + }; |
| 340 | + assert_eq!(a.try_normalize(), None); |
| 341 | + |
| 342 | + // A large vector where try_normalize returns Some |
| 343 | + // Because the magnitude is f64::MAX (Just before overflow to f64::INFINITY) |
| 344 | + let a = coord! { |
| 345 | + x: f64::sqrt(f64::MAX/2.0), |
| 346 | + y: f64::sqrt(f64::MAX/2.0) |
| 347 | + }; |
| 348 | + assert!(a.try_normalize().is_some()); |
| 349 | + |
| 350 | + // A large vector where try_normalize returns None |
| 351 | + // because the magnitude is just above f64::MAX |
| 352 | + let a = coord! { |
| 353 | + x: f64::sqrt(f64::MAX / 2.0), |
| 354 | + y: f64::sqrt(f64::MAX / 2.0).next_after(f64::INFINITY) |
| 355 | + }; |
| 356 | + assert_eq!(a.try_normalize(), None); |
| 357 | + |
| 358 | + // Where one of the components is NaN try_normalize returns None |
| 359 | + let a = coord! { x: f64::NAN, y: 0.0 }; |
| 360 | + assert_eq!(a.try_normalize(), None); |
| 361 | + |
| 362 | + // Where one of the components is Infinite try_normalize returns None |
| 363 | + let a = coord! { x: f64::INFINITY, y: 0.0 }; |
| 364 | + assert_eq!(a.try_normalize(), None); |
| 365 | + } |
| 366 | +} |
0 commit comments