Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ One short program per module is in [examples/](examples/); a test runs them all.
or the Go string value, `method: "L-BFGS-B"`), a bound `[lo, hi]` with `nil`
for a missing side, a struct a Hash. An unknown keyword is an ArgumentError
that names the known ones.
- **Constraints** (`method: :slsqp`) are SciPy's dictionaries, a Hash per block
of `optimize.Constraint`: `Optimize.minimize(x0, method: :slsqp, constraints:
[{kind: :eq, fun: ->(x) { x[0] + x[1] - 1 }}]) { |x| ... }`. `kind:` (SciPy's
`type:`) is `:eq` (`fun(x) = 0`) or `:ineq` (`fun(x) >= 0`); `fun:` is a Proc
returning a number or an Array of `m:` values (`m:` defaults to 1: SciPy finds
it by calling `fun`, the Go side must be told); `jac:` is an optional Proc
returning the `m`×`n` Jacobian as an Array of rows, a flat row-major Array or
an NDArray (finite differences when absent). `res.multipliers` holds the
Lagrange multipliers, equalities first. A bad `kind:`, a missing `fun:` or
`kind:`, or a `fun:` returning the wrong count is an ArgumentError or
TypeError, never a panic.
- **Data** is an Array of numbers or an NDArray (an NDArray goes to the Go
function as it is: `stats.Data` is `[]float64 | *ndarray.Array`). Elementwise
methods (`pdf`, `cdf`, `ppf`, … and every real function of Special) take a
Expand Down
199 changes: 199 additions & 0 deletions constraints.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package ruby

import (
"reflect"

rb "github.com/go-embedded-ruby/ruby"
"github.com/go-numerics/optimize"
)

// This file binds optimize.Options.Constraints, the constraints of the
// :slsqp method. optimize.ConstraintSpec is a sealed interface (constraints.go:15
// of go-numerics/optimize v0.3.1) whose block form, optimize.Constraint
// (constraints.go:31), is SciPy's dictionary {'type': 'eq'|'ineq', 'fun': ...,
// 'jac': ...}; the Ruby shape follows it:
//
// constraints: [
// {kind: :eq, fun: ->(x) { x[0] + x[1] - 1 }},
// {kind: :ineq, fun: ->(x) { [x[0] - 0.2, 0.8 - x[0]] }, m: 2,
// jac: ->(x) { [[1, 0], [-1, 0]] }},
// ]
//
// type: is accepted for kind:, as SciPy spells it. fun: returns a number, an
// Array or an NDArray of m values; m: (default 1) is the number of values it
// returns, which SciPy finds by calling fun, and which the Go side must be
// told. jac: is optional (forward differences when absent) and returns the
// m×n Jacobian as an Array of rows, or an NDArray, or a flat Array, row-major.
func init() {
converters[reflect.TypeFor[optimize.ConstraintSpec]()] = func(v any) (reflect.Value, error) {
c, err := toConstraint(v)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(c), nil
}
}

// maxConstraintM bounds m: alone; the memory is m×n per constraint, bounded
// once n is known by checkConstraintCells (maxConstraintCells).
const maxConstraintM = 1 << 20

// constraintKeys are the keys of a constraint Hash, for the error that names
// them.
const constraintKeys = "kind (or type), fun, m, jac"

