__init__.py 11 KB

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