xdenisx

kl_geotiff

Oct 9th, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.74 KB | None | 0 0
  1. from netCDF4 import Dataset
  2. import numpy as np
  3. import sys
  4. import matplotlib.pyplot as plt
  5. import datetime
  6. import os
  7. import matplotlib.ticker as ticker
  8. import glob
  9. import pyresample
  10.  
  11. def kl_2_ll(ffile2):
  12.     ffile = open(ffile2,'r')
  13.     lines = ffile.readlines()
  14.     lon_00 = np.zeros(shape=(81, 77))
  15.     lat_00 = np.zeros(shape=(81, 77))
  16.     for iline in lines:
  17.         #float(ilat), float(ilon), int(stolb), int(stroka) = iline.split()
  18.         ilat = float(iline.split()[0])
  19.         ilon = float(iline.split()[1])
  20.         stolb = int(iline.split()[2])
  21.         stroka = int(iline.split()[3])
  22.         lon_00[stroka-1,stolb-1] = ilon
  23.         lat_00[stroka-1,stolb-1] = ilat
  24.     ffile.close()
  25.     return lon_00, lat_00
  26.  
  27. def resample_kl_ice_grid(fname, lons, lats, data):    
  28.     # Reproject to Klyachkin ice model grid
  29.     lon_kl, lat_kl = kl_2_ll('grid/grid_kl.txt')
  30.  
  31.     # Setka dannyh kotorye nuzhno sproecirovat
  32.     orig_def = pyresample.geometry.SwathDefinition(lons=lons, lats=lats)
  33.    
  34.     # Klyachkin rep
  35.     targ_def_kl = pyresample.geometry.SwathDefinition(lons=lon_kl, lats=lat_kl)
  36.  
  37.                    
  38.     # Klyachkin
  39.     nn_kl = pyresample.kd_tree.resample_gauss(orig_def, data, \
  40.                            targ_def_kl, radius_of_influence=100000, neighbours=1,\
  41.                            sigmas=250000, fill_value=np.nan)
  42.  
  43.     np.savetxt("%s.txt" % fname, nn_kl, fmt = "%8.3f")
  44.     return nn_kl
  45.  
  46. def calc_deformations(dx, dy, normalization=False, normalization_time=None, cell_size=10.):
  47.     ''' Calculate deformation fields from U and V '''
  48.     m_div = np.empty((dx.shape[0], dx.shape[1],))
  49.     m_div[:] = np.NAN
  50.     m_curl = np.empty((dx.shape[0], dx.shape[1],))
  51.     m_curl[:] = np.NAN
  52.     m_shear = np.empty((dx.shape[0], dx.shape[1],))
  53.     m_shear[:] = np.NAN
  54.     m_tdef = np.empty((dx.shape[0], dx.shape[1],))
  55.     m_tdef[:] = np.NAN
  56.  
  57.     # Invert meridional component
  58.     dy = dy * (-1)
  59.    
  60.     # Calculate magnitude
  61.     mag = np.hypot(dx, dy)
  62.  
  63.     # Normilize u and v to 1 hour
  64.     if not normalization:
  65.         pass
  66.     else:
  67.         # Normilize to cell size
  68.         dx = dx / cell_size
  69.         dy = dy / cell_size
  70.        
  71.         # Normilize to time
  72.         dx = dx / normalization_time
  73.         dy = dy / normalization_time
  74.  
  75.     # Test
  76.     plt.clf()
  77.     plt.imshow(m_div)
  78.        
  79.     for i in range(1, dx.shape[0] - 1):
  80.         for j in range(1, dx.shape[1] - 1):
  81.             # div
  82.             if (np.isnan(dx[i, j + 1]) == False and np.isnan(dx[i, j - 1]) == False
  83.                     and np.isnan(dy[i - 1, j]) == False and np.isnan(dy[i + 1, j]) == False
  84.                     and (np.isnan(dx[i, j]) == False or np.isnan(dy[i, j]) == False)):
  85.                 # m_div[i,j] = 0.5*((u_int[i,j + 1] - u_int[i,j - 1])  + (v_int[i + 1,j] - v_int[i - 1,j]))/m_cell_size
  86.                 m_div[i, j] = 0.5 * ((dx[i, j + 1] - dx[i, j - 1])
  87.                                                       + (dy[i - 1, j] - dy[i + 1, j]))
  88.                 #print m_div[i,j]
  89.             # curl
  90.             if (np.isnan(dy[i, j + 1]) == False and np.isnan(dy[i, j - 1]) == False and
  91.                     np.isnan(dx[i - 1, j]) == False and np.isnan(dx[i + 1, j]) == False
  92.                     and (np.isnan(dx[i, j]) == False or np.isnan(dy[i, j]) == False)):
  93.                 m_curl[i, j] = 0.5 * (dy[i, j + 1] - dy[i, j - 1]
  94.                                       - dx[i - 1, j] + dx[i + 1, j]) / cell_size
  95.  
  96.  
  97.                 # m_curl[i,j] = 0.5*(v_int[i,j - 1] - v_int[i,j + 1]  - u_int[i - 1,j] + u_int[i + 1,j])/m_cell_size
  98.  
  99.             # shear
  100.             if (np.isnan(dy[i + 1, j]) == False and np.isnan(dy[i - 1, j]) == False and
  101.                     np.isnan(dx[i, j - 1]) == False and np.isnan(dx[i, j + 1]) == False and \
  102.                     np.isnan(dy[i, j - 1]) == False and np.isnan(dy[i, j + 1]) == False and \
  103.                     np.isnan(dx[i + 1, j]) == False and np.isnan(dx[i - 1, j]) == False and \
  104.                     (np.isnan(dx[i, j]) == False or np.isnan(dy[i, j]) == False)):
  105.                 dc_dc = 0.5 * (dy[i + 1, j] - dy[i - 1, j])
  106.                 dr_dr = 0.5 * (dx[i, j - 1] - dx[i, j + 1])
  107.                 dc_dr = 0.5 * (dy[i, j - 1] - dy[i, j + 1])
  108.                 dr_dc = 0.5 * (dx[i + 1, j] - dx[i - 1, j])
  109.                 m_shear[i, j] = np.sqrt(
  110.                     (dc_dc - dr_dr) * (dc_dc - dr_dr) + (dc_dr - dr_dc) * (dc_dr - dr_dc)) / cell_size
  111.  
  112.                 '''
  113.                # Den
  114.                dc_dc = 0.5*(v_int[i + 1,j] - v_int[i - 1,j])
  115.                dr_dr = 0.5*(u_int[i,j + 1] - u_int[i,j - 1])
  116.                dc_dr = 0.5*(v_int[i,j + 1] - v_int[i,j - 1])
  117.                dr_dc = 0.5*(u_int[i + 1,j] - u_int[i - 1,j])
  118.  
  119.                m_shear[i,j] = np.sqrt((dc_dc -dr_dr) * (dc_dc -dr_dr) + (dc_dr - dr_dc) * (dc_dr - dr_dc))/m_cell_size
  120.                '''
  121.  
  122.             # deformation
  123.             if (np.isnan(m_shear[i, j]) == False and np.isnan(m_div[i, j]) == False):
  124.                 m_tdef[i, j] = np.hypot(m_shear[i, j], m_div[i, j])
  125.  
  126.     # Invert dy back
  127.     dy = dy * (-1)
  128.  
  129.     # data = np.vstack((np.ravel(xx_int), np.ravel(yy_int), np.ravel(m_div), np.ravel(u_int), np.ravel(v_int))).T
  130.     divergence = m_div
  131.    
  132.     # TODO: Test
  133.     '''
  134.    plt.imshow(divergence, cmap='RdBu', vmin=-0.06, vmax=0.06, interpolation='None')
  135.    # Plot u and v values inside cells (for testing porposes)
  136.    for ii in range(dx.shape[1]):
  137.        for jj in range(dx.shape[0]):
  138.            try:
  139.                if not np.isnan(dx[ii,jj]):
  140.                    plt.text(jj, ii,
  141.                             'dx:%.2f\ndy:%.2f\n%.2f\nij:(%s,%s)' %
  142.                             (dx[ii,jj], dy[ii,jj], divergence[ii,jj], ii, jj),
  143.                             horizontalalignment='center',
  144.                             verticalalignment='center', fontsize=0.05, color='k')
  145.            except:
  146.                pass
  147.    
  148.    plt.savefig('test.png', bbox_inches='tight', dpi=1000)
  149.    '''
  150.    
  151.     curl = m_curl
  152.     shear = m_shear
  153.     total_deform = m_tdef
  154.     return mag, divergence, curl, shear, total_deform
  155.  
  156. def fmt(x, pos):
  157.     a, b = '{:.0e}'.format(x).split('e')
  158.     b = int(b)
  159.     return r'${} \times 10^{{{}}}$'.format(a, b)
  160.  
  161. def plot_div(fname):
  162.     xxc = ff.variables['xc'][:]
  163.     yyc = ff.variables['yc'][:]
  164.  
  165.     xc, yc = np.meshgrid(xxc, yyc)
  166.  
  167.     dX = ff.variables['dX'][0,:,:]
  168.     dY = ff.variables['dY'][0,:,:]
  169.  
  170.     # Make nan where
  171.     dX[dX==9.96921e+36] = np.nan
  172.     dY[dY==9.96921e+36] = np.nan
  173.  
  174.     # Lats Lons
  175.     lats = ff.variables['lat'][:]
  176.     lons = ff.variables['lon'][:]
  177.  
  178.     # Calculate time delta and define norm time
  179.     ddd1 = os.path.basename(fname).split('_')[5].split('-')[0]
  180.     dt1_str = '%s-%s-%s %s:%s:%s' % (ddd1[0:4], ddd1[4:6], ddd1[6:8], ddd1[8:10], ddd1[10:12],
  181.                                      ddd1[12:14])
  182.     dt1 = datetime.datetime.strptime(dt1_str, '%Y-%m-%d %H:%M:%S')
  183.  
  184.     ddd2 = os.path.basename(fname).split('_')[5].split('-')[1]
  185.     dt2_str = '%s-%s-%s %s:%s:%s' % (ddd2[0:4], ddd2[4:6], ddd2[6:8], ddd2[8:10], ddd2[10:12],
  186.                                      ddd2[12:14])
  187.     dt2 = datetime.datetime.strptime(dt2_str, '%Y-%m-%d %H:%M:%S')
  188.  
  189.     # Time for normalization
  190.     time_delta = (dt2 - dt1).total_seconds()
  191.     norm_times = 12 * 3600 # normilize to 12 hours
  192.     normalization_time = time_delta / norm_times
  193.    
  194.     #print 'Date1: %s' % dt1
  195.     #print 'Date2: %s' % dt2
  196.     #print 'Time delta: %s, Normalization time: %s' % (time_delta, normalization_time)
  197.  
  198.     # Caclulation
  199.     mag, divergence, curl, shear, total_deform = calc_deformations(dX, dY, normalization=True,
  200.                                                                    normalization_time = normalization_time,
  201.                                                                    cell_size=cell_size)
  202.  
  203.     # Calculate min and max
  204.     minima = np.nanpercentile(divergence, 2)
  205.     maxima = np.nanpercentile(divergence, 98)
  206.  
  207.     mmax = maxima
  208.  
  209.     if minima > mmax:
  210.         mmax = minima
  211.     mmin = -mmax
  212.  
  213.     # Divergence max and min
  214.     #print 'Div min: %s   Div max: %s' % (np.nanmin(divergence), np.nanmax(divergence))
  215.     #print 'Prec. Div min: %s   Div max: %s' % (mmin, mmax)
  216.     #print ('Minima: %s   Maxima: %s') % (minima, maxima)
  217.  
  218.     plt.clf()
  219.  
  220.     # Make plot with vertical (default) colorbar
  221.     fig, ax = plt.subplots()
  222.  
  223.     div_plot = plt.imshow(divergence, cmap='RdBu', vmin=-0.06, vmax=0.06, interpolation='None')
  224.     ax.set_title(u'Скорость дивергенции дрейфа льда\n%s - %s' % (dt1_str, dt2_str))
  225.  
  226.     plt.quiver(range(dX.shape[1]), range(dX.shape[0]), dX, (-1) * dY, facecolor='#000000',
  227.                angles='xy', scale_units='xy', alpha=.5)
  228.                #, linewidth=0.01,
  229.                #width=0.0012, headwidth=4.5, scale=0.2)
  230.     '''
  231.    # Testing
  232.    # Plot u and v values inside cells (for testing porposes)
  233.    for ii in range(dX.shape[1]):
  234.        for jj in range(dX.shape[0]):
  235.            try:
  236.                if not np.isnan(dX[ii,jj]):
  237.                    plt.text(jj, ii,
  238.                             'dx:%.2f\ndy:%.2f\n%.2f' % (dX[ii,jj], dY[ii,jj], divergence[ii,jj]),
  239.                             horizontalalignment='center',
  240.                             verticalalignment='center', fontsize=0.1, color='k')
  241.            except:
  242.                pass
  243.    '''
  244.    
  245.  
  246.     #ticks=[mmin, 0, mmax]
  247.     cbar = fig.colorbar(div_plot,  format=ticker.FuncFormatter(fmt))
  248.     #cbar.ax.set_yticklabels(['< %.3f' % mmin, '0', '> %.3f' % mmax])
  249.     cbar.ax.set_ylabel(u'1/12 часов', rotation=90)
  250.  
  251.     plt.savefig('div_plot/div_%s_%s.png' % (ddd1, ddd2), bbox_inches='tight', dpi=150)
  252.    
  253.     return divergence
  254.    
  255.  
  256. ########################
  257. # CONSTANTS
  258. ########################
  259.  
  260. cell_size = 10.182338
  261.  
  262. ########################
  263. # END CONSTANTS
  264. ########################
  265.  
  266. #fname = '../drift/ice_drift_polstereo_sarbased_north_20170304020917-20170305020024_7156.nc'
  267.  
  268. ffiles = glob.glob('../drift/*201706*.nc')
  269. num_of_files = len(ffiles) - 1
  270.  
  271. for i, fname in enumerate(ffiles):
  272.     print '%s of %s' % (i, num_of_files)
  273.     ff = Dataset(fname, 'r')
  274.     # Lats Lons
  275.     lats = ff.variables['lat'][:]
  276.     lons = ff.variables['lon'][:]
  277.     lats[lats==9.96921e+36] = np.nan
  278.     lons[lons==9.96921e+36] = np.nan
  279.  
  280.     lon_min = np.nanmin(lons)
  281.     lon_max = np.nanmax(lons)
  282.     lat_min = np.nanmin(lats)
  283.     lat_max = np.nanmax(lats)
  284.  
  285.     # If lats and lons inside bbox of Kara sea
  286.     if lon_min >= 54. and lon_max <= 84. and lat_min >= 67.1 and lat_max <= 77.3:
  287.         div = plot_div(fname)
  288.         nn_kl = resample_kl_ice_grid('grid/aari_ice_model_grid/sar_div_%s' %
  289.                                      os.path.basename(fname).split('_')[5], lons, lats, div)
  290.         #plot_mag(fname)
Advertisement
Add Comment
Please, Sign In to add comment