utils.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """
  2. @package iscatt.utils
  3. @brief Misc utilities for iscatt
  4. (C) 2020 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Nicklas Larsson <n_larsson yahoo com>
  8. """
  9. import numpy as np
  10. # Code originate from matplotlib
  11. # https://matplotlib.org/3.0.0/_modules/matplotlib/mlab.html#dist
  12. def dist(x, y):
  13. """
  14. Return the distance between two points.
  15. """
  16. d = x - y
  17. return np.sqrt(np.dot(d, d))
  18. # Code originate from matplotlib
  19. # https://matplotlib.org/3.0.0/_modules/matplotlib/mlab.html#dist_point_to_segment
  20. def dist_point_to_segment(p, s0, s1):
  21. """
  22. Get the distance of a point to a segment.
  23. *p*, *s0*, *s1* are *xy* sequences
  24. This algorithm from
  25. http://geomalgorithms.com/a02-_lines.html
  26. """
  27. p = np.asarray(p, float)
  28. s0 = np.asarray(s0, float)
  29. s1 = np.asarray(s1, float)
  30. v = s1 - s0
  31. w = p - s0
  32. c1 = np.dot(w, v)
  33. if c1 <= 0:
  34. return dist(p, s0)
  35. c2 = np.dot(v, v)
  36. if c2 <= c1:
  37. return dist(p, s1)
  38. b = c1 / c2
  39. pb = s0 + b * v
  40. return dist(p, pb)