File: hessian_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 (112 lines) | stat: -rw-r--r-- 2,309 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
// Copyright ©2017 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 fd

import (
	"testing"

	"gonum.org/v1/gonum/mat"
)

type HessianTester interface {
	Func(x []float64) float64
	Grad(grad, x []float64)
	Hess(dst mat.MutableSymmetric, x []float64)
}

type hessianTestCase struct {
	h        HessianTester
	x        []float64
	settings *Settings
	tol      float64
}

var _hessianTestCases = []hessianTestCase{
	{
		h:   Watson{},
		x:   []float64{0.2, 0.3, 0.1, 0.4},
		tol: 1e-3,
	},
	{
		h:   Watson{},
		x:   []float64{2, 3, 1, 4},
		tol: 1e-3,
		settings: &Settings{
			Step:    1e-5,
			Formula: Central,
		},
	},
	{
		h:   Watson{},
		x:   []float64{2, 3, 1},
		tol: 1e-3,
		settings: &Settings{
			OriginKnown: true,
			OriginValue: 7606.529501201192,
		},
	},
	{
		h:   ConstFunc(5),
		x:   []float64{1, 9},
		tol: 1e-16,
	},
	{
		h:   LinearFunc{w: []float64{10, 6, -1}, c: 5},
		x:   []float64{3, 1, 8},
		tol: 1e-6,
	},
	{
		h: QuadFunc{
			a: mat.NewSymDense(3, []float64{
				10, 2, 1,
				2, 5, -3,
				1, -3, 6,
			}),
			b: mat.NewVecDense(3, []float64{3, -2, -1}),
			c: 5,
		},
		x:   []float64{-1.6, -3, 2},
		tol: 1e-6,
	},
}

func hessianTestCases() []hessianTestCase {
	xs := []hessianTestCase{}
	for _, test := range _hessianTestCases {
		n := test
		if test.settings != nil {
			clone := *test.settings
			n.settings = &clone
		}
		xs = append(xs, n)
	}
	return xs
}

func TestHessian(t *testing.T) {
	t.Parallel()
	for cas, test := range hessianTestCases() {
		n := len(test.x)
		var got mat.SymDense
		Hessian(&got, test.h.Func, test.x, test.settings)
		want := mat.NewSymDense(n, nil)
		test.h.Hess(want, test.x)
		if !mat.EqualApprox(&got, want, test.tol) {
			t.Errorf("Cas %d: Hessian mismatch\ngot=\n%0.4v\nwant=\n%0.4v\n", cas, mat.Formatted(&got), mat.Formatted(want))
		}

		// Test that concurrency works.
		settings := test.settings
		if settings == nil {
			settings = &Settings{}
		}
		settings.Concurrent = true
		var got2 mat.SymDense
		Hessian(&got2, test.h.Func, test.x, settings)
		if !mat.EqualApprox(&got, &got2, 1e-5) {
			t.Errorf("Cas %d: Hessian mismatch concurrent\ngot=\n%0.6v\nwant=\n%0.6v\n", cas, mat.Formatted(&got2), mat.Formatted(&got))
		}
	}
}