-
Notifications
You must be signed in to change notification settings - Fork 227
Description
TypeError with numpy.can_cast() in newer NumPy versions (NEP 50 compatibility issue)
Description
The library fails with a TypeError when using newer versions of NumPy due to changes in numpy.can_cast() behavior as part of NEP 50 adoption.
Error Details
TypeError Traceback (most recent call last)
File ~/workspace/HWS-Algo-Dev/.venv/lib/python3.11/site-packages/pysheds/sview.py:85, in Raster.new(cls, input_array, viewfinder, metadata)
84 try:
---> 85 assert np.can_cast(viewfinder.nodata, obj.dtype, casting='safe')
86 except:
TypeError: can_cast() does not support Python ints, floats, and complex because the result used to depend on the value.
This change was part of adopting NEP 50, we may explicitly allow them again in the future.
Root Cause
The issue occurs in pysheds/sview.py:85 where np.can_cast() is called with Python scalar types (like int, float) rather than NumPy scalar types. NumPy's NEP 50 implementation removed support for Python scalars in can_cast() because the behavior was value-dependent and inconsistent.
Proposed Solution
Replace Python scalar default values with NumPy scalar types throughout the codebase. For example:
Fixed code:
# sgrid.py line 624 instead of nodata_out = 0
def _d8_flowdir(self, dem, nodata_cells, nodata_out=np.int64(0), flats=-1, pits=-2,
dirmap=(64, 128, 1, 2, 4, 8, 16, 32)):
# sgrid.py line 602 instead of nodata_out = 0
nodata_out = np.int64(0)Files Affected
Based on the error trace and code inspection, the following areas need attention:
pysheds/sgrid.py - Several functions already use np.int64(0) correctly (lines 602, 624-625) but others may need updates
Environment
- NumPy version: Recent versions implementing NEP 50
- Python version: 3.11+
- pysheds version: pysheds==0.4