Вы находитесь на странице: 1из 28

Using C++ with CPLEX

Daniel Simmons, Dr. Qipeng Phil Zheng


Department of Industrial and Management Systems Engineering
West Virginia University

Nonlinear Programming, Summer 2012

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

1 / 28

Overview
1. C++
* Creating a new project
* Program structure
* Defining variables
* Arrays
* Pointers
* Basic Operations
* Loops
* Functions
* Input/Output
* Debugging
* General coding tips

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

2 / 28

Overview, cont.

2. CPLEX
* Linking to Visual C++ 2008
* Initialization
* Constructing constraints
* Constructing constraint arrays
* Extracting the model
* Retrieving information
3. Additional Resources

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

3 / 28

C++: Create a new project

* Open Visual Studio 2008 (C++ should be default language).


* File New Project.
* Under Visual C++, select Win32, then Win32 Console
Application.
* Enter a name for the project and click OK.
* When the Application Wizard appears, click Finish.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

4 / 28

C++: Program structure

The C++ program file has two main partsthe header and the functions.
The command #include loads header files into the program.
#include<file> indicates a system header file, and #includefile
indicates a header file created by the user.
The function int tmain(. . .) is created by Visual Studio and will be the
first to run when debugging the program.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

5 / 28

C++: Defining variables


Variables must be declared before use.
Variable Type
int
double
float
char
bool
string

Definition
Integer
Double-precision floating point number
Single-precision floating point number
Characters
Boolean (binary) number
Grouped characters

Table : Common Variable Types

You can declare variables in any of these ways:


* type variablename;
* type variablename=0;
* type variablename1, variablename2,...;
D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

6 / 28

C++: Arrays

Arrays can be defined in two different ways.


* Int array[3];
* int array[] = {1,2,3};
To reference a value in an array, use the name of the array followed by the
value position in brackets, e.g. array[2] refers to the 3rd value in the array
(since the first value is in position 0).

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

7 / 28

C++: Pointers

If the exact size of an array is not known when variables are declared, it
can be defined as a pointer, which allocates a specified amount of
dynamic memory for the contents of the array. A pointer is denoted by an
asterisk after the variable type, e.g.
double* array = new double[variable1];
After using a dynamic array, the program should close it with the delete
command delete [] array; in order to free up memory.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

8 / 28

C++: Basic Operations

The basic mathematical operations can be used in C++ + (addition), (subtraction), * (multiplication), / (division). Variables can be advanced
by one by the ++ operation, i.e. number++; is the same as
number=number+1; Additionally, an operater paired with an equals sign
performs that operation between the variables and/or numbers on either
side of the sign. For example, number1 += number2 is equivalent to
number1 = number1+number2. This is especially helpful to use inside
loops.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

9 / 28

C++: Loops
The main loops that will occur in basic programs are the if, if else, for,
and while loops. The if loop performs a task when the specified critera
are met and takes this format: if(number1 < number2) {expression}.
If else loops perform one task if the critera are met and another if not, or
it another set of critera are met. For example,
if (number1 == number2) {expression}
else {expression}
or
else if(number 1 < number 2) {expression}
Note: when setting a variable equal to a number or another variable, use
=. When comparing a variable to a number or other variable, use
==.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

10 / 28

C++: Loops, cont.

For loops perform a specified number of iterations of a task.


for(i=0;i<number1;i++) {expression}
performs the expression number1 times, i.e. from iteration 0 to iteration
number1 - 1. The i++ advances the counter i by one after each
iteration; this can be modified depending on the desired step size.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

11 / 28

C++: Loops, cont.


While loops, like for loops, perform multiple iterations of a task. The
difference is that while loops can perform an unspecified number of
iterations, e.g.
while(number1<>7)
{expresssion}
performs the task until number1 is 7, at which point it exits the loop.
Infinite while loops can be constructed by while(1) {expression} and can
be broken by the command break. For example,
while (1)
{runprogram();
if(status == optimal)
{break;}}
will run the task indefinitely until the optimal solution is found.
D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

12 / 28

