diff --git a/uxarray/core/accessors.py b/uxarray/core/accessors.py index 45415df7a..4d4dd4c84 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, Set +from typing import Any import xarray as xr @@ -148,7 +148,7 @@ def remove_preserve_method(cls, method_name: str): cls._preserve_methods.discard(method_name) @classmethod - def set_preserve_methods(cls, methods: Set[str]): + def set_preserve_methods(cls, methods: set[str]): """Set the complete list of methods that preserve uxgrid.""" cls._preserve_methods = set(methods) diff --git a/uxarray/core/api.py b/uxarray/core/api.py index f357a267e..2a9c6c728 100644 --- a/uxarray/core/api.py +++ b/uxarray/core/api.py @@ -1,7 +1,7 @@ from __future__ import annotations import os -from typing import TYPE_CHECKING, Any, Dict, Optional, Union +from typing import TYPE_CHECKING, Any from warnings import warn import numpy as np @@ -21,8 +21,8 @@ def open_grid( grid_filename_or_obj: str | os.PathLike[Any] | dict | Dataset, chunks=None, - use_dual: Optional[bool] = False, - **kwargs: Dict[str, Any], + use_dual: bool | None = False, + **kwargs: dict[str, Any], ): """Constructs and returns a ``Grid`` from a grid file. @@ -128,9 +128,9 @@ def open_dataset( filename_or_obj: str | os.PathLike[Any], chunks=None, chunk_grid: bool = True, - use_dual: Optional[bool] = False, - grid_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Dict[str, Any], + use_dual: bool | None = False, + grid_kwargs: dict[str, Any] | None = None, + **kwargs: dict[str, Any], ) -> UxDataset: """Wraps ``xarray.open_dataset()`` for loading in a dataset paired with a grid file. @@ -199,12 +199,12 @@ def open_dataset( def open_mfdataset( grid_filename_or_obj: str | os.PathLike[Any] | dict | Dataset, - paths: Union[str, os.PathLike], + paths: str | os.PathLike, chunks=None, chunk_grid: bool = True, - use_dual: Optional[bool] = False, - grid_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Dict[str, Any], + use_dual: bool | None = False, + grid_kwargs: dict[str, Any] | None = None, + **kwargs: dict[str, Any], ) -> UxDataset: """Wraps ``xarray.open_dataset()`` to support reading in a grid and multiple data files together. diff --git a/uxarray/core/dataarray.py b/uxarray/core/dataarray.py index 7ad62050c..e4c802ce8 100644 --- a/uxarray/core/dataarray.py +++ b/uxarray/core/dataarray.py @@ -2,7 +2,7 @@ import warnings from html import escape -from typing import TYPE_CHECKING, Any, Hashable, Literal, Mapping, Optional +from typing import TYPE_CHECKING, Any, Hashable, Literal, Mapping from warnings import warn import numpy as np @@ -164,12 +164,12 @@ def data_mapping(self): def to_geodataframe( self, - periodic_elements: Optional[str] = "exclude", + periodic_elements: str | None = "exclude", projection=None, - cache: Optional[bool] = True, - override: Optional[bool] = False, - engine: Optional[str] = "spatialpandas", - exclude_antimeridian: Optional[bool] = None, + cache: bool | None = True, + override: bool | None = False, + engine: str | None = "spatialpandas", + exclude_antimeridian: bool | None = None, **kwargs, ): """Constructs a ``GeoDataFrame`` consisting of polygons representing @@ -462,7 +462,7 @@ def to_xarray(self): return xr.DataArray(self) def integrate( - self, quadrature_rule: Optional[str] = "triangular", order: Optional[int] = 4 + self, quadrature_rule: str | None = "triangular", order: int | None = 4 ) -> UxDataArray: """Computes the integral of a data variable. @@ -1501,7 +1501,7 @@ def divergence(self, other: "UxDataArray", **kwargs) -> "UxDataArray": return divergence_da - def difference(self, destination: Optional[str] = "edge"): + def difference(self, destination: str | None = "edge"): """Computes the absolute difference of a data variable. The difference for a face-centered data variable can be computed on each edge using the ``edge_face_connectivity``, diff --git a/uxarray/core/dataset.py b/uxarray/core/dataset.py index 68ea428ae..8528494a8 100644 --- a/uxarray/core/dataset.py +++ b/uxarray/core/dataset.py @@ -3,7 +3,7 @@ import os import sys from html import escape -from typing import IO, Any, Mapping, Optional, Union +from typing import IO, Any, Mapping from warnings import warn import numpy as np @@ -75,7 +75,7 @@ def __init__( self, *args, uxgrid: Grid = None, - source_datasets: Optional[str] = None, + source_datasets: str | None = None, **kwargs, ): self._uxgrid = None @@ -301,7 +301,7 @@ def from_xarray(cls, ds: xr.Dataset, uxgrid: Grid = None, ugrid_dims: dict = Non @classmethod def from_healpix( cls, - ds: Union[str, os.PathLike, xr.Dataset], + ds: str | os.PathLike | xr.Dataset, pixels_only: bool = True, face_dim: str = "cell", **kwargs, diff --git a/uxarray/grid/coordinates.py b/uxarray/grid/coordinates.py index a00e2a002..e1be03172 100644 --- a/uxarray/grid/coordinates.py +++ b/uxarray/grid/coordinates.py @@ -1,5 +1,4 @@ import math -from typing import Union import numpy as np import xarray as xr @@ -12,8 +11,8 @@ @njit(cache=True) def _lonlat_rad_to_xyz( - lon: Union[np.ndarray, float], - lat: Union[np.ndarray, float], + lon: np.ndarray | float, + lat: np.ndarray | float, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Converts Spherical latitude and longitude coordinates into Cartesian x, y, z coordinates.""" @@ -26,9 +25,9 @@ def _lonlat_rad_to_xyz( @njit(cache=True) def _xyz_to_lonlat_rad_no_norm( - x: Union[np.ndarray, float], - y: Union[np.ndarray, float], - z: Union[np.ndarray, float], + x: np.ndarray | float, + y: np.ndarray | float, + z: np.ndarray | float, ): """Converts a Cartesian x,y,z coordinates into Spherical latitude and longitude without normalization, decorated with Numba. @@ -93,9 +92,9 @@ def _xyz_to_lonlat_rad_scalar(x, y, z, normalize=True): def _xyz_to_lonlat_rad( - x: Union[np.ndarray, float], - y: Union[np.ndarray, float], - z: Union[np.ndarray, float], + x: np.ndarray | float, + y: np.ndarray | float, + z: np.ndarray | float, normalize: bool = True, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Converts Cartesian x, y, z coordinates in Spherical longitude and @@ -103,20 +102,20 @@ def _xyz_to_lonlat_rad( Parameters ---------- - x : Union[np.ndarray, float] + x : np.ndarray | float Cartesian x coordinates - y: Union[np.ndarray, float] + y: np.ndarray | float Cartesiain y coordinates - z: Union[np.ndarray, float] + z: np.ndarray | float Cartesian z coordinates normalize: bool Flag to select whether to normalize the coordinates Returns ------- - lon : Union[np.ndarray, float] + lon : np.ndarray | float Longitude in radians - lat: Union[np.ndarray, float] + lat: np.ndarray | float Latitude in radians """ @@ -142,9 +141,9 @@ def _xyz_to_lonlat_rad( def _xyz_to_lonlat_deg( - x: Union[np.ndarray, float], - y: Union[np.ndarray, float], - z: Union[np.ndarray, float], + x: np.ndarray | float, + y: np.ndarray | float, + z: np.ndarray | float, normalize: bool = True, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Converts Cartesian x, y, z coordinates in Spherical latitude and @@ -152,20 +151,20 @@ def _xyz_to_lonlat_deg( Parameters ---------- - x : Union[np.ndarray, float] + x : np.ndarray | float Cartesian x coordinates - y: Union[np.ndarray, float] + y: np.ndarray | float Cartesiain y coordinates - z: Union[np.ndarray, float] + z: np.ndarray | float Cartesian z coordinates normalize: bool Flag to select whether to normalize the coordinates Returns ------- - lon : Union[np.ndarray, float] + lon : np.ndarray | float Longitude in degrees - lat: Union[np.ndarray, float] + lat: np.ndarray | float Latitude in degrees """ lon_rad, lat_rad = _xyz_to_lonlat_rad(x, y, z, normalize=normalize) @@ -178,9 +177,9 @@ def _xyz_to_lonlat_deg( def _normalize_xyz( - x: Union[np.ndarray, float], - y: Union[np.ndarray, float], - z: Union[np.ndarray, float], + x: np.ndarray | float, + y: np.ndarray | float, + z: np.ndarray | float, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Normalizes a set of Cartesian coordinates.""" denom = np.linalg.norm( @@ -695,9 +694,9 @@ def _set_desired_longitude_range(uxgrid): with xr.set_options(keep_attrs=True): for lon_name in ["node_lon", "edge_lon", "face_lon"]: if lon_name in uxgrid._ds: - if uxgrid._ds[lon_name].max() > 180: - da = uxgrid._ds[lon_name] - wrapped = (uxgrid._ds[lon_name] + 180) % 360 - 180 + da = uxgrid._ds[lon_name] + if da.max() > 180: + wrapped = (da + 180) % 360 - 180 wrapped.name = da.name uxgrid._ds[lon_name] = wrapped diff --git a/uxarray/grid/grid.py b/uxarray/grid/grid.py index b940912bb..16c012552 100644 --- a/uxarray/grid/grid.py +++ b/uxarray/grid/grid.py @@ -1,14 +1,7 @@ import copy import os from html import escape -from typing import ( - List, - Optional, - Sequence, - Set, - Tuple, - Union, -) +from typing import Sequence from warnings import warn import numpy as np @@ -159,10 +152,10 @@ class Grid: def __init__( self, grid_ds: xr.Dataset, - source_grid_spec: Optional[str] = None, - source_dims_dict: Optional[dict] = None, + source_grid_spec: str | None = None, + source_dims_dict: dict | None = None, is_subset: bool = False, - inverse_indices: Optional[xr.Dataset] = None, + inverse_indices: xr.Dataset | None = None, ): # check if inputted dataset is a minimum representable 2D UGRID unstructured grid if source_grid_spec != "HEALPix": @@ -244,7 +237,7 @@ def __init__( cross_section = UncachedAccessor(GridCrossSectionAccessor) @classmethod - def from_dataset(cls, dataset, use_dual: Optional[bool] = False, **kwargs): + def from_dataset(cls, dataset, use_dual: bool | None = False, **kwargs): """Constructs a ``Grid`` object from a dataset. Parameters @@ -315,7 +308,7 @@ def from_dataset(cls, dataset, use_dual: Optional[bool] = False, **kwargs): def from_file( cls, filename: str, - backend: Optional[str] = "geopandas", + backend: str | None = "geopandas", **kwargs, ): """Constructs a ``Grid`` object from a using the read_file method with @@ -430,9 +423,9 @@ def from_topology( node_lon: np.ndarray, node_lat: np.ndarray, face_node_connectivity: np.ndarray, - fill_value: Optional = None, - start_index: Optional[int] = 0, - dims_dict: Optional[dict] = None, + fill_value: int | float | None = None, + start_index: int | None = 0, + dims_dict: dict | None = None, **kwargs, ): """Constructs a ``Grid`` object from user-defined topology variables @@ -450,11 +443,11 @@ def from_topology( Latitude of node coordinates face_node_connectivity : np.ndarray Face node connectivity, mapping each face to the nodes that surround them - fill_value: Optional + fill_value: int | float | None Value used for padding connectivity variables when the maximum number of elements in a row is less than the maximum. - start_index: Optional, default=0 + start_index: int | None, default=0 Start index (typically 0 or 1) - dims_dict : Optional, dict + dims_dict : dict | None Dictionary of dimension names mapped to the ugrid conventions (i.e. {"nVertices": "n_node}) **kwargs : @@ -483,7 +476,7 @@ def from_topology( @classmethod def from_structured( - cls, ds: xr.Dataset = None, lon=None, lat=None, tol: Optional[float] = 1e-10 + cls, ds: xr.Dataset = None, lon=None, lat=None, tol: float | None = 1e-10 ): """ Converts a structured ``xarray.Dataset`` or longitude and latitude coordinates into an unstructured ``uxarray.Grid``. @@ -530,8 +523,8 @@ def from_structured( @classmethod def from_face_vertices( cls, - face_vertices: Union[list, tuple, np.ndarray], - latlon: Optional[bool] = True, + face_vertices: list | tuple | np.ndarray, + latlon: bool | None = True, ): """Constructs a ``Grid`` object from user-defined face vertices. @@ -1719,9 +1712,9 @@ def chunk(self, n_node="auto", n_edge="auto", n_face="auto"): def get_ball_tree( self, - coordinates: Optional[str] = "face centers", - coordinate_system: Optional[str] = "spherical", - distance_metric: Optional[str] = "haversine", + coordinates: str | None = "face centers", + coordinate_system: str | None = "spherical", + distance_metric: str | None = "haversine", reconstruct: bool = False, ): """Get the BallTree data structure of this Grid that allows for nearest @@ -1768,7 +1761,7 @@ def get_ball_tree( return self._ball_tree def _get_scipy_kd_tree( - self, coordinates: Optional[str] = "face", reconstruct: bool = False + self, coordinates: str | None = "face", reconstruct: bool = False ): """ Build or retrieve a KDTree for efficient nearest-neighbor searches on grid points. @@ -1821,9 +1814,9 @@ def _get_scipy_kd_tree( def get_kd_tree( self, - coordinates: Optional[str] = "face centers", - coordinate_system: Optional[str] = "cartesian", - distance_metric: Optional[str] = "minkowski", + coordinates: str | None = "face centers", + coordinate_system: str | None = "cartesian", + distance_metric: str | None = "minkowski", reconstruct: bool = False, ): """Get the KDTree data structure of this Grid that allows for nearest @@ -1921,9 +1914,9 @@ def copy(self): def calculate_total_face_area( self, - quadrature_rule: Optional[str] = "triangular", - order: Optional[int] = 4, - latitude_adjusted_area: Optional[bool] = False, + quadrature_rule: str | None = "triangular", + order: int | None = 4, + latitude_adjusted_area: bool | None = False, ) -> float: """Function to calculate the total surface area of all the faces in a mesh. @@ -1946,9 +1939,9 @@ def calculate_total_face_area( def compute_face_areas( self, - quadrature_rule: Optional[str] = "triangular", - order: Optional[int] = 4, - latitude_adjusted_area: Optional[bool] = False, + quadrature_rule: str | None = "triangular", + order: int | None = 4, + latitude_adjusted_area: bool | None = False, ): """Face areas calculation function for grid class, calculates area of all faces in the grid. @@ -1990,9 +1983,9 @@ def compute_face_areas( def _compute_face_areas( self, - quadrature_rule: Optional[str] = "triangular", - order: Optional[int] = 4, - latitude_adjusted_area: Optional[bool] = False, + quadrature_rule: str | None = "triangular", + order: int | None = 4, + latitude_adjusted_area: bool | None = False, ): """Internal face areas calculation function for grid class, calculates area of all faces in the grid. @@ -2117,7 +2110,7 @@ def sphere_radius(self, radius: float) -> None: self._ds.attrs["sphere_radius"] = radius - def to_xarray(self, grid_format: Optional[str] = "ugrid"): + def to_xarray(self, grid_format: str | None = "ugrid"): """Returns an ``xarray.Dataset`` with the variables stored under the ``Grid`` encoded in a specific grid format. @@ -2163,14 +2156,14 @@ def to_xarray(self, grid_format: Optional[str] = "ugrid"): def to_geodataframe( self, - periodic_elements: Optional[str] = "exclude", + periodic_elements: str | None = "exclude", projection=None, - cache: Optional[bool] = True, - override: Optional[bool] = False, - engine: Optional[str] = "spatialpandas", - exclude_antimeridian: Optional[bool] = None, - return_non_nan_polygon_indices: Optional[bool] = False, - exclude_nan_polygons: Optional[bool] = True, + cache: bool | None = True, + override: bool | None = False, + engine: str | None = "spatialpandas", + exclude_antimeridian: bool | None = None, + return_non_nan_polygon_indices: bool | None = False, + exclude_nan_polygons: bool | None = True, **kwargs, ): """Constructs a ``GeoDataFrame`` consisting of polygons representing @@ -2405,9 +2398,7 @@ def get_dual(self, check_duplicate_nodes: bool = False): return dual - def isel( - self, inverse_indices: Union[List[str], Set[str], bool] = False, **dim_kwargs - ): + def isel(self, inverse_indices: list[str] | set[str] | bool = False, **dim_kwargs): """Indexes an unstructured grid along a given dimension (``n_node``, ``n_edge``, or ``n_face``) and returns a new grid. @@ -2418,7 +2409,7 @@ def isel( Parameters ---------- - inverse_indices : Union[List[str], Set[str], bool], default=False + inverse_indices : list[str] | set[str] | bool, default=False Indicates whether to store the original grids indices. Passing `True` stores the original face indices, other reverse indices can be stored by passing any or all of the following: (["face", "edge", "node"], True) **dims_kwargs: kwargs @@ -2584,12 +2575,12 @@ def get_faces_at_constant_longitude(self, lon: float): faces = constant_lon_intersections_face_bounds(lon, self.face_bounds_lon.values) return faces - def get_faces_between_longitudes(self, lons: Tuple[float, float]): + def get_faces_between_longitudes(self, lons: tuple[float, float]): """Identifies the indices of faces that are strictly between two lines of constant longitude. Parameters ---------- - lons: Tuple[float, float] + lons: tuple[float, float] A tuple of longitudes that define that minimum and maximum longitude. Returns @@ -2600,12 +2591,12 @@ def get_faces_between_longitudes(self, lons: Tuple[float, float]): """ return faces_within_lon_bounds(lons, self.face_bounds_lon.values) - def get_faces_between_latitudes(self, lats: Tuple[float, float]): + def get_faces_between_latitudes(self, lats: tuple[float, float]): """Identifies the indices of faces that are strictly between two lines of constant latitude. Parameters ---------- - lats: Tuple[float, float + lats: tuple[float, float] A tuple of latitudes that define that minimum and maximum latitudes. Returns @@ -2620,7 +2611,7 @@ def get_faces_containing_point( self, points: Sequence[float] | np.ndarray, return_counts: bool = True, - ) -> Tuple[np.ndarray, np.ndarray] | List[List[int]]: + ) -> tuple[np.ndarray, np.ndarray] | list[list[int]]: """ Identify which grid faces contain the given point(s). @@ -2646,7 +2637,7 @@ def get_faces_containing_point( Number of valid face indices in each row of `face_indices`. If `return_counts=False`: - List[List[int]] + list[list[int]] Python list of length `N`, where each element is the list of face indices for that point (no padding, in natural order). @@ -2692,7 +2683,7 @@ def get_faces_containing_point( # Return a list of lists if counts are not desired if not return_counts: - output: List[List[int]] = [] + output: list[list[int]] = [] for i, c in enumerate(counts): output.append(face_indices[i, :c].tolist()) return output diff --git a/uxarray/grid/neighbors.py b/uxarray/grid/neighbors.py index 62480b62b..1c4d4f145 100644 --- a/uxarray/grid/neighbors.py +++ b/uxarray/grid/neighbors.py @@ -1,5 +1,3 @@ -from typing import Optional, Union - import numpy as np import xarray as xr from numba import njit @@ -40,9 +38,9 @@ class KDTree: def __init__( self, grid, - coordinates: Optional[str] = "face centers", - coordinate_system: Optional[str] = "cartesian", - distance_metric: Optional[str] = "minkowski", + coordinates: str | None = "face centers", + coordinate_system: str | None = "cartesian", + distance_metric: str | None = "minkowski", reconstruct: bool = False, ): # Set up references @@ -203,13 +201,13 @@ def _current_tree(self): def query( self, - coords: Union[np.ndarray, list, tuple], - k: Optional[int] = 1, - return_distance: Optional[bool] = True, - in_radians: Optional[bool] = False, - dualtree: Optional[bool] = False, - breadth_first: Optional[bool] = False, - sort_results: Optional[bool] = True, + coords: np.ndarray | list | tuple, + k: int | None = 1, + return_distance: bool | None = True, + in_radians: bool | None = False, + dualtree: bool | None = False, + breadth_first: bool | None = False, + sort_results: bool | None = True, ): """Queries the tree for the ``k`` nearest neighbors. @@ -289,12 +287,12 @@ def query( def query_radius( self, - coords: Union[np.ndarray, list, tuple], - r: Optional[int] = 1.0, - return_distance: Optional[bool] = False, - in_radians: Optional[bool] = False, - count_only: Optional[bool] = False, - sort_results: Optional[bool] = False, + coords: np.ndarray | list | tuple, + r: int | None = 1.0, + return_distance: bool | None = False, + in_radians: bool | None = False, + count_only: bool | None = False, + sort_results: bool | None = False, ): """Queries the tree for all neighbors within a radius ``r``. @@ -432,9 +430,9 @@ class BallTree: def __init__( self, grid, - coordinates: Optional[str] = "face centers", - coordinate_system: Optional[str] = "spherical", - distance_metric: Optional[str] = "haversine", + coordinates: str | None = "face centers", + coordinate_system: str | None = "spherical", + distance_metric: str | None = "haversine", reconstruct: bool = False, ): # maintain a reference to the source grid @@ -589,13 +587,13 @@ def _current_tree(self): def query( self, - coords: Union[np.ndarray, list, tuple], - k: Optional[int] = 1, - in_radians: Optional[bool] = False, - return_distance: Optional[bool] = True, - dualtree: Optional[bool] = False, - breadth_first: Optional[bool] = False, - sort_results: Optional[bool] = True, + coords: np.ndarray | list | tuple, + k: int | None = 1, + in_radians: bool | None = False, + return_distance: bool | None = True, + dualtree: bool | None = False, + breadth_first: bool | None = False, + sort_results: bool | None = True, ): """Queries the tree for the ``k`` nearest neighbors. @@ -674,12 +672,12 @@ def query( def query_radius( self, - coords: Union[np.ndarray, list, tuple], - r: Optional[int] = 1.0, - in_radians: Optional[bool] = False, - return_distance: Optional[bool] = False, - count_only: Optional[bool] = False, - sort_results: Optional[bool] = False, + coords: np.ndarray | list | tuple, + r: int | None = 1.0, + in_radians: bool | None = False, + return_distance: bool | None = False, + count_only: bool | None = False, + sort_results: bool | None = False, ): """Queries the tree for all neighbors within a radius ``r``. @@ -894,9 +892,9 @@ def _initialize_face_hash_table(self): def query( self, - coords: Union[np.ndarray, list, tuple], - in_radians: Optional[bool] = False, - tol: Optional[float] = 1e-6, + coords: np.ndarray | list | tuple, + in_radians: bool | None = False, + tol: float | None = 1e-6, ): """Queries the hash table. diff --git a/uxarray/grid/point_in_face.py b/uxarray/grid/point_in_face.py index 9d5e93f1a..a622eb8dc 100644 --- a/uxarray/grid/point_in_face.py +++ b/uxarray/grid/point_in_face.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Tuple +from typing import TYPE_CHECKING import numpy as np from numba import njit, prange @@ -130,7 +130,7 @@ def _batch_point_in_face( node_x: np.ndarray, node_y: np.ndarray, node_z: np.ndarray, -) -> Tuple[np.ndarray, np.ndarray]: +) -> tuple[np.ndarray, np.ndarray]: """ Parallel entry-point: for each point, test all candidate faces in batch. @@ -177,7 +177,7 @@ def _batch_point_in_face( def _point_in_face_query( source_grid: Grid, points: ArrayLike -) -> Tuple[np.ndarray, np.ndarray]: +) -> tuple[np.ndarray, np.ndarray]: """ Find grid faces that contain given Cartesian point(s) on the unit sphere. diff --git a/uxarray/grid/slice.py b/uxarray/grid/slice.py index bbd149b16..3bc97b9d1 100644 --- a/uxarray/grid/slice.py +++ b/uxarray/grid/slice.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Set, Union +from typing import TYPE_CHECKING import numpy as np import xarray as xr @@ -75,7 +75,7 @@ def _slice_face_indices( grid, indices, inclusive=True, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Slices (indexes) an unstructured grid given a list/array of face indices, returning a new Grid composed of elements that contain the faces @@ -90,7 +90,7 @@ def _slice_face_indices( inclusive: bool Whether to perform inclusive (i.e. elements must contain at least one desired feature from a slice) as opposed to exclusive (i.e elements be made up all desired features from a slice) - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Indicates whether to store the original grids indices. Passing `True` stores the original face centers, other reverse indices can be stored by passing any or all of the following: (["face", "edge", "node"], True) """ diff --git a/uxarray/plot/accessor.py b/uxarray/plot/accessor.py index 6f28c0fcc..2085b6095 100644 --- a/uxarray/plot/accessor.py +++ b/uxarray/plot/accessor.py @@ -1,7 +1,7 @@ from __future__ import annotations import warnings -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any import pandas as pd @@ -366,14 +366,14 @@ def __getattr__(self, name: str) -> Any: def polygons( self, - periodic_elements: Optional[str] = "exclude", - backend: Optional[str] = None, - engine: Optional[str] = "spatialpandas", - rasterize: Optional[bool] = True, - dynamic: Optional[bool] = False, + periodic_elements: str | None = "exclude", + backend: str | None = None, + engine: str | None = "spatialpandas", + rasterize: bool | None = True, + dynamic: bool | None = False, projection=None, - xlabel: Optional[str] = "Longitude", - ylabel: Optional[str] = "Latitude", + xlabel: str | None = "Longitude", + ylabel: str | None = "Latitude", *args, **kwargs, ): diff --git a/uxarray/subset/dataarray_accessor.py b/uxarray/subset/dataarray_accessor.py index 97c108c5f..f240b0958 100644 --- a/uxarray/subset/dataarray_accessor.py +++ b/uxarray/subset/dataarray_accessor.py @@ -1,7 +1,5 @@ from __future__ import annotations -from typing import List, Optional, Set, Tuple, Union - import numpy as np @@ -28,9 +26,9 @@ def __repr__(self): def bounding_box( self, - lon_bounds: Union[Tuple, List, np.ndarray], - lat_bounds: Union[Tuple, List, np.ndarray], - inverse_indices: Union[List[str], Set[str], bool] = False, + lon_bounds: tuple | list | np.ndarray, + lat_bounds: tuple | list | np.ndarray, + inverse_indices: list[str] | set[str] | bool = False, ): """Subsets an unstructured grid between two latitude and longitude points which form a bounding box. @@ -50,10 +48,10 @@ def bounding_box( face centers, or edge centers lie within the bounds. element: str Element for use with `coords` comparison, one of `nodes`, `face centers`, or `edge centers` - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) """ grid = self.uxda.uxgrid.subset.bounding_box( @@ -64,10 +62,10 @@ def bounding_box( def bounding_circle( self, - center_coord: Union[Tuple, List, np.ndarray], - r: Union[float, int], - element: Optional[str] = "face centers", - inverse_indices: Union[List[str], Set[str], bool] = False, + center_coord: tuple | list | np.ndarray, + r: float | int, + element: str | None = "face centers", + inverse_indices: list[str] | set[str] | bool = False, **kwargs, ): """Subsets an unstructured grid by returning all elements within some @@ -81,10 +79,10 @@ def bounding_circle( Radius of bounding circle (in degrees) element: str Element for use with `coords` comparison, one of `nodes`, `face centers`, or `edge centers` - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) """ grid = self.uxda.uxgrid.subset.bounding_circle( @@ -94,10 +92,10 @@ def bounding_circle( def nearest_neighbor( self, - center_coord: Union[Tuple, List, np.ndarray], + center_coord: tuple | list | np.ndarray, k: int, - element: Optional[str] = "face centers", - inverse_indices: Union[List[str], Set[str], bool] = False, + element: str | None = "face centers", + inverse_indices: list[str] | set[str] | bool = False, **kwargs, ): """Subsets an unstructured grid by returning the ``k`` closest @@ -111,10 +109,10 @@ def nearest_neighbor( Number of neighbors to query element: str Element for use with `coords` comparison, one of `nodes`, `face centers`, or `edge centers` - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) """ @@ -127,7 +125,7 @@ def nearest_neighbor( def constant_latitude( self, lat: float, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of the data array across a line of constant-latitude. @@ -136,10 +134,10 @@ def constant_latitude( lat : float The latitude at which to extract the subset, in degrees. Must be between -90.0 and 90.0 - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns @@ -179,7 +177,7 @@ def constant_latitude( def constant_longitude( self, lon: float, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of the data array across a line of constant-longitude. @@ -188,10 +186,10 @@ def constant_longitude( lon : float The longitude at which to extract the subset, in degrees. Must be between -180.0 and 180.0 - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns @@ -233,21 +231,21 @@ def constant_longitude( def constant_latitude_interval( self, - lats: Tuple[float, float], - inverse_indices: Union[List[str], Set[str], bool] = False, + lats: tuple[float, float], + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of data by selecting all faces that are within a specified latitude interval. Parameters ---------- - lats : Tuple[float, float] + lats : tuple[float, float] The latitude interval (min_lat, max_lat) at which to extract the subset, in degrees. Values must be between -90.0 and 90.0 - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns @@ -274,20 +272,20 @@ def constant_latitude_interval( def constant_longitude_interval( self, - lons: Tuple[float, float], - inverse_indices: Union[List[str], Set[str], bool] = False, + lons: tuple[float, float], + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of data by selecting all faces that are within a specified longitude interval. Parameters ---------- - lons : Tuple[float, float] + lons : tuple[float, float] The longitude interval (min_lon, max_lon) at which to extract the subset, in degrees. Values must be between -180.0 and 180.0 - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns diff --git a/uxarray/subset/grid_accessor.py b/uxarray/subset/grid_accessor.py index 4d9cf5d64..30e263e2c 100644 --- a/uxarray/subset/grid_accessor.py +++ b/uxarray/subset/grid_accessor.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional, Set, Tuple, Union +from typing import TYPE_CHECKING import numpy as np @@ -31,9 +31,9 @@ def __repr__(self): def bounding_box( self, - lon_bounds: Tuple[float, float], - lat_bounds: Tuple[float, float], - inverse_indices: Union[List[str], Set[str], bool] = False, + lon_bounds: tuple[float, float], + lat_bounds: tuple[float, float], + inverse_indices: list[str] | set[str] | bool = False, ): """Subsets an unstructured grid between two latitude and longitude points which form a bounding box. @@ -48,10 +48,10 @@ def bounding_box( the antimeridian, otherwise lon_left > lon_right, both between [-180, 180] lat_bounds: tuple, list, np.ndarray (lat_bottom, lat_top) where lat_top > lat_bottom and between [-90, 90] - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) """ @@ -64,10 +64,10 @@ def bounding_box( def bounding_circle( self, - center_coord: Union[Tuple, List, np.ndarray], - r: Union[float, int], - element: Optional[str] = "face centers", - inverse_indices: Union[List[str], Set[str], bool] = False, + center_coord: tuple | list | np.ndarray, + r: float | int, + element: str | None = "face centers", + inverse_indices: list[str] | set[str] | bool = False, **kwargs, ): """Subsets an unstructured grid by returning all elements within some @@ -81,10 +81,10 @@ def bounding_circle( Radius of bounding circle (in degrees) element: str Element for use with `coords` comparison, one of `nodes`, `face centers`, or `edge centers` - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) """ @@ -103,10 +103,10 @@ def bounding_circle( def nearest_neighbor( self, - center_coord: Union[Tuple, List, np.ndarray], + center_coord: tuple | list | np.ndarray, k: int, - element: Optional[str] = "face centers", - inverse_indices: Union[List[str], Set[str], bool] = False, + element: str | None = "face centers", + inverse_indices: list[str] | set[str] | bool = False, **kwargs, ): """Subsets an unstructured grid by returning the ``k`` closest @@ -120,10 +120,10 @@ def nearest_neighbor( Number of neighbors to query element: str Element for use with `coords` comparison, one of `nodes`, `face centers`, or `edge centers` - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) """ @@ -139,7 +139,7 @@ def constant_latitude( self, lat: float, return_face_indices: bool = False, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of the grid by selecting all faces that intersect with a specified line of constant latitude. @@ -152,10 +152,10 @@ def constant_latitude( return_face_indices : bool, optional If True, also returns the indices of the faces that intersect with the line of constant latitude. - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns @@ -163,7 +163,7 @@ def constant_latitude( uxarray.Grid A subset of the original grid containing only the faces that intersect with the specified latitude. - Tuple[uxarray.Grid, numpy.ndarray], optional + tuple[uxarray.Grid, numpy.ndarray], optional If return_face_indices=True, returns a tuple of (grid_subset, face_indices) Raises @@ -206,7 +206,7 @@ def constant_longitude( self, lon: float, return_face_indices: bool = False, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of the grid by selecting all faces that intersect with a specified line of constant longitude. @@ -219,10 +219,10 @@ def constant_longitude( return_face_indices : bool, optional If True, also returns the indices of the faces that intersect with the line of constant longitude. - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns @@ -230,7 +230,7 @@ def constant_longitude( uxarray.Grid A subset of the original grid containing only the faces that intersect with the specified longitude. - Tuple[uxarray.Grid, numpy.ndarray], optional + tuple[uxarray.Grid, numpy.ndarray], optional If return_face_indices=True, returns a tuple of (grid_subset, face_indices) Raises @@ -270,32 +270,32 @@ def constant_longitude( def constant_latitude_interval( self, - lats: Tuple[float, float], + lats: tuple[float, float], return_face_indices: bool = False, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of the grid by selecting all faces that are within a specified latitude interval. Parameters ---------- - lats : Tuple[float, float] + lats : tuple[float, float] The latitude interval (min_lat, max_lat) at which to extract the subset, in degrees. Values must be between -90.0 and 90.0 return_face_indices : bool, optional If True, also returns the indices of the faces that intersect with the latitude interval. - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns ------- uxarray.Grid A subset of the original grid containing only the faces that are within a specified latitude interval. - Tuple[uxarray.Grid, numpy.ndarray], optional + tuple[uxarray.Grid, numpy.ndarray], optional If return_face_indices=True, returns a tuple of (grid_subset, face_indices) Raises @@ -332,23 +332,23 @@ def constant_latitude_interval( def constant_longitude_interval( self, - lons: Tuple[float, float], + lons: tuple[float, float], return_face_indices: bool = False, - inverse_indices: Union[List[str], Set[str], bool] = False, + inverse_indices: list[str] | set[str] | bool = False, ): """Extracts a subset of the grid by selecting all faces that are within a specified longitude interval. Parameters ---------- - lons : Tuple[float, float] + lons : tuple[float, float] The longitude interval (min_lon, max_lon) at which to extract the subset, in degrees. Values must be between -180.0 and 180.0 return_face_indices : bool, optional If True, also returns the indices of the faces that are within a specified longitude interval. - inverse_indices : Union[List[str], Set[str], bool], optional + inverse_indices : list[str] | set[str] | bool, optional Controls storage of original grid indices. Options: - True: Stores original face indices - - List/Set of strings: Stores specified index types (valid values: "face", "edge", "node") + - list/set of strings: Stores specified index types (valid values: "face", "edge", "node") - False: No index storage (default) Returns @@ -356,7 +356,7 @@ def constant_longitude_interval( uxarray.Grid A subset of the original grid containing only the faces that intersect with the specified longitude interval. - Tuple[uxarray.Grid, numpy.ndarray], optional + tuple[uxarray.Grid, numpy.ndarray], optional If return_face_indices=True, returns a tuple of (grid_subset, face_indices) Raises