Skip to content

Commit

Permalink
Fix netcdf_to_ee bug (#1973)
Browse files Browse the repository at this point in the history
  • Loading branch information
giswqs authored Apr 16, 2024
1 parent 5fea512 commit 215048e
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions geemap/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3217,7 +3217,7 @@ def get_image_collection_thumbnails(
print(e)


def netcdf_to_ee(nc_file, var_names, band_names=None, lon="lon", lat="lat"):
def netcdf_to_ee(nc_file, var_names, band_names=None, lon="lon", lat="lat", decimal=2):
"""
Creates an ee.Image from netCDF variables band_names that are read from nc_file. Currently only supports variables in a regular longitude/latitude grid (EPSG:4326).

Expand All @@ -3227,6 +3227,7 @@ def netcdf_to_ee(nc_file, var_names, band_names=None, lon="lon", lat="lat"):
band_names (list, optional): if given, the bands are renamed to band_names. Defaults to the original var_names
lon (str, optional): the name of the longitude variable in the netCDF file. Defaults to "lon"
lat (str, optional): the name of the latitude variable in the netCDF file. Defaults to "lat"
decimal (int, optional): the number of decimal places to round the longitude and latitude values to. Defaults to 2.

Returns:
image: An ee.Image
Expand All @@ -3241,6 +3242,12 @@ def netcdf_to_ee(nc_file, var_names, band_names=None, lon="lon", lat="lat"):
)

import numpy as np
from collections import Counter

def most_common_value(lst):
counter = Counter(lst)
most_common = counter.most_common(1)
return float(format(most_common[0][0], f".{decimal}f"))

try:
if not isinstance(nc_file, str):
Expand All @@ -3261,10 +3268,12 @@ def netcdf_to_ee(nc_file, var_names, band_names=None, lon="lon", lat="lat"):

dim_lon = np.unique(np.ediff1d(lon_data))
dim_lat = np.unique(np.ediff1d(lat_data))
dim_lon = [most_common_value(dim_lon)]
dim_lat = [most_common_value(dim_lat)]

if (len(dim_lon) != 1) or (len(dim_lat) != 1):
print("The netCDF file is not a regular longitude/latitude grid")
return
# if (len(dim_lon) != 1) or (len(dim_lat) != 1):
# print("The netCDF file is not a regular longitude/latitude grid")
# return

try:
data = data.to_array()
Expand Down

0 comments on commit 215048e

Please sign in to comment.