C++: Functions
New functions can be created in the following way: type functionname
(type variable1, type variable2,...). The first type here refers to the
type of the output returned by the function. Any of the variable types
listed earlier can be used, as well as void for a function that does not
return a value. A commonly used type is int, where the program ends with
the command return 0;
The variables listed in parentheses are external inputs required by the
function. By default, these variables are passed by value, which means
that the values of these variables are copied and used in the function,
leaving the original variable unaltered. In order to alter the value of the
external variable from inside the function (to pass the variable by
reference), an ampersand must be added to the variable type, e.g.
int functionname (int& variable1)

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

13 / 28

C++: Functions, cont.

New functions must be declared in the header after the header files and
before the main function.
type functionname (type variable1, type variable2,...);
The function itself can be started after the main function like this:
type functionname (type variable1, type variable2,...)
{expression}
To call a function, all that is needed is its name and inputs, e.g.
functionname(variable1, variable2); These variable names do not have
to match the names given in the function declaration; they are assigned in
order to the corresponding declared variable.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

14 / 28

C++: Input/Output
The cout command prints to the terminal window, and the cin command
receives values typed into the terminal as variables. For example,
cin >> arraysize
will enter whatever is typed into the terminal as the value of the variable
array size, and
cout << Array size = << arraysize << endl;
prints the phrase Array size = followed by the value for the variable
array size. The command endl ends the current line and moves to the
next.
Note: Each line of code writing to the screen must start with cout, even if
the output will not be on a new line. Printing to a text file is more
challenging and will be discussed at a later date.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

15 / 28

C++: Sprintf

One important function for text concatenation is sprintf, which can


combine multiple types of values into a single string. For example,
sprintf(filename,%c(%d,%f),file, 10, 3.5)
will output the string file(10,3.5). The symbol %c represents a char or
string, %d is an integer, and %f is a floating point number. This function
is useful when naming CPLEX objects.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

16 / 28

C++: Building and Running Program

To build and run a program in Visual C++, click the green triangular
button in the toolbar or press F5 on the keyboard. This starts the
debugging process, which compiles the program, checks for errors, and
executes if no errors are found. If errors are found, they will be listed at
the bottom of the Visual C++ window in the Output frame. Clicking on
an error message will move the cursor to the corresponding line of code.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

17 / 28

C++: Breakpoints

In order to test the behavior of the program, breakpoints can be added to


the program. Breakpoints pause the program at specified points during
debugging, allowing the user to see variable values and identify errors. To
add a breakpoint, click on the vertical grey bar to the left of the line of
code to be tested. A red dot will appear, showing the breakpoint location.
When the program runs next, the breakpoint will be highlighted when the
line of code is reached. To continue the program or to move to the next
breakpoint, press F5 on the keyboard.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

18 / 28

C++: Coding Tips


* Dont have to code in Visual C++. Try Notepad ++ or Sublime Text
(links at the end).
* Use strong, memorable variable names.
* Comment on everything. // comments out everything after it on that
line. / . . . / comments out multiple lines.
* Indent loops to reduce confusion.
* Use #define TEST MODE , # ifdef . . . #endif to reduce
computation time.
* Use cin.get() to prevent terminal window from closing automatically.
This keeps the program running until the user manually presses Enter
on the keyboard.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

19 / 28

CPLEX: Linking to Visual C++ 2008


To link the C++ project to CPLEX, in Visual C++ go to
ProjectProperties (or press Alt+F7).
* Under Configuration PropertiesC/C++General, in
Additional Include Directories add
C:\ILOG\CPLEX_Studio_AcademicResearch122\concert\include;
C:\ILOG\CPLEX_Studio_AcademicResearch122\CPLEX\include
and change Detect 64-bit Portability Issues to Yes.
* Under Configuration PropertiesC/C++Preprocessor, the
Preprocessor Definitions should include
WIN32; DEBUG; CONSOLE;IL STD.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

20 / 28

CPLEX: Linking to Visual C++ 2008, cont.

* Under Configuration PropertiesLinkerInput, add the following


to Additional Dependencies:
C:\ILOG\CPLEX_Studio_AcademicResearch122\CPLEX\lib
\x86_windows_vs2008\stat_mda\cplex122.lib
C:\ILOG\CPLEX_Studio_AcademicResearch122\CPLEX\lib
\x86_windows_vs2008\stat_mda\ilocplex.lib
C:\ILOG\CPLEX_Studio_AcademicResearch122\concert\lib
\x86_windows_vs2008\stat_mda\concert.lib
Note: The C++ file must include the header filesilcplex\cplex.h and
ilcplex\ilocplex.h.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

