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

Using C++ with CPLEX by Daniel Simmons

  • Upload
    vunhi

  • View
    234

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Using C++ with CPLEX by Daniel Simmons

Using C++ with CPLEX

Daniel Simmons, Dr. Qipeng Phil Zheng

Department of Industrial and Management Systems EngineeringWest Virginia University

Nonlinear Programming, Summer 2012

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 1 / 28

Page 2: Using C++ with CPLEX by Daniel Simmons

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

Page 3: Using C++ with CPLEX by Daniel Simmons

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

Page 4: Using C++ with CPLEX by Daniel Simmons

C++: Create a new project

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

* File→ New→ Project.

* Under “Visual C++”, select “Win32”, then “Win32 ConsoleApplication”.

* 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

Page 5: Using C++ with CPLEX by Daniel Simmons

C++: Program structure

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

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 5 / 28

Page 6: Using C++ with CPLEX by Daniel Simmons

C++: Defining variables

Variables must be declared before use.

Variable Type Definition

int Integerdouble Double-precision floating point numberfloat Single-precision floating point numberchar Charactersbool Boolean (binary) numberstring 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

Page 7: Using C++ with CPLEX by Daniel Simmons

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 thevalue 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

Page 8: Using C++ with CPLEX by Daniel Simmons

C++: Pointers

If the exact size of an array is not known when variables are declared, itcan be defined as a pointer, which allocates a specified amount ofdynamic memory for the contents of the array. A pointer is denoted by anasterisk after the variable type, e.g.

double* array = new double[variable1];

After using a dynamic array, the program should close it with the deletecommand delete [] array; in order to free up memory.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 8 / 28

Page 9: Using C++ with CPLEX by Daniel Simmons

C++: Basic Operations

The basic mathematical operations can be used in C++ – + (addition), -(subtraction), * (multiplication), / (division). Variables can be advancedby one by the ++ operation, i.e. number++; is the same asnumber=number+1; Additionally, an operater paired with an equals signperforms that operation between the variables and/or numbers on eitherside of the sign. For example, number1 += number2 is equivalent tonumber1 = number1+number2. This is especially helpful to use insideloops.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 9 / 28

Page 10: Using C++ with CPLEX by Daniel Simmons

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 criteraare met and takes this format: if(number1 < number2) {expression}.If else loops perform one task if the critera are met and another if not, orit 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

Page 11: Using C++ with CPLEX by Daniel Simmons

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 iterationnumber1 - 1. The “i++” advances the counter i by one after eachiteration; this can be modified depending on the desired step size.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 11 / 28

Page 12: Using C++ with CPLEX by Daniel Simmons

C++: Loops, cont.

While loops, like for loops, perform multiple iterations of a task. Thedifference is that while loops can perform an unspecified number ofiterations, 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 canbe 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

Page 13: Using C++ with CPLEX by Daniel Simmons

C++: Functions

New functions can be created in the following way: type functionname(type variable1, type variable2,...). The first type here refers to thetype of the output returned by the function. Any of the variable typeslisted earlier can be used, as well as void for a function that does notreturn a value. A commonly used type is int, where the program ends withthe command return 0;The variables listed in parentheses are external inputs required by thefunction. By default, these variables are passed by value, which meansthat the values of these variables are copied and used in the function,leaving the original variable unaltered. In order to alter the value of theexternal variable from inside the function (to pass the variable byreference), 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

Page 14: Using C++ with CPLEX by Daniel Simmons

C++: Functions, cont.

New functions must be declared in the header after the header files andbefore 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 haveto match the names given in the function declaration; they are assigned inorder to the corresponding declared variable.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 14 / 28

Page 15: Using C++ with CPLEX by Daniel Simmons

C++: Input/Output

The cout command prints to the terminal window, and the cin commandreceives values typed into the terminal as variables. For example,

cin >> arraysize

will enter whatever is typed into the terminal as the value of the variablearray size, and

cout << “Array size = ”<< arraysize << endl;

prints the phrase “Array size = ” followed by the value for the variablearray size. The command endl ends the current line and moves to thenext.Note: Each line of code writing to the screen must start with cout, even ifthe output will not be on a new line. Printing to a text file is morechallenging and will be discussed at a later date.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 15 / 28

