Skip to content
Closed
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
68 commits
Select commit Hold shift + click to select a range
657b612
Add function to test if lat and lon are in geographic coords
luseverin Sep 22, 2024
b594b7f
Add test for geographic coords in dist_to_coast
luseverin Sep 22, 2024
e36ded8
Add test for geographic coords in coord_on_land
luseverin Sep 22, 2024
dc78a13
Merge branch 'develop-white' into feature/remove_implicit_use_crs
luseverin Oct 23, 2024
b88ecc4
Switch branch feature/remove_implicite_use_crs to black format
luseverin Oct 23, 2024
96ede79
Merge branch 'develop-black' into feature/remove_implicit_use_crs
luseverin Oct 23, 2024
2bc5c6a
Merge branch 'develop' into feature/remove_implicit_use_crs
luseverin Oct 23, 2024
b139e8f
Merge branch 'develop' into feature/remove_implicit_use_crs
luseverin Jan 14, 2025
c8aac80
Merge branch 'develop' into feature/remove_implicit_use_crs
luseverin Mar 5, 2025
320d0f7
Extend allowed extent for geo coords
luseverin Mar 5, 2025
9ef7323
Modify allowed extents in geo_coords check function to allow for bounds
luseverin Mar 6, 2025
f27c4aa
Include possible wrong lat lon extension in error message
luseverin Mar 6, 2025
df439a5
Add check for geo coords in get_country_code
luseverin Mar 6, 2025
d3aea1e
Add test for geocoords in convert_wgs_to_utm
luseverin Mar 6, 2025
fb3cf7e
Update error message in coord_on_land
luseverin Mar 6, 2025
cf57963
Harmonize error messages
luseverin Mar 6, 2025
cb1e718
Adapt test get_country_geometries_fail
luseverin Mar 6, 2025
2a1f9b1
Check for geo coords in match_coordinates
luseverin Mar 6, 2025
322a9d3
Add check for lat in get_gridcellarea
luseverin Mar 6, 2025
60dc067
Modify check geo coords function to please linter
luseverin Mar 6, 2025
a0e02be
Add test for geo coords in calc of coriolis param
luseverin Mar 6, 2025
127d9cc
Add tests for check_if_geo_coords function
luseverin Mar 6, 2025
737fcd4
Merge branch 'develop' into feature/remove_implicit_use_crs
luseverin Apr 8, 2025
eca9f77
Incorporate suggestions from review 1
luseverin Apr 8, 2025
99635bf
Start adapating match_coordinates function to other crs
luseverin May 15, 2025
a642c04
Add handling of unit in match_centroids
luseverin May 15, 2025
eea31cb
Rename deg to degrees
luseverin May 15, 2025
35f0f7f
Add function to infer unit of coordinates
luseverin May 15, 2025
782b53d
Use infer_unit_coords in match_centroids function
luseverin May 15, 2025
ffee7f8
Add tests for unit_infer and unit-adapted match_coordinates
luseverin May 15, 2025
61e7b0f
Make test_tack_land_params compliant with new requirement of geodetic…
luseverin May 15, 2025
ef250c4
Correct wrong is_geodetic crs attribute
luseverin May 15, 2025
bca6e3a
Add restriction for haversine with non-degree units
luseverin May 15, 2025
54e2f75
Finish adding test for handling of different units
luseverin May 15, 2025
63bf8b5
Add test invalid unit for match coords and docstrings
luseverin May 15, 2025
da1c965
Update docstrings
luseverin May 15, 2025
5d53512
Try to fix new linter issues
luseverin May 15, 2025
54c8565
Correct error in logger warning
luseverin May 15, 2025
e1c9633
Force check_antimeridian to False in distance euclidean if unit is no…
luseverin Jun 19, 2025
fbcb163
Remove outdated test for raise of ValueError when check_antimeridian …
luseverin Jun 19, 2025
41b66bb
Add function to get coordinates from axis of coordinates'crs
luseverin Jun 27, 2025
7d1d3f3
Update unit names to be consistent with epsg notation and remove unit…
luseverin Jun 27, 2025
2176402
Clarify docstring check_if_geo_coords
luseverin Jun 27, 2025
8edb184
Make conversion between radians and degrees more consistent
luseverin Jun 27, 2025
91600a9
Remove deprecated infer_unit_coords function
luseverin Jun 27, 2025
f0d8dcc
Update tests
luseverin Jun 27, 2025
d45e55f
Force input coords and centroids to have crs attribute in match_centr…
luseverin Jun 27, 2025
409ff73
Re-harmonize unit names and raise error when crs of centroids or coor…
luseverin Jun 27, 2025
028fa0b
Add missing tests
luseverin Jun 27, 2025
2da2e2e
Fix linter issues
luseverin Jun 27, 2025
e2022ba
Refix linter
luseverin Jun 27, 2025
9c4b51e
Wrap valuerror raising in check_if_geo_coords
luseverin Jul 28, 2025
f14d5f0
Update tests
luseverin Jul 28, 2025
a733e8e
Remove useless info in get_crs_unit docstring
luseverin Jul 28, 2025
685c241
Raise separate exceptions for missing crs in coord_gdf and centroids
luseverin Jul 28, 2025
a5d5c20
Fix error in _nearest_neighbor_approx docstring
luseverin Jul 28, 2025
16bcc84
Make clearer error message for _nearest_neighbor with non-allowed units
luseverin Jul 30, 2025
07a4a73
Simplify crs check in match_centroids
luseverin Jul 30, 2025
f2d49b3
Correct typo and update tests for new error messages in match_centroids
luseverin Jul 30, 2025
0f3de31
Only warn for check_antimeridian when it is true and add tests
luseverin Jul 30, 2025
c67d6da
Allow for units other than degree km and m by keeping distance thresh…
luseverin Jul 30, 2025
a260848
Update thresholds in test to be consisten with handling of thresholds…
luseverin Jul 30, 2025
2f6bb5e
Remove mention to calling functions in error message in _nearest_neig…
luseverin Jul 30, 2025
734541a
Remove mention to calling functions in error message in _nearest_neig…
luseverin Jul 30, 2025
86d8126
Update docstrings match_centroids
luseverin Jul 30, 2025
faf8666
update docstrings for match_coordinates
luseverin Jul 30, 2025
b55b02a
Update changelog
luseverin Jul 30, 2025
45175c2
Remove confusing comments in code
luseverin Aug 5, 2025
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
5 changes: 5 additions & 0 deletions climada/hazard/trop_cyclone/trop_cyclone_windfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,11 @@ def _coriolis_parameter(lat: np.ndarray) -> np.ndarray:
cp : np.ndarray of same shape as input
Coriolis parameter.
"""
if not u_coord.check_if_geo_coords(lat, 0):
raise ValueError(
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon."
)
Comment thread
luseverin marked this conversation as resolved.
Outdated
return 2 * V_ANG_EARTH * np.sin(np.radians(np.abs(lat)))


Expand Down
60 changes: 57 additions & 3 deletions climada/util/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,24 @@
are not considered."""


