Completed
Pull Request — master (#470)
by
unknown
59s
created

test_convert_and_drop_units()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
c 1
b 0
f 1
dl 0
loc 10
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 (convert_and_drop_units, find_intersections, interpolate_nans,
11
                        log_interp,
12
                        nearest_intersection_idx, reduce_point_density, resample_nn_1d)
13
from metpy.calc.tools import _next_non_masked_element, 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
def test_convert_and_drop_units():
194
    """Test of conversion to common units and drop units."""
195
    x = 100000. * units.Pa
196
    y = 1000. * units.hPa
197
    z = 1000. * units.hPa
198
    x1, y1, z1, = convert_and_drop_units(x, y, z, units='hPa')
199
    truth = 1000.
200
    assert_array_almost_equal(x1, truth, 7)
201
    assert_array_almost_equal(y1, truth, 7)
202
    assert_array_almost_equal(z1, truth, 7)
203
204
205
def test_convert_and_drop_units_none_specified():
206
    """Test of conversion to common units and drop units with no unit specified."""
207
    x = 100000. * units.Pa
208
    y = 1000. * units.hPa
209
    z = 1000. * units.hPa
210
    x1, y1, z1, = convert_and_drop_units(x, y, z)
211
    truth = 100000.
212
    assert_array_almost_equal(x1, truth, 7)
213
    assert_array_almost_equal(y1, truth, 7)
214
    assert_array_almost_equal(z1, truth, 7)
215
216
217
def test_convert_and_drop_units_no_units():
218
    """Test of conversion to common units and drop units with no units attached."""
219
    x = 100000.
220
    y = 100000.
221
    x1, y1 = convert_and_drop_units(x, y)
222
    truth = 100000.
223
    assert_array_almost_equal(x1, truth, 7)
224
    assert_array_almost_equal(y1, truth, 7)
225