xdenisx

currents2grib

Sep 14th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.58 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Sep 07 18:46:15 2016
  4.  
  5. @author: Компьютер
  6. """
  7. ##################################
  8. #
  9. #  !!!!!MAKE IT FOR EACH LEVEL SEPARETELY!!!!
  10. #
  11. ###################################
  12.  
  13. from netCDF4 import Dataset
  14. import numpy as np
  15. import pyresample
  16. import glob
  17. import os
  18. #import time
  19. from pylab import *
  20.  
  21. def get_data_from_txt(fname):
  22.     ff =open(fname, 'r')
  23.     lines = ff.readlines()
  24.     lats = []
  25.     lons = []
  26.     uu = []
  27.     vv = []
  28.     for line in lines:
  29.         try:
  30.             lat, lon, u, v = line.split()[0], line.split()[1], line.split()[2], \
  31.                              line.split()[3]
  32.             lats.append(float(lat))
  33.             lons.append(float(lon))
  34.             uu.append(float(u))
  35.             vv.append(float(v))
  36.         except:
  37.             pass
  38.     ff.close()
  39.     return lats, lons, uu, vv
  40.    
  41. def interpolate_data(uu_grid, vv_grid):
  42.     np.set_printoptions(formatter={'float': '{: .3f}'.format})
  43.     # Initial model grid
  44.     orig_def = pyresample.geometry.SwathDefinition(lons=ilon, lats=ilat)
  45.     # Target regular grid
  46.     targ_def = pyresample.geometry.SwathDefinition(lons=lons_out, lats=lats_out)
  47.    
  48.     # Interpolate U
  49.     uu_interpolated = pyresample.kd_tree.resample_nearest(orig_def, uu_grid, \
  50.                            targ_def, radius_of_influence=16000,\
  51.                             fill_value=0.) #, sigmas=250000,)
  52.     # Interpolate V                      
  53.     vv_interpolated = pyresample.kd_tree.resample_nearest(orig_def, vv_grid, \
  54.                            targ_def, radius_of_influence=16000, \
  55.                             fill_value=0.) #, sigmas=250000,)
  56.     return uu_interpolated, vv_interpolated
  57.  
  58. basedir = 'currents'
  59.  
  60. # Open initial data
  61. # Get date and lat lon
  62. ffiles = glob.glob('currents\\*.dat')
  63. idate = os.path.basename(ffiles[0]).split('_')[1].split('.')[0]
  64. lats, lons, uu, vv = get_data_from_txt(ffiles[0])
  65. lats, lons, uu, vv = np.array(lats), np.array(lons), np.array(uu), np.array(vv)
  66.  
  67. # Reshape lon, lat, U, V
  68. ilon, ilat       = lons[:].reshape(9,113), lats[:].reshape(9,113)
  69.  
  70. # Make regular lon lat grid
  71. ilats_out = np.arange(min(lats),max(lats),0.125,dtype='float16')
  72. ilons_out = np.arange(min(lons),max(lons),0.125,dtype='float16')
  73. lons_out, lats_out = np.meshgrid(ilons_out, ilats_out)
  74.  
  75. # the output array to write will be nlats x nlons
  76. nlats = len(ilats_out)
  77. nlons = len(ilons_out)
  78.  
  79. # Create NETCDF4
  80. #dataset = Dataset('AARI_SEA_CURRENTS_%s.nc' % idate,'w',format='NETCDF4_CLASSIC')
  81. dataset = Dataset('AARI_SEA_CURRENTS_%s.nc' % idate,'w',format='NETCDF3_CLASSIC')
  82. latitudes =   dataset.createDimension('latitude', nlats)
  83. longitudes =   dataset.createDimension('longitude', nlons)
  84. #level = dataset.createDimension('level', 4)
  85. time =  dataset.createDimension('time', None)
  86.  
  87. # Create coordinate variables for 4-dimensions
  88. latitudes =  dataset.createVariable('latitude', 'f4', ('latitude',))
  89. longitudes = dataset.createVariable('longitude','f4', ('longitude',))
  90. #levels =     dataset.createVariable('level', np.int32, ('level',))
  91. times =      dataset.createVariable('time', np.float64, ('time',))
  92.  
  93. # Create the actual 4-d variable
  94. u = dataset.createVariable('u', 'f4',('time','latitude','longitude'))#,zlib=True)#,least_significant_digit=7)
  95. v = dataset.createVariable('v', 'f4',('time','latitude','longitude'))#,zlib=True)#,least_significant_digit=7)
  96.  
  97. # Global Attributes
  98. dataset.description = 'Sea currents from AARI-IOCM model'
  99. import time
  100. dataset.history = 'Created ' + time.ctime(time.time())
  101. dataset.source = 'AARI-IOCM'
  102.  
  103. # Variable Attributes
  104. latitudes.units = 'degrees_north'
  105. longitudes.units = 'degrees_east'
  106.  
  107. #levels.units = 'meters'
  108. u.units = 'm/s'
  109. v.units = 'm/s'
  110.  
  111. times.units = 'hours since 0001-01-01 00:00:00'
  112. times.calendar = 'gregorian'
  113.  
  114. latitudes[:] = ilats_out
  115. longitudes[:] = ilons_out
  116.  
  117. nlats = len(dataset.dimensions['latitude'])
  118. nlons = len(dataset.dimensions['longitude'])
  119.  
  120. # Levels
  121. ll = []
  122. for ifile in ffiles:
  123.     lll = os.path.basename(ifile)[1:3]
  124.     ll.append(lll)
  125.  
  126. uniq_ll = set(ll)
  127. uu_ll   = list(uniq_ll)
  128. m       = np.array(uu_ll)
  129. m.sort()
  130.  
  131. # Fill LEVEL values    
  132. #levels[:] =  m
  133.  
  134. # Get number of Times
  135. t_num = len(glob.glob('%s\\w%02d*' % (basedir,int(m[0]))))
  136.  
  137. # Go through levels
  138. #level_ch = 0
  139. #for ilevel in levels:
  140. #    print '\nLEVEL: %s\n' % ilevel
  141. ilevel = m[0]
  142.  
  143. ffiles = glob.glob('%s\\w%02d*' % (basedir,int(ilevel)))
  144. #print ffiles
  145. time_ch = 0
  146.  
  147.  
  148. for ifile in ffiles:
  149.     #print 'level_ch: %s' % level_ch
  150.     print 'time_ch: %s' % time_ch
  151.  
  152.     print ifile
  153.    
  154.     lats, lons, uu, vv = get_data_from_txt(ifile)
  155.     lats, lons, uu, vv = np.array(lats), np.array(lons), np.array(uu), np.array(vv)
  156.    
  157.     uu_grid, vv_grid = uu.reshape(9,113), vv.reshape(9,113)
  158.     uu_interpolated, vv_interpolated = interpolate_data(uu_grid, vv_grid)
  159.     #plt.clf()
  160.     #imshow(uu_interpolted)
  161.     #plt.show()
  162.  
  163.     #print uu_interpolated[10:20,4:50] #, vv_interpolated
  164.     #print np.min(uu_interpolated[~np.isnan(uu_interpolated)])
  165.     #print np.min(vv_interpolated[~np.isnan(vv_interpolated)])
  166.  
  167.     u[time_ch,:] = uu_interpolated
  168.     v[time_ch,:] = vv_interpolated
  169.  
  170.     time_ch = time_ch + 1
  171.     #level_ch = level_ch + 1
  172.        
  173.  
  174. # Fill in times.
  175. from datetime import datetime, timedelta
  176. from netCDF4 import num2date, date2num
  177. dates = []
  178.  
  179. for n in range(u.shape[0]):
  180.     dates.append(datetime(2016, 4, 4) + n * timedelta(hours=6))
  181.  
  182. times[:] = date2num(dates, units = times.units, calendar = times.calendar)
  183. dates = num2date(times[:], units=times.units, calendar=times.calendar)
  184.  
  185. dataset.close()
Advertisement
Add Comment
Please, Sign In to add comment