def check_if_geo_coords(lat, lon):
"""
Check if latitude and longitude arrays are likely in geographic coordinates,
testing if min/max values are within -90 to 90 for latitude and -180 to 540
for longitude.
Returns True if lat/lon ranges are in the geographic coordinates range, otherwise False.
Comment thread
ValentinGebhart marked this conversation as resolved.
Outdated
"""
lat = np.array(lat)
lon = np.array(lon)

# Check if latitude is within -90 to 90 and longitude is within -180 to 540
# and extent are smaller than 180 and 360 respectively
test = (
lat.min() >= -91 and lat.max() <= 91 and lon.min() >= -181 and lon.max() <= 541
Comment thread
luseverin marked this conversation as resolved.
Outdated
) and ((lat.max() - lat.min()) <= 181 and (lon.max() - lon.min()) <= 361)
return bool(test)


def latlon_to_geosph_vector(lat, lon, rad=False, basis=False):
"""Convert lat/lon coodinates to radial vectors (on geosphere)

Expand Down Expand Up @@ -448,7 +466,12 @@ def get_gridcellarea(lat, resolution=0.5, unit="ha"):
unit: string, optional
unit of the output area (default: ha, alternatives: m2, km2)
"""

# first check that lat is in geographic coordinates
if not check_if_geo_coords(lat, 0):
raise ValueError(
"Input lat and lon coordinates are not geographic "
Comment thread
luseverin marked this conversation as resolved.
Outdated
"or have total extents > 180° for lat or > 360° for lon."
)
if unit == "m2":
area = (ONE_LAT_KM * resolution) ** 2 * np.cos(np.deg2rad(lat)) * 1000000
Comment thread
luseverin marked this conversation as resolved.
elif unit == "km2":
Expand Down Expand Up @@ -507,6 +530,11 @@ def convert_wgs_to_utm(lon, lat):
epsg_code : int
EPSG code of UTM projection.
"""
if not check_if_geo_coords(lat, lon):
raise ValueError(
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon."
Comment thread
luseverin marked this conversation as resolved.
Outdated
)
epsg_utm_base = 32601 + (0 if lat >= 0 else 100)
return epsg_utm_base + (math.floor((lon + 180) / 6) % 60)

Expand Down Expand Up @@ -564,6 +592,11 @@ def dist_to_coast(coord_lat, lon=None, highres=False, signed=False):
raise ValueError(
f"Mismatching input coordinates size: {lat.size} != {lon.size}"
)
if not check_if_geo_coords(lat, lon):
raise ValueError(
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon."
Comment thread
luseverin marked this conversation as resolved.
Outdated
)
return dist_to_coast_nasa(lat, lon, highres=highres, signed=signed)


Expand Down Expand Up @@ -679,6 +712,11 @@ def coord_on_land(lat, lon, land_geom=None):
)
if lat.size == 0:
return np.empty((0,), dtype=bool)
if not check_if_geo_coords(lat, lon):
raise ValueError(
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon."
Comment thread
luseverin marked this conversation as resolved.
Outdated
)
delta_deg = 1
lons = lon.copy()
if land_geom is None:
Expand Down Expand Up @@ -796,9 +834,10 @@ def get_country_geometries(
out = out[country_mask]

if extent:
if extent[1] - extent[0] > 360:
if not check_if_geo_coords(extent[2:], extent[:2]):
raise ValueError(
f"longitude extent range is greater than 360: {extent[0]} to {extent[1]}"
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon."
Comment thread
luseverin marked this conversation as resolved.
Outdated
)

if extent[1] < extent[0]:
Expand Down Expand Up @@ -1089,6 +1128,15 @@ def match_coordinates(

# assign remaining coordinates to their geographically nearest neighbor
if threshold > 0 and exact_assign_idx.size != coords_view.size:
# check that coords are geographic before proceeding to nearest neighbor search
if not (
check_if_geo_coords(coords[:, 0], coords[:, 1])
and check_if_geo_coords(coords_to_assign[:, 0], coords_to_assign[:, 1])
):
raise ValueError(
"Input lat and lon coordinates are not geographic "
Comment thread
luseverin marked this conversation as resolved.
Outdated
"or have total extents > 180° for lat or > 360° for lon."
)
not_assigned_idx_mask = assigned_idx == -1
assigned_idx[not_assigned_idx_mask] = nearest_neighbor_funcs[distance](
coords_to_assign, coords[not_assigned_idx_mask], threshold, **kwargs
Expand Down Expand Up @@ -1596,6 +1644,12 @@ def get_country_code(lat, lon, gridded=False):
return np.empty((0,), dtype=int)
LOGGER.info("Setting region_id %s points.", str(lat.size))
if gridded:
# first check that input lat lon are geographic
Comment thread
ValentinGebhart marked this conversation as resolved.
Outdated
if not check_if_geo_coords(lat, lon):
raise ValueError(
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon."
Comment thread
luseverin marked this conversation as resolved.
Outdated
)
base_file = u_hdf5.read(NATEARTH_CENTROIDS[150])
meta, region_id = base_file["meta"], base_file["region_id"]
transform = rasterio.Affine(*meta["transform"])
Expand Down
25 changes: 22 additions & 3 deletions climada/util/test/test_coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,23 @@ def data_arrays_resampling_demo():
class TestFunc(unittest.TestCase):
"""Test auxiliary functions"""

def test_check_geo_coords(self):
"""Test the check_if_geo_coords function"""
# test correct geographical coords
lat, lon = np.array([0, -2, 5]), np.array([-179, 175, 178])
self.assertEqual(u_coord.check_if_geo_coords(lat, lon), True)
# test wrong lat
lat, lon = np.array([0, 200, 5]), np.array([-179, 175, 178])
self.assertEqual(u_coord.check_if_geo_coords(lat, lon), False)
# test wrong lon
lat, lon = np.array([0, -2, 5]), np.array([-400, 175, 176])
self.assertEqual(u_coord.check_if_geo_coords(lat, lon), False)
lat, lon = np.array([0, -2, 5]), np.array([700, 1000, 800])
self.assertEqual(u_coord.check_if_geo_coords(lat, lon), False)
# test wrong extent
lat, lon = np.array([0, -2, 5]), np.array([-179, 175, 370])
self.assertEqual(u_coord.check_if_geo_coords(lat, lon), False)

def test_lon_normalize(self):
"""Test the longitude normalization function"""
data = np.array([-180, 20.1, -30, 190, -350])
Expand Down Expand Up @@ -1460,12 +1477,14 @@ def test_get_country_geometries_fail(self):
with self.assertRaises(ValueError) as cm:
u_coord.get_country_geometries(extent=(-20, 350, 0, 0))
self.assertIn(
"longitude extent range is greater than 360: -20 to 350", str(cm.exception)
"Input lat and lon coordinates are not geographic "
"or have total extents > 180° for lat or > 360° for lon.",
Comment thread
luseverin marked this conversation as resolved.
Outdated
str(cm.exception),
)
with self.assertRaises(ValueError) as cm:
u_coord.get_country_geometries(extent=(350, -20, 0, 0))
u_coord.get_country_geometries(extent=(340, -20, 0, 0))
self.assertIn(
"longitude extent at the left (350) is larger "
"longitude extent at the left (340) is larger "
"than longitude extent at the right (-20)",
str(cm.exception),
)
Expand Down