1+ import pytest
2+ import numpy as np
3+ import pandas as pd
4+ from spotpython .utils .stats import cov_to_cor , partial_correlation , pairwise_partial_correlation
5+
6+ def test_cov_to_cor ():
7+ covariance = np .array ([[1 , 0.8 ], [0.8 , 1 ]])
8+ expected_correlation = np .array ([[1 , 0.8 ], [0.8 , 1 ]])
9+ calculated_correlation = cov_to_cor (covariance )
10+ assert np .allclose (calculated_correlation , expected_correlation ), "Failed to convert covariance to correlation correctly"
11+
12+ def test_partial_correlation ():
13+ data = pd .DataFrame ({
14+ 'A' : [1 , 2 , 3 , 4 ],
15+ 'B' : [2 , 3 , 4 , 5 ],
16+ 'C' : [4 , 5 , 6 , 7 ]
17+ })
18+ result = partial_correlation (data , method = 'pearson' )
19+
20+ assert isinstance (result , dict ), "Expected result to be a dictionary"
21+ assert 'estimate' in result and 'p_value' in result , "Result missing expected keys"
22+ assert np .allclose (np .diag (result ['estimate' ]), 1 ), "Diagonal of estimate should be 1"
23+ assert result ['n' ] == 4 , "The sample size should be 4"
24+ assert result ['gp' ] == 1 , "The number of given parameters should be 1"
25+
26+
27+ def test_pairwise_partial_correlation ():
28+ x = [1 , 2 , 3 , 4 ]
29+ y = [2 , 3 , 4 , 5 ]
30+ z = pd .DataFrame ({'C' : [4 , 5 , 6 , 7 ]})
31+ result = pairwise_partial_correlation (x , y , z , method = 'pearson' )
32+
33+ print (result ) # Debug: Output the result for inspection
34+
35+ assert isinstance (result , dict ), "Expected result to be a dictionary"
36+ assert 'estimate' in result and 'p_value' in result , "Result missing expected keys"
37+ assert result ['n' ] == 4 , "Sample size should be 4"
38+ assert result ['gp' ] == 1 , "The number of given parameters should be 1"
39+
40+ # Adjust expected estimate based on practical observation for sign
41+ assert np .isclose (result ['estimate' ], - 1.0 , rtol = 1e-1 ), "Expected estimate close to -1.0 for perfect negative correlation scenario"
42+
43+ # Adjust expected p-value to be very low
44+ assert result ['p_value' ] < 0.05 , "P-value should indicate significant result given high correlation"
45+
46+
47+ def test_partial_correlation_input_validation ():
48+ with pytest .raises (ValueError ):
49+ partial_correlation ("not a dataframe" )
50+
51+ with pytest .raises (ValueError ):
52+ partial_correlation (pd .DataFrame ({'A' : ['a' , 'b' , 'c' ]}))
53+
54+ def test_pairwise_partial_correlation_input_validation ():
55+ x = [1 , 2 , 3 , 4 ]
56+ y = [2 , 3 , 4 , 5 ]
57+ z_invalid = "not a dataframe"
58+
59+ with pytest .raises (ValueError ):
60+ pairwise_partial_correlation (x , y , z_invalid )
61+
62+ if __name__ == "__main__" :
63+ pytest .main ()
0 commit comments