Completed
Pull Request — master (#444)
by
unknown
02:10
created

get_bounds_hgts()   A

Complexity

Conditions 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
1
# Copyright (c) 2008-2015 MetPy Developers.
2
# Distributed under the terms of the BSD 3-Clause License.
3
# SPDX-License-Identifier: BSD-3-Clause
4
"""Tests for `calc.tools` module."""
5
6
import numpy as np
7
import numpy.ma as ma
8
import pytest
9
10
from metpy.calc import (find_intersections, interpolate_nans, log_interp,
11
                        nearest_intersection_idx, reduce_point_density, resample_nn_1d)
12
from metpy.calc.tools import (_get_bound_pressure_height, _next_non_masked_element,
13
                              delete_masked_points)
14
from metpy.testing import assert_array_almost_equal, assert_array_equal
15
from metpy.units import units
16
17
18
def test_resample_nn():
19
    """Test 1d nearest neighbor functionality."""
20
    a = np.arange(5.)
21
    b = np.array([2, 3.8])
22
    truth = np.array([2, 4])
23
24
    assert_array_equal(truth, resample_nn_1d(a, b))
25
26
27
def test_nearest_intersection_idx():
28
    """Test nearest index to intersection functionality."""
29
    x = np.linspace(5, 30, 17)
30
    y1 = 3 * x**2
31
    y2 = 100 * x - 650
32
    truth = np.array([2, 12])
33
34
    assert_array_equal(truth, nearest_intersection_idx(y1, y2))
35
36
37
@pytest.mark.parametrize('direction, expected', [
38
    ('all', np.array([[8.88, 24.44], [238.84, 1794.53]])),
39
    ('increasing', np.array([[24.44], [1794.53]])),
40
    ('decreasing', np.array([[8.88], [238.84]]))
41
])
42
def test_find_intersections(direction, expected):
43
    """Test finding the intersection of two curves functionality."""
44
    x = np.linspace(5, 30, 17)
45
    y1 = 3 * x**2
46
    y2 = 100 * x - 650
47
    # Note: Truth is what we will get with this sampling, not the mathematical intersection
48
    assert_array_almost_equal(expected, find_intersections(x, y1, y2, direction=direction), 2)
49
50
51
def test_find_intersections_no_intersections():
52
    """Test finding the intersection of two curves with no intersections."""
53
    x = np.linspace(5, 30, 17)
54
    y1 = 3 * x + 0
55
    y2 = 5 * x + 5
56
    # Note: Truth is what we will get with this sampling, not the mathematical intersection
57
    truth = np.array([[],
58
                      []])
59
    assert_array_equal(truth, find_intersections(x, y1, y2))
60
61
62
def test_find_intersections_invalid_direction():
63
    """Test exception if an invalid direction is given."""
64
    x = np.linspace(5, 30, 17)
65
    y1 = 3 * x ** 2
66
    y2 = 100 * x - 650
67
    with pytest.raises(ValueError):
68
        find_intersections(x, y1, y2, direction='increaing')
69
70
71
def test_interpolate_nan_linear():
72
    """Test linear interpolation of arrays with NaNs in the y-coordinate."""
73
    x = np.linspace(0, 20, 15)
74
    y = 5 * x + 3
75
    nan_indexes = [1, 5, 11, 12]
76
    y_with_nan = y.copy()
77
    y_with_nan[nan_indexes] = np.nan
78
    assert_array_almost_equal(y, interpolate_nans(x, y_with_nan), 2)
79
80
81
def test_interpolate_nan_log():
82
    """Test log interpolation of arrays with NaNs in the y-coordinate."""
83
    x = np.logspace(1, 5, 15)
84
    y = 5 * np.log(x) + 3
85
    nan_indexes = [1, 5, 11, 12]
86
    y_with_nan = y.copy()
87
    y_with_nan[nan_indexes] = np.nan
88
    assert_array_almost_equal(y, interpolate_nans(x, y_with_nan, kind='log'), 2)
89
90
91
def test_interpolate_nan_invalid():
92
    """Test log interpolation with invalid parameter."""
93
    x = np.logspace(1, 5, 15)
94
    y = 5 * np.log(x) + 3
95
    with pytest.raises(ValueError):
96
        interpolate_nans(x, y, kind='loog')
97
98
99
@pytest.mark.parametrize('mask, expected_idx, expected_element', [
100
    ([False, False, False, False, False], 1, 1),
101
    ([False, True, True, False, False], 3, 3),
102
    ([False, True, True, True, True], None, None)
103
])
104
def test_non_masked_elements(mask, expected_idx, expected_element):
105
    """Test with a valid element."""
106
    a = ma.masked_array(np.arange(5), mask=mask)
107
    idx, element = _next_non_masked_element(a, 1)
108
    assert idx == expected_idx
109
    assert element == expected_element
110
111
112
@pytest.fixture
113
def thin_point_data():
114
    r"""Provide scattered points for testing."""
115
    xy = np.array([[0.8793620, 0.9005706], [0.5382446, 0.8766988], [0.6361267, 0.1198620],
116
                   [0.4127191, 0.0270573], [0.1486231, 0.3121822], [0.2607670, 0.4886657],
117
                   [0.7132257, 0.2827587], [0.4371954, 0.5660840], [0.1318544, 0.6468250],
118
                   [0.6230519, 0.0682618], [0.5069460, 0.2326285], [0.1324301, 0.5609478],
119
                   [0.7975495, 0.2109974], [0.7513574, 0.9870045], [0.9305814, 0.0685815],
120
                   [0.5271641, 0.7276889], [0.8116574, 0.4795037], [0.7017868, 0.5875983],
121
                   [0.5591604, 0.5579290], [0.1284860, 0.0968003], [0.2857064, 0.3862123]])
122
    return xy
123 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
124
125
@pytest.mark.parametrize('radius, truth',
126
                         [(2.0, np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
127
                                          0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=np.bool)),
128
                          (1.0, np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
129
                                          0, 0, 0, 0, 0, 0, 0, 0, 1, 0], dtype=np.bool)),
