Import the cplex
module
In [1]:
import cplex
Create an instance of the Cplex
class through which the optimization problem is defined and solved.
In [2]:
c = cplex.Cplex()
Add variables
In [3]:
var_names = ['x1', 'x2', 'x3'] # variable names
lb = [-4, -1, -3] # lower bounds
ub = [ 2, 3, 4] # upper bounds
var_types = ['C', 'C', 'C'] # variables types
In [4]:
variable_indices = c.variables.add(names = var_names,
lb = lb,
ub = ub,
types = var_types)
variable_indices
Out[4]:
In [5]:
lin_expr = [
[["x1","x2","x3"],[-1.0, 1.0, 1.0]],
[["x1","x2","x3"],[ 3.0, 4.0, 4.0]]
]
lin_constr_rhs = [20.0, 5.0]
lin_constr_senses = ["L", "L"]
lin_constr_names = ['linear_constraint1', 'linear_constraint2']
In [6]:
lin_constr_indeces = c.linear_constraints.add(lin_expr=lin_expr,
rhs=lin_constr_rhs,
senses=lin_constr_senses,
names=lin_constr_names
)
lin_constr_indeces
Out[6]:
In [7]:
linear_objective = [("x1", 1.0), ("x2", 2.0), ("x3", 1.0)]
c.objective.set_linear(linear_objective)
In [8]:
c.objective.set_sense(c.objective.sense.minimize)
In [9]:
c.solve()
In [10]:
c.solution.get_status_string()
Out[10]:
In [11]:
c.solution.get_values(["x1", "x2", "x3"])
Out[11]:
In [12]:
problem_path = "./linear_programming_problem.cplex"
solution_path = "./linear_programming_solution.cplex"
In [13]:
c.write(problem_path, filetype="lp")
c.solution.write(solution_path)