UU-Hydro / PCR-GLOBWB_model

PCR-GLOBWB (PCRaster Global Water Balance) is a large-scale hydrological model intended for global to regional studies and developed at the Department of Physical Geography, Utrecht University (Netherlands). Contact: Edwin Sutanudjaja (E.H.Sutanudjaja@uu.nl).
GNU General Public License v3.0
116 stars 79 forks source link

Fix bug in reading input data. #13

Closed Peter9192 closed 2 years ago

Peter9192 commented 4 years ago

The following configuration exposes the bug:

xULClone = 0.75
cellsizeInput = 0.75
lons = np.arange(0, 10, cellsizeInput)
print(lons)
>> array([0.  , 0.75, 1.5 , 2.25, 3.  , 3.75, 4.5 , 5.25, 6.  , 6.75, 7.5 , 8.25, 9.  , 9.75])
minX = np.min(np.abs(lons - xULClone - cellsizeInput/2))
print(minX)
>> 0.375
print(np.abs(lons - xULClone - cellsizeInput/2))
>> [1.125 0.375 0.375 1.125 1.875 2.625 3.375 4.125 4.875 5.625 6.375 7.125 7.875 8.625] # note that minX occurs twice!
print(np.where(np.abs(lons - (xULClone - cellsizeInput/2)) == minX))
>> (array([0, 1]),)
xIdxSta = np.where(np.abs(lons - (xULClone - cellsizeInput/2)) == minX)[0]
print(xIdxSta)
>> [0 1]
int(xIdxSta)
>> TypeError: only size-1 arrays can be converted to Python scalars

Note that the bug can easily be solved by adding one more pair of brackets: xIdxSta = int(np.where(np.abs(lons - (xULClone - cellsizeInput/2)) == minX)[0][0])

However, the proposed fix using np.argmin avoids the need to explicitly identify minX first and then identify the corresponding point with np.where. Note the numpy docs: In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned. Also, there is no need to convert to int explicitly, because that's the default return type of np.argmin.