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()

Variables

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]:
range(0, 3)

Linear constraints


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]:
range(0, 2)

Objective function


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)

Solving the optimization problem


In [9]:
c.solve()


CPXPARAM_Read_DataCheck                          1
CPLEX Error  1017: Not available for mixed-integer problems.
CPXPARAM_Read_DataCheck                          1
Found incumbent of value 0.000000 after 0.00 sec. (0.00 ticks)
Found incumbent of value -9.000000 after 0.00 sec. (0.00 ticks)

Root node processing (before b&c):
  Real time             =    0.01 sec. (0.00 ticks)
Parallel b&c, 2 threads:
  Real time             =    0.00 sec. (0.00 ticks)
  Sync time (average)   =    0.00 sec.
  Wait time (average)   =    0.00 sec.
                          ------------
Total (root+branch&cut) =    0.01 sec. (0.00 ticks)

In [10]:
c.solution.get_status_string()


Out[10]:
'integer optimal solution'

In [11]:
c.solution.get_values(["x1", "x2", "x3"])


Out[11]:
[-4.0, -1.0, -3.0]

Saving output to file


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)