__init__.py 10 KB

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