grid_finder.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import numpy as np
  2. from matplotlib import ticker as mticker
  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. crossings.append([])
  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. crossings[-1].append((crossing, theta))
  40. return crossings
  41. class ExtremeFinderSimple:
  42. """
  43. A helper class to figure out the range of grid lines that need to be drawn.
  44. """
  45. def __init__(self, nx, ny):
  46. """
  47. Parameters
  48. ----------
  49. nx, ny : int
  50. The number of samples in each direction.
  51. """
  52. self.nx = nx
  53. self.ny = ny
  54. def __call__(self, transform_xy, x1, y1, x2, y2):
  55. """
  56. Compute an approximation of the bounding box obtained by applying
  57. *transform_xy* to the box delimited by ``(x1, y1, x2, y2)``.
  58. The intended use is to have ``(x1, y1, x2, y2)`` in axes coordinates,
  59. and have *transform_xy* be the transform from axes coordinates to data
  60. coordinates; this method then returns the range of data coordinates
  61. that span the actual axes.
  62. The computation is done by sampling ``nx * ny`` equispaced points in
  63. the ``(x1, y1, x2, y2)`` box and finding the resulting points with
  64. extremal coordinates; then adding some padding to take into account the
  65. finite sampling.
  66. As each sampling step covers a relative range of *1/nx* or *1/ny*,
  67. the padding is computed by expanding the span covered by the extremal
  68. coordinates by these fractions.
  69. """
  70. x, y = np.meshgrid(
  71. np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny))
  72. xt, yt = transform_xy(np.ravel(x), np.ravel(y))
  73. return self._add_pad(xt.min(), xt.max(), yt.min(), yt.max())
  74. def _add_pad(self, x_min, x_max, y_min, y_max):
  75. """Perform the padding mentioned in `__call__`."""
  76. dx = (x_max - x_min) / self.nx
  77. dy = (y_max - y_min) / self.ny
  78. return x_min - dx, x_max + dx, y_min - dy, y_max + dy
  79. class _User2DTransform(Transform):
  80. """A transform defined by two user-set functions."""
  81. input_dims = output_dims = 2
  82. def __init__(self, forward, backward):
  83. """
  84. Parameters
  85. ----------
  86. forward, backward : callable
  87. The forward and backward transforms, taking ``x`` and ``y`` as
  88. separate arguments and returning ``(tr_x, tr_y)``.
  89. """
  90. # The normal Matplotlib convention would be to take and return an
  91. # (N, 2) array but axisartist uses the transposed version.
  92. super().__init__()
  93. self._forward = forward
  94. self._backward = backward
  95. def transform_non_affine(self, values):
  96. # docstring inherited
  97. return np.transpose(self._forward(*np.transpose(values)))
  98. def inverted(self):
  99. # docstring inherited
  100. return type(self)(self._backward, self._forward)
  101. class GridFinder:
  102. """
  103. Internal helper for `~.grid_helper_curvelinear.GridHelperCurveLinear`, with
  104. the same constructor parameters; should not be directly instantiated.
  105. """
  106. def __init__(self,
  107. transform,
  108. extreme_finder=None,
  109. grid_locator1=None,
  110. grid_locator2=None,
  111. tick_formatter1=None,
  112. tick_formatter2=None):
  113. if extreme_finder is None:
  114. extreme_finder = ExtremeFinderSimple(20, 20)
  115. if grid_locator1 is None:
  116. grid_locator1 = MaxNLocator()
  117. if grid_locator2 is None:
  118. grid_locator2 = MaxNLocator()
  119. if tick_formatter1 is None:
  120. tick_formatter1 = FormatterPrettyPrint()
  121. if tick_formatter2 is None:
  122. tick_formatter2 = FormatterPrettyPrint()
  123. self.extreme_finder = extreme_finder
  124. self.grid_locator1 = grid_locator1
  125. self.grid_locator2 = grid_locator2
  126. self.tick_formatter1 = tick_formatter1
  127. self.tick_formatter2 = tick_formatter2
  128. self.set_transform(transform)
  129. def get_grid_info(self, x1, y1, x2, y2):
  130. """
  131. lon_values, lat_values : list of grid values. if integer is given,
  132. rough number of grids in each direction.
  133. """
  134. extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)
  135. # min & max rage of lat (or lon) for each grid line will be drawn.
  136. # i.e., gridline of lon=0 will be drawn from lat_min to lat_max.
  137. lon_min, lon_max, lat_min, lat_max = extremes
  138. lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max)
  139. lon_levs = np.asarray(lon_levs)
  140. lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max)
  141. lat_levs = np.asarray(lat_levs)
  142. lon_values = lon_levs[:lon_n] / lon_factor
  143. lat_values = lat_levs[:lat_n] / lat_factor
  144. lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,
  145. lat_values,
  146. lon_min, lon_max,
  147. lat_min, lat_max)
  148. ddx = (x2-x1)*1.e-10
  149. ddy = (y2-y1)*1.e-10
  150. bb = Bbox.from_extents(x1-ddx, y1-ddy, x2+ddx, y2+ddy)
  151. grid_info = {
  152. "extremes": extremes,
  153. "lon_lines": lon_lines,
  154. "lat_lines": lat_lines,
  155. "lon": self._clip_grid_lines_and_find_ticks(
  156. lon_lines, lon_values, lon_levs, bb),
  157. "lat": self._clip_grid_lines_and_find_ticks(
  158. lat_lines, lat_values, lat_levs, bb),
  159. }
  160. tck_labels = grid_info["lon"]["tick_labels"] = {}
  161. for direction in ["left", "bottom", "right", "top"]:
  162. levs = grid_info["lon"]["tick_levels"][direction]
  163. tck_labels[direction] = self.tick_formatter1(
  164. direction, lon_factor, levs)
  165. tck_labels = grid_info["lat"]["tick_labels"] = {}
  166. for direction in ["left", "bottom", "right", "top"]:
  167. levs = grid_info["lat"]["tick_levels"][direction]
  168. tck_labels[direction] = self.tick_formatter2(
  169. direction, lat_factor, levs)
  170. return grid_info
  171. def _get_raw_grid_lines(self,
  172. lon_values, lat_values,
  173. lon_min, lon_max, lat_min, lat_max):
  174. lons_i = np.linspace(lon_min, lon_max, 100) # for interpolation
  175. lats_i = np.linspace(lat_min, lat_max, 100)
  176. lon_lines = [self.transform_xy(np.full_like(lats_i, lon), lats_i)
  177. for lon in lon_values]
  178. lat_lines = [self.transform_xy(lons_i, np.full_like(lons_i, lat))
  179. for lat in lat_values]
  180. return lon_lines, lat_lines
  181. def _clip_grid_lines_and_find_ticks(self, lines, values, levs, bb):
  182. gi = {
  183. "values": [],
  184. "levels": [],
  185. "tick_levels": dict(left=[], bottom=[], right=[], top=[]),
  186. "tick_locs": dict(left=[], bottom=[], right=[], top=[]),
  187. "lines": [],
  188. }
  189. tck_levels = gi["tick_levels"]
  190. tck_locs = gi["tick_locs"]
  191. for (lx, ly), v, lev in zip(lines, values, levs):
  192. tcks = _find_line_box_crossings(np.column_stack([lx, ly]), bb)
  193. gi["levels"].append(v)
  194. gi["lines"].append([(lx, ly)])
  195. for tck, direction in zip(tcks,
  196. ["left", "right", "bottom", "top"]):
  197. for t in tck:
  198. tck_levels[direction].append(lev)
  199. tck_locs[direction].append(t)
  200. return gi
  201. def set_transform(self, aux_trans):
  202. if isinstance(aux_trans, Transform):
  203. self._aux_transform = aux_trans
  204. elif len(aux_trans) == 2 and all(map(callable, aux_trans)):
  205. self._aux_transform = _User2DTransform(*aux_trans)
  206. else:
  207. raise TypeError("'aux_trans' must be either a Transform "
  208. "instance or a pair of callables")
  209. def get_transform(self):
  210. return self._aux_transform
  211. update_transform = set_transform # backcompat alias.
  212. def transform_xy(self, x, y):
  213. return self._aux_transform.transform(np.column_stack([x, y])).T
  214. def inv_transform_xy(self, x, y):
  215. return self._aux_transform.inverted().transform(
  216. np.column_stack([x, y])).T
  217. def update(self, **kwargs):
  218. for k, v in kwargs.items():
  219. if k in ["extreme_finder",
  220. "grid_locator1",
  221. "grid_locator2",
  222. "tick_formatter1",
  223. "tick_formatter2"]:
  224. setattr(self, k, v)
  225. else:
  226. raise ValueError(f"Unknown update property {k!r}")
  227. class MaxNLocator(mticker.MaxNLocator):
  228. def __init__(self, nbins=10, steps=None,
  229. trim=True,
  230. integer=False,
  231. symmetric=False,
  232. prune=None):
  233. # trim argument has no effect. It has been left for API compatibility
  234. super().__init__(nbins, steps=steps, integer=integer,
  235. symmetric=symmetric, prune=prune)
  236. self.create_dummy_axis()
  237. def __call__(self, v1, v2):
  238. locs = super().tick_values(v1, v2)
  239. return np.array(locs), len(locs), 1 # 1: factor (see angle_helper)
  240. class FixedLocator:
  241. def __init__(self, locs):
  242. self._locs = locs
  243. def __call__(self, v1, v2):
  244. v1, v2 = sorted([v1, v2])
  245. locs = np.array([l for l in self._locs if v1 <= l <= v2])
  246. return locs, len(locs), 1 # 1: factor (see angle_helper)
  247. # Tick Formatter
  248. class FormatterPrettyPrint:
  249. def __init__(self, useMathText=True):
  250. self._fmt = mticker.ScalarFormatter(
  251. useMathText=useMathText, useOffset=False)
  252. self._fmt.create_dummy_axis()
  253. def __call__(self, direction, factor, values):
  254. return self._fmt.format_ticks(values)
  255. class DictFormatter:
  256. def __init__(self, format_dict, formatter=None):
  257. """
  258. format_dict : dictionary for format strings to be used.
  259. formatter : fall-back formatter
  260. """
  261. super().__init__()
  262. self._format_dict = format_dict
  263. self._fallback_formatter = formatter
  264. def __call__(self, direction, factor, values):
  265. """
  266. factor is ignored if value is found in the dictionary
  267. """
  268. if self._fallback_formatter:
  269. fallback_strings = self._fallback_formatter(
  270. direction, factor, values)
  271. else:
  272. fallback_strings = [""] * len(values)
  273. return [self._format_dict.get(k, v)
  274. for k, v in zip(values, fallback_strings)]