_tritools.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. """
  2. Tools for triangular grids.
  3. """
  4. import numpy as np
  5. from matplotlib import _api
  6. from matplotlib.tri import Triangulation
  7. class TriAnalyzer:
  8. """
  9. Define basic tools for triangular mesh analysis and improvement.
  10. A TriAnalyzer encapsulates a `.Triangulation` object and provides basic
  11. tools for mesh analysis and mesh improvement.
  12. Attributes
  13. ----------
  14. scale_factors
  15. Parameters
  16. ----------
  17. triangulation : `~matplotlib.tri.Triangulation`
  18. The encapsulated triangulation to analyze.
  19. """
  20. def __init__(self, triangulation):
  21. _api.check_isinstance(Triangulation, triangulation=triangulation)
  22. self._triangulation = triangulation
  23. @property
  24. def scale_factors(self):
  25. """
  26. Factors to rescale the triangulation into a unit square.
  27. Returns
  28. -------
  29. (float, float)
  30. Scaling factors (kx, ky) so that the triangulation
  31. ``[triangulation.x * kx, triangulation.y * ky]``
  32. fits exactly inside a unit square.
  33. """
  34. compressed_triangles = self._triangulation.get_masked_triangles()
  35. node_used = (np.bincount(np.ravel(compressed_triangles),
  36. minlength=self._triangulation.x.size) != 0)
  37. return (1 / np.ptp(self._triangulation.x[node_used]),
  38. 1 / np.ptp(self._triangulation.y[node_used]))
  39. def circle_ratios(self, rescale=True):
  40. """
  41. Return a measure of the triangulation triangles flatness.
  42. The ratio of the incircle radius over the circumcircle radius is a
  43. widely used indicator of a triangle flatness.
  44. It is always ``<= 0.5`` and ``== 0.5`` only for equilateral
  45. triangles. Circle ratios below 0.01 denote very flat triangles.
  46. To avoid unduly low values due to a difference of scale between the 2
  47. axis, the triangular mesh can first be rescaled to fit inside a unit
  48. square with `scale_factors` (Only if *rescale* is True, which is
  49. its default value).
  50. Parameters
  51. ----------
  52. rescale : bool, default: True
  53. If True, internally rescale (based on `scale_factors`), so that the
  54. (unmasked) triangles fit exactly inside a unit square mesh.
  55. Returns
  56. -------
  57. masked array
  58. Ratio of the incircle radius over the circumcircle radius, for
  59. each 'rescaled' triangle of the encapsulated triangulation.
  60. Values corresponding to masked triangles are masked out.
  61. """
  62. # Coords rescaling
  63. if rescale:
  64. (kx, ky) = self.scale_factors
  65. else:
  66. (kx, ky) = (1.0, 1.0)
  67. pts = np.vstack([self._triangulation.x*kx,
  68. self._triangulation.y*ky]).T
  69. tri_pts = pts[self._triangulation.triangles]
  70. # Computes the 3 side lengths
  71. a = tri_pts[:, 1, :] - tri_pts[:, 0, :]
  72. b = tri_pts[:, 2, :] - tri_pts[:, 1, :]
  73. c = tri_pts[:, 0, :] - tri_pts[:, 2, :]
  74. a = np.hypot(a[:, 0], a[:, 1])
  75. b = np.hypot(b[:, 0], b[:, 1])
  76. c = np.hypot(c[:, 0], c[:, 1])
  77. # circumcircle and incircle radii
  78. s = (a+b+c)*0.5
  79. prod = s*(a+b-s)*(a+c-s)*(b+c-s)
  80. # We have to deal with flat triangles with infinite circum_radius
  81. bool_flat = (prod == 0.)
  82. if np.any(bool_flat):
  83. # Pathologic flow
  84. ntri = tri_pts.shape[0]
  85. circum_radius = np.empty(ntri, dtype=np.float64)
  86. circum_radius[bool_flat] = np.inf
  87. abc = a*b*c
  88. circum_radius[~bool_flat] = abc[~bool_flat] / (
  89. 4.0*np.sqrt(prod[~bool_flat]))
  90. else:
  91. # Normal optimized flow
  92. circum_radius = (a*b*c) / (4.0*np.sqrt(prod))
  93. in_radius = (a*b*c) / (4.0*circum_radius*s)
  94. circle_ratio = in_radius/circum_radius
  95. mask = self._triangulation.mask
  96. if mask is None:
  97. return circle_ratio
  98. else:
  99. return np.ma.array(circle_ratio, mask=mask)
  100. def get_flat_tri_mask(self, min_circle_ratio=0.01, rescale=True):
  101. """
  102. Eliminate excessively flat border triangles from the triangulation.
  103. Returns a mask *new_mask* which allows to clean the encapsulated
  104. triangulation from its border-located flat triangles
  105. (according to their :meth:`circle_ratios`).
  106. This mask is meant to be subsequently applied to the triangulation
  107. using `.Triangulation.set_mask`.
  108. *new_mask* is an extension of the initial triangulation mask
  109. in the sense that an initially masked triangle will remain masked.
  110. The *new_mask* array is computed recursively; at each step flat
  111. triangles are removed only if they share a side with the current mesh
  112. border. Thus, no new holes in the triangulated domain will be created.
  113. Parameters
  114. ----------
  115. min_circle_ratio : float, default: 0.01
  116. Border triangles with incircle/circumcircle radii ratio r/R will
  117. be removed if r/R < *min_circle_ratio*.
  118. rescale : bool, default: True
  119. If True, first, internally rescale (based on `scale_factors`) so
  120. that the (unmasked) triangles fit exactly inside a unit square
  121. mesh. This rescaling accounts for the difference of scale which
  122. might exist between the 2 axis.
  123. Returns
  124. -------
  125. array of bool
  126. Mask to apply to encapsulated triangulation.
  127. All the initially masked triangles remain masked in the
  128. *new_mask*.
  129. Notes
  130. -----
  131. The rationale behind this function is that a Delaunay
  132. triangulation - of an unstructured set of points - sometimes contains
  133. almost flat triangles at its border, leading to artifacts in plots
  134. (especially for high-resolution contouring).
  135. Masked with computed *new_mask*, the encapsulated
  136. triangulation would contain no more unmasked border triangles
  137. with a circle ratio below *min_circle_ratio*, thus improving the
  138. mesh quality for subsequent plots or interpolation.
  139. """
  140. # Recursively computes the mask_current_borders, true if a triangle is
  141. # at the border of the mesh OR touching the border through a chain of
  142. # invalid aspect ratio masked_triangles.
  143. ntri = self._triangulation.triangles.shape[0]
  144. mask_bad_ratio = self.circle_ratios(rescale) < min_circle_ratio
  145. current_mask = self._triangulation.mask
  146. if current_mask is None:
  147. current_mask = np.zeros(ntri, dtype=bool)
  148. valid_neighbors = np.copy(self._triangulation.neighbors)
  149. renum_neighbors = np.arange(ntri, dtype=np.int32)
  150. nadd = -1
  151. while nadd != 0:
  152. # The active wavefront is the triangles from the border (unmasked
  153. # but with a least 1 neighbor equal to -1
  154. wavefront = (np.min(valid_neighbors, axis=1) == -1) & ~current_mask
  155. # The element from the active wavefront will be masked if their
  156. # circle ratio is bad.
  157. added_mask = wavefront & mask_bad_ratio
  158. current_mask = added_mask | current_mask
  159. nadd = np.sum(added_mask)
  160. # now we have to update the tables valid_neighbors
  161. valid_neighbors[added_mask, :] = -1
  162. renum_neighbors[added_mask] = -1
  163. valid_neighbors = np.where(valid_neighbors == -1, -1,
  164. renum_neighbors[valid_neighbors])
  165. return np.ma.filled(current_mask, True)
  166. def _get_compressed_triangulation(self):
  167. """
  168. Compress (if masked) the encapsulated triangulation.
  169. Returns minimal-length triangles array (*compressed_triangles*) and
  170. coordinates arrays (*compressed_x*, *compressed_y*) that can still
  171. describe the unmasked triangles of the encapsulated triangulation.
  172. Returns
  173. -------
  174. compressed_triangles : array-like
  175. the returned compressed triangulation triangles
  176. compressed_x : array-like
  177. the returned compressed triangulation 1st coordinate
  178. compressed_y : array-like
  179. the returned compressed triangulation 2nd coordinate
  180. tri_renum : int array
  181. renumbering table to translate the triangle numbers from the
  182. encapsulated triangulation into the new (compressed) renumbering.
  183. -1 for masked triangles (deleted from *compressed_triangles*).
  184. node_renum : int array
  185. renumbering table to translate the point numbers from the
  186. encapsulated triangulation into the new (compressed) renumbering.
  187. -1 for unused points (i.e. those deleted from *compressed_x* and
  188. *compressed_y*).
  189. """
  190. # Valid triangles and renumbering
  191. tri_mask = self._triangulation.mask
  192. compressed_triangles = self._triangulation.get_masked_triangles()
  193. ntri = self._triangulation.triangles.shape[0]
  194. if tri_mask is not None:
  195. tri_renum = self._total_to_compress_renum(~tri_mask)
  196. else:
  197. tri_renum = np.arange(ntri, dtype=np.int32)
  198. # Valid nodes and renumbering
  199. valid_node = (np.bincount(np.ravel(compressed_triangles),
  200. minlength=self._triangulation.x.size) != 0)
  201. compressed_x = self._triangulation.x[valid_node]
  202. compressed_y = self._triangulation.y[valid_node]
  203. node_renum = self._total_to_compress_renum(valid_node)
  204. # Now renumbering the valid triangles nodes
  205. compressed_triangles = node_renum[compressed_triangles]
  206. return (compressed_triangles, compressed_x, compressed_y, tri_renum,
  207. node_renum)
  208. @staticmethod
  209. def _total_to_compress_renum(valid):
  210. """
  211. Parameters
  212. ----------
  213. valid : 1D bool array
  214. Validity mask.
  215. Returns
  216. -------
  217. int array
  218. Array so that (`valid_array` being a compressed array
  219. based on a `masked_array` with mask ~*valid*):
  220. - For all i with valid[i] = True:
  221. valid_array[renum[i]] = masked_array[i]
  222. - For all i with valid[i] = False:
  223. renum[i] = -1 (invalid value)
  224. """
  225. renum = np.full(np.size(valid), -1, dtype=np.int32)
  226. n_valid = np.sum(valid)
  227. renum[valid] = np.arange(n_valid, dtype=np.int32)
  228. return renum