21 / 28

CPLEX: Initialization
In order to use CPLEX, an environment must first be created in C++.
IloEnv env; creates an environment called env. Next, the model that
will be sent to the CPLEX solver must be created. IloModel model(env);
creates model called model inside existing environment env. The
variables used in the model are created through IloNumVar or
IloNumVarArray var x(env,0.0, 40.0, ILOFLOAT);
IloNumVarcreates a single variable, whereas IloNumVarArray creates an
array of variables. The first term in parentheses is the name of the
environment, the second is the lower bound, the third is the upper bound,
and the fourth is the variable type. ILOFLOAT is a continuous floating
point number, ILOINT is an integer, and ILOBOOL is a boolean.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

22 / 28

CPLEX: Constructing constraints


As with variables, constraints can be added to the model individually or in
an array. Individual constraints can be added directly to the model by
model.add(IloRange(env,IloInfinity,x1+x2+x3,0,constraint1));
This example adds the constraint x1 + x2 + x3 0 in the environment
env to the model model. The last item in parentheses is the name by
which the constraint is referenced in the model. The objective function
can be added in a similar fashion, by
model.add(IloMinimize(env,x1+2*x2+3*x3));
which sets Min x1 + 2x2 + 3x3 as the objective function for the model
(IloMaximize is used for Max problems).

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

23 / 28

CPLEX: Constructing constraint arrays


To add sets of constraints, use IloRangeArray.
IloRangeArray cst a(env,4);
creates an array of 4 constraints in environment env. The individual
constraints can then be created using loops as follows. First, create a new
CPLEX expression with IloExpr xpr(env). This expression is a variable
that can hold all variables and coefficients needed to construct a
constraint.
For example, say we need to generate the following constraints
cst a(1): x1 + x2 + x3 0
cst a(2): 2x1 + 2x2 + 2x3 0
cst a(3): 3x1 + 3x2 + 3x3 0
cst a(4): 4x1 + 4x2 + 4x3 0

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

24 / 28

CPLEX: Constraint Array Example


for(i=0;i<4;i++) {
IloExpr xpr(env);
for(j=0;j<3;j++) {
xpr += (i+1)*var x[j];
}
sprintf(temp,cst a(%d),i+1);
cst a.add(IloRange(env,0,xpr,+IloInfinity,temp));
xpr.end();
}
Note: To add the constraint array to the model, use model.add(cst a).

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

25 / 28

CPLEX: Extracting the model

After the objective function and all constraints have been added, the
model can be extracted to the CPLEX solver.
IloCplex cplex(env);
cplex.extract(model);
cplex.solve();
This returns a Boolean value that is true if the problem is feasible (not
necessarily optimal) and false if no solution was found. If running multiple
iterations where the model is extracted and solved each time, run
cplex.clear() before the model is extracted to prevent solution
contamination.

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

26 / 28

CPLEX: Retrieving information


After extracting the model to the solver, you may wish to retrieve
information about the solution.
* Cplex.getStatus(); returns the status of the current solution (e.g.
Optimal or Infeasible).
* Cplex.getValue(var x[1]); returns the value of the variable x2 in the
current solution.
* Cplex.getObjValue(); returns the value of the objective function for
the current solution.
Once the model is completed, the environment must be cleared before the
program can exit. To do this, use env.end();
When testing your program, it is important to know whether the model
being extracted to CPLEX is accurate. To check this, use
cplex.exportModel(filepath) which creates a text file containing the
current model to the specified location in the project folder.
D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

27 / 28

Additional resources

* More information on C++: http://www.cplusplus.com


* Download Notepad++ (free):
http://www.notepad-plus-plus.org
* Download Sublime Text 2 (shareware):
http://www.sublimetext.com/2
* More information on CPLEX: On Desktop,
CPLEXOptimDoc2006bindex.chm

D. A. Simmons (IMSE@WVU)

C++/CPLEX

NLP

28 / 28