示例#1
0
func TestExampleModel(t *testing.T) {
	//badly conditioned Hessian leads to zig-zagging of the steepest descent
	//algorithm
	condNo := 100.0
	optSol := mat.Vec{1, 2}

	A := mat.NewFromArray([]float64{condNo, 0, 0, 1}, true, 2, 2)
	b := mat.Vec{-2 * optSol[0] * condNo, -2 * optSol[1]}
	c := -0.5 * mat.Dot(b, optSol)

	//define objective function
	fun := opt.NewQuadratic(A, b, c)

	//set inital solution estimate
	sol := NewSolution(mat.NewVec(2))

	//set termination parameters
	p := NewParams()
	p.IterMax = 5

	//Use steepest descent solver to solve the model
	result := NewSteepestDescent().Solve(fun, sol, p, NewDisplay(1))

	fmt.Println("x =", result.X)
	//should be [1,2], but because of the bad conditioning we made little
	//progress in the second dimension

	//Use a BFGS solver to refine the result:
	result = NewLBFGS().Solve(fun, result.Solution, p, NewDisplay(1))

	fmt.Println("x =", result.X)
}
示例#2
0
func TestLinprog2(t *testing.T) {
	m := 1
	n := 5
	tol := 1e-8

	a := mat.NewVec(n).AddSc(1)
	xStar := mat.NewVec(n)
	xStar[0] = 1

	A := mat.NewFromArray(a, true, m, n)
	At := A.TrView()
	b := mat.NewVec(m).AddSc(1)
	c := mat.NewVec(n)
	c[0] = -1

	prob := NewStandard(c, A, b)

	result := Solve(prob, nil)

	rd := mat.NewVec(n)
	rp := mat.NewVec(m)
	rs := mat.NewVec(n)

	rd.Sub(c, result.S)
	rd.AddMul(At, result.Y, -1)
	rp.Apply(A, result.X)
	rp.Sub(b, rp)
	rs.Mul(result.X, result.S)
	rs.Neg(rs)
	dev := (rd.Asum() + rp.Asum() + rs.Asum()) / float64(n)
	if dev > tol {
		t.Fail()
	}

	temp := mat.NewVec(n)
	temp.Sub(result.X, xStar)

	if temp.Nrm2() > tol {
		t.Log(result.X)
		t.Fail()
	}
}