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) - [2, 3, 4, 2][self.dt]]) 37 e_hi = np.sum(e[len(e) - [2, 3, 4, 2][self.dt]:]) 38 39 return 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 i0 = dt - T.DT_7M5 67 sr = T.SRATE_16K 68 69 ok = True 70 71 e = lc3.energy_compute(dt, sr, C.X[i0][0])[0] 72 ok = ok and np.amax(np.abs(1 - e/C.E_B[i0][0])) < 1e-6 73 74 e = lc3.energy_compute(dt, sr, C.X[i0][1])[0] 75 ok = ok and np.amax(np.abs(1 - e/C.E_B[i0][1])) < 1e-6 76 77 return ok 78 79def check(): 80 81 rng = np.random.default_rng(1234) 82 83 ok = True 84 85 for dt in range(T.NUM_DT): 86 for sr in range(T.SRATE_8K, T.SRATE_48K + 1): 87 ok = ok and check_unit(rng, dt, sr) 88 89 for dt in ( T.DT_2M5, T.DT_5M, T.DT_10M ): 90 for sr in ( T.SRATE_48K_HR, T.SRATE_96K_HR ): 91 ok = ok and check_unit(rng, dt, sr) 92 93 for dt in ( T.DT_7M5, T.DT_10M ): 94 ok = ok and check_appendix_c(dt) 95 96 return ok 97 98### ------------------------------------------------------------------------ ### 99