|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/MatProGo-dev/MatProInterface.go/problem" |
| 5 | + getKVector "github.com/MatProGo-dev/SymbolicMath.go/get/KVector" |
| 6 | + "github.com/MatProGo-dev/SymbolicMath.go/symbolic" |
| 7 | + "github.com/MatProGo-dev/simplex/simplexSolver" |
| 8 | +) |
| 9 | + |
| 10 | +/* |
| 11 | +Description: |
| 12 | +
|
| 13 | + This function builds an optimization problem where we attempt to find |
| 14 | + the optimal solution to a linear programming problem that is in a feasible |
| 15 | + region that is a box. |
| 16 | +
|
| 17 | + The problem will be: |
| 18 | +
|
| 19 | + Minimize: x1 + 2*x2 |
| 20 | + Subject to: |
| 21 | + 0 <= x1 <= 1 |
| 22 | + 0 <= x2 <= 1 |
| 23 | +
|
| 24 | + The optimal solution is x1 = 0, x2 = 0 with an objective value of 0. |
| 25 | +*/ |
| 26 | +func BuildOptimizationProblem() problem.OptimizationProblem { |
| 27 | + // setup |
| 28 | + varCount := 2 |
| 29 | + out := problem.NewProblem("Box LP Problem") |
| 30 | + |
| 31 | + // Create the variables |
| 32 | + x := out.AddVariableVector(varCount) |
| 33 | + |
| 34 | + // Create the objective |
| 35 | + c := getKVector.From( |
| 36 | + []float64{1, 2}, |
| 37 | + ) |
| 38 | + out.SetObjective( |
| 39 | + c.Transpose().Multiply(x), |
| 40 | + problem.SenseMinimize, |
| 41 | + ) |
| 42 | + |
| 43 | + // Create the constraints |
| 44 | + // - x >= 0 |
| 45 | + out.Constraints = append( |
| 46 | + out.Constraints, |
| 47 | + x.GreaterEq(symbolic.ZerosVector(varCount)), |
| 48 | + ) |
| 49 | + |
| 50 | + // - x <= 1 |
| 51 | + out.Constraints = append( |
| 52 | + out.Constraints, |
| 53 | + x.LessEq(symbolic.OnesVector(varCount)), |
| 54 | + ) |
| 55 | + |
| 56 | + return *out |
| 57 | +} |
| 58 | + |
| 59 | +func main() { |
| 60 | + // This is just a placeholder to make the package "main" valid. |
| 61 | + trickyProblem := BuildOptimizationProblem() |
| 62 | + |
| 63 | + // Use solver to solve the problem |
| 64 | + solver := simplexSolver.New("Simplex Solver Example") |
| 65 | + solver.IterationLimit = 100 |
| 66 | + |
| 67 | + // Solve the problem |
| 68 | + solution, err := solver.Solve(trickyProblem) |
| 69 | + if err != nil { |
| 70 | + panic(err) |
| 71 | + } |
| 72 | + |
| 73 | + // Print the solution |
| 74 | + solutionMessage, _ := solution.Status.ToMessage() |
| 75 | + println("Solution Status: ", solutionMessage) |
| 76 | + println("Objective Value: ", solution.Objective) |
| 77 | + println("Number of Iterations: ", solution.Iterations) |
| 78 | + println("Variable Values: ") |
| 79 | + for varName, varValue := range solution.VariableValues { |
| 80 | + println(" ", varName, ": ", varValue) |
| 81 | + } |
| 82 | +} |
0 commit comments