Coverage for lasso/dimred/svd/test_pod_functions.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.2.4, created at 2023-04-28 18:42 +0100

1from unittest import TestCase 

2from lasso.dimred.svd.pod_functions import calculate_v_and_betas 

3import numpy as np 

4from typing import Tuple 

5 

6 

7class PodFunctionsTest(TestCase): 

8 def test_calculate_v_and_betas(self): 

9 """Verify svd works 

10 Test for: 

11 - returns V and B of correct shape 

12 - failes if dataset to small (1 sample)""" 

13 

14 # random input for 1 sample, 5 timesteps, 100 nodes, 3 dimensions 

15 rand_samples = np.random.rand(1, 5, 100, 3) 

16 

17 # should return error message string 

18 err_msg = calculate_v_and_betas(rand_samples) 

19 self.assertTrue(isinstance(err_msg, str)) 

20 

21 # random input for 5 samples, 5 timesteps, 100 nodes, 3 dimensions 

22 test_shape = (5, 5, 100, 3) 

23 samples, timesteps, nodes, dimensions = test_shape 

24 rand_samples = np.random.rand(samples, timesteps, nodes, dimensions) 

25 result = calculate_v_and_betas(rand_samples) 

26 

27 # returns Tuple containing v_rob and betas 

28 self.assertTrue(isinstance(result, Tuple)) 

29 

30 v_rob, betas = result 

31 

32 # v_rob and betas should both be numpy arrays 

33 self.assertTrue(isinstance(v_rob, np.ndarray)) 

34 self.assertTrue(isinstance(betas, np.ndarray)) 

35 

36 # v_rob should be of shape (k_eigen, timesteps, nodes*dimensions) 

37 # k_eigen should be min(10, samples-1), so in this case k_eigen = samples-1 = 4 

38 k_eigen = min(10, samples - 1) 

39 self.assertEqual(v_rob.shape, (k_eigen, timesteps, nodes * dimensions)) 

40 

41 # betas should be of shape (samples, timesteps, k_eigen) 

42 self.assertEqual(betas.shape, (samples, timesteps, k_eigen)) 

43 

44 # v_rob and betas should result in difference in displacements of original result 

45 reshaped_samples = rand_samples.reshape(samples, timesteps, nodes * dimensions) 

46 

47 delta_displ = reshaped_samples[:, :] - np.stack( 

48 [reshaped_samples[0, :] for _ in range(timesteps)] 

49 ) 

50 

51 recacl_displ = np.einsum("ktn, stk -> stn", v_rob, betas) 

52 

53 # check if both original and recalc have the same shape 

54 self.assertEqual(delta_displ.shape, recacl_displ.shape)