.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/isentropic_example.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_isentropic_example.py: =================== Isentropic Analysis =================== The MetPy function `mpcalc.isentropic_interpolation` allows for isentropic analysis from model analysis data in isobaric coordinates. .. GENERATED FROM PYTHON SOURCE LINES 14-25 .. code-block:: Python import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import numpy as np import xarray as xr import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.plots import add_metpy_logo, add_timestamp from metpy.units import units .. GENERATED FROM PYTHON SOURCE LINES 26-32 **Getting the data** In this example, [NARR reanalysis data]( https://www.ncei.noaa.gov/products/weather-climate-models/north-american-regional) for 18 UTC 04 April 1987 from the National Centers for Environmental Information will be used. .. GENERATED FROM PYTHON SOURCE LINES 32-35 .. code-block:: Python data = xr.open_dataset(get_test_data('narr_example.nc', False)) .. GENERATED FROM PYTHON SOURCE LINES 36-38 .. code-block:: Python print(list(data.variables)) .. rst-class:: sphx-glr-script-out .. code-block:: none ['Temperature', 'time', 'isobaric', 'y', 'x', 'Lambert_Conformal', 'lat', 'lon', 'u_wind', 'v_wind', 'Geopotential_height', 'Specific_humidity'] .. GENERATED FROM PYTHON SOURCE LINES 39-41 We will reduce the dimensionality of the data as it is pulled in to remove an empty time dimension, as well as add longitude and latitude as coordinates (instead of data variables). .. GENERATED FROM PYTHON SOURCE LINES 41-44 .. code-block:: Python data = data.squeeze().set_coords(['lon', 'lat']) .. GENERATED FROM PYTHON SOURCE LINES 45-47 To properly interpolate to isentropic coordinates, the function must know the desired output isentropic levels. An array with these levels will be created below. .. GENERATED FROM PYTHON SOURCE LINES 47-50 .. code-block:: Python isentlevs = [296.] * units.kelvin .. GENERATED FROM PYTHON SOURCE LINES 51-59 **Conversion to Isentropic Coordinates** Once three dimensional data in isobaric coordinates has been pulled and the desired isentropic levels created, the conversion to isentropic coordinates can begin. Data will be passed to the function as below. The function requires that isentropic levels, as well as a DataArray of temperature on isobaric coordinates be input. Any additional inputs (in this case specific humidity, geopotential height, and u and v wind components) will be logarithmicaly interpolated to isentropic space. .. GENERATED FROM PYTHON SOURCE LINES 59-69 .. code-block:: Python isent_data = mpcalc.isentropic_interpolation_as_dataset( isentlevs, data['Temperature'], data['u_wind'], data['v_wind'], data['Specific_humidity'], data['Geopotential_height'] ) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/MetPy/MetPy/examples/isentropic_example.py:60: UserWarning: Interpolation point out of data bounds encountered isent_data = mpcalc.isentropic_interpolation_as_dataset( .. GENERATED FROM PYTHON SOURCE LINES 70-71 The output is an xarray Dataset: .. GENERATED FROM PYTHON SOURCE LINES 71-74 .. code-block:: Python isent_data .. raw:: html
<xarray.Dataset> Size: 2MB
    Dimensions:              (isentropic_level: 1, y: 118, x: 292)
    Coordinates:
      * isentropic_level     (isentropic_level) float64 8B 296.0
        time                 datetime64[ns] 8B 1987-04-04T18:00:00
      * y                    (y) float64 944B -3.087e+03 -3.054e+03 ... 678.9 711.4
      * x                    (x) float64 2kB -3.977e+03 -3.945e+03 ... 5.47e+03
        lat                  (y, x) float64 276kB ...
        lon                  (y, x) float64 276kB ...
    Data variables:
        pressure             (isentropic_level, y, x) float64 276kB <Quantity([[[...
        temperature          (isentropic_level, y, x) float64 276kB <Quantity([[[...
        u_wind               (isentropic_level, y, x) float64 276kB <Quantity([[[...
        v_wind               (isentropic_level, y, x) float64 276kB <Quantity([[[...
        Specific_humidity    (isentropic_level, y, x) float64 276kB <Quantity([[[...
        Geopotential_height  (isentropic_level, y, x) float64 276kB <Quantity([[[...


.. GENERATED FROM PYTHON SOURCE LINES 75-77 Note that the units on our wind variables are not ideal for plotting. Instead, let us convert them to more appropriate values. .. GENERATED FROM PYTHON SOURCE LINES 77-81 .. code-block:: Python isent_data['u_wind'] = isent_data['u_wind'].metpy.convert_units('kt') isent_data['v_wind'] = isent_data['v_wind'].metpy.convert_units('kt') .. GENERATED FROM PYTHON SOURCE LINES 82-86 **Converting to Relative Humidity** The NARR only gives specific humidity on isobaric vertical levels, so relative humidity will have to be calculated after the interpolation to isentropic space. .. GENERATED FROM PYTHON SOURCE LINES 86-93 .. code-block:: Python isent_data['Relative_humidity'] = mpcalc.relative_humidity_from_specific_humidity( isent_data['pressure'], isent_data['temperature'], isent_data['Specific_humidity'] ).metpy.convert_units('percent') .. GENERATED FROM PYTHON SOURCE LINES 94-95 **Plotting the Isentropic Analysis** .. GENERATED FROM PYTHON SOURCE LINES 95-140 .. code-block:: Python # Set up our projection and coordinates crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0) lon = isent_data['pressure'].metpy.longitude lat = isent_data['pressure'].metpy.latitude # Coordinates to limit map area bounds = [(-122., -75., 25., 50.)] # Choose a level to plot, in this case 296 K (our sole level in this example) level = 0 fig = plt.figure(figsize=(17., 12.)) add_metpy_logo(fig, 120, 245, size='large') ax = fig.add_subplot(1, 1, 1, projection=crs) ax.set_extent(*bounds, crs=ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75) ax.add_feature(cfeature.STATES, linewidth=0.5) # Plot the surface clevisent = np.arange(0, 1000, 25) cs = ax.contour(lon, lat, isent_data['pressure'].isel(isentropic_level=level), clevisent, colors='k', linewidths=1.0, linestyles='solid', transform=ccrs.PlateCarree()) cs.clabel(fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True, use_clabeltext=True) # Plot RH cf = ax.contourf(lon, lat, isent_data['Relative_humidity'].isel(isentropic_level=level), range(10, 106, 5), cmap=plt.cm.gist_earth_r, transform=ccrs.PlateCarree()) cb = fig.colorbar(cf, orientation='horizontal', aspect=65, shrink=0.5, pad=0.05, extendrect='True') cb.set_label('Relative Humidity', size='x-large') # Plot wind barbs ax.barbs(lon.values, lat.values, isent_data['u_wind'].isel(isentropic_level=level).values, isent_data['v_wind'].isel(isentropic_level=level).values, length=6, regrid_shape=20, transform=ccrs.PlateCarree()) # Make some titles ax.set_title(f'{isentlevs[level]:~.0f} Isentropic Pressure (hPa), Wind (kt), ' 'Relative Humidity (percent)', loc='left') add_timestamp(ax, isent_data['time'].values.astype('datetime64[ms]').astype('O'), y=0.02, high_contrast=True) fig.tight_layout() .. image-sg:: /examples/images/sphx_glr_isentropic_example_001.png :alt: 296 K Isentropic Pressure (hPa), Wind (kt), Relative Humidity (percent) :srcset: /examples/images/sphx_glr_isentropic_example_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 141-146 **Montgomery Streamfunction** The Montgomery Streamfunction, :math:`{\psi} = gdz + CpT`, is often desired because its gradient is proportional to the geostrophic wind in isentropic space. This can be easily calculated with `mpcalc.montgomery_streamfunction`. .. GENERATED FROM PYTHON SOURCE LINES 146-191 .. code-block:: Python # Calculate Montgomery Streamfunction and scale by 10^-2 for plotting msf = mpcalc.montgomery_streamfunction( isent_data['Geopotential_height'], isent_data['temperature'] ).data.to_base_units() * 1e-2 # Choose a level to plot, in this case 296 K level = 0 fig = plt.figure(figsize=(17., 12.)) add_metpy_logo(fig, 120, 250, size='large') ax = plt.subplot(111, projection=crs) ax.set_extent(*bounds, crs=ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75) ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.5) # Plot the surface clevmsf = np.arange(0, 4000, 5) cs = ax.contour(lon, lat, msf[level, :, :], clevmsf, colors='k', linewidths=1.0, linestyles='solid', transform=ccrs.PlateCarree()) cs.clabel(fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True, use_clabeltext=True) # Plot RH cf = ax.contourf(lon, lat, isent_data['Relative_humidity'].isel(isentropic_level=level), range(10, 106, 5), cmap=plt.cm.gist_earth_r, transform=ccrs.PlateCarree()) cb = fig.colorbar(cf, orientation='horizontal', aspect=65, shrink=0.5, pad=0.05, extendrect='True') cb.set_label('Relative Humidity', size='x-large') # Plot wind barbs ax.barbs(lon.values, lat.values, isent_data['u_wind'].isel(isentropic_level=level).values, isent_data['v_wind'].isel(isentropic_level=level).values, length=6, regrid_shape=20, transform=ccrs.PlateCarree()) # Make some titles ax.set_title(f'{isentlevs[level]:~.0f} Montgomery Streamfunction ' r'($10^{-2} m^2 s^{-2}$), Wind (kt), Relative Humidity (percent)', loc='left') add_timestamp(ax, isent_data['time'].values.astype('datetime64[ms]').astype('O'), y=0.02, pretext='Valid: ', high_contrast=True) fig.tight_layout() plt.show() .. image-sg:: /examples/images/sphx_glr_isentropic_example_002.png :alt: 296 K Montgomery Streamfunction ($10^{-2} m^2 s^{-2}$), Wind (kt), Relative Humidity (percent) :srcset: /examples/images/sphx_glr_isentropic_example_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 10.678 seconds) .. _sphx_glr_download_examples_isentropic_example.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: isentropic_example.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: isentropic_example.py ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_