Skip to content

Commit 5ef66d8

Browse files
authored
Merge pull request #1652 from UXARRAY/sevans/error-types-cleanup
Fix misleading/confusing error types throughout uxarray
2 parents 3228024 + 908a503 commit 5ef66d8

17 files changed

Lines changed: 40 additions & 32 deletions

File tree

test/core/test_api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def test_open_dataset_single_argument_rejects_invalid_combined_file(datasetpath)
8585

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

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

9191

test/grid/grid/test_core.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,5 +131,5 @@ def test_dual_mesh_mpas(gridpath):
131131
def test_dual_duplicate(gridpath):
132132
"""Test dual mesh creation with duplicate grids."""
133133
dataset = ux.open_dataset(gridpath("ugrid", "geoflow-small", "grid.nc"), gridpath("ugrid", "geoflow-small", "grid.nc"))
134-
with pytest.raises(RuntimeError):
134+
with pytest.raises(ux.errors.GridInvalidError):
135135
dataset.get_dual()

test/io/test_utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import pytest
33
import xarray as xr
44

5+
from uxarray.errors import GridInvalidError
56
from uxarray.io.utils import _parse_grid_type
67

78

@@ -61,5 +62,5 @@ def test_parse_grid_type_detects_structured_grid():
6162
],
6263
)
6364
def test_parse_grid_type_rejects_incomplete_format_signals(dataset):
64-
with pytest.raises(RuntimeError, match="Failed to parse uxgrid information from xarray.Dataset."):
65+
with pytest.raises(GridInvalidError, match="Failed to parse uxgrid information from xarray.Dataset."):
6566
_parse_grid_type(dataset)

uxarray/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from . import tutorial
1+
from . import errors, tutorial
22
from .constants import INT_DTYPE, INT_FILL_VALUE
33
from .core.api import (
44
concat,
@@ -37,4 +37,5 @@
3737
"INT_DTYPE",
3838
"INT_FILL_VALUE",
3939
"Grid",
40+
"errors",
4041
)

uxarray/core/aggregation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def _node_to_face_aggregation(uxda, aggregation, aggregation_func_kwargs):
9090
uxda, NUMPY_AGGREGATIONS[aggregation], aggregation_func_kwargs
9191
)
9292
else:
93-
raise ValueError
93+
raise TypeError
9494

9595
return uxarray.core.dataarray.UxDataArray(
9696
uxgrid=uxda.uxgrid,
@@ -158,7 +158,7 @@ def _node_to_edge_aggregation(uxda, aggregation, aggregation_func_kwargs):
158158
uxda, NUMPY_AGGREGATIONS[aggregation], aggregation_func_kwargs
159159
)
160160
else:
161-
raise ValueError
161+
raise TypeError
162162

