Completed
Pull Request — master (#283)
by Ryan
01:32
created

basic_map()   A

Complexity

Conditions 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
1
# Copyright (c) 2008-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(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=to_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 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
38
    f = get_test_data('station_data.txt')
39
40
    all_data = np.loadtxt(f, skiprows=1, delimiter=',',
41
                          usecols=(1, 2, 3, 4, 5, 6, 7, 17, 18, 19),
42
                          dtype=np.dtype([('stid', '3S'), ('lat', 'f'), ('lon', 'f'),
43
                                          ('slp', 'f'), ('air_temperature', 'f'),
44
                                          ('cloud_fraction', 'f'), ('dewpoint', 'f'),
45
                                          ('weather', '16S'),
46
                                          ('wind_dir', 'f'), ('wind_speed', 'f')]))
47
48
    all_stids = [s.decode('ascii') for s in all_data['stid']]
49
50
    data = np.concatenate([all_data[all_stids.index(site)].reshape(1, ) for site in all_stids])
51
52
    value = data[variable_names]
53
    lon = data['lon']
54
    lat = data['lat']
55
56
    if proj_from is not None and proj_to is not None:
57
58
        try:
59
60
            proj_points = proj_to.transform_points(proj_from, lon, lat)
61
            return proj_points[:, 0], proj_points[:, 1], value
62
63
        except Exception as e:
64
65
            print(e)
66
            return None
67
68
    return lon, lat, value
69
70
71
from_proj = ccrs.Geodetic()
72
to_proj = ccrs.AlbersEqualArea(central_longitude=-97.0000, central_latitude=38.0000)
73
74
levels = list(range(-20, 20, 1))
75
cmap = plt.get_cmap('magma')
76
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
77
78
x, y, temp = station_test_data('air_temperature', from_proj, to_proj)
79
80
x, y, temp = remove_nan_observations(x, y, temp)
81
x, y, temp = remove_repeat_coordinates(x, y, temp)
82
83
###########################################
84
# Scipy.interpolate linear
85
# ------------------------
86
gx, gy, img = interpolate(x, y, temp, interp_type='linear', hres=75000)
87
img = np.ma.masked_where(np.isnan(img), img)
88
view = basic_map(to_proj)
89
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
90
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
91
92
###########################################
93
# Natural neighbor interpolation (MetPy implementation)
94
# -----------------------------------------------------
95
# `Reference <https://github.com/Unidata/MetPy/files/138653/cwp-657.pdf>`_
96
gx, gy, img = interpolate(x, y, temp, interp_type='natural_neighbor', hres=75000)
97
img = np.ma.masked_where(np.isnan(img), img)
98
view = basic_map(to_proj)
99
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
100
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
101
102
###########################################
103
# Cressman interpolation
104
# ----------------------
105
# search_radius = 100 km
106
#
107
# grid resolution = 25 km
108
#
109
# min_neighbors = 1
110
gx, gy, img = interpolate(x, y, temp, interp_type='cressman', minimum_neighbors=1, hres=75000,
111
                          search_radius=100000)
112
img = np.ma.masked_where(np.isnan(img), img)
113
view = basic_map(to_proj)
114
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
115
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
116
117
###########################################
118
# Barnes Interpolation
119
# --------------------
120
# search_radius = 100km
121
#
122
# min_neighbors = 3
123
gx, gy, img1 = interpolate(x, y, temp, interp_type='barnes', hres=75000, search_radius=100000)
124
img1 = np.ma.masked_where(np.isnan(img1), img1)
125
view = basic_map(to_proj)
126
mmb = view.pcolormesh(gx, gy, img1, cmap=cmap, norm=norm)
127
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
128
129
###########################################
130
# Radial basis function interpolation
131
# ------------------------------------
132
# linear
133
gx, gy, img = interpolate(x, y, temp, interp_type='rbf', hres=75000, rbf_func='linear',
134
                          rbf_smooth=0)
135
img = np.ma.masked_where(np.isnan(img), img)
136
view = basic_map(to_proj)
137
mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm)
138
plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
139
140
plt.show()
141