Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion test/core/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def test_open_dataset_single_argument_rejects_invalid_combined_file(datasetpath)

data_path = datasetpath("ugrid", "outCSne30", "outCSne30_var2.nc")

with pytest.raises(RuntimeError, match="Failed to parse uxgrid information from xarray.Dataset."):
with pytest.raises(ux.errors.GridInvalidError, match="Failed to parse uxgrid information from xarray.Dataset."):
ux.open_dataset(data_path)


Expand Down
2 changes: 1 addition & 1 deletion test/grid/grid/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,5 +131,5 @@ def test_dual_mesh_mpas(gridpath):
def test_dual_duplicate(gridpath):
"""Test dual mesh creation with duplicate grids."""
dataset = ux.open_dataset(gridpath("ugrid", "geoflow-small", "grid.nc"), gridpath("ugrid", "geoflow-small", "grid.nc"))
with pytest.raises(RuntimeError):
with pytest.raises(ux.errors.GridInvalidError):
dataset.get_dual()
3 changes: 2 additions & 1 deletion test/io/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pytest
import xarray as xr

from uxarray.errors import GridInvalidError
from uxarray.io.utils import _parse_grid_type


Expand Down Expand Up @@ -61,5 +62,5 @@ def test_parse_grid_type_detects_structured_grid():
],
)
def test_parse_grid_type_rejects_incomplete_format_signals(dataset):
with pytest.raises(RuntimeError, match="Failed to parse uxgrid information from xarray.Dataset."):
with pytest.raises(GridInvalidError, match="Failed to parse uxgrid information from xarray.Dataset."):
_parse_grid_type(dataset)
3 changes: 2 additions & 1 deletion uxarray/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from . import tutorial
from . import errors, tutorial
from .constants import INT_DTYPE, INT_FILL_VALUE
from .core.api import (
concat,
Expand Down Expand Up @@ -37,4 +37,5 @@
"INT_DTYPE",
"INT_FILL_VALUE",
"Grid",
"errors",
)
4 changes: 2 additions & 2 deletions uxarray/core/aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def _node_to_face_aggregation(uxda, aggregation, aggregation_func_kwargs):
uxda, NUMPY_AGGREGATIONS[aggregation], aggregation_func_kwargs
)
else:
raise ValueError
raise TypeError

return uxarray.core.dataarray.UxDataArray(
uxgrid=uxda.uxgrid,
Expand Down Expand Up @@ -158,7 +158,7 @@ def _node_to_edge_aggregation(uxda, aggregation, aggregation_func_kwargs):
uxda, NUMPY_AGGREGATIONS[aggregation], aggregation_func_kwargs
)
else:
raise ValueError
raise TypeError

