Search code examples
pythonarraysnumpycartopy

Create a land mask from latitude and longitude arrays


Given latitude and longitude arrays, I'm tryin to genereate a land_mask, an array of the same size that tells whether a coordinate is land or not.

lon=np.random.uniform(0,150,size=[1000,1000])
lat=np.random.uniform(-90,90,size=[1000,1000])

from global_land_mask import globe
land_mask=globe.is_land(lat,lon)

This is a very efficient method to create land mask if all values are defined. But if some values in lat or lon are masked or are nan values, it throws an error.

I've tried to use for loops to avoid that error but it's taking almost 15-20 minutes to run. I've to run it on an array with 3000×3000 elements, some of which are masked.

What would be a better way for generating land mask for arrays with masked/nan values?


Solution

  • so it seems globe.is_land(y,x) doesn't take a masked array. An equitable solution would be to use a coord outside your domain (if possible). So:

    lon[lon==327.67] = 170
    lat[lat==327.67] = -90
    
    from global_land_mask import globe
    land_mask=globe.is_land(lat,lon)
    
    masked = np.where((lat==-90)|(lon==170), False, land_mask)
    

    Alternatively, you could mask the values prior to passing them in:

    lat_mask = np.where(lat==326.67, np.nan, lat)
    lon_mask = np.where(lon==326.67, np.nan, lon)
    
    master_mask = np.where((lat_mask==np.nan)|(lon_mask==np.nan), False, True)
    
    lat[master_mask]==True 
    lon[master_mask]==True 
    
    from global_land_mask import globe
    land_mask=globe.is_land(lat,lon)
    

    The second solution will change (flatten) your lat/lon arrays but does not require you to find an area outside of your domain