163163
return uxarray.core.dataarray.UxDataArray(
164164
uxgrid=uxda.uxgrid,

uxarray/core/dataarray.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -860,7 +860,7 @@ def zonal_anomaly(self, lat=(-90, 90, 10), conservative: bool = False):
860860
elif isinstance(lat, (list, np.ndarray)):
861861
edges = np.asarray(lat, dtype=float)
862862
else:
863-
raise ValueError(
863+
raise TypeError(
864864
"Invalid value for 'lat'. Must be a tuple (start, end, step) or array-like band edges."
865865
)
866866

@@ -2167,7 +2167,7 @@ def get_dual(self):
21672167
"""
21682168

21692169
if _check_duplicate_nodes_indices(self.uxgrid):
2170-
raise RuntimeError("Duplicate nodes found, cannot construct dual")
2170+
raise GridInvalidError("Duplicate nodes found, cannot construct dual")
21712171

21722172
if self.uxgrid.partial_sphere_coverage:
21732173
warn(

uxarray/core/dataset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,7 @@ def get_dual(self):
708708
"""
709709

710710
if _check_duplicate_nodes_indices(self.uxgrid):
711-
raise RuntimeError("Duplicate nodes found, cannot construct dual")
711+
raise GridInvalidError("Duplicate nodes found, cannot construct dual")
712712

713713
if self.uxgrid.partial_sphere_coverage:
714714
warn(

uxarray/grid/bounds.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True):
416416
else:
417417
# Validate longitude point
418418
if not np.isnan(lon_pt) and (lon_pt < 0.0 or lon_pt > 2.0 * np.pi):
419-
raise Exception("Longitude point out of range")
419+
raise ValueError("Longitude point out of range")
420420

421421
# Check for pole points
422422
is_pole_point = False
@@ -465,7 +465,7 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True):
465465

466466
# Ensure widths are non-negative
467467
if (d_width_a < 0.0) or (d_width_b < 0.0):
468-
raise Exception(
468+
raise AssertionError(
469469
"Logic error in longitude box width calculation"
470470
)
471471

uxarray/grid/grid.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# Import the utility function for opening datasets with fallback
1818
from uxarray.core.utils import _open_dataset_with_fallback
1919
from uxarray.cross_sections import GridCrossSectionAccessor
20-
from uxarray.errors import DataCenteringError, GridInvalidError
20+
from uxarray.errors import DataCenteringError, DimensionError, GridInvalidError
2121
from uxarray.formatting_html import grid_repr
2222
from uxarray.grid.area import _get_all_face_area_from_coords
2323
from uxarray.grid.bounds import _populate_face_bounds
@@ -569,7 +569,7 @@ def from_face_vertices(
569569
Indicates whether the inputted vertices are in lat/lon, with units in degrees
570570
"""
571571
if not isinstance(face_vertices, (list, tuple, np.ndarray)):
572-
raise ValueError("Input must be either a list, tuple, or np.ndarray")
572+
raise TypeError("Input must be either a list, tuple, or np.ndarray")
573573

574574
face_vertices = np.asarray(face_vertices)
575575

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

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

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

16171617
return self._ds["boundary_node_indices"]
16181618

@@ -1663,7 +1663,7 @@ def inverse_indices(self) -> xr.Dataset:
16631663
if self.is_subset:
16641664
return self._inverse_indices
16651665
else:
1666-
raise Exception(
1666+
raise AttributeError(
16671667
"Grid is not a subset, therefore no inverse face indices exist"
16681668
)
16691669

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

25392539
# Get dual mesh node face connectivity
25402540
dual_node_face_conn = construct_dual(grid=self)

uxarray/grid/neighbors.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from numpy import deg2rad
55

66
from uxarray.constants import ERROR_TOLERANCE, INT_DTYPE, INT_FILL_VALUE
7+
from uxarray.errors import DimensionError
78

89

910
class KDTree:
@@ -96,7 +97,7 @@ def _build_from_nodes(self):
9697
).T
9798

9899
else:
99-
raise TypeError(
100+
raise ValueError(
100101
f"Unknown coordinate_system, {self.coordinate_system}, use either 'cartesian' or "
101102
f"'spherical'"
102103
)
@@ -192,7 +193,7 @@ def _current_tree(self):
192193
elif self._coordinates == "edge centers":
193194
_tree = self._tree_from_edge_centers
194195
else:
195-
raise TypeError(
196+
raise ValueError(
196197
f"Unknown coordinates location, {self._coordinates}, use either 'nodes', 'face centers', "
197198
f"or 'edge centers'"
198199
)
@@ -1010,13 +1011,13 @@ def _prepare_xy_for_query(xy, use_radians, distance_metric):
10101011

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

10181019
if xy.shape[1] != 2:
1019-
raise AssertionError(
1020+
raise DimensionError(
10201021
"The dimension of each coordinate pair must be two (lon, lat).)"
10211022
)
10221023

@@ -1044,13 +1045,13 @@ def _prepare_xyz_for_query(xyz):
10441045

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

10521053
if xyz.shape[1] != 3:
1053-
raise AssertionError(
1054+
raise DimensionError(
10541055
"The dimension of each coordinate pair must be three (x, y, z).)"
10551056
)
10561057

0 commit comments

Comments
 (0)