<jupyter_start><jupyter_text>Interpolate 2D field on regular and irregular gridsFrom https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html, we know There are several general interpolation facilities available in SciPy, for data in 1, 2, and higher dimensions:* A class representing an interpolant (interp1d) in 1-D, offering several interpolation methods.* Convenience function griddata offering a simple interface to interpolation in N dimensions (N = 1, 2, 3, 4, ...). Object-oriented interface for the underlying routines is also available.* Functions for 1- and 2-dimensional (smoothed) cubic-spline interpolation, based on the FORTRAN library FITPACK. There are both procedural and object-oriented interfaces for the FITPACK library.* Interpolation using Radial Basis Functions.In this notebook, we mainly use **interp2d** for regular grids while **griddata** for irregular grids.  1. Load basic libs<jupyter_code>% matplotlib inline

import numpy as np
from scipy.interpolate import interp2d, griddata
import matplotlib.pyplot as plt
import numpy.ma as ma
from numpy.random import uniform, seed

from netCDF4 import Dataset as netcdf # netcdf4-python module<jupyter_output><empty_output><jupyter_text>2. Work on regular grids  2.1 Extract data from skt data<jupyter_code>ncset= netcdf(r'data\skt.mon.mean.nc')

lon = ncset['lon'][:]  
lat = ncset['lat'][:]            
skt = ncset['skt'][0,:,:]   
skt.shape<jupyter_output><empty_output><jupyter_text>2.2 Prepare new grids of longitude and latitudeKeep longitude and latitude in a monotonic increasing manner<jupyter_code>lat_new = np.linspace(np.min(lat), np.max(lat), skt.shape[0]*2)
lon_new = np.linspace(np.min(lon), np.max(lon), skt.shape[1]*2)<jupyter_output><empty_output><jupyter_text>2.3 Contruct interploate function and apply to new grids<jupyter_code>func = interp2d(lon, lat, skt, kind='cubic')
# apply to new level and latitude
sktnew = func(lon_new, lat_new)<jupyter_output><empty_output><jupyter_text>2.4 Have a comparision plot<jupyter_code>f, axarr = plt.subplots(2)
f.set_figwidth(12)
f.set_figheight(9)

[lons, lats] = np.meshgrid(lon, lat)
axarr[0].pcolormesh(lons, lats, skt)
axarr[0].set_title('SKT in Jan, 1948 [$^oC$]')

[lons_new, lats_new] = np.meshgrid(lon_new, lat_new)
axarr[1].pcolormesh(lons_new, lats_new, sktnew)<jupyter_output><empty_output><jupyter_text>3. Work on irregular gridsA commonly asked question on the matplotlib mailing lists is "how do I make a contour plot of my irregularly spaced data?". The answer is, first you interpolate it to a regular grid. As of version 0.98.3, matplotlib provides a griddata function that behaves similarly to the matlab version. It performs "natural neighbor interpolation" of irregularly spaced data a regular grid, which you can then plot with contour, imshow or pcolor.  3.1 Have a try on fake dataAn example from http://scipy-cookbook.readthedocs.io/items/Matplotlib_Gridding_irregularly_spaced_data.html<jupyter_code># make up some randomly distributed data
seed(1234)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid.
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,100)
# grid the data.
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
# contour the gridded data, plotting dots at the randomly spaced data points.
CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
plt.colorbar() # draw colorbar
# plot data points.
plt.scatter(x,y,marker='o',c='b',s=5)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)<jupyter_output><empty_output><jupyter_text>3.2 Try skt dataHere the interpolation method of griddata is used. Before using it, have to use ravel to transform data from 2D into 1D array (i.e., like scatter dots).<jupyter_code># grid the data.
skt_new = griddata((lons.ravel(), lats.ravel()), skt.ravel(), (lon_new[None,:], lat_new[:,None]), method='cubic')
f, axarr = plt.subplots(2)
f.set_figwidth(12)
f.set_figheight(9)

[lons, lats] = np.meshgrid(lon, lat)
axarr[0].pcolormesh(lons, lats, skt)
axarr[0].set_title('SKT in Jan, 1948 [$^oC$]')

[lons_new, lats_new] = np.meshgrid(lon_new, lat_new)
axarr[1].pcolormesh(lons_new, lats_new, skt_new)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12362957779332867, 'fraction_numerical': 0.023792862141357594, 'mean_word_length': 5.893890675241158, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '162728', 'license': 'MIT', 'n_tokens_mistral': 1633, 'n_tokens_neox': 1549, 'n_words': 442, 'path': 'ex07-Interpolate 2D field on regular and irregular grids.ipynb', 'repo_name': 'monocilindro/Python-Practical-Application-on-Climate-Variability-Studies', 'size': '4287'}