1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import xarray as xr
def generate_grid_file_from_netcdf(input_file, output_grid_file, resolution): """ 從 NetCDF 檔案自動生成目標網格文件。
:param input_file: NetCDF 檔案路徑 :param output_grid_file: 目標網格文件名 :param resolution: 目標網格解析度(度) """ dataset = xr.open_dataset(input_file) lat = dataset["XLAT"] lon = dataset["XLONG"]
lat_min, lat_max = lat.min().item(), lat.max().item() lon_min, lon_max = lon.min().item(), lon.max().item() print(f"Latitude range: {lat_min} to {lat_max}") print(f"Longitude range: {lon_min} to {lon_max}")
x_size = int((lon_max - lon_min) / resolution) + 1 y_size = int((lat_max - lat_min) / resolution) + 1
with open(output_grid_file, "w") as f: f.write("gridtype = latlon\n") f.write(f"xsize = {x_size}\n") f.write(f"ysize = {y_size}\n") f.write(f"xfirst = {lon_min}\n") f.write(f"xinc = {resolution}\n") f.write(f"yfirst = {lat_min}\n") f.write(f"yinc = {resolution}\n") print(f"Grid file '{output_grid_file}' has been created.")
input_nc_file = "input.nc" grid_file = "grid_2km.txt" resolution = 0.018
generate_grid_file_from_netcdf(input_nc_file, grid_file, resolution)
|