File: sample_test.go

package info (click to toggle)
golang-gonum-v1-gonum 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,792 kB
  • sloc: asm: 6,252; fortran: 5,271; sh: 377; ruby: 211; makefile: 98
file content (297 lines) | stat: -rw-r--r-- 7,302 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright ©2016 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package samplemv

import (
	"fmt"
	"math"
	"testing"

	"golang.org/x/exp/rand"

	"gonum.org/v1/gonum/floats"
	"gonum.org/v1/gonum/mat"
	"gonum.org/v1/gonum/spatial/r1"
	"gonum.org/v1/gonum/stat"
	"gonum.org/v1/gonum/stat/distmv"
)

type lhDist interface {
	Quantile(x, p []float64) []float64
	CDF(p, x []float64) []float64
	Dim() int
}

func TestLatinHypercube(t *testing.T) {
	src := rand.New(rand.NewSource(1))
	for _, nSamples := range []int{1, 2, 5, 10, 20} {
		for _, dist := range []lhDist{
			distmv.NewUniform([]r1.Interval{{Min: 0, Max: 3}}, src),
			distmv.NewUniform([]r1.Interval{{Min: 0, Max: 3}, {Min: -1, Max: 5}, {Min: -4, Max: -1}}, src),
		} {
			dim := dist.Dim()
			batch := mat.NewDense(nSamples, dim, nil)
			LatinHypercube{Src: src, Q: dist}.Sample(batch)
			// Latin hypercube should have one entry per hyperrow.
			present := make([][]bool, nSamples)
			for i := range present {
				present[i] = make([]bool, dim)
			}
			cdf := make([]float64, dim)
			for i := 0; i < nSamples; i++ {
				dist.CDF(cdf, batch.RawRowView(i))
				for j := 0; j < dim; j++ {
					p := cdf[j]
					quadrant := int(math.Floor(p * float64(nSamples)))
					present[quadrant][j] = true
				}
			}
			allPresent := true
			for i := 0; i < nSamples; i++ {
				for j := 0; j < dim; j++ {
					if !present[i][j] {
						allPresent = false
					}
				}
			}
			if !allPresent {
				t.Errorf("All quadrants not present")
			}
		}
	}
}

func TestImportance(t *testing.T) {
	src := rand.New(rand.NewSource(1))
	// Test by finding the expected value of a multi-variate normal.
	dim := 3
	target, ok := randomNormal(dim, src)
	if !ok {
		t.Fatal("bad test, sigma not pos def")
	}

	muImp := make([]float64, dim)
	sigmaImp := mat.NewSymDense(dim, nil)
	for i := 0; i < dim; i++ {
		sigmaImp.SetSym(i, i, 3)
	}
	proposal, ok := distmv.NewNormal(muImp, sigmaImp, src)
	if !ok {
		t.Fatal("bad test, sigma not pos def")
	}

	nSamples := 200000
	batch := mat.NewDense(nSamples, dim, nil)
	weights := make([]float64, nSamples)
	Importance{Target: target, Proposal: proposal}.SampleWeighted(batch, weights)

	compareNormal(t, target, batch, weights, 5e-2, 5e-2)
}

func TestRejection(t *testing.T) {
	src := rand.New(rand.NewSource(1))
	// Test by finding the expected value of a uniform.
	dim := 3
	bounds := make([]r1.Interval, dim)
	for i := 0; i < dim; i++ {
		min := src.NormFloat64()
		max := src.NormFloat64()
		if min > max {
			min, max = max, min
		}
		bounds[i].Min = min
		bounds[i].Max = max
	}
	target := distmv.NewUniform(bounds, src)
	mu := target.Mean(nil)

	muImp := make([]float64, dim)
	sigmaImp := mat.NewSymDense(dim, nil)
	for i := 0; i < dim; i++ {
		sigmaImp.SetSym(i, i, 6)
	}
	proposal, ok := distmv.NewNormal(muImp, sigmaImp, src)
	if !ok {
		t.Fatal("bad test, sigma not pos def")
	}

	nSamples := 1000
	batch := mat.NewDense(nSamples, dim, nil)
	weights := make([]float64, nSamples)
	rej := Rejection{Target: target, Proposal: proposal, C: 1000, Src: src}
	rej.Sample(batch)
	err := rej.Err()
	if err != nil {
		t.Error("Bad test, nan samples")
	}

	for i := 0; i < dim; i++ {
		col := mat.Col(nil, i, batch)
		ev := stat.Mean(col, weights)
		if math.Abs(ev-mu[i]) > 1e-2 {
			t.Errorf("Mean mismatch: Want %v, got %v", mu[i], ev)
		}
	}
}

