Modifying and querying problem data in the Python API

Shows how to modify and query data by index or by name.

Tip:

For performance, access objects of your model by index, rather than by name.

Although you can use names or indices interchangeably, you can achieve better performance with CPLEX when you use indices whenever possible because doing so avoids excessive queries to get the indices. For example, when you add constraints, it is faster to use variable indices to specify the constraint matrix. In fact, it is a good idea to maintain a name-index dictionary in your program, and to use that dictionary to convert names into indices before you pass them to CPLEX.

For convenience, you can use either object names or indices as handles to modify and query problem data. For example, assume that you have already created c, an instance of the class Cplex, and that it contains ten variables in this session of Python. Then the following line adds a new variable to that model and sets the upper bound of the new variable as 1.0.

>>> c.variables.add(names = ["new_var"], ub = [1.0])

Afterwards, the following lines in the same session query that new variable by its name and return its index and upper bound, like this:

>>> c.variables.get_index("new_var")
10
>>> c.variables.get_upper_bounds("new_var")
1.0

Likewise, you can query the new variable by its index to return its upper bound.

>>> c.variables.get_upper_bounds(10)
1.0

In fact, you can modify the upper bound of that variable, accessing it either by its name or by its index, as you see in the following lines of the same session:

>>> c.variables.set_upper_bounds("new_var", 2.0)
>>> c.variables.get_upper_bounds(10)
2.0
>>> c.variables.set_upper_bounds(10, 3.0)
>>> c.variables.get_upper_bounds("new_var")
3.0