testing.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. """Utilities for testing with shapely geometries."""
  2. from functools import partial
  3. import numpy as np
  4. import shapely
  5. __all__ = ["assert_geometries_equal"]
  6. def _equals_exact_with_ndim(x, y, tolerance):
  7. dimension_equals = shapely.get_coordinate_dimension(
  8. x
  9. ) == shapely.get_coordinate_dimension(y)
  10. with np.errstate(invalid="ignore"):
  11. # Suppress 'invalid value encountered in equals_exact' with nan coordinates
  12. geometry_equals = shapely.equals_exact(x, y, tolerance=tolerance)
  13. return dimension_equals & geometry_equals
  14. def _replace_nan(arr):
  15. return np.where(np.isnan(arr), 0.0, arr)
  16. def _assert_nan_coords_same(x, y, tolerance, err_msg, verbose):
  17. x, y = np.broadcast_arrays(x, y)
  18. x_coords = shapely.get_coordinates(x, include_z=True)
  19. y_coords = shapely.get_coordinates(y, include_z=True)
  20. # Check the shapes (condition is copied from numpy test_array_equal)
  21. if x_coords.shape != y_coords.shape:
  22. return False
  23. # Check NaN positional equality
  24. x_id = np.isnan(x_coords)
  25. y_id = np.isnan(y_coords)
  26. if not (x_id == y_id).all():
  27. msg = build_err_msg(
  28. [x, y],
  29. err_msg + "\nx and y nan coordinate location mismatch:",
  30. verbose=verbose,
  31. )
  32. raise AssertionError(msg)
  33. # If this passed, replace NaN with a number to be able to use equals_exact
  34. x_no_nan = shapely.transform(x, _replace_nan, include_z=True)
  35. y_no_nan = shapely.transform(y, _replace_nan, include_z=True)
  36. return _equals_exact_with_ndim(x_no_nan, y_no_nan, tolerance=tolerance)
  37. def _assert_none_same(x, y, err_msg, verbose):
  38. x_id = shapely.is_missing(x)
  39. y_id = shapely.is_missing(y)
  40. if not (x_id == y_id).all():
  41. msg = build_err_msg(
  42. [x, y],
  43. err_msg + "\nx and y None location mismatch:",
  44. verbose=verbose,
  45. )
  46. raise AssertionError(msg)
  47. # If there is a scalar, then here we know the array has the same
  48. # flag as it everywhere, so we should return the scalar flag.
  49. if x.ndim == 0:
  50. return bool(x_id)
  51. elif y.ndim == 0:
  52. return bool(y_id)
  53. else:
  54. return y_id
  55. def assert_geometries_equal(
  56. x,
  57. y,
  58. tolerance=1e-7,
  59. equal_none=True,
  60. equal_nan=True,
  61. normalize=False,
  62. err_msg="",
  63. verbose=True,
  64. ):
  65. """Raise an AssertionError if two geometry array_like objects are not equal.
  66. Given two array_like objects, check that the shape is equal and all elements
  67. of these objects are equal. An exception is raised at shape mismatch or
  68. conflicting values. In contrast to the standard usage in shapely, no
  69. assertion is raised if both objects have NaNs/Nones in the same positions.
  70. Parameters
  71. ----------
  72. x, y : Geometry or array_like
  73. Geometry or geometries to compare.
  74. tolerance: float, default 1e-7
  75. The tolerance to use when comparing geometries.
  76. equal_none : bool, default True
  77. Whether to consider None elements equal to other None elements.
  78. equal_nan : bool, default True
  79. Whether to consider nan coordinates as equal to other nan coordinates.
  80. normalize : bool, default False
  81. Whether to normalize geometries prior to comparison.
  82. err_msg : str, optional
  83. The error message to be printed in case of failure.
  84. verbose : bool, optional
  85. If True, the conflicting values are appended to the error message.
  86. """
  87. __tracebackhide__ = True # Hide traceback for py.test
  88. if normalize:
  89. x = shapely.normalize(x)
  90. y = shapely.normalize(y)
  91. x = np.asarray(x)
  92. y = np.asarray(y)
  93. is_scalar = x.ndim == 0 or y.ndim == 0
  94. # Check the shapes (condition is copied from numpy test_array_equal)
  95. if not (is_scalar or x.shape == y.shape):
  96. msg = build_err_msg(
  97. [x, y],
  98. err_msg + f"\n(shapes {x.shape}, {y.shape} mismatch)",
  99. verbose=verbose,
  100. )
  101. raise AssertionError(msg)
  102. flagged = False
  103. if equal_none:
  104. flagged = _assert_none_same(x, y, err_msg, verbose)
  105. if not np.isscalar(flagged):
  106. x, y = x[~flagged], y[~flagged]
  107. # Only do the comparison if actual values are left
  108. if x.size == 0:
  109. return
  110. elif flagged:
  111. # no sense doing comparison if everything is flagged.
  112. return
  113. is_equal = _equals_exact_with_ndim(x, y, tolerance=tolerance)
  114. if is_scalar and not np.isscalar(is_equal):
  115. is_equal = bool(is_equal[0])
  116. if np.all(is_equal):
  117. return
  118. elif not equal_nan:
  119. msg = build_err_msg(
  120. [x, y],
  121. err_msg + f"\nNot equal to tolerance {tolerance:g}",
  122. verbose=verbose,
  123. )
  124. raise AssertionError(msg)
  125. # Optionally refine failing elements if NaN should be considered equal
  126. if not np.isscalar(is_equal):
  127. x, y = x[~is_equal], y[~is_equal]
  128. # Only do the NaN check if actual values are left
  129. if x.size == 0:
  130. return
  131. elif is_equal:
  132. # no sense in checking for NaN if everything is equal.
  133. return
  134. is_equal = _assert_nan_coords_same(x, y, tolerance, err_msg, verbose)
  135. if not np.all(is_equal):
  136. msg = build_err_msg(
  137. [x, y],
  138. err_msg + f"\nNot equal to tolerance {tolerance:g}",
  139. verbose=verbose,
  140. )
  141. raise AssertionError(msg)
  142. ## BELOW A COPY FROM numpy.testing._private.utils (numpy version 1.20.2)
  143. def build_err_msg(
  144. arrays,
  145. err_msg,
  146. header="Geometries are not equal:",
  147. verbose=True,
  148. names=("x", "y"),
  149. precision=8,
  150. ):
  151. msg = ["\n" + header]
  152. if err_msg:
  153. if err_msg.find("\n") == -1 and len(err_msg) < 79 - len(header):
  154. msg = [msg[0] + " " + err_msg]
  155. else:
  156. msg.append(err_msg)
  157. if verbose:
  158. for i, a in enumerate(arrays):
  159. if isinstance(a, np.ndarray):
  160. # precision argument is only needed if the objects are ndarrays
  161. r_func = partial(np.array_repr, precision=precision)
  162. else:
  163. r_func = repr
  164. try:
  165. r = r_func(a)
  166. except Exception as exc:
  167. r = f"[repr failed for <{type(a).__name__}>: {exc}]"
  168. if r.count("\n") > 3:
  169. r = "\n".join(r.splitlines()[:3])
  170. r += "..."
  171. msg.append(f" {names[i]}: {r}")
  172. return "\n".join(msg)