130
                          (0.3, np.array([1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0,
131
                                          0, 0, 0, 0, 0, 1, 0, 0, 0, 0], dtype=np.bool)),
132
                          (0.1, np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1,
133
                                          0, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.bool))
134
                          ])
135
def test_reduce_point_density(thin_point_data, radius, truth):
136
    r"""Test that reduce_point_density works."""
137
    assert_array_equal(reduce_point_density(thin_point_data, radius=radius), truth)
138 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
139
140
@pytest.mark.parametrize('radius, truth',
141
                         [(2.0, np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
142
                                          0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dtype=np.bool)),
143
                          (0.7, np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
144
                                          0, 0, 0, 1, 0, 0, 0, 0, 0, 1], dtype=np.bool)),
145
                          (0.3, np.array([1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0,
146
                                          0, 0, 0, 1, 0, 0, 0, 1, 0, 1], dtype=np.bool)),
147
                          (0.1, np.array([1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
148
                                          0, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.bool))
149
                          ])
150
def test_reduce_point_density_priority(thin_point_data, radius, truth):
151
    r"""Test that reduce_point_density works properly with priority."""
152
    key = np.array([8, 6, 2, 8, 6, 4, 4, 8, 8, 6, 3, 4, 3, 0, 7, 4, 3, 2, 3, 3, 9])
153
    assert_array_equal(reduce_point_density(thin_point_data, radius, key), truth)
154
155
156
def test_reduce_point_density_1d():
157
    r"""Test that reduce_point_density works with 1D points."""
158
    x = np.array([1, 3, 4, 8, 9, 10])
159
    assert_array_equal(reduce_point_density(x, 2.5),
160
                       np.array([1, 0, 1, 1, 0, 0], dtype=np.bool))
161
162
163
def test_delete_masked_points():
164
    """Test deleting masked points."""
165
    a = ma.masked_array(np.arange(5), mask=[False, True, False, False, False])
166
    b = ma.masked_array(np.arange(5), mask=[False, False, False, True, False])
167
    expected = np.array([0, 2, 4])
168
    a, b = delete_masked_points(a, b)
169
    assert_array_equal(a, expected)
170
    assert_array_equal(b, expected)
171
172
173
def test_log_interp():
174
    """Test interpolating with log x-scale."""
175
    x_log = np.array([1e3, 1e4, 1e5, 1e6])
176
    y_log = np.log(x_log) * 2 + 3
177
    x_interp = np.array([5e3, 5e4, 5e5])
178
    y_interp_truth = np.array([20.0343863828, 24.6395565688, 29.2447267548])
179
    y_interp = log_interp(x_interp, x_log, y_log)
180
    assert_array_almost_equal(y_interp, y_interp_truth, 7)
