fork download
  1. import numpy as np
  2. import math
  3.  
  4.  
  5. # ############################################################
  6. # unutbu's model() (https://stackoverflow.com/a/35118683/27358)
  7.  
  8. def model(params, xyz):
  9. a, b, c, d = params
  10. x, y, z = xyz
  11. length = (a ** 2 + b ** 2 + c ** 2)
  12. return ((a * x + b * y + c * z + d) ** 2 / length).sum()
  13.  
  14.  
  15. # ############################################################
  16. # naive implementation
  17.  
  18. def z_from(x, y, abcd):
  19. """Returns the z coordinate from a pair of (x, y) coordinates
  20. and a list of coefficients in the form ax + by + cz + d = 0.
  21. """
  22. a, b, c, d = abcd
  23. return (a * x + b * y + d) / -c
  24.  
  25.  
  26. # see https://m...content-available-to-author-only...t.org/distance_point_plane
  27. def unit_normal_vector(abcd):
  28. a, b, c, d = abcd
  29. n = np.array([a, b, c])
  30. len_n = (a ** 2 + b ** 2 + c ** 2) ** .5
  31. return n / len_n
  32.  
  33.  
  34. # see https://m...content-available-to-author-only...t.org/distance_point_plane
  35. def dist_point_plane(point, abcd):
  36. x0, y0, z0 = np.array([0, 0, z_from(0, 0, abcd)])
  37. x1, y1, z1 = point
  38. n = unit_normal_vector(abcd)
  39. v = np.array([x1 - x0, y1 - y0, z1 - z0])
  40. d = np.abs(np.dot(v, n))
  41. return d
  42.  
  43.  
  44. def total_dist_plane_points(abcd, xyz):
  45. total = 0
  46. for i, x in enumerate(xyz[0]):
  47. y, z = xyz[1][i], xyz[2][i]
  48. point = [x, y, z]
  49. total = total + dist_point_plane(point, abcd)**2
  50. return total
  51.  
  52.  
  53. # ############################################################
  54. # Main program
  55.  
  56. # points (2, 4, 6), (8, 10, 12), (14, 16, 18)
  57. xyz = np.array([
  58. [2, 8, 14],
  59. [4, 10, 16],
  60. [6, 12, 18]
  61. ])
  62. # x + 2y + 3z + 4 = 0
  63. abcd = np.array([1, 2, 3, 4])
  64.  
  65. expected = total_dist_plane_points(abcd, xyz)
  66. actual = model(abcd, xyz)
  67.  
  68. print("Expected: {}".format(expected))
  69. print("Actual: {}".format(actual))
  70.  
Success #stdin #stdout 0.08s 92352KB
stdin
Standard input is empty
stdout
Expected: 1176.0
Actual:   1176.0