func TestMetropolisHastings(t *testing.T) {
	src := rand.New(rand.NewSource(1))
	// Test by finding the expected value of a normal distribution.
	dim := 3
	target, ok := randomNormal(dim, src)
	if !ok {
		t.Fatal("bad test, sigma not pos def")
	}

	sigmaImp := mat.NewSymDense(dim, nil)
	for i := 0; i < dim; i++ {
		sigmaImp.SetSym(i, i, 0.25)
	}
	proposal, ok := NewProposalNormal(sigmaImp, src)
	if !ok {
		t.Fatal("bad test, sigma not pos def")
	}

	nSamples := 100000
	burnin := 5000
	batch := mat.NewDense(nSamples, dim, nil)
	initial := make([]float64, dim)
	metropolisHastings(batch, initial, target, proposal, src)
	batch = batch.Slice(burnin, nSamples, 0, dim).(*mat.Dense)

	compareNormal(t, target, batch, nil, 5e-1, 5e-1)
}

// randomNormal constructs a random Normal distribution using the provided
// random source.
func randomNormal(dim int, src *rand.Rand) (*distmv.Normal, bool) {
	data := make([]float64, dim*dim)
	for i := range data {
		data[i] = src.Float64()
	}
	a := mat.NewDense(dim, dim, data)
	var sigma mat.SymDense
	sigma.SymOuterK(1, a)
	mu := make([]float64, dim)
	for i := range mu {
		mu[i] = rand.NormFloat64()
	}
	return distmv.NewNormal(mu, &sigma, src)
}

func compareNormal(t *testing.T, want *distmv.Normal, batch *mat.Dense, weights []float64, meanTol, covTol float64) {
	t.Helper()

	dim := want.Dim()
	mu := want.Mean(nil)
	var sigma mat.SymDense
	want.CovarianceMatrix(&sigma)
	n, _ := batch.Dims()
	if weights == nil {
		weights = make([]float64, n)
		for i := range weights {
			weights[i] = 1
		}
	}
	for i := 0; i < dim; i++ {
		col := mat.Col(nil, i, batch)
		ev := stat.Mean(col, weights)
		if math.Abs(ev-mu[i]) > meanTol {
			t.Errorf("Mean mismatch: Want %v, got %v", mu[i], ev)
		}
	}

	var cov mat.SymDense
	stat.CovarianceMatrix(&cov, batch, weights)
	if !mat.EqualApprox(&cov, &sigma, covTol) {
		t.Errorf("Covariance matrix mismatch")
	}
}

func TestMetropolisHastingser(t *testing.T) {
	for _, test := range []struct {
		dim, burnin, rate, samples int
	}{
		{3, 10, 1, 1},
		{3, 10, 2, 1},
		{3, 10, 1, 2},
		{3, 10, 3, 2},
		{3, 10, 7, 4},
		{3, 10, 7, 4},

		{3, 11, 51, 103},
		{3, 11, 103, 51},
		{3, 51, 11, 103},
		{3, 51, 103, 11},
		{3, 103, 11, 51},
		{3, 103, 51, 11},
	} {
		src := rand.New(rand.NewSource(1))
		dim := test.dim

		initial := make([]float64, dim)
		target, ok := randomNormal(dim, src)
		if !ok {
			t.Fatal("bad test, sigma not pos def")
		}

		sigmaImp := mat.NewSymDense(dim, nil)
		for i := 0; i < dim; i++ {
			sigmaImp.SetSym(i, i, 0.25)
		}

		// Test the Metropolis Hastingser by generating all the samples, then generating
		// the same samples with a burnin and rate.
		src = rand.New(rand.NewSource(1))
		proposal, ok := NewProposalNormal(sigmaImp, src)
		if !ok {
			t.Fatal("bad test, sigma not pos def")
		}

		mh := MetropolisHastingser{
			Initial:  initial,
			Target:   target,
			Proposal: proposal,
			Src:      src,
			BurnIn:   0,
			Rate:     0,
		}
		samples := test.samples
		burnin := test.burnin
		rate := test.rate
		fullBatch := mat.NewDense(1+burnin+rate*(samples-1), dim, nil)
		mh.Sample(fullBatch)

		src = rand.New(rand.NewSource(1))
		proposal, _ = NewProposalNormal(sigmaImp, src)
		mh = MetropolisHastingser{
			Initial:  initial,
			Target:   target,
			Proposal: proposal,
			Src:      src,
			BurnIn:   burnin,
			Rate:     rate,
		}
		batch := mat.NewDense(samples, dim, nil)
		mh.Sample(batch)

		same := true
		count := burnin
		for i := 0; i < samples; i++ {
			if !floats.Equal(batch.RawRowView(i), fullBatch.RawRowView(count)) {
				fmt.Println("sample ", i, "is different")
				same = false
				break
			}
			count += rate
		}

		if !same {
			fmt.Printf("%v\n", mat.Formatted(batch))
			fmt.Printf("%v\n", mat.Formatted(fullBatch))

			t.Errorf("sampling mismatch: dim = %v, burnin = %v, rate = %v, samples = %v", dim, burnin, rate, samples)
		}
	}
}