flip_y.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python
  2. import sys
  3. import os
  4. #import numpy as nmp
  5. from netCDF4 import Dataset
  6. from string import replace
  7. if len(sys.argv) != 2:
  8. print 'Usage: '+sys.argv[0]+' <runoff_depth.nc>'
  9. sys.exit(0)
  10. cf_orig = sys.argv[1]
  11. #cf_in = sys.argv[2]
  12. #cmin_dept = sys.argv[3] ; rmin_depth = float(cmin_dept)
  13. cf_in = replace(cf_orig, '.nc', '_yflipped.nc')
  14. os.system('rm -f '+cf_in)
  15. os.system('cp '+cf_orig+' '+cf_in)
  16. print '\n'
  17. f_in = Dataset(cf_in, 'r+')
  18. list_var = f_in.variables.keys()
  19. nbvar = len(list_var)
  20. print '\n *** '+str(nbvar)+'variables =>', list_var
  21. for jv in range(nbvar):
  22. print ''
  23. cv = list_var[jv]
  24. l_dim = f_in.variables[cv].dimensions
  25. nbdim = len(l_dim)
  26. l_y = ( 'y' in l_dim )
  27. idx_y = -1
  28. if l_y: idx_y = l_dim.index('y')
  29. print ' '+cv+' => ', l_dim, nbdim, l_y, idx_y
  30. if l_y:
  31. if nbdim==4:
  32. xf = f_in.variables[cv][:,:,:,:]
  33. if idx_y==2:
  34. print ' flipping variable '+cv+' along axis # 2'
  35. f_in.variables[cv][:,:,:,:] = f_in.variables[cv][:,:,::-1,:]
  36. elif nbdim==3:
  37. xf = f_in.variables[cv][:,:,:]
  38. if idx_y==1:
  39. print ' flipping variable '+cv+' along axis # 1'
  40. f_in.variables[cv][:,:,:] = f_in.variables[cv][:,::-1,:]
  41. elif nbdim==2:
  42. xf = f_in.variables[cv][:,:]
  43. print ' flipping variable '+cv+' along axis # 0'
  44. if idx_y==0: f_in.variables[cv][:,:] = f_in.variables[cv][::-1,:]
  45. else:
  46. print 'ERROR: only dimensions 2 up to 4!' ; sys.exit(0)
  47. f_in.close()
  48. print '\n *** '+cf_in+' written!\n'