// toConstraint reads one constraint Hash into an optimize.Constraint.
func toConstraint(v any) (optimize.ConstraintSpec, error) {
h, ok := v.(map[any]any)
if !ok {
return nil, typeError(v, "a constraint Hash {kind: :eq, fun: ->(x) { ... }}")
}
var c optimize.Constraint
var funV, jacV rb.Value
var haveKind, haveFun, haveJac bool
c.M = 1
for k, e := range h {
name, err := toString(k)
if err != nil {
return nil, err
}
switch normalize(name) {
case "kind", "type":
if haveKind {
return nil, argError("a constraint takes kind: or type:, not both (they are the same key)")
}
kind, err := convert(e, reflect.TypeFor[optimize.ConstraintKind]())
if err != nil {
return nil, err
}
c.Kind, haveKind = kind.Interface().(optimize.ConstraintKind), true
case "fun":
if funV, haveFun = e.(rb.Value); !haveFun {
return nil, typeError(e, "a Proc")
}
case "jac":
if e == nil {
continue
}
if jacV, haveJac = e.(rb.Value); !haveJac {
return nil, typeError(e, "a Proc")
}
case "m":
m, err := toInt(e)
if err != nil {
return nil, err
}
if m < 1 || m > maxConstraintM {
return nil, argError("constraint m: must be between 1 and %d, got %d", maxConstraintM, m)
}
c.M = int(m)
default:
return nil, argError("unknown key %s for a constraint (known: %s)", name, constraintKeys)
}
}
if !haveKind {
return nil, argError("a constraint needs kind: :eq or :ineq (known keys: %s)", constraintKeys)
}
if !haveFun {
return nil, argError("a constraint needs fun: a Proc of x (known keys: %s)", constraintKeys)
}
call, err := procCaller(funV)
if err != nil {
return nil, err
}
c.Func = constraintCallback(call, "fun")
if haveJac {
jcall, err := procCaller(jacV)
if err != nil {
return nil, err
}
c.Jac = constraintCallback(jcall, "jac")
}
return c, nil
}

// constraintCallback calls a Ruby constraint function or Jacobian with x as an
// NDArray and writes the len(out) values it returns into out: m values for
// fun, m×n for jac. Unlike the other callbacks it accepts a bare number (m is
// 1) and nested Arrays (the rows of a Jacobian); an error, or a wrong count,
// aborts the minimization (see abortOn).
func constraintCallback(call caller, what string) func(x, out []float64) {
return func(x, out []float64) {
r, err := call(vec(x))
abortOn(err)
rowLen := 0
if what == "jac" {
rowLen = len(x)
}
vals, err := flatFloats(r.Go(), rowLen)
abortOn(err)
if len(vals) != len(out) {
abortOn(argError("the constraint %s: returned %d values, expected %d", what, len(vals), len(out)))
}
copy(out, vals)
}
}

// flatFloats reads a number, an Array of numbers or of Arrays (row-major) or
// an NDArray into one vector.
//
// The nesting is bounded by construction, not by a depth counter: a number, a
// row, or an Array of rows, so a self-containing Array is a TypeError, never
// a stack overflow. When rowLen > 0 every row of an Array of rows must have
// exactly rowLen values (a Jacobian row has n).
func flatFloats(v any, rowLen int) ([]float64, error) {
list, ok := v.([]any)
if !ok {
if f, err := toFloat(v); err == nil {
return []float64{f}, nil
}
return toFloats(v)
}
var out []float64
var scalars, rows bool // an Array is all numbers or all rows, never both
for _, e := range list {
if f, err := toFloat(e); err == nil {
scalars = true
out = append(out, f)
} else {
rows = true
row, err := toFloats(e)
if err != nil {
return nil, err
}
out = append(out, row...)
if rowLen > 0 && len(row) != rowLen {
return nil, argError("the constraint jac: has a row of %d values, expected %d", len(row), rowLen)
}
}
if scalars && rows {
return nil, argError("a constraint returned an Array mixing numbers and rows: give all numbers or all rows")
}
}
return out, nil
}

// maxConstraintCells bounds the Go-side Jacobian buffers of a minimization:
// the optimizer allocates a row-major m×n block per constraint (and one of
// the largest m by n), so the sum of m×n over the constraints is what costs
// memory. The optimizer holds two such buffers (the Jacobian block and its
// copy), so 2^25 float64s, 256 MiB each, is about 520 MiB in all.
const maxConstraintCells = 1 << 25

