From 6850456e520d4a19ead43a3c4a8cc7a746e6de12 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 16:32:41 +0100 Subject: [PATCH 1/3] feat: SLSQP constraints from Ruby; generator filters kernels by signature Optimize.minimize(method: :slsqp, constraints: [{kind: :eq, fun: ...}]) raised "no implicit conversion of Hash into optimize.ConstraintSpec": conv.go had no converter for the interface. Add one, mapping a Hash {kind:/type:, fun:, m:, jac:} to optimize.Constraint (go-numerics/optimize v0.3.1 constraints.go:31), so Result#multipliers and the generated ConstraintKind enum are reachable. m: is bounded (resource limit, 32-bit). internal/gen skipped special's in-place kernels by the "To" name suffix; it now tests the signature (no result, first parameter []float64), so a scalar named FooTo is still bound. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 11 +++ constraints.go | 149 ++++++++++++++++++++++++++++++++++++++ constraints_test.go | 112 ++++++++++++++++++++++++++++ internal/gen/main.go | 30 ++++++-- internal/gen/main_test.go | 44 +++++++++++ 5 files changed, 338 insertions(+), 8 deletions(-) create mode 100644 constraints.go create mode 100644 constraints_test.go diff --git a/README.md b/README.md index baa25fb..0db4bb3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/constraints.go b/constraints.go new file mode 100644 index 0000000..3c14cb2 --- /dev/null +++ b/constraints.go @@ -0,0 +1,149 @@ +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:, which sizes Go-side buffers (m×n for a Jacobian): +// a Ruby script must not be able to ask for terabytes, nor overflow an int on +// a 32-bit build. +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": + 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) + vals, err := flatFloats(r.Go()) + 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. +func flatFloats(v any) ([]float64, error) { + if list, ok := v.([]any); ok { + var out []float64 + for _, e := range list { + f, err := flatFloats(e) + if err != nil { + return nil, err + } + out = append(out, f...) + } + return out, nil + } + if f, err := toFloat(v); err == nil { + return []float64{f}, nil + } + return toFloats(v) +} diff --git a/constraints_test.go b/constraints_test.go new file mode 100644 index 0000000..8f9f192 --- /dev/null +++ b/constraints_test.go @@ -0,0 +1,112 @@ +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"}, + } { + evalErr(t, in, c.src, c.class, c.msg) + } +} diff --git a/internal/gen/main.go b/internal/gen/main.go index a714fb2..4e8c395 100644 --- a/internal/gen/main.go +++ b/internal/gen/main.go @@ -80,19 +80,33 @@ func generateSpecial(mod func(string) (string, error)) ([]byte, error) { b.WriteString("// Code generated by internal/gen; DO NOT EDIT.\n\npackage ruby\n\nimport \"github.com/go-numerics/special\"\n\n") b.WriteString("// specialFuncs are the exported functions of go-numerics/special.\nvar specialFuncs = []namedFunc{\n") for _, n := range names { - // special v0.2.0 added in-place slice kernels (ErfTo(dst, x []float64)); - // the Special module binds scalar functions, so they are not listed. - if strings.HasSuffix(n, "To") { - continue - } fmt.Fprintf(&b, "\t{%q, special.%s},\n", n, n) } b.WriteString("}\n") return format.Source(b.Bytes()) } -// funcs lists the exported, non-generic top-level functions of the package in -// dir, sorted. +// isKernel reports whether a signature is an in-place slice kernel, such as +// special v0.2.0's ErfTo(dst, x []float64): no result, first parameter a +// []float64 destination. The Special module binds scalar functions, so those +// are not listed; the signature decides, never the name. +func isKernel(t *ast.FuncType) bool { + if t.Results != nil && len(t.Results.List) > 0 { + return false + } + if t.Params == nil || len(t.Params.List) == 0 { + return false + } + a, ok := t.Params.List[0].Type.(*ast.ArrayType) + if !ok || a.Len != nil { + return false + } + id, ok := a.Elt.(*ast.Ident) + return ok && id.Name == "float64" +} + +// funcs lists the exported, non-generic, non-kernel top-level functions of the +// package in dir, sorted. func funcs(dir string) ([]string, error) { files, err := goFiles(dir) if err != nil { @@ -106,7 +120,7 @@ func funcs(dir string) ([]string, error) { return nil, err } for _, d := range file.Decls { - if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv == nil && fd.Name.IsExported() && fd.Type.TypeParams == nil { + if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv == nil && fd.Name.IsExported() && fd.Type.TypeParams == nil && !isKernel(fd.Type) { out = append(out, fd.Name.Name) } } diff --git a/internal/gen/main_test.go b/internal/gen/main_test.go index e47def8..58b0fa0 100644 --- a/internal/gen/main_test.go +++ b/internal/gen/main_test.go @@ -103,6 +103,50 @@ func TestFailures(t *testing.T) { } } +// A kernel is told by its signature, not its name: a scalar named FooTo is +// still bound, and an in-place kernel is skipped whatever it is called. +func TestKernelsAreFilteredBySignature(t *testing.T) { + dir := t.TempDir() + src := `package special + +func FooTo(x float64) float64 { return x } +func ErfTo(dst, x []float64) {} +func Plain(dst []float64) {} +func NoArgs() {} +func Fixed(d [4]float64) {} +func Nested(d [][]float64) {} +func Singles(d []float32) {} +func Sum(d []float64) float64 { return 0 } +` + if err := os.WriteFile(filepath.Join(dir, "x.go"), []byte(src), 0o644); err != nil { + t.Fatal(err) + } + got, err := funcs(dir) + if err != nil { + t.Fatal(err) + } + want := []string{"FooTo", "Fixed", "NoArgs", "Nested", "Singles", "Sum"} + have := map[string]bool{} + for _, n := range got { + have[n] = true + } + for _, n := range want { + if !have[n] { + t.Errorf("funcs dropped %s", n) + } + } + if len(got) != len(want) { + t.Errorf("funcs = %v, want only %v", got, want) + } + out, err := generateSpecial(func(string) (string, error) { return dir, nil }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(out), `"FooTo"`) || strings.Contains(string(out), `"ErfTo"`) { + t.Errorf("generated source:\n%s", out) + } +} + func TestWords(t *testing.T) { for in, want := range map[string]string{ "TwoSided": "two_sided", "LBFGSB": "lbfgsb", "RK45": "rk45", "GumbelL": "gumbel_l", "NewtonCG": "newton_cg", "DOP853": "dop853", From 276f688987d1a8b79db34292a32e35a4261b696f Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 19:00:56 +0100 Subject: [PATCH 2/3] slsqp constraints: bound nesting, Jacobian memory, kind/type conflict, jagged jac - flatFloats has no recursion: number | row | Array of rows, so a self-containing Array is a TypeError, not a stack overflow. - minimize refuses constraints whose summed m*n exceeds 2^26 values (division-checked, overflow-safe on 32-bit); false 32-bit comment fixed. - kind: and type: together are an ArgumentError. - each jac row must have n values. Co-Authored-By: Claude Sonnet 5.5 --- constraints.go | 77 +++++++++++++++++++++++++++++++++++---------- constraints_test.go | 50 +++++++++++++++++++++++++++++ optimize.go | 5 +++ 3 files changed, 115 insertions(+), 17 deletions(-) diff --git a/constraints.go b/constraints.go index 3c14cb2..b499825 100644 --- a/constraints.go +++ b/constraints.go @@ -34,9 +34,8 @@ func init() { } } -// maxConstraintM bounds m:, which sizes Go-side buffers (m×n for a Jacobian): -// a Ruby script must not be able to ask for terabytes, nor overflow an int on -// a 32-bit build. +// 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 @@ -60,6 +59,9 @@ func toConstraint(v any) (optimize.ConstraintSpec, error) { } 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 @@ -119,7 +121,11 @@ func constraintCallback(call caller, what string) func(x, out []float64) { return func(x, out []float64) { r, err := call(vec(x)) abortOn(err) - vals, err := flatFloats(r.Go()) + 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))) @@ -130,20 +136,57 @@ func constraintCallback(call caller, what string) func(x, out []float64) { // flatFloats reads a number, an Array of numbers or of Arrays (row-major) or // an NDArray into one vector. -func flatFloats(v any) ([]float64, error) { - if list, ok := v.([]any); ok { - var out []float64 - for _, e := range list { - f, err := flatFloats(e) - if err != nil { - return nil, err - } - out = append(out, f...) +// +// 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 + for _, e := range list { + if f, err := toFloat(e); err == nil { + out = append(out, f) + continue } - return out, nil + row, err := toFloats(e) + if err != nil { + return nil, err + } + if rowLen > 0 && len(row) != rowLen { + return nil, argError("the constraint jac: has a row of %d values, expected %d", len(row), rowLen) + } + out = append(out, row...) } - if f, err := toFloat(v); err == nil { - return []float64{f}, nil + 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. 2^26 float64s is 512 MiB. +const maxConstraintCells = 1 << 26 + +// 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 toFloats(v) + return nil } diff --git a/constraints_test.go b/constraints_test.go index 8f9f192..141f3d5 100644 --- a/constraints_test.go +++ b/constraints_test.go @@ -106,7 +106,57 @@ func TestConstraintErrors(t *testing.T) { {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"}, } { 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 67108864-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 67108864-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), c(1 << 20), c(1 << 20)}, 16); err != nil { + t.Errorf("exactly 2^26 values refused: %v", err) + } + if err := checkConstraintCells([]optimize.ConstraintSpec{c(1 << 20), c(1 << 20), c(1 << 20), c(1<<20 + 1)}, 16); err == nil { + t.Error("2^26 + 16 values accepted") + } + if err := checkConstraintCells([]optimize.ConstraintSpec{c(3)}, 0); err != nil { + t.Errorf("no variables: %v", err) + } +} diff --git a/optimize.go b/optimize.go index ff71689..5b54fcb 100644 --- a/optimize.go +++ b/optimize.go @@ -210,6 +210,11 @@ func minimize(c *rb.Call) (any, error) { if err != nil { return nil, err } + if o != nil { // no options at all is a nil *Options + if err := checkConstraintCells(o.Constraints, len(x0)); err != nil { + return nil, err + } + } res, err := optimize.Minimize(p, x0, method, o) return finish(g, res, err) } From 8415151eac8c6bfe8c0b66ddb425df04afe6c671 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 19:17:13 +0100 Subject: [PATCH 3/3] slsqp constraints: halve the Jacobian cap, refuse mixed numbers and rows - cap 2^25 values: the optimizer holds two buffers, about 520 MiB. - an Array a constraint returns is all numbers or all rows. Co-Authored-By: Claude Sonnet 5.5 --- constraints.go | 27 +++++++++++++++++---------- constraints_test.go | 15 +++++++++------ 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/constraints.go b/constraints.go index b499825..ee049aa 100644 --- a/constraints.go +++ b/constraints.go @@ -150,19 +150,25 @@ func flatFloats(v any, rowLen int) ([]float64, error) { 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) - continue - } - row, err := toFloats(e) - if err != nil { - return nil, err + } 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 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") } - out = append(out, row...) } return out, nil } @@ -170,8 +176,9 @@ func flatFloats(v any, rowLen int) ([]float64, error) { // 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. 2^26 float64s is 512 MiB. -const maxConstraintCells = 1 << 26 +// 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 diff --git a/constraints_test.go b/constraints_test.go index 141f3d5..c4f987f 100644 --- a/constraints_test.go +++ b/constraints_test.go @@ -113,6 +113,9 @@ func TestConstraintErrors(t *testing.T) { // 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) } @@ -140,9 +143,9 @@ func TestConstraintMemoryIsBounded(t *testing.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 67108864-value limit on a Jacobian"}, + {"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 67108864-value limit"}, + {"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) } @@ -150,11 +153,11 @@ func TestConstraintMemoryIsBounded(t *testing.T) { 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), c(1 << 20), c(1 << 20)}, 16); err != nil { - t.Errorf("exactly 2^26 values refused: %v", err) + 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), c(1 << 20), c(1<<20 + 1)}, 16); err == nil { - t.Error("2^26 + 16 values accepted") + 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)