Completed
Push — master ( 270284...081a41 )
by Ryan
19s
created

station_test_data()   C

Complexity

Conditions 7

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
c 0
b 0
f 0
dl 0
loc 31
rs 5.5
1
# Copyright (c) 2016 MetPy Developers.
2
# Distributed under the terms of the BSD 3-Clause License.
3
# SPDX-License-Identifier: BSD-3-Clause
4
"""
5
Point Interpolation
6
===================
7
8
Compares different point interpolation approaches.
9
"""
10
import cartopy
11
import cartopy.crs as ccrs
12
from matplotlib.colors import BoundaryNorm
13
import matplotlib.pyplot as plt
14
import numpy as np
15
16
from metpy.cbook import get_test_data
17
from metpy.gridding.gridding_functions import (interpolate, remove_nan_observations,
18
                                               remove_repeat_coordinates)
19
20
21
###########################################
22
def basic_map(proj):
23
    """Make our basic default map for plotting"""
24
    fig = plt.figure(figsize=(15, 10))
25
    view = fig.add_axes([0, 0, 1, 1], projection=proj)
26
    view.set_extent([-120, -70, 20, 50])
27
    view.add_feature(cartopy.feature.NaturalEarthFeature(category='cultural',
28
                                                         name='admin_1_states_provinces_lakes',
29
                                                         scale='50m', facecolor='none'))
30
    view.add_feature(cartopy.feature.OCEAN)
31
    view.add_feature(cartopy.feature.COASTLINE)
32
    view.add_feature(cartopy.feature.BORDERS, linestyle=':')
33
    return view
34
35
36
def station_test_data(variable_names, proj_from=None, proj_to=None):
37
    with get_test_data('station_data.txt') as f:
38
        all_data = np.loadtxt(f, skiprows=1, delimiter=',',
39
                              usecols=(1, 2, 3, 4, 5, 6, 7, 17, 18, 19),
40
                              dtype=np.dtype([('stid', '3S'), ('lat', 'f'), ('lon', 'f'),
41
                                              ('slp', 'f'), ('air_temperature', 'f'),
42
                                              ('cloud_fraction', 'f'), ('dewpoint', 'f'),
43
                                              ('weather', '16S'),
44
                                              ('wind_dir', 'f'), ('wind_speed', 'f')]))
45
46
    all_stids = [s.decode('ascii') for s in all_data['stid']]
47
48
    data = np.concatenate([all_data[all_stids.index(site)].reshape(1, ) for site in all_stids])
49
50
    value = data[variable_names]
51
    lon = data['lon']
52
    lat = data['lat']
53
54
    if proj_from is not None and proj_to is not None:
55
56
        try:
57
58
            proj_points = proj_to.transform_points(proj_from, lon, lat)
59
            return proj_points[:, 0], proj_points[:, 1], value
60
61
        except Exception as e:
62
63
            print(e)
64
            return None
65
66
    return lon, lat, value
67
68
69
from_proj = ccrs.Geodetic()
70
to_proj = ccrs.AlbersEqualArea(central_longitude=-97.0000, central_latitude=38.0000)
71
72
levels = list(range(-20, 20, 1))
73
cmap = plt.get_cmap('magma')
74
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
75
76
x, y, temp = station_test_data('air_temperature', from_proj, to_proj)
77
78
x, y, temp = remove_nan_observations(x, y, temp)
79
x, y, temp = remove_repeat_coordinates(x, y, temp)
80
81
###########################################
82
# Scipy.interpolate linear
83
# ------------------------
84
gx, gy, img = interpolate(x, y, temp, interp_type='linear', hres=75000)
85
img = np.ma.masked_where(np.isnan(img), img)
86
view = basic_map(to_proj)
87
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
88
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
89
90
###########################################
91
# Natural neighbor interpolation (MetPy implementation)
92
# -----------------------------------------------------
93
# `Reference <https://github.com/Unidata/MetPy/files/138653/cwp-657.pdf>`_
94
gx, gy, img = interpolate(x, y, temp, interp_type='natural_neighbor', hres=75000)
95
img = np.ma.masked_where(np.isnan(img), img)
96
view = basic_map(to_proj)
97
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
98
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
99
100
###########################################
101
# Cressman interpolation
102
# ----------------------
103
# search_radius = 100 km
104
#
105
# grid resolution = 25 km
106
#
107
# min_neighbors = 1
108
gx, gy, img = interpolate(x, y, temp, interp_type='cressman', minimum_neighbors=1, hres=75000,
109
                          search_radius=100000)
110
img = np.ma.masked_where(np.isnan(img), img)
111
view = basic_map(to_proj)
112
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
113
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
114
115
###########################################
116
# Barnes Interpolation
117
# --------------------
118
# search_radius = 100km
119
#
120
# min_neighbors = 3
121
gx, gy, img1 = interpolate(x, y, temp, interp_type='barnes', hres=75000, search_radius=100000)
122
img1 = np.ma.masked_where(np.isnan(img1), img1)
123
view = basic_map(to_proj)
124
mmb = view.pcolormesh(gx, gy, img1, cmap=cmap, norm=norm)
125
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
126
127
###########################################
128
# Radial basis function interpolation
129
# ------------------------------------
130
# linear
131
gx, gy, img = interpolate(x, y, temp, interp_type='rbf', hres=75000, rbf_func='linear',
132
                          rbf_smooth=0)
133
img = np.ma.masked_where(np.isnan(img), img)
134
view = basic_map(to_proj)
135
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
136
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
137
138
plt.show()
139