1#
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import numpy as np
18
19import lc3
20import tables as T, appendix_c as C
21
22### ------------------------------------------------------------------------ ###
23
24class EnergyBand:
25
26    def __init__(self, dt, sr):
27
28        self.dt = dt
29        self.I = T.I[dt][sr]
30
31    def compute(self, x):
32
33        e = [ np.mean(np.square(x[self.I[i]:self.I[i+1]]))
34               for i in range(len(self.I)-1) ]
35
36        e_lo = np.sum(e[:len(e) - [4, 2][self.dt]])
37        e_hi = np.sum(e[len(e) - [4, 2][self.dt]:])
38
39        return np.append(e, np.zeros(64-len(e))), (e_hi > 30*e_lo)
40
41### ------------------------------------------------------------------------ ###
42
43def check_unit(rng, dt, sr):
44
45    ns = T.NS[dt][sr]
46    ok = True
47
48    nrg = EnergyBand(dt, sr)
49
50    x = (2 * rng.random(T.NS[dt][sr])) - 1
51
52    (e  , nn  ) = nrg.compute(x)
53    (e_c, nn_c) = lc3.energy_compute(dt, sr, x)
54    ok = ok and np.amax(np.abs(e_c - e)) < 1e-5 and nn_c == nn
55
56    x[15*ns//16:] *= 1e2;
57
58    (e  , nn  ) = nrg.compute(x)
59    (e_c, nn_c) = lc3.energy_compute(dt, sr, x)
60    ok = ok and np.amax(np.abs(e_c - e)) < 1e-3 and nn_c == nn
61
62    return ok
63
64def check_appendix_c(dt):
65
66    sr = T.SRATE_16K
67    ok = True
68
69    e  = lc3.energy_compute(dt, sr, C.X[dt][0])[0]
70    ok = ok and np.amax(np.abs(1 - e/C.E_B[dt][0])) < 1e-6
71
72    e  = lc3.energy_compute(dt, sr, C.X[dt][1])[0]
73    ok = ok and np.amax(np.abs(1 - e/C.E_B[dt][1])) < 1e-6
74
75    return ok
76
77def check():
78
79    rng = np.random.default_rng(1234)
80
81    ok = True
82
83    for dt in range(T.NUM_DT):
84        for sr in range(T.NUM_SRATE):
85            ok = ok and check_unit(rng, dt, sr)
86
87    for dt in range(T.NUM_DT):
88        ok = ok and check_appendix_c(dt)
89
90    return ok
91
92### ------------------------------------------------------------------------ ###
93