grid_finder.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import numpy as np
  2. from matplotlib import ticker as mticker, _api
  3. from matplotlib.transforms import Bbox, Transform
  4. def _find_line_box_crossings(xys, bbox):
  5. """
  6. Find the points where a polyline crosses a bbox, and the crossing angles.
  7. Parameters
  8. ----------
  9. xys : (N, 2) array
  10. The polyline coordinates.
  11. bbox : `.Bbox`
  12. The bounding box.
  13. Returns
  14. -------
  15. list of ((float, float), float)
  16. Four separate lists of crossings, for the left, right, bottom, and top
  17. sides of the bbox, respectively. For each list, the entries are the
  18. ``((x, y), ccw_angle_in_degrees)`` of the crossing, where an angle of 0
  19. means that the polyline is moving to the right at the crossing point.
  20. The entries are computed by linearly interpolating at each crossing
  21. between the nearest points on either side of the bbox edges.
  22. """
  23. crossings = []
  24. dxys = xys[1:] - xys[:-1]
  25. for sl in [slice(None), slice(None, None, -1)]:
  26. us, vs = xys.T[sl] # "this" coord, "other" coord
  27. dus, dvs = dxys.T[sl]
  28. umin, vmin = bbox.min[sl]
  29. umax, vmax = bbox.max[sl]
  30. for u0, inside in [(umin, us > umin), (umax, us < umax)]:
  31. cross = []
  32. idxs, = (inside[:-1] ^ inside[1:]).nonzero()
  33. for idx in idxs:
  34. v = vs[idx] + (u0 - us[idx]) * dvs[idx] / dus[idx]
  35. if not vmin <= v <= vmax:
  36. continue
  37. crossing = (u0, v)[sl]
  38. theta = np.degrees(np.arctan2(*dxys[idx][::-1]))
  39. cross.append((crossing, theta))
  40. crossings.append(cross)
  41. return crossings
  42. class ExtremeFinderSimple:
  43. """
  44. A helper class to figure out the range of grid lines that need to be drawn.
  45. """
  46. def __init__(self, nx, ny):
  47. """
  48. Parameters
  49. ----------
  50. nx, ny : int
  51. The number of samples in each direction.
  52. """
  53. self.nx = nx
  54. self.ny = ny
  55. def __call__(self, transform_xy, x1, y1, x2, y2):
  56. """
  57. Compute an approximation of the bounding box obtained by applying
  58. *transform_xy* to the box delimited by ``(x1, y1, x2, y2)``.
  59. The intended use is to have ``(x1, y1, x2, y2)`` in axes coordinates,
  60. and have *transform_xy* be the transform from axes coordinates to data
  61. coordinates; this method then returns the range of data coordinates
  62. that span the actual axes.
  63. The computation is done by sampling ``nx * ny`` equispaced points in
  64. the ``(x1, y1, x2, y2)`` box and finding the resulting points with
  65. extremal coordinates; then adding some padding to take into account the
  66. finite sampling.
  67. As each sampling step covers a relative range of *1/nx* or *1/ny*,
  68. the padding is computed by expanding the span covered by the extremal
  69. coordinates by these fractions.
  70. """
  71. x, y = np.meshgrid(
  72. np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny))
  73. xt, yt = transform_xy(np.ravel(x), np.ravel(y))
  74. return self._add_pad(xt.min(), xt.max(), yt.min(), yt.max())
  75. def _add_pad(self, x_min, x_max, y_min, y_max):
  76. """Perform the padding mentioned in `__call__`."""
  77. dx = (x_max - x_min) / self.nx
  78. dy = (y_max - y_min) / self.ny
  79. return x_min - dx, x_max + dx, y_min - dy, y_max + dy
  80. class _User2DTransform(Transform):
  81. """A transform defined by two user-set functions."""
  82. input_dims = output_dims = 2
  83. def __init__(self, forward, backward):
  84. """
  85. Parameters
  86. ----------
  87. forward, backward : callable
  88. The forward and backward transforms, taking ``x`` and ``y`` as
  89. separate arguments and returning ``(tr_x, tr_y)``.
  90. """
  91. # The normal Matplotlib convention would be to take and return an
  92. # (N, 2) array but axisartist uses the transposed version.
  93. super().__init__()
  94. self._forward = forward
  95. self._backward = backward
  96. def transform_non_affine(self, values):
  97. # docstring inherited
  98. return np.transpose(self._forward(*np.transpose(values)))
  99. def inverted(self):
  100. # docstring inherited
  101. return type(self)(self._backward, self._forward)
  102. class GridFinder:
  103. """
  104. Internal helper for `~.grid_helper_curvelinear.GridHelperCurveLinear`, with
  105. the same constructor parameters; should not be directly instantiated.
  106. """
  107. def __init__(self,
  108. transform,
  109. extreme_finder=None,
  110. grid_locator1=None,
  111. grid_locator2=None,
  112. tick_formatter1=None,
  113. tick_formatter2=None):
  114. if extreme_finder is None:
  115. extreme_finder = ExtremeFinderSimple(20, 20)
  116. if grid_locator1 is None:
  117. grid_locator1 = MaxNLocator()
  118. if grid_locator2 is None:
  119. grid_locator2 = MaxNLocator()
  120. if tick_formatter1 is None:
  121. tick_formatter1 = FormatterPrettyPrint()
  122. if tick_formatter2 is None:
  123. tick_formatter2 = FormatterPrettyPrint()
  124. self.extreme_finder = extreme_finder
  125. self.grid_locator1 = grid_locator1
  126. self.grid_locator2 = grid_locator2
  127. self.tick_formatter1 = tick_formatter1
  128. self.tick_formatter2 = tick_formatter2
  129. self.set_transform(transform)
  130. def _format_ticks(self, idx, direction, factor, levels):
  131. """
  132. Helper to support both standard formatters (inheriting from
  133. `.mticker.Formatter`) and axisartist-specific ones; should be called instead of
  134. directly calling ``self.tick_formatter1`` and ``self.tick_formatter2``. This
  135. method should be considered as a temporary workaround which will be removed in
  136. the future at the same time as axisartist-specific formatters.
  137. """
  138. fmt = _api.check_getitem(
  139. {1: self.tick_formatter1, 2: self.tick_formatter2}, idx=idx)
  140. return (fmt.format_ticks(levels) if isinstance(fmt, mticker.Formatter)
  141. else fmt(direction, factor, levels))
  142. def get_grid_info(self, x1, y1, x2, y2):
  143. """
  144. lon_values, lat_values : list of grid values. if integer is given,
  145. rough number of grids in each direction.
  146. """
  147. extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)
  148. # min & max rage of lat (or lon) for each grid line will be drawn.
  149. # i.e., gridline of lon=0 will be drawn from lat_min to lat_max.
  150. lon_min, lon_max, lat_min, lat_max = extremes
  151. lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max)
  152. lon_levs = np.asarray(lon_levs)
  153. lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max)
  154. lat_levs = np.asarray(lat_levs)
  155. lon_values = lon_levs[:lon_n] / lon_factor
  156. lat_values = lat_levs[:lat_n] / lat_factor
  157. lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,
  158. lat_values,
  159. lon_min, lon_max,
  160. lat_min, lat_max)
  161. bb = Bbox.from_extents(x1, y1, x2, y2).expanded(1 + 2e-10, 1 + 2e-10)
  162. grid_info = {
  163. "extremes": extremes,
  164. # "lon", "lat", filled below.
  165. }
  166. for idx, lon_or_lat, levs, factor, values, lines in [
  167. (1, "lon", lon_levs, lon_factor, lon_values, lon_lines),
  168. (2, "lat", lat_levs, lat_factor, lat_values, lat_lines),
  169. ]:
  170. grid_info[lon_or_lat] = gi = {
  171. "lines": [[l] for l in lines],
  172. "ticks": {"left": [], "right": [], "bottom": [], "top": []},
  173. }
  174. for (lx, ly), v, level in zip(lines, values, levs):
  175. all_crossings = _find_line_box_crossings(np.column_stack([lx, ly]), bb)
  176. for side, crossings in zip(
  177. ["left", "right", "bottom", "top"], all_crossings):
  178. for crossing in crossings:
  179. gi["ticks"][side].append({"level": level, "loc": crossing})
  180. for side in gi["ticks"]:
  181. levs = [tick["level"] for tick in gi["ticks"][side]]
  182. labels = self._format_ticks(idx, side, factor, levs)
  183. for tick, label in zip(gi["ticks"][side], labels):
  184. tick["label"] = label
  185. return grid_info
  186. def _get_raw_grid_lines(self,
  187. lon_values, lat_values,
  188. lon_min, lon_max, lat_min, lat_max):
  189. lons_i = np.linspace(lon_min, lon_max, 100) # for interpolation
  190. lats_i = np.linspace(lat_min, lat_max, 100)
  191. lon_lines = [self.transform_xy(np.full_like(lats_i, lon), lats_i)
  192. for lon in lon_values]
  193. lat_lines = [self.transform_xy(lons_i, np.full_like(lons_i, lat))
  194. for lat in lat_values]
  195. return lon_lines, lat_lines
  196. def set_transform(self, aux_trans):
  197. if isinstance(aux_trans, Transform):
  198. self._aux_transform = aux_trans
  199. elif len(aux_trans) == 2 and all(map(callable, aux_trans)):
  200. self._aux_transform = _User2DTransform(*aux_trans)
  201. else:
  202. raise TypeError("'aux_trans' must be either a Transform "
  203. "instance or a pair of callables")
  204. def get_transform(self):
  205. return self._aux_transform
  206. update_transform = set_transform # backcompat alias.
  207. def transform_xy(self, x, y):
  208. return self._aux_transform.transform(np.column_stack([x, y])).T
  209. def inv_transform_xy(self, x, y):
  210. return self._aux_transform.inverted().transform(
  211. np.column_stack([x, y])).T
  212. def update(self, **kwargs):
  213. for k, v in kwargs.items():
  214. if k in ["extreme_finder",
  215. "grid_locator1",
  216. "grid_locator2",
  217. "tick_formatter1",
  218. "tick_formatter2"]:
  219. setattr(self, k, v)
  220. else:
  221. raise ValueError(f"Unknown update property {k!r}")
  222. class MaxNLocator(mticker.MaxNLocator):
  223. def __init__(self, nbins=10, steps=None,
  224. trim=True,
  225. integer=False,
  226. symmetric=False,
  227. prune=None):
  228. # trim argument has no effect. It has been left for API compatibility
  229. super().__init__(nbins, steps=steps, integer=integer,
  230. symmetric=symmetric, prune=prune)
  231. self.create_dummy_axis()
  232. def __call__(self, v1, v2):
  233. locs = super().tick_values(v1, v2)
  234. return np.array(locs), len(locs), 1 # 1: factor (see angle_helper)
  235. class FixedLocator:
  236. def __init__(self, locs):
  237. self._locs = locs
  238. def __call__(self, v1, v2):
  239. v1, v2 = sorted([v1, v2])
  240. locs = np.array([l for l in self._locs if v1 <= l <= v2])
  241. return locs, len(locs), 1 # 1: factor (see angle_helper)
  242. # Tick Formatter
  243. class FormatterPrettyPrint:
  244. def __init__(self, useMathText=True):
  245. self._fmt = mticker.ScalarFormatter(
  246. useMathText=useMathText, useOffset=False)
  247. self._fmt.create_dummy_axis()
  248. def __call__(self, direction, factor, values):
  249. return self._fmt.format_ticks(values)
  250. class DictFormatter:
  251. def __init__(self, format_dict, formatter=None):
  252. """
  253. format_dict : dictionary for format strings to be used.
  254. formatter : fall-back formatter
  255. """
  256. super().__init__()
  257. self._format_dict = format_dict
  258. self._fallback_formatter = formatter
  259. def __call__(self, direction, factor, values):
  260. """
  261. factor is ignored if value is found in the dictionary
  262. """
  263. if self._fallback_formatter:
  264. fallback_strings = self._fallback_formatter(
  265. direction, factor, values)
  266. else:
  267. fallback_strings = [""] * len(values)
  268. return [self._format_dict.get(k, v)
  269. for k, v in zip(values, fallback_strings)]