reduced.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import netCDF4 as nc
  2. import sys
  3. import math
  4. import numpy as np
  5. def from_reduced(N,M):
  6. "N elements from south to north and N elements around equator "
  7. hmax = 2*math.pi/N
  8. hmin = hmax/2
  9. nlon = N
  10. cells_lon = []
  11. cells_lat = []
  12. for i in range(M/2):
  13. lat1 = 180.0/M*i
  14. lat2 = 180.0/M*(i+1)
  15. y = math.sin(lat1*math.pi/180)
  16. r = math.cos(lat1*math.pi/180)
  17. h = 2.0*r/nlon
  18. reduce_nlon = (h < hmin) and (i > 0) and (nlon > 4)
  19. if reduce_nlon:
  20. nlon = nlon/2
  21. for j in range(nlon):
  22. lon1 = 360.0*j/nlon
  23. lon2 = 360.0*(j+1)/nlon
  24. bounds_lon = [lon1, lon1, lon2, lon2]
  25. bounds_lat = [lat1, lat2, lat2, lat1]
  26. if reduce_nlon:
  27. bounds_lon.append((lon1+lon2)/2)
  28. bounds_lat.append(lat1)
  29. else: # close by netCDF convention
  30. bounds_lon.append(bounds_lon[0])
  31. bounds_lat.append(bounds_lat[0])
  32. # northern hemisphere
  33. cells_lon.append(bounds_lon)
  34. cells_lat.append(bounds_lat)
  35. # southern hemisphere
  36. cells_lon.append(bounds_lon)
  37. cells_lat.append(list(-np.array(bounds_lat))) # convert to array to negate elementwise
  38. return np.array(cells_lon), np.array(cells_lat)
  39. for N in [64, 128, 256, 512]:
  40. filename = "reduced" + str(N) + ".nc"
  41. print "Generating: N =", N
  42. lon, lat = from_reduced(N*2,N)
  43. print lon.shape[0], "cells -> writing as ", filename
  44. f = nc.Dataset(filename,'w')
  45. f.createDimension('n_vert', 5)
  46. f.createDimension('n_cell', lon.shape[0])
  47. var = f.createVariable('lat', 'd', ('n_cell'))
  48. var.setncattr("long_name", "latitude")
  49. var.setncattr("units", "degrees_north")
  50. var.setncattr("bounds", "bounds_lat")
  51. var[:] = np.zeros(lon.shape[0])
  52. var = f.createVariable('lon', 'd', ('n_cell'))
  53. var.setncattr("long_name", "longitude")
  54. var.setncattr("units", "degrees_east")
  55. var.setncattr("bounds", "bounds_lon")
  56. var[:] = np.zeros(lon.shape[0])
  57. var = f.createVariable('bounds_lon', 'd', ('n_cell','n_vert'))
  58. var[:] = lon
  59. var = f.createVariable('bounds_lat', 'd', ('n_cell','n_vert'))
  60. var[:] = lat
  61. var = f.createVariable('val', 'd', ('n_cell'))
  62. var.setncattr("coordinates", "lon lat")
  63. var[:] = np.arange(lon.shape[0])
  64. f.close()