__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING
  3. import numpy as np
  4. from contourpy._contourpy import (
  5. ContourGenerator,
  6. FillType,
  7. LineType,
  8. Mpl2005ContourGenerator,
  9. Mpl2014ContourGenerator,
  10. SerialContourGenerator,
  11. ThreadedContourGenerator,
  12. ZInterp,
  13. max_threads,
  14. )
  15. from contourpy._version import __version__
  16. from contourpy.chunk import calc_chunk_sizes
  17. from contourpy.convert import (
  18. convert_filled,
  19. convert_lines,
  20. convert_multi_filled,
  21. convert_multi_lines,
  22. )
  23. from contourpy.dechunk import (
  24. dechunk_filled,
  25. dechunk_lines,
  26. dechunk_multi_filled,
  27. dechunk_multi_lines,
  28. )
  29. from contourpy.enum_util import as_fill_type, as_line_type, as_z_interp
  30. if TYPE_CHECKING:
  31. from typing import Any
  32. from numpy.typing import ArrayLike
  33. from ._contourpy import CoordinateArray, MaskArray
  34. __all__ = [
  35. "__version__",
  36. "contour_generator",
  37. "convert_filled",
  38. "convert_lines",
  39. "convert_multi_filled",
  40. "convert_multi_lines",
  41. "dechunk_filled",
  42. "dechunk_lines",
  43. "dechunk_multi_filled",
  44. "dechunk_multi_lines",
  45. "max_threads",
  46. "FillType",
  47. "LineType",
  48. "ContourGenerator",
  49. "Mpl2005ContourGenerator",
  50. "Mpl2014ContourGenerator",
  51. "SerialContourGenerator",
  52. "ThreadedContourGenerator",
  53. "ZInterp",
  54. ]
  55. # Simple mapping of algorithm name to class name.
  56. _class_lookup: dict[str, type[ContourGenerator]] = {
  57. "mpl2005": Mpl2005ContourGenerator,
  58. "mpl2014": Mpl2014ContourGenerator,
  59. "serial": SerialContourGenerator,
  60. "threaded": ThreadedContourGenerator,
  61. }
  62. def _remove_z_mask(
  63. z: ArrayLike | np.ma.MaskedArray[Any, Any] | None,
  64. ) -> tuple[CoordinateArray, MaskArray | None]:
  65. # Preserve mask if present.
  66. z_array = np.ma.asarray(z, dtype=np.float64) # type: ignore[no-untyped-call]
  67. z_masked = np.ma.masked_invalid(z_array, copy=False) # type: ignore[no-untyped-call]
  68. if np.ma.is_masked(z_masked):
  69. mask = np.ma.getmask(z_masked)
  70. else:
  71. mask = None
  72. return np.ma.getdata(z_masked), mask # type: ignore[no-untyped-call]
  73. def contour_generator(
  74. x: ArrayLike | None = None,
  75. y: ArrayLike | None = None,
  76. z: ArrayLike | np.ma.MaskedArray[Any, Any] | None = None,
  77. *,
  78. name: str = "serial",
  79. corner_mask: bool | None = None,
  80. line_type: LineType | str | None = None,
  81. fill_type: FillType | str | None = None,
  82. chunk_size: int | tuple[int, int] | None = None,
  83. chunk_count: int | tuple[int, int] | None = None,
  84. total_chunk_count: int | None = None,
  85. quad_as_tri: bool = False,
  86. z_interp: ZInterp | str | None = ZInterp.Linear,
  87. thread_count: int = 0,
  88. ) -> ContourGenerator:
  89. """Create and return a :class:`~.ContourGenerator` object.
  90. The class and properties of the returned :class:`~.ContourGenerator` are determined by the
  91. function arguments, with sensible defaults.
  92. Args:
  93. x (array-like of shape (ny, nx) or (nx,), optional): The x-coordinates of the ``z`` values.
  94. May be 2D with the same shape as ``z.shape``, or 1D with length ``nx = z.shape[1]``.
  95. If not specified are assumed to be ``np.arange(nx)``. Must be ordered monotonically.
  96. y (array-like of shape (ny, nx) or (ny,), optional): The y-coordinates of the ``z`` values.
  97. May be 2D with the same shape as ``z.shape``, or 1D with length ``ny = z.shape[0]``.
  98. If not specified are assumed to be ``np.arange(ny)``. Must be ordered monotonically.
  99. z (array-like of shape (ny, nx), may be a masked array): The 2D gridded values to calculate
  100. the contours of. May be a masked array, and any invalid values (``np.inf`` or
  101. ``np.nan``) will also be masked out.
  102. name (str): Algorithm name, one of ``"serial"``, ``"threaded"``, ``"mpl2005"`` or
  103. ``"mpl2014"``, default ``"serial"``.
  104. corner_mask (bool, optional): Enable/disable corner masking, which only has an effect if
  105. ``z`` is a masked array. If ``False``, any quad touching a masked point is masked out.
  106. If ``True``, only the triangular corners of quads nearest these points are always masked
  107. out, other triangular corners comprising three unmasked points are contoured as usual.
  108. If not specified, uses the default provided by the algorithm ``name``.
  109. line_type (LineType or str, optional): The format of contour line data returned from calls
  110. to :meth:`~.ContourGenerator.lines`, specified either as a :class:`~.LineType` or its
  111. string equivalent such as ``"SeparateCode"``.
  112. If not specified, uses the default provided by the algorithm ``name``.
  113. The relationship between the :class:`~.LineType` enum and the data format returned from
  114. :meth:`~.ContourGenerator.lines` is explained at :ref:`line_type`.
  115. fill_type (FillType or str, optional): The format of filled contour data returned from calls
  116. to :meth:`~.ContourGenerator.filled`, specified either as a :class:`~.FillType` or its
  117. string equivalent such as ``"OuterOffset"``.
  118. If not specified, uses the default provided by the algorithm ``name``.
  119. The relationship between the :class:`~.FillType` enum and the data format returned from
  120. :meth:`~.ContourGenerator.filled` is explained at :ref:`fill_type`.
  121. chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same
  122. size in both directions if only one value is specified.
  123. chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the
  124. same count in both directions if only one value is specified.
  125. total_chunk_count (int, optional): Total number of chunks.
  126. quad_as_tri (bool): Enable/disable treating quads as 4 triangles, default ``False``.
  127. If ``False``, a contour line within a quad is a straight line between points on two of
  128. its edges. If ``True``, each full quad is divided into 4 triangles using a virtual point
  129. at the centre (mean x, y of the corner points) and a contour line is piecewise linear
  130. within those triangles. Corner-masked triangles are not affected by this setting, only
  131. full unmasked quads.
  132. z_interp (ZInterp or str, optional): How to interpolate ``z`` values when determining where
  133. contour lines intersect the edges of quads and the ``z`` values of the central points of
  134. quads, specified either as a :class:`~contourpy.ZInterp` or its string equivalent such
  135. as ``"Log"``. Default is ``ZInterp.Linear``.
  136. thread_count (int): Number of threads to use for contour calculation, default 0. Threads can
  137. only be used with an algorithm ``name`` that supports threads (currently only
  138. ``name="threaded"``) and there must be at least the same number of chunks as threads.
  139. If ``thread_count=0`` and ``name="threaded"`` then it uses the maximum number of threads
  140. as determined by the C++11 call ``std::thread::hardware_concurrency()``. If ``name`` is
  141. something other than ``"threaded"`` then the ``thread_count`` will be set to ``1``.
  142. Return:
  143. :class:`~.ContourGenerator`.
  144. Note:
  145. A maximum of one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` may be
  146. specified.
  147. Warning:
  148. The ``name="mpl2005"`` algorithm does not implement chunking for contour lines.
  149. """
  150. x = np.asarray(x, dtype=np.float64)
  151. y = np.asarray(y, dtype=np.float64)
  152. z, mask = _remove_z_mask(z)
  153. # Check arguments: z.
  154. if z.ndim != 2:
  155. raise TypeError(f"Input z must be 2D, not {z.ndim}D")
  156. if z.shape[0] < 2 or z.shape[1] < 2:
  157. raise TypeError(f"Input z must be at least a (2, 2) shaped array, but has shape {z.shape}")
  158. ny, nx = z.shape
  159. # Check arguments: x and y.
  160. if x.ndim != y.ndim:
  161. raise TypeError(f"Number of dimensions of x ({x.ndim}) and y ({y.ndim}) do not match")
  162. if x.ndim == 0:
  163. x = np.arange(nx, dtype=np.float64)
  164. y = np.arange(ny, dtype=np.float64)
  165. x, y = np.meshgrid(x, y)
  166. elif x.ndim == 1:
  167. if len(x) != nx:
  168. raise TypeError(f"Length of x ({len(x)}) must match number of columns in z ({nx})")
  169. if len(y) != ny:
  170. raise TypeError(f"Length of y ({len(y)}) must match number of rows in z ({ny})")
  171. x, y = np.meshgrid(x, y)
  172. elif x.ndim == 2:
  173. if x.shape != z.shape:
  174. raise TypeError(f"Shapes of x {x.shape} and z {z.shape} do not match")
  175. if y.shape != z.shape:
  176. raise TypeError(f"Shapes of y {y.shape} and z {z.shape} do not match")
  177. else:
  178. raise TypeError(f"Inputs x and y must be None, 1D or 2D, not {x.ndim}D")
  179. # Check mask shape just in case.
  180. if mask is not None and mask.shape != z.shape:
  181. raise ValueError("If mask is set it must be a 2D array with the same shape as z")
  182. # Check arguments: name.
  183. if name not in _class_lookup:
  184. raise ValueError(f"Unrecognised contour generator name: {name}")
  185. # Check arguments: chunk_size, chunk_count and total_chunk_count.
  186. y_chunk_size, x_chunk_size = calc_chunk_sizes(
  187. chunk_size, chunk_count, total_chunk_count, ny, nx)
  188. cls = _class_lookup[name]
  189. # Check arguments: corner_mask.
  190. if corner_mask is None:
  191. # Set it to default, which is True if the algorithm supports it.
  192. corner_mask = cls.supports_corner_mask()
  193. elif corner_mask and not cls.supports_corner_mask():
  194. raise ValueError(f"{name} contour generator does not support corner_mask=True")
  195. # Check arguments: line_type.
  196. if line_type is None:
  197. line_type = cls.default_line_type
  198. else:
  199. line_type = as_line_type(line_type)
  200. if not cls.supports_line_type(line_type):
  201. raise ValueError(f"{name} contour generator does not support line_type {line_type}")
  202. # Check arguments: fill_type.
  203. if fill_type is None:
  204. fill_type = cls.default_fill_type
  205. else:
  206. fill_type = as_fill_type(fill_type)
  207. if not cls.supports_fill_type(fill_type):
  208. raise ValueError(f"{name} contour generator does not support fill_type {fill_type}")
  209. # Check arguments: quad_as_tri.
  210. if quad_as_tri and not cls.supports_quad_as_tri():
  211. raise ValueError(f"{name} contour generator does not support quad_as_tri=True")
  212. # Check arguments: z_interp.
  213. if z_interp is None:
  214. z_interp = ZInterp.Linear
  215. else:
  216. z_interp = as_z_interp(z_interp)
  217. if z_interp != ZInterp.Linear and not cls.supports_z_interp():
  218. raise ValueError(f"{name} contour generator does not support z_interp {z_interp}")
  219. # Check arguments: thread_count.
  220. if thread_count not in (0, 1) and not cls.supports_threads():
  221. raise ValueError(f"{name} contour generator does not support thread_count {thread_count}")
  222. # Prepare args and kwargs for contour generator constructor.
  223. args = [x, y, z, mask]
  224. kwargs: dict[str, int | bool | LineType | FillType | ZInterp] = {
  225. "x_chunk_size": x_chunk_size,
  226. "y_chunk_size": y_chunk_size,
  227. }
  228. if name not in ("mpl2005", "mpl2014"):
  229. kwargs["line_type"] = line_type
  230. kwargs["fill_type"] = fill_type
  231. if cls.supports_corner_mask():
  232. kwargs["corner_mask"] = corner_mask
  233. if cls.supports_quad_as_tri():
  234. kwargs["quad_as_tri"] = quad_as_tri
  235. if cls.supports_z_interp():
  236. kwargs["z_interp"] = z_interp
  237. if cls.supports_threads():
  238. kwargs["thread_count"] = thread_count
  239. # Create contour generator.
  240. return cls(*args, **kwargs)