// checkConstraintCells refuses constraints whose Jacobians would need more
// than maxConstraintCells values for n variables. Each product is checked by
// division before it is formed, so nothing overflows, 32-bit builds included.
func checkConstraintCells(specs []optimize.ConstraintSpec, n int) error {
total := 0
for _, s := range specs {
m := s.(optimize.Constraint).M // toConstraint builds only Constraints
if n > 0 && m > maxConstraintCells/n {
return argError("constraint m: %d with %d variables is over the %d-value limit on a Jacobian", m, n, maxConstraintCells)
}
total += m * n // m*n <= 2^26, and total stays <= 2^26 after the check below
if total > maxConstraintCells {
return argError("the constraints need %d Jacobian values for %d variables, over the %d-value limit", total, n, maxConstraintCells)
}
}
return nil
}
165 changes: 165 additions & 0 deletions constraints_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package ruby

import (
"math"
"testing"

nd "github.com/go-ndarray/ndarray"
"github.com/go-numerics/optimize"
)

func near(t *testing.T, what string, got any, want ...float64) {
t.Helper()
a, ok := got.(*nd.Array)
if !ok {
t.Fatalf("%s: %#v, not an NDArray", what, got)
}
g := arrayFloats(a)
if len(g) != len(want) {
t.Fatalf("%s = %v, want %v", what, g, want)
}
for i := range want {
if math.Abs(g[i]-want[i]) > 1e-6 {
t.Errorf("%s = %v, want %v", what, g, want)
}
}
}

// min x²+y² s.t. x+y = 1 is (1/2, 1/2); the multiplier is |∇f|/|∇c| = 1 (the
// gradient of the objective, (1, 1), is the multiplier times (1, 1)).
func TestSLSQPEqualityConstraint(t *testing.T) {
in := newInterp(t)
src := `Optimize.minimize([2.0, -1.0], method: :slsqp,
constraints: [{kind: :eq, fun: ->(x) { x[0] + x[1] - 1 }}]) { |x| x[0]**2 + x[1]**2 }`
near(t, "x", eval(t, in, "("+src+").x"), 0.5, 0.5)
m := eval(t, in, "("+src+").multipliers").(*nd.Array)
if got := arrayFloats(m); len(got) != 1 || math.Abs(math.Abs(got[0])-1) > 1e-6 {
t.Errorf("multipliers = %v, want ±1", got)
}
// SciPy's spelling, type:, a Jacobian as an Array of rows, and the same
// result as the Go API with the same problem.
want := must[*optimize.Result](t)(optimize.Minimize(
optimize.Problem{Func: func(x []float64) float64 { return x[0]*x[0] + x[1]*x[1] }},
[]float64{2, -1}, optimize.SLSQP, &optimize.Options{Constraints: []optimize.ConstraintSpec{
optimize.Constraint{Kind: optimize.Eq, M: 1, Func: func(x, c []float64) { c[0] = x[0] + x[1] - 1 }},
}}))
check(t, in, `Optimize.minimize([2.0, -1.0], method: :slsqp,
constraints: [{type: 'eq', fun: ->(x) { x[0] + x[1] - 1 }}]) { |x| x[0]**2 + x[1]**2 }.multipliers`, vec(want.Multipliers))
near(t, "x with jac", eval(t, in, `Optimize.minimize([2.0, -1.0], method: :slsqp,
constraints: [{type: :eq, fun: ->(x) { [x[0] + x[1] - 1] }, jac: ->(x) { [[1, 1]] }}]) { |x| x[0]**2 + x[1]**2 }.x`), 0.5, 0.5)
}

