File: t_Bonmin_MIT15.py

package info (click to toggle)
openturns 1.24-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 66,204 kB
  • sloc: cpp: 256,662; python: 63,381; ansic: 4,414; javascript: 406; sh: 180; xml: 164; yacc: 123; makefile: 98; lex: 55
file content (68 lines) | stat: -rwxr-xr-x 1,964 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
"""
An optimization problem with mixed discrete input variables.

Simple PLNE :

maximize     15*x + 12*y + 4*z + 2*t
subject to   -(8*x + 5*y + 3*z + 2*t - 10) >= 0

where x, y, z, t in {0,1}
Solution is [0, 1, 1, 1] with objectif value = 18

Without discrete constraint, we get :
x*= [0.625,1,0,0], f(x*)= [-21.375]

References
https://ocw.mit.edu/courses/sloan-school-of-management/15-053-optimization-methods-in-management-science-spring-2013/tutorials/MIT15_053S13_tut10.pdf
"""

import openturns as ot
import openturns.testing as ott

# Define the objective function
objectiveFun = ot.SymbolicFunction(["x", "y", "z", "t"], ["-(15*x + 12*y + 4*z + 2*t)"])
constraintFun = ot.SymbolicFunction(
    ["x", "y", "z", "t"], ["-(8*x + 5*y + 3*z + 2*t -10)"]
)
x = [0, 1, 1, 1]
print(f"f(x)={objectiveFun(x)}")
print(f"g(x)={constraintFun(x)}")

# Define problem
problem = ot.OptimizationProblem(objectiveFun)
problem.setInequalityConstraint(constraintFun)
bounds = ot.Interval([0.0] * 4, [1.0] * 4)
problem.setBounds(bounds)
problem.setMinimization(True)
problem.setVariablesType(
    [
        ot.OptimizationProblemImplementation.BINARY,
        ot.OptimizationProblemImplementation.BINARY,
        ot.OptimizationProblemImplementation.BINARY,
        ot.OptimizationProblemImplementation.BINARY,
    ]
)

# Define OptimizationAlgorithm
x0 = [0.0] * 4
algo = ot.Bonmin(problem)
algo.setStartingPoint(x0)
algo.setMaximumCallsNumber(10000)
algo.setMaximumIterationNumber(1000)


for name in ot.Bonmin.GetAlgorithmNames():
    print(f"-- {name} algorithm...")
    algo.setAlgorithmName(name)
    algo.run()

    # Retrieve result
    result = algo.getResult()
    x_star = result.getOptimalPoint()
    print("x*=", x_star)
    y_star = result.getOptimalValue()
    neval = result.getCallsNumber()
    print(f"f(x*)={y_star} neval={neval}")
    print(f"g(x*)={constraintFun(x_star)}")
    ott.assert_almost_equal(x_star, [0, 1, 1, 1], 1, 5e-4)