181
182
183
def test_log_interp_units():
184
    """Test interpolating with log x-scale with units."""
185
    x_log = np.array([1e3, 1e4, 1e5, 1e6]) * units.hPa
186
    y_log = (np.log(x_log.m) * 2 + 3) * units.degC
187
    x_interp = np.array([5e3, 5e4, 5e5]) * units.hPa
188
    y_interp_truth = np.array([20.0343863828, 24.6395565688, 29.2447267548]) * units.degC
189
    y_interp = log_interp(x_interp, x_log, y_log)
190
    assert_array_almost_equal(y_interp, y_interp_truth, 7)
191
192
193
@pytest.fixture
194
def get_bounds_hgts():
195
    """Provide height data for testing layer bounds calculation."""
196
    heights = np.array([0.11082868, 0.98800289, 1.94800715, 3.01066419,
197
                        4.20430387, 5.5716246, 7.18180831, 9.15932561,
198
                        11.76894096, 15.78930499]) * units.kilometer
199
    return heights
200
201
202
@pytest.fixture
203
def get_bounds_press():
204
    """Provide pressure data for testing layer bounds calculation."""
205
    pressure = np.linspace(1000, 100, 10) * units.hPa
206
    return pressure
207
208
209
@pytest.mark.parametrize('pressure, bound, hgts, interp, expected', [
210
    (get_bounds_press(), 900 * units.hPa, None, True,
211
     (900 * units.hPa, 0.9880028 * units.kilometer)),
212
    (get_bounds_press(), 900 * units.hPa, None, False,
213
     (900 * units.hPa, 0.9880028 * units.kilometer)),
214
    (get_bounds_press(), 870 * units.hPa, None, True,
215
     (870 * units.hPa, 1.2665298 * units.kilometer)),
216
    (get_bounds_press(), 870 * units.hPa, None, False,
217
     (900 * units.hPa, 0.9880028 * units.kilometer)),
218
    (get_bounds_press(), 0.9880028 * units.kilometer, None, True,
219
     (900 * units.hPa, 0.9880028 * units.kilometer)),
220
    (get_bounds_press(), 0.9880028 * units.kilometer, None, False,
221
     (900 * units.hPa, 0.9880028 * units.kilometer)),
222
    (get_bounds_press(), 1.2665298 * units.kilometer, None, True,
223
     (870 * units.hPa, 1.2665298 * units.kilometer)),
224
    (get_bounds_press(), 1.2665298 * units.kilometer, None, False,
225
     (900 * units.hPa, 0.9880028 * units.kilometer)),
226
    (get_bounds_press(), 900 * units.hPa, get_bounds_hgts(), True,
227
     (900 * units.hPa, 0.9880028 * units.kilometer)),
228
    (get_bounds_press(), 900 * units.hPa, get_bounds_hgts(), False,
229
     (900 * units.hPa, 0.9880028 * units.kilometer)),
230
    (get_bounds_press(), 870 * units.hPa, get_bounds_hgts(), True,
231
     (870 * units.hPa, 1.2643214 * units.kilometer)),
232
    (get_bounds_press(), 870 * units.hPa, get_bounds_hgts(), False,
233
     (900 * units.hPa, 0.9880028 * units.kilometer)),
234
    (get_bounds_press(), 0.9880028 * units.kilometer, get_bounds_hgts(), True,
235
     (900 * units.hPa, 0.9880028 * units.kilometer)),
236
    (get_bounds_press(), 0.9880028 * units.kilometer, get_bounds_hgts(), False,
237
     (900 * units.hPa, 0.9880028 * units.kilometer)),
238
    (get_bounds_press(), 1.2665298 * units.kilometer, get_bounds_hgts(), True,
239
     (870 * units.hPa, 1.2665298 * units.kilometer)),
240
    (get_bounds_press(), 1.2665298 * units.kilometer, get_bounds_hgts(), False,
241
     (900 * units.hPa, 0.9880028 * units.kilometer))
242
])
243
def test_get_bound_pressure_height(pressure, bound, hgts, interp, expected):
244
    """Test getting bounds in layers with various parameter combinations."""
245
    bounds = _get_bound_pressure_height(pressure, bound, heights=hgts, interpolate=interp)
246
    assert_array_almost_equal(bounds[0], expected[0], 5)
247
    assert_array_almost_equal(bounds[1], expected[1], 5)
248