return uxarray.core.dataarray.UxDataArray(
uxgrid=uxda.uxgrid,
Expand Down
4 changes: 2 additions & 2 deletions uxarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,7 +860,7 @@ def zonal_anomaly(self, lat=(-90, 90, 10), conservative: bool = False):
elif isinstance(lat, (list, np.ndarray)):
edges = np.asarray(lat, dtype=float)
else:
raise ValueError(
raise TypeError(
"Invalid value for 'lat'. Must be a tuple (start, end, step) or array-like band edges."
)

Expand Down Expand Up @@ -2167,7 +2167,7 @@ def get_dual(self):
"""

if _check_duplicate_nodes_indices(self.uxgrid):
raise RuntimeError("Duplicate nodes found, cannot construct dual")
raise GridInvalidError("Duplicate nodes found, cannot construct dual")

if self.uxgrid.partial_sphere_coverage:
warn(
Expand Down
2 changes: 1 addition & 1 deletion uxarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,7 @@ def get_dual(self):
"""

if _check_duplicate_nodes_indices(self.uxgrid):
raise RuntimeError("Duplicate nodes found, cannot construct dual")
raise GridInvalidError("Duplicate nodes found, cannot construct dual")

if self.uxgrid.partial_sphere_coverage:
warn(
Expand Down
4 changes: 2 additions & 2 deletions uxarray/grid/bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True):
else:
# Validate longitude point
if not np.isnan(lon_pt) and (lon_pt < 0.0 or lon_pt > 2.0 * np.pi):
raise Exception("Longitude point out of range")
raise ValueError("Longitude point out of range")

# Check for pole points
is_pole_point = False
Expand Down Expand Up @@ -465,7 +465,7 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True):

# Ensure widths are non-negative
if (d_width_a < 0.0) or (d_width_b < 0.0):
raise Exception(
raise AssertionError(
"Logic error in longitude box width calculation"
)

Expand Down
14 changes: 7 additions & 7 deletions uxarray/grid/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# Import the utility function for opening datasets with fallback
from uxarray.core.utils import _open_dataset_with_fallback
from uxarray.cross_sections import GridCrossSectionAccessor
from uxarray.errors import DataCenteringError, GridInvalidError
from uxarray.errors import DataCenteringError, DimensionError, GridInvalidError
from uxarray.formatting_html import grid_repr
from uxarray.grid.area import _get_all_face_area_from_coords
from uxarray.grid.bounds import _populate_face_bounds
Expand Down Expand Up @@ -569,7 +569,7 @@ def from_face_vertices(
Indicates whether the inputted vertices are in lat/lon, with units in degrees
"""
if not isinstance(face_vertices, (list, tuple, np.ndarray)):
raise ValueError("Input must be either a list, tuple, or np.ndarray")
raise TypeError("Input must be either a list, tuple, or np.ndarray")

face_vertices = np.asarray(face_vertices)

Expand All @@ -580,7 +580,7 @@ def from_face_vertices(
grid_ds = _read_face_vertices(np.array([face_vertices]), latlon)

else:
raise RuntimeError(
raise DimensionError(
f"Invalid Input Dimension: {face_vertices.ndim}. Expected dimension should be "
f"3: [n_face, n_node, two/three] or 2 when only "
f"one face is passed in."
Expand Down Expand Up @@ -633,7 +633,7 @@ def validate(self, check_duplicates=True):
print("Mesh validation successful.")
return True
else:
raise RuntimeError("Mesh validation failed.")
raise GridInvalidError("Mesh validation failed.")

def construct_face_centers(self, method="cartesian average"):
"""Constructs face centers, this method provides users direct control
Expand Down Expand Up @@ -1612,7 +1612,7 @@ def boundary_node_indices(self):
"""Indices of nodes that border regions not covered by any geometry
(holes) in a partial grid."""
if "boundary_node_indices" not in self._ds:
raise ValueError
raise NotImplementedError

return self._ds["boundary_node_indices"]

Expand Down Expand Up @@ -1663,7 +1663,7 @@ def inverse_indices(self) -> xr.Dataset:
if self.is_subset:
return self._inverse_indices
else:
raise Exception(
raise AttributeError(
"Grid is not a subset, therefore no inverse face indices exist"
)

Expand Down Expand Up @@ -2534,7 +2534,7 @@ def get_dual(self, check_duplicate_nodes: bool = False):
if check_duplicate_nodes:
if _check_duplicate_nodes_indices(self):
# TODO: This is very slow
raise RuntimeError("Duplicate nodes found, cannot construct dual")
raise GridInvalidError("Duplicate nodes found, cannot construct dual")

# Get dual mesh node face connectivity
dual_node_face_conn = construct_dual(grid=self)
Expand Down
13 changes: 7 additions & 6 deletions uxarray/grid/neighbors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from numpy import deg2rad

from uxarray.constants import ERROR_TOLERANCE, INT_DTYPE, INT_FILL_VALUE
from uxarray.errors import DimensionError


class KDTree:
Expand Down Expand Up @@ -96,7 +97,7 @@ def _build_from_nodes(self):
).T

else:
raise TypeError(
raise ValueError(
f"Unknown coordinate_system, {self.coordinate_system}, use either 'cartesian' or "
f"'spherical'"
)
Expand Down Expand Up @@ -192,7 +193,7 @@ def _current_tree(self):
elif self._coordinates == "edge centers":
_tree = self._tree_from_edge_centers
else:
raise TypeError(
raise ValueError(
f"Unknown coordinates location, {self._coordinates}, use either 'nodes', 'face centers', "
f"or 'edge centers'"
)
Expand Down Expand Up @@ -1010,13 +1011,13 @@ def _prepare_xy_for_query(xy, use_radians, distance_metric):

# expected shape is [n_pairs, 2]
if xy.shape[1] == 3:
raise AssertionError(
raise DimensionError(
"The dimension of each coordinate pair must be two (lon, lat). Did you attempt to query using Cartesian "
"(x, y, z) coordinates?"
)

if xy.shape[1] != 2:
raise AssertionError(
raise DimensionError(
"The dimension of each coordinate pair must be two (lon, lat).)"
)

Expand Down Expand Up @@ -1044,13 +1045,13 @@ def _prepare_xyz_for_query(xyz):

# expected shape is [n_pairs, 3]
if xyz.shape[1] == 2:
raise AssertionError(
raise DimensionError(
"The dimension of each coordinate pair must be three (x, y, z). Did you attempt to query using latlon "
"(lat, lon) coordinates?"
)

if xyz.shape[1] != 3:
raise AssertionError(
raise DimensionError(
"The dimension of each coordinate pair must be three (x, y, z).)"
)

Expand Down
4 changes: 2 additions & 2 deletions uxarray/grid/slice.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def _slice_node_indices(
"""

if inclusive is False:
raise ValueError("Exclusive slicing is not yet supported.")
raise NotImplementedError("Exclusive slicing is not yet supported.")

# faces that saddle nodes given in 'indices'
face_indices = np.unique(grid.node_face_connectivity.values[indices].ravel())
Expand Down Expand Up @@ -62,7 +62,7 @@ def _slice_edge_indices(
"""

if inclusive is False:
raise ValueError("Exclusive slicing is not yet supported.")
raise NotImplementedError("Exclusive slicing is not yet supported.")

# faces that saddle nodes given in 'indices'
face_indices = np.unique(grid.edge_face_connectivity.values[indices].ravel())
Expand Down
2 changes: 1 addition & 1 deletion uxarray/grid/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ def make_setter(key: str):

def setter(self, value):
if not isinstance(value, xr.DataArray):
raise ValueError(f"{key} must be an xr.DataArray")
raise TypeError(f"{key} must be an xr.DataArray")
self._ds[key] = value

return setter
2 changes: 1 addition & 1 deletion uxarray/io/_esmf.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def _read_esmf(in_ds):
)

else:
raise ValueError(
raise NotImplementedError(
"Reading in ESMF grids with Cartesian coordinates not yet supported"
)

Expand Down
4 changes: 3 additions & 1 deletion uxarray/io/_icon.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,6 @@ def _read_icon(ext_ds, use_dual=False):
if not use_dual:
return _primal_to_ugrid(ext_ds, out_ds)
else:
raise ValueError("Conversion of the ICON Dual mesh is not yet supported.")
raise NotImplementedError(
"Conversion of the ICON Dual mesh is not yet supported."
)
2 changes: 1 addition & 1 deletion uxarray/io/_scrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def _to_ugrid(in_ds, out_ds):
)

else:
raise Exception("Structured scrip files are not yet supported")
raise NotImplementedError("Structured scrip files are not yet supported")

# populate source dims
source_dims_dict[in_ds["grid_center_lon"].dims[0]] = "n_face"
Expand Down
5 changes: 4 additions & 1 deletion uxarray/io/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
import xarray as xr

from uxarray.errors import GridInvalidError
from uxarray.io._esmf import _esmf_to_ugrid_dims
from uxarray.io._icon import _icon_to_ugrid_dims
from uxarray.io._mpas import _mpas_to_ugrid_dims
Expand Down Expand Up @@ -120,7 +121,9 @@ def _parse_grid_type(dataset):
mesh_type = "Structured"
return mesh_type, lon_name, lat_name
else:
raise RuntimeError("Failed to parse uxgrid information from xarray.Dataset.")
raise GridInvalidError(
"Failed to parse uxgrid information from xarray.Dataset."
)

return mesh_type, None, None

Expand Down
2 changes: 1 addition & 1 deletion uxarray/remap/yac.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def _get_lon_lat(grid, dim: str) -> tuple[np.ndarray, np.ndarray]:
lon = getattr(grid, lon_attr, None)
lat = getattr(grid, lat_attr, None)
if lon is None or lat is None:
raise ValueError(
raise AttributeError(
f"Grid does not provide {lon_attr}/{lat_attr} required for YAC remapping."
)
return np.deg2rad(np.asarray(lon.values, dtype=np.float64)), np.deg2rad(
Expand Down