Guest User

Untitled

a guest
May 26th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. """
  2. Module for modifying pop model output to be compatible with xgcm
  3. """
  4.  
  5. import numpy as np
  6. import xarray as xr
  7.  
  8. def _add_pop_dims_to_dataset(ds):
  9. ds_new = ds.copy()
  10. ds_new['nlon_u'] = xr.Variable(('nlon_u'), np.arange(len(ds.nlon)) + 1, {'axis': 'X', 'c_grid_axis_shift': 0.5})
  11. ds_new['nlat_u'] = xr.Variable(('nlat_u'), np.arange(len(ds.nlat)) + 1, {'axis': 'Y', 'c_grid_axis_shift': 0.5})
  12. ds_new['nlon_t'] = xr.Variable(('nlon_t'), np.arange(len(ds.nlon)) + 0.5, {'axis': 'X'})
  13. ds_new['nlat_t'] = xr.Variable(('nlat_t'), np.arange(len(ds.nlat)) + 0.5, {'axis': 'Y'})
  14.  
  15. # add metadata to z grid
  16. ds_new['z_t'].attrs.update({'axis': 'Z'})
  17. ds_new['z_w'].attrs.update({'axis': 'Z', 'c_grid_axis_shift': -0.5})
  18. ds_new['z_w_top'].attrs.update({'axis': 'Z', 'c_grid_axis_shift': -0.5})
  19. ds_new['z_w_bot'].attrs.update({'axis': 'Z', 'c_grid_axis_shift': 0.5})
  20.  
  21. return ds_new
  22.  
  23. def _dims_from_grid_loc(grid_loc):
  24. grid_loc = str(grid_loc)
  25. ndim = int(grid_loc[0])
  26. x_loc_key = int(grid_loc[1])
  27. y_loc_key = int(grid_loc[2])
  28. z_loc_key = int(grid_loc[3])
  29.  
  30. x_loc = {1: 'nlon_t', 2: 'nlon_u'}[x_loc_key]
  31. y_loc = {1: 'nlat_t', 2: 'nlat_u'}[y_loc_key]
  32. z_loc = {0: 'surface', 1: 'z_t', 2: 'z_w', 3: 'z_w_bot', 4: 'z_t_150m'}[z_loc_key]
  33.  
  34. if ndim == 3:
  35. return z_loc, y_loc, x_loc
  36. elif ndim == 2:
  37. return y_loc, x_loc
  38.  
  39. def _label_coord_grid_locs(ds):
  40. grid_locs = {'ANGLE': '2220', 'ANGLET': '2110',
  41. 'DXT': '2110', 'DXU': '2220',
  42. 'DYT': '2110', 'DYU': '2220',
  43. 'HT': '2110', 'HU': '2220',
  44. 'HTE': '2210', 'HTN': '2120',
  45. 'HUS': '2210', 'HUW': '2120',
  46. 'KMT': '2110', 'KMU': '2220',
  47. 'REGION_MASK': '2110',
  48. 'TAREA': '2110', 'TLAT': '2110', 'TLONG': '2110',
  49. 'UAREA': '2220', 'ULAT': '2220', 'ULONG': '2220'}
  50. ds_new = ds.copy()
  51. for vname, grid_loc in grid_locs.items():
  52. ds_new[vname].attrs['grid_loc'] = grid_loc
  53. return ds_new
  54.  
  55.  
  56.  
  57. def relabel_pop_dims(ds):
  58. """Return a new xarray dataset with distinct dimensions for variables at different
  59. grid points.
  60. """
  61. ds_new = _label_coord_grid_locs(ds)
  62. ds_new = _add_pop_dims_to_dataset(ds_new)
  63. for vname in ds_new.variables:
  64. if 'grid_loc' in ds_new[vname].attrs:
  65. da = ds_new[vname]
  66. dims_orig = da.dims
  67. new_spatial_dims = _dims_from_grid_loc(da.attrs['grid_loc'])
  68. if dims_orig[0] == 'time':
  69. dims = ('time',) + new_spatial_dims
  70. else:
  71. dims = new_spatial_dims
  72. ds_new[vname] = xr.Variable(dims, da.data, da.attrs, da.encoding, fastpath=True)
  73. return ds_new
Add Comment
Please, Sign In to add comment