// min x²+y² s.t. x >= 1 is (1, 0), with multiplier 2: ∇f = (2, 0) = 2·∇c.
// The block form: two inequalities from one function, m: 2, with a flat
// row-major Jacobian and an NDArray result.
func TestSLSQPInequalityConstraints(t *testing.T) {
in := newInterp(t)
near(t, "x", eval(t, in, `Optimize.minimize([3.0, 3.0], method: :slsqp,
constraints: [{kind: :ineq, fun: ->(x) { x[0] - 1 }}]) { |x| x[0]**2 + x[1]**2 }.x`), 1, 0)
near(t, "multipliers", eval(t, in, `Optimize.minimize([3.0, 3.0], method: :slsqp,
constraints: [{kind: :ineq, fun: ->(x) { x[0] - 1 }}]) { |x| x[0]**2 + x[1]**2 }.multipliers`), 2)
// 1 <= x <= 2 and y free: the lower bound is active.
res := `Optimize.minimize([1.5, 3.0], method: :slsqp, constraints: [
{kind: :ineq, m: 2, fun: ->(x) { [x[0] - 1, 2 - x[0]] }, jac: ->(x) { [1, 0, -1, 0] }}
]) { |x| x[0]**2 + x[1]**2 }`
near(t, "x", eval(t, in, "("+res+").x"), 1, 0)
near(t, "multipliers", eval(t, in, "("+res+").multipliers"), 2, 0)
}

// Equality and inequality constraints together, and constraints with bounds.
func TestSLSQPMixedConstraints(t *testing.T) {
in := newInterp(t)
// x + y = 1, x >= 0.8: the inequality is active at (0.8, 0.2).
near(t, "x", eval(t, in, `Optimize.minimize([0.9, 0.1], method: :slsqp, constraints: [
{kind: :eq, fun: ->(x) { x[0] + x[1] - 1 }},
{kind: :ineq, fun: ->(x) { x[0] - 0.8 }},
]) { |x| x[0]**2 + x[1]**2 }.x`), 0.8, 0.2)
near(t, "x with bounds", eval(t, in, `Optimize.minimize([0.9, 0.1], method: :slsqp, bounds: [[0, 1], [0, 1]],
constraints: [{kind: :eq, fun: ->(x) { x[0] + x[1] - 1 }}]) { |x| x[0]**2 + x[1]**2 }.x`), 0.5, 0.5)
}

func TestConstraintErrors(t *testing.T) {
in := newInterp(t)
const obj = ") { |x| x[0]**2 }"
cons := func(c string) string {
return "Optimize.minimize([1.0], method: :slsqp, constraints: [" + c + "]" + obj
}
for _, c := range []struct{ src, class, msg string }{
{cons(`{kind: :weird, fun: ->(x) { x[0] }}`), "ArgumentError", `unknown constraint_kind "weird"`},
{cons(`{kind: 3, fun: ->(x) { x[0] }}`), "TypeError", "Symbol"},
{cons(`{kind: :eq}`), "ArgumentError", "needs fun:"},
{cons(`{fun: ->(x) { x[0] }}`), "ArgumentError", "needs kind:"},
{cons(`{}`), "ArgumentError", "needs kind:"},
{cons(`{kind: :eq, fun: 3}`), "TypeError", "Proc"},
{cons(`{kind: :eq, fun: Object.new}`), "TypeError", "Proc"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, jac: 3}`), "TypeError", "Proc"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, jac: Object.new}`), "TypeError", "Proc"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, m: 0}`), "ArgumentError", "must be between 1 and"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, m: 4611686018427387904}`), "ArgumentError", "must be between 1 and"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, m: 1.5}`), "TypeError", "Integer"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, bogus: 1}`), "ArgumentError", "unknown key bogus"},
{cons(`{1 => 2}`), "TypeError", "String"},
{cons(`3`), "TypeError", "constraint Hash"},
{cons(`{kind: :eq, fun: ->(x) { [x[0], 1] }}`), "ArgumentError", "returned 2 values, expected 1"},
{cons(`{kind: :eq, fun: ->(x) { "a" }}`), "TypeError", "Array of Floats"},
{cons(`{kind: :eq, fun: ->(x) { [["a"]] }}`), "TypeError", "Float"},
{cons(`{kind: :eq, fun: ->(x) { raise "boom" }}`), "RuntimeError", "boom"},
{cons(`{kind: :eq, fun: ->(x) { x[0] }, jac: ->(x) { [1, 2] }}`), "ArgumentError", "jac: returned 2 values, expected 1"},
{"Optimize.minimize([1.0], method: :slsqp, constraints: 3" + obj, "TypeError", "Array"},
// kind: and type: are one key: giving both is refused whatever the
// Hash's iteration order.
{cons(`{kind: :eq, type: :ineq, fun: ->(x) { x[0] }}`), "ArgumentError", "not both"},
{cons(`{type: :eq, kind: :eq, fun: ->(x) { x[0] }}`), "ArgumentError", "not both"},
// A jagged Jacobian is refused row by row.
{cons(`{kind: :ineq, m: 2, fun: ->(x) { [x[0], x[0]] }, jac: ->(x) { [[1], [1, 2]] }}`), "ArgumentError", "row of 2 values, expected 1"},
{cons(`{kind: :ineq, m: 2, fun: ->(x) { [x[0], x[0]] }, jac: ->(x) { [[1], []] }}`), "ArgumentError", "row of 0 values, expected 1"},
// An Array is all numbers or all rows.
{cons(`{kind: :ineq, m: 3, fun: ->(x) { [x[0], x[0], x[0]] }, jac: ->(x) { [1, [0], 1] }}`), "ArgumentError", "mixing numbers and rows"},
{cons(`{kind: :ineq, m: 3, fun: ->(x) { [x[0], [x[0]], x[0]] }}`), "ArgumentError", "mixing numbers and rows"},
} {
evalErr(t, in, c.src, c.class, c.msg)
}
}

