diff --git a/docs/conf.py b/docs/conf.py index 75afe2b64..e9dafdbcc 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -29,16 +29,11 @@ import uxarray -__all__ = (uxarray, matplotlib.pyplot) - sys.path.insert(0, os.path.abspath("../")) # Source code dir relative to this file LOGGER = logging.getLogger("conf") -try: - from unittest.mock import MagicMock -except ImportError: - from mock import Mock as MagicMock +from unittest.mock import MagicMock class Mock(MagicMock): @@ -137,7 +132,7 @@ def __getattr__(cls, name): project = "uxarray" current_year = datetime.datetime.now().year -copyright = "{}, UXarray".format(current_year) +copyright = f"{current_year}, UXarray" author = "UXARRAY" # The language for content autogenerated by Sphinx. Refer to documentation diff --git a/docs/examples/e3sm-calc-workflow.ipynb b/docs/examples/e3sm-calc-workflow.ipynb old mode 100755 new mode 100644 diff --git a/docs/examples/visualization/mpas-hurricane-maria-contours.ipynb b/docs/examples/visualization/mpas-hurricane-maria-contours.ipynb index ab26a17d9..a6c870c4f 100644 --- a/docs/examples/visualization/mpas-hurricane-maria-contours.ipynb +++ b/docs/examples/visualization/mpas-hurricane-maria-contours.ipynb @@ -130,7 +130,7 @@ } ], "source": [ - "storm_box = dict(lon_bounds=(-71, -59), lat_bounds=(13, 22))\n", + "storm_box = {\"lon_bounds\": (-71, -59), \"lat_bounds\": (13, 22)}\n", "\n", "mslp_storm = mslp.subset.bounding_box(**storm_box)\n", "wind_storm = wind.subset.bounding_box(**storm_box)\n", @@ -993,7 +993,7 @@ "metadata": {}, "outputs": [], "source": [ - "region_box = dict(lon_bounds=(-105, -35), lat_bounds=(0, 48))\n", + "region_box = {\"lon_bounds\": (-105, -35), \"lat_bounds\": (0, 48)}\n", "\n", "z500_region = z500.subset.bounding_box(**region_box)\n", "pw_region = pw.subset.bounding_box(**region_box)" diff --git a/docs/user-guide/area_calc.ipynb b/docs/user-guide/area_calc.ipynb index 349b720a4..9000735b3 100644 --- a/docs/user-guide/area_calc.ipynb +++ b/docs/user-guide/area_calc.ipynb @@ -2337,9 +2337,7 @@ "print(\"Area calculated using Gaussian Quadrature Order 2: \", area_gaussian)\n", "\n", "print(\n", - " \"Percentage difference between gaussian area above and corrected area: {:.4f}%\".format(\n", - " (corrected_area - area_gaussian) / corrected_area * 100\n", - " )\n", + " f\"Percentage difference between gaussian area above and corrected area: {(corrected_area - area_gaussian) / corrected_area * 100:.4f}%\"\n", ")" ] }, @@ -2524,7 +2522,6 @@ "source": [ "verts_grid = ux.open_grid(faces_verts_ndarray, latlon=True)\n", "\n", - "verts_grid\n", "verts_grid.plot()" ] }, diff --git a/docs/user-guide/mpl.ipynb b/docs/user-guide/mpl.ipynb index a59b12b72..24a3702e2 100644 --- a/docs/user-guide/mpl.ipynb +++ b/docs/user-guide/mpl.ipynb @@ -367,7 +367,7 @@ " 1,\n", " facecolor=\"w\",\n", " constrained_layout=True,\n", - " subplot_kw=dict(projection=projection),\n", + " subplot_kw={\"projection\": projection},\n", ")\n", "\n", "ax.add_feature(cfeature.COASTLINE)\n", @@ -418,7 +418,7 @@ " figsize=(7, 3.5),\n", " facecolor=\"w\",\n", " constrained_layout=True,\n", - " subplot_kw=dict(projection=projection),\n", + " subplot_kw={\"projection\": projection},\n", ")\n", "\n", "ax.set_extent(lon_bounds + lat_bounds)\n", @@ -475,7 +475,7 @@ " 1,\n", " facecolor=\"w\",\n", " constrained_layout=True,\n", - " subplot_kw=dict(projection=projection),\n", + " subplot_kw={\"projection\": projection},\n", ")\n", "\n", "ax.add_feature(cfeature.COASTLINE)\n", diff --git a/docs/user-guide/parallel-load-ux-with-dask.ipynb b/docs/user-guide/parallel-load-ux-with-dask.ipynb index 8de33730b..7f322f290 100644 --- a/docs/user-guide/parallel-load-ux-with-dask.ipynb +++ b/docs/user-guide/parallel-load-ux-with-dask.ipynb @@ -6806,9 +6806,9 @@ "metadata": {}, "outputs": [], "source": [ - "face_chunk = round(41_943_042 // 256)\n", - "node_chunk = round(83_886_080 // 256)\n", - "edge_chunk = round(125_829_120 // 256)" + "face_chunk = 41_943_042 // 256\n", + "node_chunk = 83_886_080 // 256\n", + "edge_chunk = 125_829_120 // 256" ] }, { diff --git a/docs/user-guide/zonal-average.ipynb b/docs/user-guide/zonal-average.ipynb index 6145b4ecc..a1f275981 100644 --- a/docs/user-guide/zonal-average.ipynb +++ b/docs/user-guide/zonal-average.ipynb @@ -39,8 +39,8 @@ "source": [ "from pathlib import Path\n", "\n", - "import hvplot.pandas # noqa: F401 - activate pandas hvplot accessor\n", - "import hvplot.xarray # noqa: F401 - activate xarray hvplot accessor\n", + "import hvplot.pandas # activate pandas hvplot accessor\n", + "import hvplot.xarray # activate xarray hvplot accessor\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import xarray as xr\n", diff --git a/uxarray/__init__.py b/uxarray/__init__.py index 677e2f7b6..e6f35f934 100644 --- a/uxarray/__init__.py +++ b/uxarray/__init__.py @@ -1,3 +1,6 @@ +from importlib.metadata import PackageNotFoundError +from importlib.metadata import version as _version + from . import errors, tutorial from .constants import INT_DTYPE, INT_FILL_VALUE from .core.api import ( @@ -12,30 +15,25 @@ from .core.dataset import UxDataset from .grid import Grid -try: - from importlib.metadata import version as _version -except Exception: - from importlib_metadata import version as _version - try: __version__ = _version("uxarray") -except Exception: +except PackageNotFoundError: # Placeholder version incase an error occurs, such as the library isn't installed __version__ = "999" __all__ = ( - "open_grid", - "open_dataset", - "open_mfdataset", - "open_multigrid", - "list_grid_names", - "concat", - "tutorial", - "UxDataset", - "UxDataArray", "INT_DTYPE", "INT_FILL_VALUE", "Grid", + "UxDataArray", + "UxDataset", + "concat", "errors", + "list_grid_names", + "open_dataset", + "open_grid", + "open_mfdataset", + "open_multigrid", + "tutorial", ) diff --git a/uxarray/core/__init__.py b/uxarray/core/__init__.py index c368ef101..106ba99cd 100644 --- a/uxarray/core/__init__.py +++ b/uxarray/core/__init__.py @@ -3,9 +3,9 @@ from .dataset import UxDataset __all__ = ( - "open_grid", + "UxDataArray", + "UxDataset", "open_dataset", + "open_grid", "open_mfdataset", - "UxDataset", - "UxDataArray", ) diff --git a/uxarray/core/accessors.py b/uxarray/core/accessors.py index fdc7aef55..0867325b5 100644 --- a/uxarray/core/accessors.py +++ b/uxarray/core/accessors.py @@ -5,7 +5,7 @@ operations return UxDataArray/UxDataset objects with preserved uxgrid. """ -from typing import Any +from typing import Any, ClassVar import xarray as xr @@ -37,7 +37,7 @@ class BaseAccessor: """Base class for all UXarray accessor classes.""" # Default methods known to return DataArrays/Datasets - optimized for performance - _DEFAULT_PRESERVE_METHODS = { + _DEFAULT_PRESERVE_METHODS: ClassVar[set[str]] = { "mean", "sum", "std", @@ -102,7 +102,7 @@ def _should_wrap_method(self, name: str) -> bool: """Determine if a method should be wrapped.""" if self._auto_wrap: # In auto-wrap mode, check if it's callable - return hasattr(getattr(self._xr_obj, name, None), "__call__") + return callable(getattr(self._xr_obj, name, None)) return name in self._preserve_methods def _wrap_method(self, method): @@ -132,7 +132,7 @@ def __len__(self): def __repr__(self): # Subclasses should override this for specific names - return f"{self.__class__.__name__}({repr(self._xr_obj)})" + return f"{self.__class__.__name__}({self._xr_obj!r})" def __dir__(self): # Combine our methods with xarray's for better IDE support @@ -192,7 +192,7 @@ def _process_result(self, result): return result def __repr__(self): - return f"UxDataArrayGroupBy({repr(self._xr_obj)})" + return f"UxDataArrayGroupBy({self._xr_obj!r})" class UxDatasetGroupByAccessor(BaseAccessor): @@ -213,7 +213,7 @@ def _process_result(self, result): return result def __repr__(self): - return f"UxDatasetGroupBy({repr(self._xr_obj)})" + return f"UxDatasetGroupBy({self._xr_obj!r})" # Similar accessors for other operations @@ -221,67 +221,67 @@ class UxDataArrayResampleAccessor(UxDataArrayGroupByAccessor): """Wraps xarray DataArrayResample to preserve uxgrid in results.""" def __repr__(self): - return f"UxDataArrayResample({repr(self._xr_obj)})" + return f"UxDataArrayResample({self._xr_obj!r})" class UxDatasetResampleAccessor(UxDatasetGroupByAccessor): """Wraps xarray DatasetResample to preserve uxgrid in results.""" def __repr__(self): - return f"UxDatasetResample({repr(self._xr_obj)})" + return f"UxDatasetResample({self._xr_obj!r})" class UxDataArrayRollingAccessor(UxDataArrayGroupByAccessor): """Wraps xarray DataArrayRolling to preserve uxgrid in results.""" def __repr__(self): - return f"UxDataArrayRolling({repr(self._xr_obj)})" + return f"UxDataArrayRolling({self._xr_obj!r})" class UxDatasetRollingAccessor(UxDatasetGroupByAccessor): """Wraps xarray DatasetRolling to preserve uxgrid in results.""" def __repr__(self): - return f"UxDatasetRolling({repr(self._xr_obj)})" + return f"UxDatasetRolling({self._xr_obj!r})" class UxDataArrayCoarsenAccessor(UxDataArrayGroupByAccessor): """Wraps xarray DataArrayCoarsen to preserve uxgrid in results.""" def __repr__(self): - return f"UxDataArrayCoarsen({repr(self._xr_obj)})" + return f"UxDataArrayCoarsen({self._xr_obj!r})" class UxDatasetCoarsenAccessor(UxDatasetGroupByAccessor): """Wraps xarray DatasetCoarsen to preserve uxgrid in results.""" def __repr__(self): - return f"UxDatasetCoarsen({repr(self._xr_obj)})" + return f"UxDatasetCoarsen({self._xr_obj!r})" class UxDataArrayWeightedAccessor(UxDataArrayGroupByAccessor): """Wraps xarray DataArrayWeighted to preserve uxgrid in results.""" def __repr__(self): - return f"UxDataArrayWeighted({repr(self._xr_obj)})" + return f"UxDataArrayWeighted({self._xr_obj!r})" class UxDatasetWeightedAccessor(UxDatasetGroupByAccessor): """Wraps xarray DatasetWeighted to preserve uxgrid in results.""" def __repr__(self): - return f"UxDatasetWeighted({repr(self._xr_obj)})" + return f"UxDatasetWeighted({self._xr_obj!r})" class UxDataArrayRollingExpAccessor(UxDataArrayGroupByAccessor): """Wraps xarray DataArrayRollingExp to preserve uxgrid in results.""" def __repr__(self): - return f"UxDataArrayRollingExp({repr(self._xr_obj)})" + return f"UxDataArrayRollingExp({self._xr_obj!r})" class UxDatasetRollingExpAccessor(UxDatasetGroupByAccessor): """Wraps xarray DatasetRollingExp to preserve uxgrid in results.""" def __repr__(self): - return f"UxDatasetRollingExp({repr(self._xr_obj)})" + return f"UxDatasetRollingExp({self._xr_obj!r})" diff --git a/uxarray/core/aggregation.py b/uxarray/core/aggregation.py index b6d561eff..b01d34bd5 100644 --- a/uxarray/core/aggregation.py +++ b/uxarray/core/aggregation.py @@ -103,7 +103,7 @@ def _node_to_face_kernel( change_ind, n_nodes_per_face_sorted_ind, element_sizes, - size_counts, + _size_counts, ) = get_face_node_partitions(n_nodes_per_face) result = np.empty(shape=(data.shape[:-1]) + (n_face,)) diff --git a/uxarray/core/api.py b/uxarray/core/api.py index c0a6336c1..c3476ffd9 100644 --- a/uxarray/core/api.py +++ b/uxarray/core/api.py @@ -1,8 +1,9 @@ from __future__ import annotations import os +from collections.abc import Hashable, Iterable, Mapping, Sequence from pathlib import Path -from typing import Any, Hashable, Iterable, Mapping, Sequence, TypeAlias +from typing import Any from warnings import warn import numpy as np @@ -27,11 +28,11 @@ ) __all__ = [ - "open_grid", - "open_multigrid", "list_grid_names", "open_dataset", + "open_grid", "open_mfdataset", + "open_multigrid", ] @@ -158,8 +159,8 @@ def open_grid( return grid -MaskValue: TypeAlias = Any | Sequence[Any] -MaskActiveValue: TypeAlias = MaskValue | Mapping[str, MaskValue] | None +type MaskValue = Any | Sequence[Any] +type MaskActiveValue = MaskValue | Mapping[str, MaskValue] | None def open_multigrid( diff --git a/uxarray/core/arithmetic.py b/uxarray/core/arithmetic.py index 00170b6b6..0c0458077 100644 --- a/uxarray/core/arithmetic.py +++ b/uxarray/core/arithmetic.py @@ -91,17 +91,16 @@ def _raise_if_grids_incompatible_during(self, other, f): OR if either grid has n_face==1 (to avoid breaking "scalar-like" workflows, because isel(n_face=int) maybe should provide scalar, but currently doesn't). """ - if isinstance(other, UxSupportsArithmetic): - if ( - (self.uxgrid.n_face > 1) - and (other.uxgrid.n_face > 1) - and (self.uxgrid != other.uxgrid) - ): - raise GridsMismatchError( - f"A.uxgrid != B.uxgrid during binary operation {f.__name__!r}, " - f"with type(A)={type(self).__name__}, type(B)={type(other).__name__}. " - f"(Got A.uxgrid.sizes={self.uxgrid.sizes}; B.uxgrid.sizes={other.uxgrid.sizes}.)" - ) + if isinstance(other, UxSupportsArithmetic) and ( + (self.uxgrid.n_face > 1) + and (other.uxgrid.n_face > 1) + and (self.uxgrid != other.uxgrid) + ): + raise GridsMismatchError( + f"A.uxgrid != B.uxgrid during binary operation {f.__name__!r}, " + f"with type(A)={type(self).__name__}, type(B)={type(other).__name__}. " + f"(Got A.uxgrid.sizes={self.uxgrid.sizes}; B.uxgrid.sizes={other.uxgrid.sizes}.)" + ) def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): """Like super().__array_ufunc__, except that if multiple inputs have a uxgrid, diff --git a/uxarray/core/dataarray.py b/uxarray/core/dataarray.py index dd3efc620..d6553e868 100644 --- a/uxarray/core/dataarray.py +++ b/uxarray/core/dataarray.py @@ -1,8 +1,9 @@ from __future__ import annotations import warnings +from collections.abc import Hashable, Iterable, Mapping from html import escape -from typing import TYPE_CHECKING, Any, Hashable, Iterable, Literal, Mapping, Optional +from typing import TYPE_CHECKING, Any, Literal from warnings import warn import numpy as np @@ -194,7 +195,7 @@ def _grid_dims(self) -> set[str]: """set of all grid dimensions associated with self. This is a (possibly-empty) subset of {"n_face", "n_edge", "n_node"}. """ - return set(d for d in GRID_DIMS if d in self.dims) + return {d for d in GRID_DIMS if d in self.dims} @property def _grid_dim(self) -> str: @@ -343,7 +344,7 @@ def to_geodataframe( def to_polycollection( self, periodic_elements: str = "exclude", - projection: Optional[ccrs.Projection] = None, + projection: ccrs.Projection | None = None, return_indices: bool = False, cache: bool = True, override: bool = False, @@ -561,7 +562,7 @@ def _is_default_extent() -> bool: "ax.set_extent(...), or ax.set_xlim(...) + ax.set_ylim(...).", stacklevel=2, ) - except Exception as e: + except Exception as e: # noqa: BLE001 warn( f"Failed to auto-set extent from grid bounds: {e}", stacklevel=2, @@ -824,7 +825,7 @@ def zonal_mean(self, lat=(-90, 90, 10), conservative: bool = False, **kwargs): UserWarning, stacklevel=2, ) - num_points = int(round((end - start) / step)) + 1 + num_points = round((end - start) / step) + 1 latitudes = np.linspace(start, end, num_points) latitudes = np.clip(latitudes, -90, 90) elif isinstance(lat, (float, int)): @@ -873,7 +874,7 @@ def zonal_mean(self, lat=(-90, 90, 10), conservative: bool = False, **kwargs): UserWarning, stacklevel=2, ) - num_points = int(round((end - start) / step)) + 1 + num_points = round((end - start) / step) + 1 edges = np.linspace(start, end, num_points) edges = np.clip(edges, -90, 90) elif isinstance(lat, (list, np.ndarray)): @@ -972,7 +973,7 @@ def zonal_anomaly(self, lat=(-90, 90, 10), conservative: bool = False): raise ValueError( f"Expected step>0 when lat=(min_lat, max_lat, step); got step={step}" ) - num_points = int(round((end - start) / step)) + 1 + num_points = round((end - start) / step) + 1 edges = np.linspace(start, end, num_points) edges = np.clip(edges, -90, 90) elif isinstance(lat, (list, np.ndarray)): @@ -1005,8 +1006,8 @@ def zonal_anomaly(self, lat=(-90, 90, 10), conservative: bool = False): def azimuthal_mean( self, center_coord, - outer_radius: int | float, - radius_step: int | float, + outer_radius: float, + radius_step: float, return_hit_counts: bool = False, ): """Compute averages along circles of constant great-circle distance from a point. @@ -1198,7 +1199,7 @@ def weighted_mean(self, weights=None): # if weights and self both have coords on grid dim, ensure exact alignment, # otherwise xarray silently only keeps locations where coords agree. try: - self, weights = xr.align(self, weights, join="exact") + _, weights = xr.align(self, weights, join="exact") except xr.AlignmentError as err: raise DimensionError( f"For DataArray weights, expected alignment with data's grid dimension " @@ -1719,9 +1720,9 @@ def gradient(self, scale_by_radius: bool = True) -> UxDataset: def curl( self, - other: "UxDataArray", + other: UxDataArray, scale_by_radius: bool = True, - ) -> "UxDataArray": + ) -> UxDataArray: """ Computes the curl of the vector field defined by this UxDataArray and ``other``, in the horizontal direction (i.e., along the unstructured grid dimension). @@ -1799,10 +1800,10 @@ def curl( u, v = xr.align(self, other, join="exact", copy=False) # Compute gradients of both components - grad_u_zonal, grad_u_meridional = _compute_gradient( + _grad_u_zonal, grad_u_meridional = _compute_gradient( u, scale_by_radius=scale_by_radius ) - grad_v_zonal, grad_v_meridional = _compute_gradient( + grad_v_zonal, _grad_v_meridional = _compute_gradient( v, scale_by_radius=scale_by_radius ) @@ -1836,8 +1837,8 @@ def curl( return result def divergence( - self, other: "UxDataArray", scale_by_radius: bool = True, **kw_unused - ) -> "UxDataArray": + self, other: UxDataArray, scale_by_radius: bool = True, **kw_unused + ) -> UxDataArray: """ Computes the divergence of the vector field defined by this UxDataArray and ``other``, in the horizontal direction (i.e., along the unstructured grid dimension). @@ -1933,10 +1934,10 @@ def divergence( u, v = xr.align(self, other, join="exact", copy=False) # Compute gradients of both components - grad_u_zonal, grad_u_meridional = _compute_gradient( + grad_u_zonal, _grad_u_meridional = _compute_gradient( u, scale_by_radius=scale_by_radius ) - grad_v_zonal, grad_v_meridional = _compute_gradient( + _grad_v_zonal, grad_v_meridional = _compute_gradient( v, scale_by_radius=scale_by_radius ) @@ -1966,7 +1967,7 @@ def divergence( result = result.assign_attrs(attrs) return result - def scalardotgradient(self, v: "UxDataArray", q: "UxDataArray") -> "UxDataArray": + def scalardotgradient(self, v: UxDataArray, q: UxDataArray) -> UxDataArray: """ Compute the dot product between a vector field and the gradient of a scalar field. The formula is: scalar_dot_gradient = u * (dq/dx) + v * (dq/dy), @@ -2270,7 +2271,7 @@ def sel( self, indexers: Mapping[Any, Any] | None = None, method: str | None = None, - tolerance: int | float | Iterable[int | float] | None = None, + tolerance: float | Iterable[int | float] | None = None, drop: bool = False, **indexers_kwargs: Any, ): @@ -2370,7 +2371,7 @@ def sel( ) elif len(grid_dims) == 1: # pop off the one grid‐dim indexer - grid_dim = list(grid_dims)[0] + grid_dim = next(iter(grid_dims)) indexers = indexers.copy() # don't modify the original dict grid_indexer = indexers.pop(grid_dim) if grid_dim in self.coords: # label-based indexing @@ -2385,7 +2386,7 @@ def sel( # crash if provided `method` or `tolerance`, as promised in docstring; if method is not None or tolerance is not None: raise ValueError( - f"cannot supply selection options {dict(method=method, tolerance=tolerance)} " + f"cannot supply selection options { {'method': method, 'tolerance': tolerance} } " f"for dimension {grid_dim!r} that has no associated coordinate or index" ) grid_indices = grid_indexer @@ -2410,7 +2411,9 @@ def sel( raise AssertionError("internal implementation error if reached this line") @classmethod - def from_xarray(cls, da: xr.DataArray, uxgrid: Grid, ugrid_dims: dict = None): + def from_xarray( + cls, da: xr.DataArray, uxgrid: Grid, ugrid_dims: dict | None = None + ): """ Converts a ``xarray.DataArray`` into a ``uxarray.UxDataset`` paired with a user-defined ``Grid`` diff --git a/uxarray/core/dataset.py b/uxarray/core/dataset.py index 69c0b95c9..488ff6b88 100644 --- a/uxarray/core/dataset.py +++ b/uxarray/core/dataset.py @@ -2,8 +2,9 @@ import os import sys +from collections.abc import Hashable, Iterable, Mapping from html import escape -from typing import IO, Any, Hashable, Iterable, Mapping +from typing import IO, Any from warnings import warn import xarray as xr @@ -80,8 +81,8 @@ class UxDataset(UxSupportsArithmetic, xr.Dataset): # expected instance attributes, required for subclassing with xarray (as of v0.13.0) __slots__ = ( - "_uxgrid", "_source_datasets", + "_uxgrid", ) def __init__( @@ -209,7 +210,7 @@ def _grid_dims(self) -> set[str]: """set of all grid dimensions associated with self. This is a (possibly-empty) subset of {"n_face", "n_edge", "n_node"}. """ - return set(d for d in GRID_DIMS if d in self.dims) + return {d for d in GRID_DIMS if d in self.dims} @property def _grid_dim(self) -> str: @@ -339,7 +340,9 @@ def from_structured(cls, ds: xr.Dataset): return cls(ds, uxgrid=uxgrid) @classmethod - def from_xarray(cls, ds: xr.Dataset, uxgrid: Grid = None, ugrid_dims: dict = None): + def from_xarray( + cls, ds: xr.Dataset, uxgrid: Grid | None = None, ugrid_dims: dict | None = None + ): """ Converts a ``xarray.Dataset`` into a ``uxarray.UxDataset``, paired with either a user-defined or parsed ``Grid`` @@ -573,7 +576,7 @@ def sel( self, indexers: Mapping[Any, Any] | None = None, method: str | None = None, - tolerance: int | float | Iterable[int | float] | None = None, + tolerance: float | Iterable[int | float] | None = None, drop: bool = False, **indexers_kwargs: Any, ): @@ -676,7 +679,7 @@ def sel( ) elif len(grid_dims) == 1: # pop off the one grid‐dim indexer - grid_dim = list(grid_dims)[0] + grid_dim = next(iter(grid_dims)) indexers = indexers.copy() # don't modify the original dict grid_indexer = indexers.pop(grid_dim) if grid_dim in self.coords: # label-based indexing @@ -692,7 +695,7 @@ def sel( # (this error logic matches xarray's error logic in this case.) if method is not None or tolerance is not None: raise ValueError( - f"cannot supply selection options {dict(method=method, tolerance=tolerance)} " + f"cannot supply selection options { {'method': method, 'tolerance': tolerance} } " f"for dimension {grid_dim!r} that has no associated coordinate or index" ) grid_indices = grid_indexer @@ -746,7 +749,7 @@ def method(*args, **kwargs): # For all other attributes, use the default behavior return super().__getattribute__(name) - def info(self, buf: IO = None, show_attrs=False) -> None: + def info(self, buf: IO | None = None, show_attrs=False) -> None: """Concise summary of Dataset variables and attributes including grid topology information stored in the ``uxgrid`` property. @@ -1158,14 +1161,14 @@ def zonal_anomaly(self, lat=(-90, 90, 10), *, conservative: bool = False): For more details about parameters, see :meth:`UxDataArray.zonal_anomaly`. """ - kw = dict(lat=lat, conservative=conservative) + kw = {"lat": lat, "conservative": conservative} return self._apply_across_data_vars("zonal_anomaly", ("n_face",), **kw) def azimuthal_mean( self, center_coord, - outer_radius: int | float, - radius_step: int | float, + outer_radius: float, + radius_step: float, *, return_hit_counts: bool = False, ) -> xr.Dataset: @@ -1181,11 +1184,11 @@ def azimuthal_mean( raise NotImplementedError( f"{type(self).__name__}.azimuthal_mean(..., return_hit_counts=True)" ) - kw = dict( - center_coord=center_coord, - outer_radius=outer_radius, - radius_step=radius_step, - ) + kw = { + "center_coord": center_coord, + "outer_radius": outer_radius, + "radius_step": radius_step, + } return self._apply_across_data_vars("azimuthal_mean", ("n_face",), **kw) azimuthal_average = azimuthal_mean # alias diff --git a/uxarray/core/gradient.py b/uxarray/core/gradient.py index cf14cb06c..b49d913bf 100644 --- a/uxarray/core/gradient.py +++ b/uxarray/core/gradient.py @@ -59,9 +59,11 @@ def _check_face_on_boundary( for node_idx in face_node_connectivity[face_idx]: if node_idx != INT_FILL_VALUE: for edge_idx in node_edge_connectivity[node_idx]: - if edge_idx != INT_FILL_VALUE: - if INT_FILL_VALUE in edge_face_connectivity[edge_idx]: - bool_bdy = True + if ( + edge_idx != INT_FILL_VALUE + and INT_FILL_VALUE in edge_face_connectivity[edge_idx] + ): + bool_bdy = True return bool_bdy diff --git a/uxarray/core/utils.py b/uxarray/core/utils.py index cb22baafc..3facf9c5f 100644 --- a/uxarray/core/utils.py +++ b/uxarray/core/utils.py @@ -37,7 +37,7 @@ def _open_dataset_with_fallback(filename_or_obj, chunks=None, **kwargs): try: # Try opening with xarray's default read engine return xr.open_dataset(filename_or_obj, chunks=chunks, **kwargs) - except Exception as default_engine_error: + except Exception as default_engine_error: # noqa: BLE001 # If it fails, use the "netcdf4" engine as backup # Extract engine from kwargs to prevent duplicate parameter error engine = kwargs.pop("engine", "netcdf4") @@ -100,7 +100,7 @@ def _map_dims_to_ugrid( ds[var_name] = ds[var_name].stack(n_node=["nf", "YCdim", "XCdim"]) else: keys_to_drop = [] - for key in _source_dims_dict.keys(): + for key in _source_dims_dict: # obtain all dimensions not present in the original dataset if key not in ds.dims: keys_to_drop.append(key) @@ -331,17 +331,19 @@ def f_wrapped(*numpy_arrays): result_dims = uxarrays[0].dims xarrays = [arr.to_xarray() for arr in uxarrays] # make a helpful warning if chunked but didn't supply output_dtypes - if any(xarr.chunks is not None for xarr in xarrays): - if dask != "forbidden": - if "output_dtypes" not in kw_apply_ufunc: - warnings.warn( - f"Input uxarray objects are chunked while calling {f.__name__}, " - "with dask!='forbidden', but `output_dtypes` was not provided. " - "If this causes a ValueError: `dtype` inference failed in `apply_gufunc`, " - "that most likely indicates an implementation error in the function which " - "called _apply_1dfunc_with_grid_core_dim, but failed to supply output_dtypes " - "to it; that function should be updated accordingly." - ) + if ( + any(xarr.chunks is not None for xarr in xarrays) + and dask != "forbidden" + and "output_dtypes" not in kw_apply_ufunc + ): + warnings.warn( + f"Input uxarray objects are chunked while calling {f.__name__}, " + "with dask!='forbidden', but `output_dtypes` was not provided. " + "If this causes a ValueError: `dtype` inference failed in `apply_gufunc`, " + "that most likely indicates an implementation error in the function which " + "called _apply_1dfunc_with_grid_core_dim, but failed to supply output_dtypes " + "to it; that function should be updated accordingly." + ) # actually do the calculations: result = xr.apply_ufunc( diff --git a/uxarray/core/zonal.py b/uxarray/core/zonal.py index 77ca4bc90..9c404e09a 100644 --- a/uxarray/core/zonal.py +++ b/uxarray/core/zonal.py @@ -202,10 +202,9 @@ def _compute_band_overlap_area( # Add face vertices that lie within the band for e in range(face_edges_xyz.shape[0]): vertex = face_edges_xyz[e, 0] # First point of edge - if z_min <= vertex[2] <= z_max: - if point_count < max_points: - polygon_points[point_count] = vertex - point_count += 1 + if z_min <= vertex[2] <= z_max and point_count < max_points: + polygon_points[point_count] = vertex + point_count += 1 if point_count < 3: return 0.0 diff --git a/uxarray/formatting_html.py b/uxarray/formatting_html.py index 6efa625f6..628e2a323 100644 --- a/uxarray/formatting_html.py +++ b/uxarray/formatting_html.py @@ -27,15 +27,13 @@ def _grid_sections(grid, max_items_collapse=15): UserWarning, ) return [] - cartesian_coordinates = list( - [coord for coord in ugrid.CARTESIAN_COORDS if coord in grid._ds] - ) - spherical_coordinates = list( - [coord for coord in ugrid.SPHERICAL_COORDS if coord in grid._ds] - ) - descriptor = list( - [desc for desc in descriptors.DESCRIPTOR_NAMES if desc in grid._ds] - ) + cartesian_coordinates = [ + coord for coord in ugrid.CARTESIAN_COORDS if coord in grid._ds + ] + spherical_coordinates = [ + coord for coord in ugrid.SPHERICAL_COORDS if coord in grid._ds + ] + descriptor = [desc for desc in descriptors.DESCRIPTOR_NAMES if desc in grid._ds] connectivity = grid.connectivity sections = [xrfm.dim_section(grid._ds)] diff --git a/uxarray/grid/arcs.py b/uxarray/grid/arcs.py index dfe410988..886acd0b1 100644 --- a/uxarray/grid/arcs.py +++ b/uxarray/grid/arcs.py @@ -95,13 +95,8 @@ def point_within_gca(pt_xyz, gca_a_xyz, gca_b_xyz): cos_theta = _numba_dot3(pt_a, pt_b) # Return True if the point lies within the interval (smaller arc) - if cos_theta < 0: - return True - elif np.isclose(cos_theta, 0.0, atol=MACHINE_EPSILON): - # set error tolerance to 0.0 - return True - else: - return False + # (set error tolerance to 0.0) + return cos_theta < 0 or np.isclose(cos_theta, 0.0, atol=MACHINE_EPSILON) @njit(cache=True) @@ -246,8 +241,8 @@ def extreme_gca_latitude(gca_cart, gca_lonlat, extreme_type): denom = (n1[2] + n2[2]) * (dot_n1_n2 - 1.0) # Initialize latitudes - lon_n1, lat_n1 = gca_lonlat[0] - lon_n2, lat_n2 = gca_lonlat[1] + _lon_n1, lat_n1 = gca_lonlat[0] + _lon_n2, lat_n2 = gca_lonlat[1] # Check if denominator is zero to avoid division by zero if denom != 0.0: diff --git a/uxarray/grid/area.py b/uxarray/grid/area.py index a06a547c5..f039518fb 100644 --- a/uxarray/grid/area.py +++ b/uxarray/grid/area.py @@ -280,7 +280,7 @@ def _get_all_face_area_from_coords( y = np.asarray(y, dtype=np.float64) z = np.asarray(z, dtype=np.float64) - n_face, n_max_face_nodes = face_nodes.shape + n_face, _n_max_face_nodes = face_nodes.shape # Compute the quadrature points once (they depend only on the rule and order, # not on the face) and reuse them across all faces, instead of rebuilding them diff --git a/uxarray/grid/bounds.py b/uxarray/grid/bounds.py index 5a2b6d743..b441942a4 100644 --- a/uxarray/grid/bounds.py +++ b/uxarray/grid/bounds.py @@ -482,10 +482,8 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True): latlon_box[0, 1] = lat_pt else: # Update latitude range - if lat_pt < latlon_box[0, 0]: - latlon_box[0, 0] = lat_pt - if lat_pt > latlon_box[0, 1]: - latlon_box[0, 1] = lat_pt + latlon_box[0, 0] = min(latlon_box[0, 0], lat_pt) + latlon_box[0, 1] = max(latlon_box[0, 1], lat_pt) # Check if the longitude range is uninitialized and update it if np.isnan(old_box[1, 0]) and np.isnan(old_box[1, 1]): @@ -499,9 +497,8 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True): # Check for pole points is_pole_point = False - if np.isnan(lon_pt): - if any_close_lat(lat_pt, ERROR_TOLERANCE): - is_pole_point = True + if np.isnan(lon_pt) and any_close_lat(lat_pt, ERROR_TOLERANCE): + is_pole_point = True if is_pole_point: # Update latitude for pole points @@ -513,10 +510,8 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True): # Update longitude range based on periodicity if not is_lon_periodic: # Non-periodic: straightforward min and max updates - if lon_pt < latlon_box[1, 0]: - latlon_box[1, 0] = lon_pt - if lon_pt > latlon_box[1, 1]: - latlon_box[1, 1] = lon_pt + latlon_box[1, 0] = min(latlon_box[1, 0], lon_pt) + latlon_box[1, 1] = max(latlon_box[1, 1], lon_pt) else: # Periodic longitude handling # Determine if the new point extends the current longitude range diff --git a/uxarray/grid/connectivity.py b/uxarray/grid/connectivity.py index 365a2a8f0..c891b38f6 100644 --- a/uxarray/grid/connectivity.py +++ b/uxarray/grid/connectivity.py @@ -780,7 +780,7 @@ def _populate_node_face_connectivity(grid): and stores it within the internal (``Grid._ds``) and through the attribute (``Grid.node_face_connectivity``).""" - node_faces, n_max_faces_per_node = _build_node_face_connectivity( + node_faces, _n_max_faces_per_node = _build_node_face_connectivity( grid.face_node_connectivity.values, grid.n_node ) @@ -806,15 +806,14 @@ def _build_node_face_connectivity(face_nodes, n_node): """ node_face_conn = {node_i: [] for node_i in range(n_node)} - for face_i, face_nodes in enumerate(face_nodes): - for node_i in face_nodes: + for face_i, nodes in enumerate(face_nodes): + for node_i in nodes: if node_i != INT_FILL_VALUE: node_face_conn[node_i].append(face_i) n_max_node_faces = -1 for face_indicies in node_face_conn.values(): - if len(face_indicies) > n_max_node_faces: - n_max_node_faces = len(face_indicies) + n_max_node_faces = max(n_max_node_faces, len(face_indicies)) node_face_connectivity = np.full( (n_node, n_max_node_faces), INT_FILL_VALUE, dtype=INT_DTYPE @@ -956,8 +955,7 @@ def _build_node_edge_connectivity(edge_nodes, n_node): # find the maximum max_edges = 0 for i in range(n_node): - if counts[i] > max_edges: - max_edges = counts[i] + max_edges = max(max_edges, counts[i]) # allocate output, pad with fill node_edge = np.full((n_node, max_edges), INT_FILL_VALUE, dtype=INT_DTYPE) diff --git a/uxarray/grid/geometry.py b/uxarray/grid/geometry.py index 4e0e270a6..9a989a820 100644 --- a/uxarray/grid/geometry.py +++ b/uxarray/grid/geometry.py @@ -791,8 +791,6 @@ def _pole_point_inside_polygon_cartesian(pole, face_edges_xyz): return pole_point_inside_polygon(pole, face_edges_xyz, face_edges_lonlat) - pass - @njit(cache=True) def pole_point_inside_polygon(pole, face_edges_xyz, face_edges_lonlat): @@ -1182,8 +1180,7 @@ def _compute_face_radii( dy = node_y[idx] - fy dz = node_z[idx] - fz d2 = dx * dx + dy * dy + dz * dz - if d2 > face_max2: - face_max2 = d2 + face_max2 = max(face_max2, d2) max2_per_face[i] = face_max2 @@ -1314,7 +1311,7 @@ def barycentric_coordinates_cartesian(polygon_xyz, point_xyz): # find the triangle containing the point, # and use`triangle_line_intersection` algorithm to calculate the weights else: - for i in range(0, n - 2): + for i in range(n - 2): # Get the three points of the triangle node_0, node_1, node_2 = ( polygon_xyz[0], diff --git a/uxarray/grid/grid.py b/uxarray/grid/grid.py index 99039a882..7544e8ff0 100644 --- a/uxarray/grid/grid.py +++ b/uxarray/grid/grid.py @@ -3,8 +3,9 @@ import copy import os import warnings +from collections.abc import Sequence from html import escape -from typing import TYPE_CHECKING, Optional, Sequence +from typing import TYPE_CHECKING import numpy as np import xarray as xr @@ -179,13 +180,12 @@ def __init__( merge_coincident_nodes: bool = True, ): # check if inputted dataset is a minimum representable 2D UGRID unstructured grid - if source_grid_spec != "HEALPix": - if not _validate_minimum_ugrid(grid_ds): - raise GridInvalidError( - "Grid unable to be represented in the UGRID conventions. Representing an unstructured grid requires " - "at least the following variables: ['node_lon', 'node_lat', 'face_node_connectivity']," - f"\nbut got grid_ds with data_vars: {list(grid_ds.data_vars)}" - ) + if source_grid_spec != "HEALPix" and not _validate_minimum_ugrid(grid_ds): + raise GridInvalidError( + "Grid unable to be represented in the UGRID conventions. Representing an unstructured grid requires " + "at least the following variables: ['node_lon', 'node_lat', 'face_node_connectivity']," + f"\nbut got grid_ds with data_vars: {list(grid_ds.data_vars)}" + ) # TODO: more checks for validate grid (lat/lon coords, etc) # canonicalize coincident node indices in connectivity before this dataset @@ -504,7 +504,7 @@ def from_topology( node_lon: np.ndarray, node_lat: np.ndarray, face_node_connectivity: np.ndarray, - fill_value: int | float | None = None, + fill_value: float | None = None, start_index: int = 0, dims_dict: dict | None = None, **kwargs, @@ -767,15 +767,15 @@ def __repr__(self): coord_heading = "Grid Coordinates (Spherical):\n" coords_str = "" - for coord_name in list( - [coord for coord in ugrid.SPHERICAL_COORDS if coord in self._ds] - ): + for coord_name in [ + coord for coord in ugrid.SPHERICAL_COORDS if coord in self._ds + ]: coords_str += f" * {coord_name}: {getattr(self, coord_name).shape}\n" coords_str += "Grid Coordinates (Cartesian):\n" - for coord_name in list( - [coord for coord in ugrid.CARTESIAN_COORDS if coord in self._ds] - ): + for coord_name in [ + coord for coord in ugrid.CARTESIAN_COORDS if coord in self._ds + ]: coords_str += f" * {coord_name}: {getattr(self, coord_name).shape}\n" connectivity_heading = "Grid Connectivity Variables:\n" @@ -786,9 +786,9 @@ def __repr__(self): descriptors_heading = "Grid Descriptor Variables:\n" descriptors_str = "" - for descriptor_name in list( - [desc for desc in descriptors.DESCRIPTOR_NAMES if desc in self._ds] - ): + for descriptor_name in [ + desc for desc in descriptors.DESCRIPTOR_NAMES if desc in self._ds + ]: descriptors_str += ( f" * {descriptor_name}: {getattr(self, descriptor_name).shape}\n" ) @@ -847,10 +847,7 @@ def __eq__(self, other) -> bool: return False if not self.node_lat.equals(other.node_lat): return False - if not self.face_node_connectivity.equals(other.face_node_connectivity): - return False - - return True + return self.face_node_connectivity.equals(other.face_node_connectivity) def __ne__(self, other) -> bool: """Two grids are not equal if they have differing grid topology @@ -872,7 +869,7 @@ def dims(self) -> set: """Names of all unstructured grid dimensions.""" from uxarray.conventions.ugrid import DIM_NAMES - return set([dim for dim in DIM_NAMES if dim in self._ds.dims]) + return {dim for dim in DIM_NAMES if dim in self._ds.dims} @property def sizes(self) -> dict: @@ -887,23 +884,23 @@ def coordinates(self) -> set: SPHERICAL_COORD_NAMES, ) - return set( - [coord for coord in SPHERICAL_COORD_NAMES if coord in self._ds] - ).union(set([coord for coord in CARTESIAN_COORD_NAMES if coord in self._ds])) + return {coord for coord in SPHERICAL_COORD_NAMES if coord in self._ds}.union( + {coord for coord in CARTESIAN_COORD_NAMES if coord in self._ds} + ) @property def connectivity(self) -> set: """Names of all connectivity variables.""" from uxarray.conventions.ugrid import CONNECTIVITY_NAMES - return set([conn for conn in CONNECTIVITY_NAMES if conn in self._ds]) + return {conn for conn in CONNECTIVITY_NAMES if conn in self._ds} @property def descriptors(self) -> set: """Names of all descriptor variables.""" from uxarray.conventions.descriptors import DESCRIPTOR_NAMES - return set([desc for desc in DESCRIPTOR_NAMES if desc in self._ds]) + return {desc for desc in DESCRIPTOR_NAMES if desc in self._ds} @property def attrs(self) -> dict: @@ -2283,7 +2280,7 @@ def compute_face_areas( latitude_adjusted_area: bool = False, return_jacobian: bool = False, as_uxarray: bool = False, - ) -> "np.ndarray | UxDataArray | tuple[np.ndarray | UxDataArray, np.ndarray]": + ) -> np.ndarray | UxDataArray | tuple[np.ndarray | UxDataArray, np.ndarray]: """Compute the area of each face in the grid. Unlike the cached :attr:`face_areas` property (which always uses the @@ -2600,13 +2597,12 @@ def to_geodataframe( ) # if project is false, projection is only used for determining central coordinates - if projection and project: - if periodic_elements == "split": - raise ValueError( - "Setting ``periodic_elements='split'`` is not supported when a " - f"projection is provided; got projection={projection!r} " - f"in {type(self).__name__}.to_geodataframe()." - ) + if projection and project and periodic_elements == "split": + raise ValueError( + "Setting ``periodic_elements='split'`` is not supported when a " + f"projection is provided; got projection={projection!r} " + f"in {type(self).__name__}.to_geodataframe()." + ) if periodic_elements not in ["ignore", "exclude", "split"]: raise ValueError( @@ -2614,14 +2610,13 @@ def to_geodataframe( f"but got {periodic_elements!r}, in {type(self).__name__}.to_geodataframe()" ) - if self._gdf_cached_parameters["gdf"] is not None: - if ( - self._gdf_cached_parameters["periodic_elements"] != periodic_elements - or self._gdf_cached_parameters["projection"] != projection - or self._gdf_cached_parameters["engine"] != engine - ): - # cached GeoDataFrame has a different projection or periodic element handling method - override = True + if self._gdf_cached_parameters["gdf"] is not None and ( + self._gdf_cached_parameters["periodic_elements"] != periodic_elements + or self._gdf_cached_parameters["projection"] != projection + or self._gdf_cached_parameters["engine"] != engine + ): + # cached GeoDataFrame has a different projection or periodic element handling method + override = True if self._gdf_cached_parameters["gdf"] is not None and not override: # use cached PolyCollection @@ -2658,7 +2653,7 @@ def to_geodataframe( def to_polycollection( self, periodic_elements: str = "exclude", - projection: Optional[ccrs.Projection] = None, + projection: ccrs.Projection | None = None, return_indices: bool = False, cache: bool = True, override: bool = False, @@ -2693,14 +2688,13 @@ def to_polycollection( f"but got {periodic_elements!r}, in {type(self).__name__}.to_polycollection()" ) - if self._poly_collection_cached_parameters["poly_collection"] is not None: - if ( - self._poly_collection_cached_parameters["periodic_elements"] - != periodic_elements - or self._poly_collection_cached_parameters["projection"] != projection - ): - # cached PolyCollection has a different projection or periodic element handling method - override = True + if self._poly_collection_cached_parameters["poly_collection"] is not None and ( + self._poly_collection_cached_parameters["periodic_elements"] + != periodic_elements + or self._poly_collection_cached_parameters["projection"] != projection + ): + # cached PolyCollection has a different projection or periodic element handling method + override = True if ( self._poly_collection_cached_parameters["poly_collection"] is not None @@ -2744,7 +2738,7 @@ def to_polycollection( def to_linecollection( self, periodic_elements: str = "exclude", - projection: Optional[ccrs.Projection] = None, + projection: ccrs.Projection | None = None, cache: bool = True, override: bool = False, **kwargs, diff --git a/uxarray/grid/integrate.py b/uxarray/grid/integrate.py index 91665d945..fbdb8ba06 100644 --- a/uxarray/grid/integrate.py +++ b/uxarray/grid/integrate.py @@ -145,29 +145,20 @@ def _zonal_face_weights_robust( intervals_df = pl.DataFrame(intervals_list) # Process intervals to get overlap contributions - try: - overlap_contributions, total_length = _process_overlapped_intervals( - intervals_df - ) - - # Build final weights dict - weights = {} - n_faces = len(faces_edges_cart_candidate) - for face_index in range(n_faces): - # fraction of total for this face - weights[face_index] = ( - overlap_contributions.get(face_index, 0.0) / total_length - ) - - # Return as Polars DataFrame - weights_df = pl.DataFrame( - list(weights.items()), schema=["face_index", "weight"], orient="row" - ) - return weights_df - - except ValueError: - # If an exception occurs, you can print debug info here if needed - raise + overlap_contributions, total_length = _process_overlapped_intervals(intervals_df) + + # Build final weights dict + weights = {} + n_faces = len(faces_edges_cart_candidate) + for face_index in range(n_faces): + # fraction of total for this face + weights[face_index] = overlap_contributions.get(face_index, 0.0) / total_length + + # Return as Polars DataFrame + weights_df = pl.DataFrame( + list(weights.items()), schema=["face_index", "weight"], orient="row" + ) + return weights_df def _get_zonal_face_interval( @@ -231,19 +222,19 @@ def _get_zonal_face_interval( ) # Handle special wrap-around cases (crossing anti-meridian, etc.) - if face_lon_bound_left >= face_lon_bound_right or ( - face_lon_bound_left == 0 and face_lon_bound_right == 2 * np.pi + if ( + face_lon_bound_left >= face_lon_bound_right + or (face_lon_bound_left == 0 and face_lon_bound_right == 2 * np.pi) + ) and not ( + (pt_lon_max >= np.pi and pt_lon_min >= np.pi) + or (0 <= pt_lon_max <= np.pi and 0 <= pt_lon_min <= np.pi) ): - if not ( - (pt_lon_max >= np.pi and pt_lon_min >= np.pi) - or (0 <= pt_lon_max <= np.pi and 0 <= pt_lon_min <= np.pi) - ): - if pt_lon_max != 2 * np.pi and pt_lon_min != 0: - # Add wrap-around points - longitudes = np.append(longitudes, [0.0, 2 * np.pi]) - elif pt_lon_max >= np.pi and pt_lon_min == 0: - # If min is 0, but we really need 2*pi - longitudes[longitudes == 0] = 2.0 * np.pi + if pt_lon_max != 2 * np.pi and pt_lon_min != 0: + # Add wrap-around points + longitudes = np.append(longitudes, [0.0, 2 * np.pi]) + elif pt_lon_max >= np.pi and pt_lon_min == 0: + # If min is 0, but we really need 2*pi + longitudes[longitudes == 0] = 2.0 * np.pi # Sort unique longitudes longitudes = np.unique(longitudes) @@ -670,11 +661,10 @@ def _zonal_face_weights( Array of weights for each face intersecting the latitude line """ - if check_equator: - # If near equator, use original approach - if np.isclose(z, 0.0, atol=ERROR_TOLERANCE): - overlap_result = _zonal_face_weights_robust(face_edges_xyz, z, face_bounds) - return overlap_result["weight"].to_numpy() + # If near equator, use original approach + if check_equator and np.isclose(z, 0.0, atol=ERROR_TOLERANCE): + overlap_result = _zonal_face_weights_robust(face_edges_xyz, z, face_bounds) + return overlap_result["weight"].to_numpy() # Otherwise, use the Numba approach return _zonal_face_weights_util_numba(face_edges_xyz, n_edges_per_face, z) diff --git a/uxarray/grid/neighbors.py b/uxarray/grid/neighbors.py index 05464a6db..bd817053f 100644 --- a/uxarray/grid/neighbors.py +++ b/uxarray/grid/neighbors.py @@ -1,7 +1,7 @@ import enum import math import warnings -from typing import Callable +from collections.abc import Callable import numpy as np import xarray as xr @@ -1054,7 +1054,7 @@ def _barycentric_coordinates(nodes, point): sum_wi = 0 w = [] - for i in range(0, n): + for i in range(n): vim1 = nodes[i - 1] vi = nodes[i] vi1 = nodes[(i + 1) % n] @@ -1142,11 +1142,11 @@ def _construct_edge_node_distances(node_lon, node_lat, edge_nodes): """Helper for computing the arc-distance between nodes compose each edge.""" - edge_lon_a = np.deg2rad((node_lon[edge_nodes[:, 0]])) - edge_lon_b = np.deg2rad((node_lon[edge_nodes[:, 1]])) + edge_lon_a = np.deg2rad(node_lon[edge_nodes[:, 0]]) + edge_lon_b = np.deg2rad(node_lon[edge_nodes[:, 1]]) - edge_lat_a = np.deg2rad((node_lat[edge_nodes[:, 0]])) - edge_lat_b = np.deg2rad((node_lat[edge_nodes[:, 1]])) + edge_lat_a = np.deg2rad(node_lat[edge_nodes[:, 0]]) + edge_lat_b = np.deg2rad(node_lat[edge_nodes[:, 1]]) # arc length edge_node_distances = np.arccos( @@ -1181,11 +1181,11 @@ def _construct_edge_face_distances(face_lon, face_lat, edge_faces): edge_face_distances = np.zeros(edge_faces.shape[0]) - edge_lon_a = np.deg2rad((face_lon[edge_faces[saddle_mask, 0]])) - edge_lon_b = np.deg2rad((face_lon[edge_faces[saddle_mask, 1]])) + edge_lon_a = np.deg2rad(face_lon[edge_faces[saddle_mask, 0]]) + edge_lon_b = np.deg2rad(face_lon[edge_faces[saddle_mask, 1]]) - edge_lat_a = np.deg2rad((face_lat[edge_faces[saddle_mask, 0]])) - edge_lat_b = np.deg2rad((face_lat[edge_faces[saddle_mask, 1]])) + edge_lat_a = np.deg2rad(face_lat[edge_faces[saddle_mask, 0]]) + edge_lat_b = np.deg2rad(face_lat[edge_faces[saddle_mask, 1]]) # arc length edge_face_distances[saddle_mask] = np.arccos( @@ -1284,8 +1284,7 @@ def _widest(counts): """Largest neighborhood, so each kernel allocates its buffer once.""" widest = 0 for i in range(counts.shape[0]): - if counts[i] > widest: - widest = counts[i] + widest = max(widest, counts[i]) return widest diff --git a/uxarray/io/_exodus.py b/uxarray/io/_exodus.py index a93946310..5f4eafd6c 100644 --- a/uxarray/io/_exodus.py +++ b/uxarray/io/_exodus.py @@ -30,8 +30,7 @@ def _read_exodus(ext_ds): max_face_nodes = 0 for dim in ext_ds.dims: if "num_nod_per_el" in dim: - if ext_ds.sizes[dim] > max_face_nodes: - max_face_nodes = ext_ds.sizes[dim] + max_face_nodes = max(max_face_nodes, ext_ds.sizes[dim]) for key, value in ext_ds.variables.items(): if key == "qa_records": diff --git a/uxarray/io/_healpix.py b/uxarray/io/_healpix.py index 38f4d155a..01c89e5a0 100644 --- a/uxarray/io/_healpix.py +++ b/uxarray/io/_healpix.py @@ -4,8 +4,8 @@ import polars as pl import xarray as xr -import uxarray.conventions.ugrid as ugrid from uxarray.constants import INT_DTYPE +from uxarray.conventions import ugrid from uxarray.utils.imports import _raise_hint_if_optional_deps_missing diff --git a/uxarray/io/_scrip.py b/uxarray/io/_scrip.py index 59a7eb186..d97593c82 100644 --- a/uxarray/io/_scrip.py +++ b/uxarray/io/_scrip.py @@ -1,4 +1,5 @@ -from typing import Any, Sequence +from collections.abc import Sequence +from typing import Any import numpy as np import polars as pl @@ -134,13 +135,13 @@ def _dedup_scrip_nodes_eager(corner_lon, corner_lat): @njit(cache=True, inline="always") def _lt_nan_last(a, b): """``a < b`` in numpy's sort order, which places NaN after every number.""" - return a < b or (b != b and a == a) + return a < b or (np.isnan(b) and not np.isnan(a)) @njit(cache=True, inline="always") def _eq_nan(a, b): """``a == b``, except that NaN equals NaN, as it does in the dedup.""" - return a == b or (a != a and b != b) + return a == b or (np.isnan(a) and np.isnan(b)) @njit(cache=True, nogil=True) diff --git a/uxarray/io/_structured.py b/uxarray/io/_structured.py index f74c85447..88fdff185 100644 --- a/uxarray/io/_structured.py +++ b/uxarray/io/_structured.py @@ -122,13 +122,13 @@ def _read_structured_grid(lon, lat, tol=None): adj_matrix = coo_matrix((data, (row, col)), shape=(n_nodes, n_nodes)) # Use connected_components to find connected components - n_components, labels = connected_components(csgraph=adj_matrix, directed=False) + _n_components, labels = connected_components(csgraph=adj_matrix, directed=False) else: # No pairs within tolerance, each node is its own component labels = np.arange(n_nodes) # Extract unique nodes based on the labels - unique_labels, index = np.unique(labels, return_index=True) + _unique_labels, index = np.unique(labels, return_index=True) unique_nodes = nodes[index] unique_node_lon = unique_nodes[:, 0] unique_node_lat = unique_nodes[:, 1] diff --git a/uxarray/io/_topology.py b/uxarray/io/_topology.py index 629ba96ef..9cff76620 100644 --- a/uxarray/io/_topology.py +++ b/uxarray/io/_topology.py @@ -1,7 +1,7 @@ import xarray as xr -import uxarray.conventions.ugrid as ugrid from uxarray.constants import INT_DTYPE, INT_FILL_VALUE +from uxarray.conventions import ugrid from uxarray.grid.connectivity import _replace_fill_values diff --git a/uxarray/io/_ugrid.py b/uxarray/io/_ugrid.py index 649da492c..a44e25306 100644 --- a/uxarray/io/_ugrid.py +++ b/uxarray/io/_ugrid.py @@ -1,8 +1,8 @@ import numpy as np import xarray as xr -import uxarray.conventions.ugrid as ugrid from uxarray.constants import INT_DTYPE, INT_FILL_VALUE +from uxarray.conventions import ugrid from uxarray.errors import GridInvalidError from uxarray.grid.connectivity import _replace_fill_values @@ -12,7 +12,7 @@ def _read_ugrid(ds): conventions.""" # Extract grid topology attributes - grid_topology_name = list(ds.filter_by_attrs(cf_role="mesh_topology").keys())[0] + grid_topology_name = next(iter(ds.filter_by_attrs(cf_role="mesh_topology").keys())) ds = ds.rename({grid_topology_name: "grid_topology"}) # get the names of node_lon and node_lat @@ -21,18 +21,24 @@ def _read_ugrid(ds): node_lon_name: ugrid.NODE_COORDINATES[0], node_lat_name: ugrid.NODE_COORDINATES[1], } - if "edge_lon" in ds and "edge_lat" in ds: - if "edge_coordinates" in ds["grid_topology"].attrs: - # get the names of edge_lon and edge_lat, if they exist - edge_lon_name, edge_lat_name = ds["grid_topology"].edge_coordinates.split() - coord_dict[edge_lon_name] = ugrid.EDGE_COORDINATES[0] - coord_dict[edge_lat_name] = ugrid.EDGE_COORDINATES[1] - if "face_lon" in ds and "face_lat" in ds: - if "face_coordinates" in ds["grid_topology"].attrs: - # get the names of face_lon and face_lat, if they exist - face_lon_name, face_lat_name = ds["grid_topology"].face_coordinates.split() - coord_dict[face_lon_name] = ugrid.FACE_COORDINATES[0] - coord_dict[face_lat_name] = ugrid.FACE_COORDINATES[1] + if ( + "edge_lon" in ds + and "edge_lat" in ds + and "edge_coordinates" in ds["grid_topology"].attrs + ): + # get the names of edge_lon and edge_lat, if they exist + edge_lon_name, edge_lat_name = ds["grid_topology"].edge_coordinates.split() + coord_dict[edge_lon_name] = ugrid.EDGE_COORDINATES[0] + coord_dict[edge_lat_name] = ugrid.EDGE_COORDINATES[1] + if ( + "face_lon" in ds + and "face_lat" in ds + and "face_coordinates" in ds["grid_topology"].attrs + ): + # get the names of face_lon and face_lat, if they exist + face_lon_name, face_lat_name = ds["grid_topology"].face_coordinates.split() + coord_dict[face_lon_name] = ugrid.FACE_COORDINATES[0] + coord_dict[face_lat_name] = ugrid.FACE_COORDINATES[1] ds = ds.rename(coord_dict) @@ -42,7 +48,7 @@ def _read_ugrid(ds): orig_conn_name = ds.grid_topology.attrs[conn_name] conn_dict[orig_conn_name] = conn_name elif len(ds.filter_by_attrs(cf_role=conn_name).keys()): - orig_conn_name = list(ds.filter_by_attrs(cf_role=conn_name).keys())[0] + orig_conn_name = next(iter(ds.filter_by_attrs(cf_role=conn_name).keys())) conn_dict[orig_conn_name] = conn_name ds = ds.rename(conn_dict) @@ -75,7 +81,7 @@ def _read_ugrid(ds): da = ds[conn_name] dims = da.dims - for grid_dim in dim_dict.keys(): + for grid_dim in dim_dict: if dims[1] == grid_dim: ds[conn_name] = da.T @@ -260,15 +266,12 @@ def _is_ugrid(ds): face_conn_dv = ds.filter_by_attrs(face_node_connectivity=lambda v: v is not None) topo_dim_dv = ds.filter_by_attrs(topology_dimension=lambda v: v is not None) mesh_topo_dv = ds.filter_by_attrs(cf_role="mesh_topology") - if ( + return ( len(mesh_topo_dv) != 0 and len(topo_dim_dv) != 0 and len(face_conn_dv) != 0 and len(node_coords_dv) != 0 - ): - return True - else: - return False + ) def _validate_minimum_ugrid(grid_ds): diff --git a/uxarray/io/utils.py b/uxarray/io/utils.py index c95e01dcf..752b7adc1 100644 --- a/uxarray/io/utils.py +++ b/uxarray/io/utils.py @@ -207,4 +207,4 @@ def _get_source_dims_dict(grid_ds, grid_spec): return _esmf_to_ugrid_dims(grid_ds) else: - return dict() + return {} diff --git a/uxarray/plot/accessor.py b/uxarray/plot/accessor.py index 98f699d4d..c37385d00 100644 --- a/uxarray/plot/accessor.py +++ b/uxarray/plot/accessor.py @@ -1,7 +1,8 @@ from __future__ import annotations import warnings -from typing import TYPE_CHECKING, Any, Sequence +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any import pandas as pd @@ -482,12 +483,12 @@ def polygons( # (commented here for future reference, since datashader appears in uxarray dependency list, # but it isn't imported explicitly anywhere in uxarray. For more details see PR #1548.) return gdf.hvplot.polygons( + *args, c=self._uxda.name if self._uxda.name is not None else "var", rasterize=rasterize, dynamic=dynamic, xlabel=xlabel, ylabel=ylabel, - *args, **kwargs, ) @@ -539,7 +540,7 @@ def points(self, backend=None, *args, **kwargs): points_df = pd.DataFrame.from_dict(verts) - return points_df.hvplot.points("lon", "lat", c="z", *args, **kwargs) + return points_df.hvplot.points("lon", "lat", *args, c="z", **kwargs) def contour( self, diff --git a/uxarray/plot/contour.py b/uxarray/plot/contour.py index 4e5d40de4..f954cf275 100644 --- a/uxarray/plot/contour.py +++ b/uxarray/plot/contour.py @@ -1,8 +1,9 @@ from __future__ import annotations from collections import defaultdict +from collections.abc import Sequence from difflib import get_close_matches -from typing import TYPE_CHECKING, Sequence +from typing import TYPE_CHECKING import numpy as np from numba import njit diff --git a/uxarray/plot/utils.py b/uxarray/plot/utils.py index c19ad5798..107a87339 100644 --- a/uxarray/plot/utils.py +++ b/uxarray/plot/utils.py @@ -65,7 +65,7 @@ def reset_mpl_backend(self): try: shell.enable_matplotlib(gui) return - except Exception: + except Exception: # noqa: BLE001, S110 - fall back to the pyplot path below pass _raise_hint_if_optional_deps_missing("matplotlib") diff --git a/uxarray/remap/__init__.py b/uxarray/remap/__init__.py index 765f10425..8bfa496a0 100644 --- a/uxarray/remap/__init__.py +++ b/uxarray/remap/__init__.py @@ -5,9 +5,9 @@ __all__ = ( "RemapWeights", - "load_remap_weights", - "clear_remap_weights_cache", "_apply_weights", - "_nearest_neighbor_remap", "_inverse_distance_weighted_remap", + "_nearest_neighbor_remap", + "clear_remap_weights_cache", + "load_remap_weights", ) diff --git a/uxarray/remap/spatial_coords_remap.py b/uxarray/remap/spatial_coords_remap.py index c41bc5f04..5423d212a 100644 --- a/uxarray/remap/spatial_coords_remap.py +++ b/uxarray/remap/spatial_coords_remap.py @@ -1,5 +1,5 @@ import warnings -from typing import Dict, Literal, Optional, Tuple +from typing import Literal import xarray as xr @@ -62,7 +62,7 @@ def __init__( self.source = source self.remap_to = remap_to - def _get_destination_grid_coords(self) -> Dict[str, xr.DataArray]: + def _get_destination_grid_coords(self) -> dict[str, xr.DataArray]: """ Get the spatial coordinates of the destination grid corresponding to `remap_to`. @@ -97,7 +97,7 @@ def _get_destination_grid_coords(self) -> Dict[str, xr.DataArray]: f"Unknown `remap_to`: {self.remap_to}. Must be either 'nodes', 'faces', or 'edges'." ) - def _find_source_coords(self) -> Dict[str, Tuple[str, str]]: + def _find_source_coords(self) -> dict[str, tuple[str, str]]: """ Find spatial coordinate variables in `source` by checking their attributes, units, and axes. @@ -167,7 +167,7 @@ def _find_source_coords(self) -> Dict[str, Tuple[str, str]]: return source_coords - def _get_element_type_from_dimension(self, dim_name: str) -> Optional[str]: + def _get_element_type_from_dimension(self, dim_name: str) -> str | None: """ Determine element type (i.e. 'nodes', 'faces', or 'edges') from dimension name. @@ -244,7 +244,7 @@ def _rename_coord_for_new_dimension( return new_name - def construct_output_coords(self) -> Dict[str, xr.DataArray]: + def construct_output_coords(self) -> dict[str, xr.DataArray]: """ Construct spatial coordinates for the remapped output by finding spatial coordinate variables, if any, in `source` and employing a logic as follows: @@ -306,7 +306,7 @@ def construct_output_coords(self) -> Dict[str, xr.DataArray]: # Swap coords on matching dimension for coord_type in COORD_TYPES.values(): if coord_type in source_coords: - source_coord_name, std_name = source_coords[coord_type] + source_coord_name, _std_name = source_coords[coord_type] out_name = source_coord_name # Assign destination grid values @@ -328,7 +328,7 @@ def construct_output_coords(self) -> Dict[str, xr.DataArray]: # Swap and rename (as needed) coords from source dimension for coord_type in COORD_TYPES.values(): if coord_type in source_coords: - source_coord_name, std_name = source_coords[coord_type] + source_coord_name, _std_name = source_coords[coord_type] # Rename to reflect new element type out_name = self._rename_coord_for_new_dimension( diff --git a/uxarray/remap/weights.py b/uxarray/remap/weights.py index 3a6cd6f62..ea2435771 100644 --- a/uxarray/remap/weights.py +++ b/uxarray/remap/weights.py @@ -17,7 +17,7 @@ # LRU-bounded cache for loaded remap operators. _WEIGHTS_CACHE_MAXSIZE = 32 -_WEIGHTS_CACHE: "OrderedDict[tuple[str, int, int], RemapWeights]" = OrderedDict() +_WEIGHTS_CACHE: OrderedDict[tuple[str, int, int], RemapWeights] = OrderedDict() def clear_remap_weights_cache() -> None: diff --git a/uxarray/remap/yac.py b/uxarray/remap/yac.py index 094a9da10..8e30b3e12 100644 --- a/uxarray/remap/yac.py +++ b/uxarray/remap/yac.py @@ -63,7 +63,7 @@ def _load_yac_core_from_file() -> ModuleType | None: module = importlib.util.module_from_spec(spec) sys.modules["yac.core"] = module spec.loader.exec_module(module) - setattr(pkg, "core", module) + pkg.core = module return module return None diff --git a/uxarray/subset/__init__.py b/uxarray/subset/__init__.py index 9a3fee391..5bc56a943 100644 --- a/uxarray/subset/__init__.py +++ b/uxarray/subset/__init__.py @@ -2,6 +2,6 @@ from .grid_accessor import GridSubsetAccessor __all__ = ( - "GridSubsetAccessor", "DataArraySubsetAccessor", + "GridSubsetAccessor", ) diff --git a/uxarray/subset/dataarray_accessor.py b/uxarray/subset/dataarray_accessor.py index 7835614d1..d65dc2969 100644 --- a/uxarray/subset/dataarray_accessor.py +++ b/uxarray/subset/dataarray_accessor.py @@ -65,7 +65,7 @@ def bounding_box( def bounding_circle( self, center_coord: tuple | list | np.ndarray, - r: float | int, + r: float, element: str = "face centers", inverse_indices: list[str] | set[str] | bool = False, **kwargs, diff --git a/uxarray/subset/grid_accessor.py b/uxarray/subset/grid_accessor.py index 862d5fbce..6095a8603 100644 --- a/uxarray/subset/grid_accessor.py +++ b/uxarray/subset/grid_accessor.py @@ -76,7 +76,7 @@ def bounding_box( def bounding_circle( self, center_coord: tuple | list | np.ndarray, - r: float | int, + r: float, element: str = "face centers", inverse_indices: list[str] | set[str] | bool = False, **kwargs, diff --git a/uxarray/utils/computing.py b/uxarray/utils/computing.py index aff800372..4287579df 100644 --- a/uxarray/utils/computing.py +++ b/uxarray/utils/computing.py @@ -41,7 +41,7 @@ def codegen(context, builder, signature, args): return sig, codegen _FMA_INTRINSIC_OK = True -except Exception: # pragma: no cover - toolchain without intrinsic support +except Exception: # noqa: BLE001 # pragma: no cover - toolchain without intrinsic support _FMA_INTRINSIC_OK = False @@ -127,7 +127,7 @@ def _validate_fma(n_samples=2000) -> bool: if pf != pv or ef != ev: return False return True - except Exception: # pragma: no cover + except Exception: # noqa: BLE001 # pragma: no cover return False diff --git a/uxarray/utils/coords.py b/uxarray/utils/coords.py index 15c0bcf2e..f4d6aac2a 100644 --- a/uxarray/utils/coords.py +++ b/uxarray/utils/coords.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Hashable, Iterable, Mapping +from collections.abc import Hashable, Iterable, Mapping import numpy as np import xarray as xr @@ -107,23 +107,22 @@ def _crash_if_1d_xarray_indexer_dim_in_uxarray_obj(uxarray_obj, grid_dim, indexe (Only handles 1D xr.DataArray indexers; 0D, 2D+, and non-DataArray indexers are handled elsewhere.) """ - if isinstance(indexer, xr.DataArray): - if indexer.ndim == 1: - the_dim = indexer.dims[0] - nonscalar_coords = [ - c for c in uxarray_obj.coords if len(uxarray_obj.coords[c].dims) > 0 - ] - if the_dim != grid_dim and ( - the_dim in uxarray_obj.dims or the_dim in nonscalar_coords - ): - raise NotImplementedError( - f"Indexing a {type(uxarray_obj).__name__} along a grid dimension ({grid_dim!r}), using " - f"an xarray DataArray whose dimension ({the_dim!r}) is already present in the original " - f"{type(uxarray_obj).__name__}'s dims or non-scalar coords, is not yet supported. " - f"Consider using obj.to_xarray() for basic xarray indexing, " - f"using indexer.data to convert to indexer to a non-DataArray object, " - f"or using indexer.rename({{{the_dim!r}: 'any_unused_dim_name'}}) to avoid matching dims." - ) + if isinstance(indexer, xr.DataArray) and indexer.ndim == 1: + the_dim = indexer.dims[0] + nonscalar_coords = [ + c for c in uxarray_obj.coords if len(uxarray_obj.coords[c].dims) > 0 + ] + if the_dim != grid_dim and ( + the_dim in uxarray_obj.dims or the_dim in nonscalar_coords + ): + raise NotImplementedError( + f"Indexing a {type(uxarray_obj).__name__} along a grid dimension ({grid_dim!r}), using " + f"an xarray DataArray whose dimension ({the_dim!r}) is already present in the original " + f"{type(uxarray_obj).__name__}'s dims or non-scalar coords, is not yet supported. " + f"Consider using obj.to_xarray() for basic xarray indexing, " + f"using indexer.data to convert to indexer to a non-DataArray object, " + f"or using indexer.rename({{{the_dim!r}: 'any_unused_dim_name'}}) to avoid matching dims." + ) # all other cases handled elsewhere. @@ -181,7 +180,7 @@ def _assign_grid_dim_indexer_coords_if_appropriate(uxarray_obj, grid_dim, indexe raise DimensionError( f"The indexer's dimension ({the_dim!r}) already exists as a scalar " f"coordinate in the {type(uxarray_obj).__name__} object being indexed." - ) # + ) coords = indexer.swap_dims({the_dim: "n_face"}).coords else: # remove any 1D coords (but keep scalar coords). @@ -205,8 +204,11 @@ def _assert_grid_dim_coord_consistent_if_in_both(uxarray_obj, grid_dim, indexer) """assert grid_dim's coordinate is consistent if in both uxarray_obj and indexer. Otherwise, does nothing. """ - if isinstance(indexer, xr.DataArray): - if grid_dim in uxarray_obj.coords and grid_dim in indexer.coords: - xr.core.coordinates.assert_coordinate_consistent( - uxarray_obj, {grid_dim: indexer.coords.variables[grid_dim]} - ) + if ( + isinstance(indexer, xr.DataArray) + and grid_dim in uxarray_obj.coords + and grid_dim in indexer.coords + ): + xr.core.coordinates.assert_coordinate_consistent( + uxarray_obj, {grid_dim: indexer.coords.variables[grid_dim]} + ) diff --git a/uxarray/utils/imports.py b/uxarray/utils/imports.py index d02a24a9d..d101bfe36 100644 --- a/uxarray/utils/imports.py +++ b/uxarray/utils/imports.py @@ -99,7 +99,7 @@ def _raise_hint_if_optional_deps_missing(*packages: str): if "all" not in or_extras: or_extras.append("all") else: # case (4) - need_extras = set(["all"]) + need_extras = {"all"} break need_extras_str = ",".join(sorted(need_extras)) # sort is just for style errmsg = "Failed to import: " + ", ".join(sorted(missing)) diff --git a/uxarray/utils/warnings.py b/uxarray/utils/warnings.py index 15470547a..a1d37bcb8 100644 --- a/uxarray/utils/warnings.py +++ b/uxarray/utils/warnings.py @@ -1,9 +1,9 @@ import inspect import os -from functools import lru_cache +from functools import cache -@lru_cache(maxsize=None) +@cache def _package_dir(): import uxarray