Page 16: Using C++ with CPLEX by Daniel Simmons

C++: Sprintf

One important function for text concatenation is sprintf, which cancombine 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 orstring, %d is an integer, and %f is a floating point number. This functionis useful when naming CPLEX objects.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 16 / 28

Page 17: Using C++ with CPLEX by Daniel Simmons

C++: Building and Running Program

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

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 17 / 28

Page 18: Using C++ with CPLEX by Daniel Simmons

C++: Breakpoints

In order to test the behavior of the program, breakpoints can be added tothe program. Breakpoints pause the program at specified points duringdebugging, allowing the user to see variable values and identify errors. Toadd a breakpoint, click on the vertical grey bar to the left of the line ofcode to be tested. A red dot will appear, showing the breakpoint location.When the program runs next, the breakpoint will be highlighted when theline of code is reached. To continue the program or to move to the nextbreakpoint, press F5 on the keyboard.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 18 / 28

Page 19: Using C++ with CPLEX by Daniel Simmons

C++: Coding Tips

* Don’t 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 thatline. / ∗ . . . ∗ / comments out multiple lines.

* Indent loops to reduce confusion.

* Use #define TEST MODE , # ifdef . . . #endif to reducecomputation time.

* Use cin.get() to prevent terminal window from closing automatically.This keeps the program running until the user manually presses Enteron the keyboard.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 19 / 28

Page 20: Using C++ with CPLEX by Daniel Simmons

CPLEX: Linking to Visual C++ 2008

To link the C++ project to CPLEX, in Visual C++ go toProject→Properties (or press Alt+F7).

* Under Configuration Properties→C/C++→General, inAdditional 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 Properties→C/C++→Preprocessor, thePreprocessor Definitions should include“WIN32; DEBUG; CONSOLE;IL STD”.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 20 / 28

Page 21: Using C++ with CPLEX by Daniel Simmons

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

* Under Configuration Properties→Linker→Input, add the followingto 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 files“ilcplex\cplex.h” and“ilcplex\ilocplex.h”.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 21 / 28

Page 22: Using C++ with CPLEX by Daniel Simmons

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 thatwill be sent to the CPLEX solver must be created. IloModel model(env);creates model called “model” inside existing environment “env”. Thevariables 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 anarray of variables. The first term in parentheses is the name of theenvironment, the second is the lower bound, the third is the upper bound,and the fourth is the variable type. ILOFLOAT is a continuous floatingpoint number, ILOINT is an integer, and ILOBOOL is a boolean.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 22 / 28

Page 23: Using C++ with CPLEX by Daniel Simmons

CPLEX: Constructing constraints

As with variables, constraints can be added to the model individually or inan 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 bywhich the constraint is referenced in the model. The objective functioncan 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

Page 24: Using C++ with CPLEX by Daniel Simmons

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 individualconstraints can then be created using loops as follows. First, create a newCPLEX expression with IloExpr xpr(env). This expression is a variablethat can hold all variables and coefficients needed to construct aconstraint.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

Page 25: Using C++ with CPLEX by Daniel Simmons

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

Page 26: Using C++ with CPLEX by Daniel Simmons

CPLEX: Extracting the model

After the objective function and all constraints have been added, themodel 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 (notnecessarily optimal) and false if no solution was found. If running multipleiterations where the model is extracted and solved each time, runcplex.clear() before the model is extracted to prevent solutioncontamination.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 26 / 28

Page 27: Using C++ with CPLEX by Daniel Simmons

CPLEX: Retrieving information

After extracting the model to the solver, you may wish to retrieveinformation 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 thecurrent solution.

* Cplex.getObjValue(); returns the value of the objective function forthe current solution.

Once the model is completed, the environment must be cleared before theprogram can exit. To do this, use env.end();When testing your program, it is important to know whether the modelbeing extracted to CPLEX is accurate. To check this, usecplex.exportModel(filepath) which creates a text file containing thecurrent model to the specified location in the project folder.

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 27 / 28

Page 28: Using C++ with CPLEX by Daniel Simmons

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,CPLEX→OptimDoc2006b→index.chm

D. A. Simmons (IMSE@WVU) C++/CPLEX NLP 28 / 28