Skip to content
This repository has been archived by the owner on Dec 22, 2018. It is now read-only.

Commit

Permalink
Add more tests for Correlation and conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
jonlawlor committed Feb 1, 2015
1 parent d642792 commit 0377773
Showing 1 changed file with 94 additions and 0 deletions.
94 changes: 94 additions & 0 deletions covariancematrix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,35 @@ func TestCorrelationMatrix(t *testing.T) {
1, 1, 1,
}),
},
{
data: mat64.NewDense(5, 2, []float64{
-2, -4,
-1, 2,
0, 0,
1, -2,
2, 4,
}),
weights: nil,
ans: mat64.NewDense(2, 2, []float64{
1, 0.6,
0.6, 1,
}),
}, {
data: mat64.NewDense(3, 2, []float64{
1, 1,
2, 4,
3, 9,
}),
weights: []float64{
1,
1.5,
1,
},
ans: mat64.NewDense(2, 2, []float64{
1, 0.9868703275903379,
0.9868703275903379, 1,
}),
},
} {
// Make a copy of the data to check that it isn't changing.
r := test.data.RawMatrix()
Expand Down Expand Up @@ -161,6 +190,71 @@ func TestCorrelationMatrix(t *testing.T) {
}
}

func TestCorrCov(t *testing.T) {
// test both Cov2Corr and Cov2Corr
for i, test := range []struct {
data *mat64.Dense
weights []float64
}{
{
data: mat64.NewDense(3, 3, []float64{
1, 2, 3,
3, 4, 5,
5, 6, 7,
}),
weights: nil,
},
{
data: mat64.NewDense(5, 2, []float64{
-2, -4,
-1, 2,
0, 0,
1, -2,
2, 4,
}),
weights: nil,
}, {
data: mat64.NewDense(3, 2, []float64{
1, 1,
2, 4,
3, 9,
}),
weights: []float64{
1,
1.5,
1,
},
},
} {
corr := CorrelationMatrix(nil, test.data, test.weights)
cov := CovarianceMatrix(nil, test.data, test.weights)

r, _ := cov.Dims()

// Get the diagonal elements from cov to determine the sigmas.
sigmas := make([]float64, r)
for i := range sigmas {
sigmas[i] = math.Sqrt(cov.At(i, i))
}

covFromCorr := mat64.DenseCopyOf(corr)
Corr2Cov(covFromCorr, sigmas)
corrFromCov := mat64.DenseCopyOf(cov)
Cov2Corr(corrFromCov)

if !corr.EqualsApprox(corrFromCov, 1e-14) {
t.Errorf("%d: Corr2Cov did not match direct Correlation calculation. Want: %v, got: %v. ", i, corr, corrFromCov)
}
if !cov.EqualsApprox(covFromCorr, 1e-14) {
t.Errorf("%d: Cov2Corr did not match direct Covariance calculation. Want: %v, got: %v. ", i, cov, covFromCorr)
}

if !Panics(func() { Corr2Cov(mat64.NewDense(2, 2, nil), []float64{}) }) {
t.Errorf("CorrelationMatrix did not panic with sigma size mismatch")
}
}
}

// benchmarks

func randMat(r, c int) mat64.Matrix {
Expand Down

0 comments on commit 0377773

Please sign in to comment.