// A self-containing Array, or one nested deeper than a Jacobian goes, is a
// TypeError: flatFloats has no recursion to overflow the stack with.
func TestConstraintNestingIsRefused(t *testing.T) {
in := newInterp(t)
const cyc = "->(x) { a = []; a << a; a }"
for _, src := range []string{
"Optimize.minimize([1.0], method: :slsqp, constraints: [{kind: :eq, fun: " + cyc + "}]) { |x| x[0]**2 }",
"Optimize.minimize([1.0], method: :slsqp, constraints: [{kind: :eq, fun: ->(x) { x[0] }, jac: " + cyc + "}]) { |x| x[0]**2 }",
"Optimize.minimize([1.0], method: :slsqp, constraints: [{kind: :eq, fun: ->(x) { [[[1.0]]] }}]) { |x| x[0]**2 }",
} {
evalErr(t, in, src, "TypeError", "Float")
}
}

// The memory a constraint set may ask for is bounded by the sum of m×n, not by
// m alone. Every case is refused before anything is allocated, so none needs
// the memory it names.
func TestConstraintMemoryIsBounded(t *testing.T) {
in := newInterp(t)
big := `{kind: :ineq, fun: ->(x) { x[0] }, m: 1048576}`
for _, c := range []struct{ src, msg string }{
// One constraint alone over the limit: n = 4096, m = 2^20 (2^32 values).
{"Optimize.minimize(Array.new(4096, 1.0), method: :slsqp, constraints: [" + big + "]) { |x| x[0]**2 }", "over the 33554432-value limit on a Jacobian"},
// Each under the limit, the sum over: 8 × (2^20 × 16) = 2^27 values.
{"Optimize.minimize(Array.new(16, 1.0), method: :slsqp, constraints: Array.new(8) { " + big + " }) { |x| x[0]**2 }", "Jacobian values for 16 variables, over the 33554432-value limit"},
} {
evalErr(t, in, c.src, "ArgumentError", c.msg)
}
}

func TestCheckConstraintCells(t *testing.T) {
c := func(m int) optimize.ConstraintSpec { return optimize.Constraint{M: m} }
if err := checkConstraintCells([]optimize.ConstraintSpec{c(1 << 20), c(1 << 20)}, 16); err != nil {
t.Errorf("exactly 2^25 values refused: %v", err)
}
if err := checkConstraintCells([]optimize.ConstraintSpec{c(1 << 20), c(1<<20 + 1)}, 16); err == nil {
t.Error("2^25 + 16 values accepted")
}
if err := checkConstraintCells([]optimize.ConstraintSpec{c(3)}, 0); err != nil {
t.Errorf("no variables: %v", err)
}
}
Loading
Loading