• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""
16Testing AmplitudeToDB op in DE
17"""
18import numpy as np
19import pytest
20
21import mindspore.dataset as ds
22import mindspore.dataset.audio.transforms as c_audio
23from mindspore import log as logger
24from mindspore.dataset.audio.utils import ScaleType
25
26CHANNEL = 1
27FREQ = 20
28TIME = 15
29
30
31def gen(shape):
32    np.random.seed(0)
33    data = np.random.random(shape)
34    yield (np.array(data, dtype=np.float32),)
35
36
37def count_unequal_element(data_expected, data_me, rtol, atol):
38    """ Precision calculation func """
39    assert data_expected.shape == data_me.shape
40    total_count = len(data_expected.flatten())
41    error = np.abs(data_expected - data_me)
42    greater = np.greater(error, atol + np.abs(data_expected) * rtol)
43    loss_count = np.count_nonzero(greater)
44    assert (loss_count / total_count) < rtol, "\ndata_expected_std:{0}\ndata_me_error:{1}\nloss:{2}".format(
45        data_expected[greater], data_me[greater], error[greater])
46
47
48def allclose_nparray(data_expected, data_me, rtol, atol, equal_nan=True):
49    """ Precision calculation formula  """
50    if np.any(np.isnan(data_expected)):
51        assert np.allclose(data_me, data_expected, rtol, atol, equal_nan=equal_nan)
52    elif not np.allclose(data_me, data_expected, rtol, atol, equal_nan=equal_nan):
53        count_unequal_element(data_expected, data_me, rtol, atol)
54
55
56def test_func_amplitude_to_db_eager():
57    """ mindspore eager mode normal testcase:amplitude_to_db op"""
58
59    logger.info("check amplitude_to_db op output")
60    ndarr_in = np.array([[[[-0.2197528, 0.3821656]]],
61                         [[[0.57418776, 0.46741104]]],
62                         [[[-0.20381108, -0.9303914]]],
63                         [[[0.3693608, -0.2017813]]],
64                         [[[-1.727381, -1.3708513]]],
65                         [[[1.259975, 0.4981323]]],
66                         [[[0.76986176, -0.5793846]]]]).astype(np.float32)
67    # cal from benchmark
68    out_expect = np.array([[[[-84.17748, -4.177484]]],
69                           [[[-2.4094608, -3.3030105]]],
70                           [[[-100., -100.]]],
71                           [[[-4.325492, -84.32549]]],
72                           [[[-100., -100.]]],
73                           [[[1.0036192, -3.0265532]]],
74                           [[[-1.1358725, -81.13587]]]]).astype(np.float32)
75
76    amplitude_to_db_op = c_audio.AmplitudeToDB()
77    out_mindspore = amplitude_to_db_op(ndarr_in)
78
79    allclose_nparray(out_mindspore, out_expect, 0.0001, 0.0001)
80
81
82def test_func_amplitude_to_db_pipeline():
83    """ mindspore pipeline mode normal testcase:amplitude_to_db op"""
84
85    logger.info("test AmplitudeToDB op with default value")
86    generator = gen([CHANNEL, FREQ, TIME])
87
88    data1 = ds.GeneratorDataset(source=generator, column_names=["multi_dimensional_data"])
89
90    transforms = [c_audio.AmplitudeToDB()]
91    data1 = data1.map(operations=transforms, input_columns=["multi_dimensional_data"])
92
93    for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
94        out_put = item["multi_dimensional_data"]
95    assert out_put.shape == (CHANNEL, FREQ, TIME)
96
97
98def test_amplitude_to_db_invalid_input():
99    def test_invalid_input(test_name, stype, ref_value, amin, top_db, error, error_msg):
100        logger.info("Test AmplitudeToDB with bad input: {0}".format(test_name))
101        with pytest.raises(error) as error_info:
102            c_audio.AmplitudeToDB(stype=stype, ref_value=ref_value, amin=amin, top_db=top_db)
103        assert error_msg in str(error_info.value)
104
105    test_invalid_input("invalid stype parameter value", "test", 1.0, 1e-10, 80.0, TypeError,
106                       "Argument stype with value test is not of type [<enum 'ScaleType'>], but got <class 'str'>.")
107    test_invalid_input("invalid ref_value parameter value", ScaleType.POWER, -1.0, 1e-10, 80.0, ValueError,
108                       "Input ref_value is not within the required interval of (0, 16777216]")
109    test_invalid_input("invalid amin parameter value", ScaleType.POWER, 1.0, -1e-10, 80.0, ValueError,
110                       "Input amin is not within the required interval of (0, 16777216]")
111    test_invalid_input("invalid top_db parameter value", ScaleType.POWER, 1.0, 1e-10, -80.0, ValueError,
112                       "Input top_db is not within the required interval of (0, 16777216]")
113
114    test_invalid_input("invalid stype parameter value", True, 1.0, 1e-10, 80.0, TypeError,
115                       "Argument stype with value True is not of type [<enum 'ScaleType'>], but got <class 'bool'>.")
116    test_invalid_input("invalid ref_value parameter value", ScaleType.POWER, "value", 1e-10, 80.0, TypeError,
117                       "Argument ref_value with value value is not of type [<class 'int'>, <class 'float'>], " +
118                       "but got <class 'str'>")
119    test_invalid_input("invalid amin parameter value", ScaleType.POWER, 1.0, "value", -80.0, TypeError,
120                       "Argument amin with value value is not of type [<class 'int'>, <class 'float'>], " +
121                       "but got <class 'str'>")
122    test_invalid_input("invalid top_db parameter value", ScaleType.POWER, 1.0, 1e-10, "value", TypeError,
123                       "Argument top_db with value value is not of type [<class 'int'>, <class 'float'>], " +
124                       "but got <class 'str'>")
125
126
127if __name__ == "__main__":
128    test_func_amplitude_to_db_eager()
129    test_func_amplitude_to_db_pipeline()
130    test_amplitude_to_db_invalid_input()
131