User guide · 2.0 development

Linear Problems

Let’s solve a simple linear program (LP):

\[\begin{split} \begin{aligned} \text{minimize} \quad & 2x + 3y \\ \text{subject to} \quad & x + y \geq 1 \\ & x, y \geq 0 \end{aligned} \end{split}\]
# Create a solver
solver = SHOTpy.Solver()

# Create a new problem
problem = SHOTpy.Problem(solver)

# Add variables
x = problem.addVariable("x", SHOTpy.VariableType.Real, 0.0, 100.0)
y = problem.addVariable("y", SHOTpy.VariableType.Real, 0.0, 100.0)

# Linear objective: minimize 2x + 3y
problem.setObjective(2 * x + 3 * y, SHOTpy.ObjectiveDirection.Minimize)

# Constraint: x + y >= 1
problem.addConstraint(x + y >= 1, "c1")

# Finalize and solve. setProblem() and solveProblem() return False if they fail
problem.finalize()
assert solver.setProblem(problem)
assert solver.solveProblem()

# The solution is optimal only if the model return status says so
status = solver.getModelReturnStatus()
print(f"Status: {status.name}, termination reason: {solver.getTerminationReason().name}")

if status == SHOTpy.ModelReturnStatus.OptimalGlobal:
    sol = solver.getPrimalSolution()
    print(f"Optimal objective value: {sol.objValue:.4f}")
    print(f"Optimal solution: x = {sol.point[0]:.4f}, y = {sol.point[1]:.4f}")

# The optimum is x = 1, y = 0
assert status == SHOTpy.ModelReturnStatus.OptimalGlobal
assert abs(solver.getPrimalSolution().objValue - 2.0) < 1e-3