124
IBM ILOG CPLEX Optimization Studio Getting Started with CPLEX Version 12 Release 6

Ibm Ilog Cplex User Manual 12.6

Embed Size (px)

DESCRIPTION

IBM cplex manual

Citation preview

Page 1: Ibm Ilog Cplex User Manual 12.6

IBM ILOG CPLEX Optimization StudioGetting Started with CPLEXVersion 12 Release 6

���

Page 2: Ibm Ilog Cplex User Manual 12.6

Copyright noticeDescribes general use restrictions and trademarks related to this document and the software described in this document.

© Copyright IBM Corp. 1987, 2013

US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract withIBM Corp.

Trademarks

IBM, the IBM logo, ibm.com, WebSphere, and ILOG are trademarks or registered trademarks of International BusinessMachines Corp., in many jurisdictions worldwide. Other product and service names might be trademarks of IBM or othercompanies. A current list of IBM trademarks is available on the Web at Copyright and trademark information.

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of AdobeSystems Incorporated in the United States, and/or other countries.

Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.

UNIX is a registered trademark of The Open Group in the United States and other countries.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States,other countries, or both.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or its affiliates.

Other company, product, or service names may be trademarks or service marks of others.

Further acknowledgments

IBM ILOG CPLEX states these additional registered trademarks, copyrights, and acknowledgments.

Additional registered trademarks, copyrights, licenses

Python is a registered trademark of the Python Software Foundation.

MATLAB is a registered trademark of The MathWorks, Inc.

OpenMPI is distributed by The Open MPI Project under the New BSD license and copyright 2004 - 2012.

MPICH2 is copyright 2002 by the University of Chicago and Argonne National Laboratory.

Acknowledgment of use: dtoa routine of the gdtoa package

IBM ILOG CPLEX acknowledges use of the dtoa routine of the gdtoa package, available at

http://www.netlib.org/fp/.

The author of this software is David M. Gay.

All Rights Reserved.

Copyright (C) 1998, 1999 by Lucent Technologies

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and withoutfee is hereby granted, provided that the above copyright notice appears in all copies and that both that thecopyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and thatthe name of Lucent or any of its entities not be used in advertising or publicity pertaining to distribution of thesoftware without specific, written prior permission.

LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITSENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OFCONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITHTHE USE OR PERFORMANCE OF THIS SOFTWARE.

(end of acknowledgment of use of dtoa routine of the gdtoa package)

© Copyright IBM Corporation 1987, 2013.US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith IBM Corp.

Page 3: Ibm Ilog Cplex User Manual 12.6

Contents

Introducing CPLEX . . . . . . . . . . vWhat is CPLEX? . . . . . . . . . . . . . v

Types of problems solved . . . . . . . . . vCPLEX components . . . . . . . . . . . viOptimizer options . . . . . . . . . . . vii

Parallel optimizers . . . . . . . . . . . . viiData entry options. . . . . . . . . . . . viiiWhat CPLEX is not . . . . . . . . . . . viiiWhat you need to know . . . . . . . . . . viiiWhat’s in this manual . . . . . . . . . . . ixNotation in this manual . . . . . . . . . . ixRelated documentation . . . . . . . . . . . x

Chapter 1. Setting up CPLEX. . . . . . 1Installing CPLEX . . . . . . . . . . . . . 1Setting up CPLEX on Windows . . . . . . . . 1Setting up CPLEX on GNU/Linux . . . . . . . 2Setting up Eclipse for the Java API of CPLEX . . . 4Setting up the Python API of CPLEX . . . . . . 5Directory structure of CPLEX . . . . . . . . . 6Using the Component Libraries . . . . . . . . 7

Chapter 2. Solving an LP with CPLEX 11Overview . . . . . . . . . . . . . . . 11Problem statement . . . . . . . . . . . . 11Using the Interactive Optimizer. . . . . . . . 11Using Concert Technology in C++ . . . . . . . 12Using Concert Technology in Java . . . . . . . 13Using Concert Technology in .NET . . . . . . 13Using the Callable Library . . . . . . . . . 14Using the Python API . . . . . . . . . . . 16

Chapter 3. Interactive Optimizer tutorial 19Starting CPLEX . . . . . . . . . . . . . 19Using help. . . . . . . . . . . . . . . 19Entering a problem . . . . . . . . . . . . 21

Overview . . . . . . . . . . . . . . 21Entering the example . . . . . . . . . . 21Using the LP format . . . . . . . . . . 22Entering data . . . . . . . . . . . . . 24

Displaying a problem . . . . . . . . . . . 24Verifying a problem with the display command 24Displaying problem statistics . . . . . . . 25Specifying item ranges. . . . . . . . . . 26Displaying variable or constraint names . . . . 27Ordering variables . . . . . . . . . . . 28Displaying constraints . . . . . . . . . . 28Displaying the objective function . . . . . . 28Displaying bounds . . . . . . . . . . . 28Displaying a histogram of nonzero counts . . . 29

Solving a problem . . . . . . . . . . . . 29Where you are . . . . . . . . . . . . 30Solving the example . . . . . . . . . . 30Solution options . . . . . . . . . . . . 31Displaying post-solution information . . . . . 32

Performing sensitivity analysis . . . . . . . . 33Writing problem and solution files. . . . . . . 34

Overview . . . . . . . . . . . . . . 34Selecting a write file format . . . . . . . . 34Writing LP files . . . . . . . . . . . . 35Writing basis files . . . . . . . . . . . 35Using path names . . . . . . . . . . . 36

Reading problem files . . . . . . . . . . . 36Overview . . . . . . . . . . . . . . 36Selecting a read file format . . . . . . . . 36Reading LP files . . . . . . . . . . . . 37Using file extensions . . . . . . . . . . 38Reading MPS files . . . . . . . . . . . 38Reading basis files . . . . . . . . . . . 38

Setting CPLEX parameters . . . . . . . . . 39Adding constraints and bounds . . . . . . . 40Changing a problem . . . . . . . . . . . 41

Overview . . . . . . . . . . . . . . 41What can be changed?. . . . . . . . . . 42Changing constraint or variable names . . . . 42Changing sense . . . . . . . . . . . . 42Changing bounds . . . . . . . . . . . 43Removing bounds . . . . . . . . . . . 43Changing coefficients of variables . . . . . . 43Objective and RHS coefficients . . . . . . . 44Deleting entire constraints or variables . . . . 44Changing small values to zero . . . . . . . 45

Executing operating system commands . . . . . 45Quitting CPLEX . . . . . . . . . . . . . 46Advanced features of the Interactive Optimizer . . 46

Chapter 4. Concert Technology tutorialfor C++ users . . . . . . . . . . . . 49The design of CPLEX in Concert Technology C++applications . . . . . . . . . . . . . . 49Compiling CPLEX in Concert Technology C++applications . . . . . . . . . . . . . . 50

Testing your installation on UNIX . . . . . . 50Testing your installation on Windows. . . . . 50In case of problems . . . . . . . . . . . 50

The anatomy of a Concert Technology C++application . . . . . . . . . . . . . . 51

Constructing the environment: IloEnv . . . . 51Creating a model: IloModel . . . . . . . . 52Solving the model: IloCplex . . . . . . . . 54Querying results. . . . . . . . . . . . 54Handling errors . . . . . . . . . . . . 55

Building and solving a small LP model in C++ . . 55Overview . . . . . . . . . . . . . . 56Modeling by rows . . . . . . . . . . . 57Modeling by columns . . . . . . . . . . 57Modeling by nonzero elements . . . . . . . 58

Writing and reading models and files. . . . . . 58Selecting an optimizer . . . . . . . . . . . 59Reading a problem from a file: example ilolpex2.cpp 60

© Copyright IBM Corp. 1987, 2013 iii

Page 4: Ibm Ilog Cplex User Manual 12.6

Overview . . . . . . . . . . . . . . 60Reading the model from a file . . . . . . . 60Selecting the optimizer . . . . . . . . . 60Accessing basis information . . . . . . . . 61Querying quality measures . . . . . . . . 61

Modifying and re-optimizing . . . . . . . . 61Modifying an optimization problem: exampleilolpex3.cpp . . . . . . . . . . . . . . 62

Overview . . . . . . . . . . . . . . 62Setting CPLEX parameters . . . . . . . . 63Modifying an optimization problem . . . . . 63Starting from a previous basis . . . . . . . 63Complete program . . . . . . . . . . . 63

Chapter 5. Concert Technology tutorialfor Java users . . . . . . . . . . . 65Overview . . . . . . . . . . . . . . . 65Compiling CPLEX in Concert Technology Javaapplications . . . . . . . . . . . . . . 65

Paths and JARs . . . . . . . . . . . . 65Adapting build procedures to your platform . . 65In case problems arise . . . . . . . . . . 66

The design of CPLEX in Concert Technology Javaapplications . . . . . . . . . . . . . . 67The anatomy of a Concert Technology Javaapplication . . . . . . . . . . . . . . 67

Structure of an application . . . . . . . . 67Create the model . . . . . . . . . . . 68Solve the model . . . . . . . . . . . . 69Query the results . . . . . . . . . . . 70

Building and solving a small LP model in Java . . 70Example: LPex1.java . . . . . . . . . . 70Modeling by rows . . . . . . . . . . . 72Modeling by columns . . . . . . . . . . 72Modeling by nonzeros . . . . . . . . . . 73

Chapter 6. Concert Technology tutorialfor .NET users . . . . . . . . . . . 75Presenting the tutorial . . . . . . . . . . . 75What you need to know: prerequisites . . . . . 75What you will be doing . . . . . . . . . . 76Describe . . . . . . . . . . . . . . . 77Model . . . . . . . . . . . . . . . . 78Solve . . . . . . . . . . . . . . . . 81Complete program . . . . . . . . . . . . 82

Chapter 7. Callable Library tutorial . . . 83The design of the CPLEX Callable Library . . . . 83

Compiling and linking Callable Library applications 83Overview . . . . . . . . . . . . . . 83Building Callable Library applications on UNIXplatforms . . . . . . . . . . . . . . 84Building Callable Library applications on Win32platforms . . . . . . . . . . . . . . 84

How CPLEX works. . . . . . . . . . . . 85Overview . . . . . . . . . . . . . . 85Opening the CPLEX environment . . . . . . 85Instantiating the problem object . . . . . . 86Populating the problem object . . . . . . . 86Changing the problem object . . . . . . . 86

Creating a successful Callable Library application 87Overview . . . . . . . . . . . . . . 87Prototype the model . . . . . . . . . . 87Identify the routines to call . . . . . . . . 87Test procedures in the application . . . . . . 87Assemble the data . . . . . . . . . . . 88Choose an optimizer . . . . . . . . . . 88Observe good programming practices . . . . 89Debug your program . . . . . . . . . . 89Test your application . . . . . . . . . . 89Use the examples . . . . . . . . . . . 89

Building and solving a small LP model in C . . . 90Reading a problem from a file: example lpex2.c . . 91Adding rows to a problem: example lpex3.c . . . 92Performing sensitivity analysis . . . . . . . . 94

Chapter 8. Python tutorial . . . . . . 97Design of CPLEX in a Python application . . . . 97Starting the CPLEX Python API . . . . . . . 97Accessing the module cplex . . . . . . . . . 97Building and solving a small LP with Python . . . 98Reading and writing CPLEX models to files withPython . . . . . . . . . . . . . . . . 98Selecting an optimizer in Python . . . . . . . 99Example: reading a problem from a file lpex2.py 100Modifying and re-optimizing in the CPLEX PythonAPI. . . . . . . . . . . . . . . . . 100Example: modifying a model lpex3.py . . . . . 101Using CPLEX parameters in the CPLEX PythonAPI. . . . . . . . . . . . . . . . . 102

Index . . . . . . . . . . . . . . . 105

iv Getting Started with CPLEX

Page 5: Ibm Ilog Cplex User Manual 12.6

Introducing CPLEX

This preface introduces CPLEX.

What is CPLEX?CPLEX consists of software components and options.

Types of problems solvedDefines the kind of problems that CPLEX solves.

IBM ILOG CPLEX Optimizer is a tool for solving linear optimization problems,commonly referred to as Linear Programming (LP) problems, of the form:

Maximize (or Minimize) c 1 x 1 + c 2 x 2 +...+ c n x n

subject toa 11 x 1 + a 12 x 2 +...+ a 1n x n ~ b 1

a 21 x 1 + a 22 x 2 +...+ a 2n x n ~ b 2

...

a m1 x 1 + a m2 x 2 +...+ a mn x n ~ b m

with these boundsl 1 ≤ x 1 ≤ u 1

...

l n ≤ x n ≤ u n

where ~ can be ≤, ≥, or =, and the upper bounds u i and lower bounds l i may bepositive infinity, negative infinity, or any real number.

The elements of data you provide as input for this LP are:

Objective function coefficients c 1 , c 2 , ... , c n

Constraint coefficientsa 11 , a 21 , ... , a n1

...

a m1 , a m2 , ... , a mn

Righthand sides b 1 , b 2 , ... , b m

Upper and lower bounds u 1 , u 2 , ... , u n and l 1 , l 2 , ... , l n

The optimal solution that CPLEX computes and returns is:

Variables x 1 , x 2 , ... , x n

CPLEX also can solve several extensions to LP:v Network Flow problems, a special case of LP that CPLEX can solve much faster

by exploiting the problem structure.

© Copyright IBM Corp. 1987, 2013 v

Page 6: Ibm Ilog Cplex User Manual 12.6

v Quadratic Programming (QP) problems, where the LP objective function isexpanded to include quadratic terms.

v Quadratically Constrained Programming (QCP) problems that include quadraticterms among the constraints. In fact, CPLEX can solve Second Order ConeProgramming (SOCP) problems.

v Mixed Integer Programming (MIP) problems, where any or all of the LP, QP, orQCP variables are further restricted to take integer values in the optimal solutionand where MIP itself is extended to include constructs like Special Ordered Sets(SOS) and semi-continuous variables.

CPLEX componentsDescribes the components of CPLEX: Interactive Optimizer, Concert Technology,Callable Library.

CPLEX comes in various forms to meet a wide range of users' needs:v The CPLEX Interactive Optimizer is an executable program that can read a

problem interactively or from files in certain standard formats, solve theproblem, and deliver the solution interactively or into text files. The programconsists of the file cplex.exe on Windows platforms or cplex on UNIXplatforms.

v Concert Technology is a set of C++, Java, and .NET class libraries offering anAPI that includes modeling facilities to allow the programmer to embed CPLEXoptimizers in C++, Java, or .NET applications. Table 1. lists the files that containthe libraries.

Table 1. Concert Technology libraries

Microsoft Windows UNIX

C++ ilocplex.lib concert.lib libilocplex.a libconcert.a

Java cplex.jar cplex.jar

.NET ILOG.CPLEX.dll

ILOG.Concert.dll

The Concert Technology libraries make use of the Callable Library (describednext).

v The CPLEX Callable Library is a C library that allows the programmer toembed CPLEX optimizers in applications written in C, Visual Basic, FORTRAN,or any other language that can call C functions. The library is provided in filescplexXXX.lib and cplexXXX.dll on Windows platforms, and in libcplex.a,libcplex.so, and libcplex.sl on UNIX platforms.

v The Python API for CPLEX a full-featured Python application programminginterface supporting all aspects of CPLEX optimization.

v The CPLEX connector for The MathWorks MATLAB enables a user to defineoptimization problems and solve them within MATLAB using either theMATLAB Toolbox or a CPLEX class in the MATLAB language.

In this manual, the phrase CPLEX Component Libraries is used to refer equally toany of these libraries. While all of the libraries are callable, the term CPLEX CallableLibrary as used here refers specifically to the C library.

vi Getting Started with CPLEX

Page 7: Ibm Ilog Cplex User Manual 12.6

Compatible platforms

CPLEX is available on Windows, UNIX, and other platforms. The programminginterface works the same way and provides the same facilities on all platforms.

Installation

If you have not yet installed CPLEX on your platform, consult Chapter 1, “Settingup CPLEX,” on page 1. It contains instructions for installing CPLEX.

Optimizer optionsIntroduces the options available in CPLEX.

This manual explains how to use the LP algorithms that are part of CPLEX. TheQP, QCP, and MIP problem types are based on the LP concepts discussed here, andthe extensions to build and solve such problems are explained in the CPLEX User’sManual.

Default settings will result in a call to an optimizer that is appropriate to the classof problem you are solving. However, you may wish to choose a differentoptimizer for special purposes. An LP or QP problem can be solved using any ofthe following CPLEX optimizers: dual simplex, primal simplex, barrier, andperhaps also the network optimizer (if the problem contains an extractable networksubstructure). Pure network models are all solved by the network optimizer. QCPmodels, including the special case of SOCP models, are all solved by the barrieroptimizer. MIP models are all solved by the mixed integer optimizer, which in turnmay invoke any of the LP or QP optimizers in the course of its computation. Thetable titled Table 2 summarizes these possible choices.

Table 2. Optimizers

LP Network QP QCP MIP

DualOptimizer

yes yes

PrimalOptimizer

yes yes

BarrierOptimizer

yes yes yes

Mixed IntegerOptimizer

yes

NetworkOptimizer

Note 1 yes Note 1

Note 1: The problem must contain an extractable network substructure.

The choice of optimizer or other parameter settings may have a very large effecton the solution speed of your particular class of problem. The CPLEX User'sManual describes the optimizers, provides suggestions for maximizingperformance, and notes the features and algorithmic parameters unique to eachoptimizer.

Parallel optimizersParallel optimizers are available in CPLEX.

Introducing CPLEX vii

Page 8: Ibm Ilog Cplex User Manual 12.6

Parallel barrier, parallel MIP, and concurrent optimizers are implemented to run onhardware platforms with parallel processors. These parallel optimizers can becalled from the Interactive Optimizer and the Component Libraries.

When small models, such as those in this document, are being solved, the effect ofparallelism will generally be negligible. On larger models, the effect is ordinarilybeneficial to solution speed.

See the topic Parallel optimizers in the CPLEX User's Manual for information aboutusing CPLEX on a parallel computer.

Data entry optionsCPLEX supports a variety of data entry options.

CPLEX provides several options for entering your problem data. When using theInteractive Optimizer, most users will enter problem data from formatted files.CPLEX supports the industry-standard MPS (Mathematical Programming System)file format as well as CPLEX LP format, a row-oriented format many users mayfind more natural. Interactive entry (using CPLEX LP format) is also a possibilityfor small problems.

Data entry options are described briefly in this manual. File formats aredocumented in the reference manual, File formats supported by CPLEX.

Concert Technology and Callable Library users may read problem data from thesame kinds of files as in the Interactive Optimizer, or they may want to pass datadirectly into CPLEX to gain efficiency. These options are discussed in a series ofexamples that begin with “Building and solving a small LP model in C++” on page55, “Building and solving a small LP model in Java” on page 70, and “Buildingand solving a small LP model in C” on page 90 for the CPLEX Callable Libraryusers.

Users can also read models from Python. For more about that approach, see thetopic “Reading and writing CPLEX models to files with Python” on page 98 in thetutorial for Python users in this manual.

Users can also read models from The MathWorks MATLAB. For more about thatapproach, see the user's manual accompanying the CPLEX connector for MATLAB.

What CPLEX is notCPLEX contrasts with other tools, such as modeling languages or integrateddevelopment environments.

CPLEX Optimizer is not a modeling language, nor is it an integrated developmentenvironment (IDE). You can completely model and solve your optimizationproblems with CPLEX; however, the optimizer that it provides does not offer theinteractive facilities of a modeling system in an integrated developmentenvironment. For such features as interactive modeling, consider the integrateddevelopment environment of IBM ILOG CPLEX Optimization Studio.

What you need to knowPrerequisites for effective use of CPLEX include familiarity with your operatingsystem, knowledge of file management, and facility in a programming language.

viii Getting Started with CPLEX

Page 9: Ibm Ilog Cplex User Manual 12.6

In order to use CPLEX effectively, you need to be familiar with your operatingsystem.

This manual assumes you already know how to create and manage files. Inaddition, if you are building an application that uses the Component Libraries, thismanual assumes that you know how to compile, link, and execute programswritten in a high-level language. The Callable Library is written in the Cprogramming language, while Concert Technology is available for users of C++,Java, and the .NET framework. This manual also assumes that you already knowhow to program in the appropriate language and that you will consult aprogramming guide when you have questions in that area.

What’s in this manualGetting Started with CPLEX offers tutorials for the components of CPLEX,including the Interactive Optimizer and the application programming interfaces.

Chapter 1, “Setting up CPLEX,” on page 1 tells how to install CPLEX.

Chapter 2, “Solving an LP with CPLEX,” on page 11 shows you at a glance how touse the Interactive Optimizer and each of the application programming interfaces(APIs): C++, Java, .NET, and C. This overview is followed by more detailedtutorials about each interface.

Chapter 3, “Interactive Optimizer tutorial,” on page 19 explains, step by step, howto use the Interactive Optimizer: how to start it, how to enter problems and data,how to read and save files, how to modify objective functions and constraints, andhow to display solutions and analytical information.

Chapter 4, “Concert Technology tutorial for C++ users,” on page 49 describes thesame activities using the classes in the C++ implementation of the CPLEX ConcertTechnology Library.

Chapter 5, “Concert Technology tutorial for Java users,” on page 65 describes thesame activities using the classes in the Java implementation of the CPLEX ConcertTechnology Library.

Chapter 6, “Concert Technology tutorial for .NET users,” on page 75 describes thesame activities using .NET facilities.

Chapter 7, “Callable Library tutorial,” on page 83, describes the same activitiesusing the routines in the CPLEX Callable Library.

Chapter 8, “Python tutorial,” on page 97 covers certain installation considerationsplus an introduction to using the CPLEX Python API to model and solveoptimization problems.

All tutorials use examples that are delivered with the standard distribution.

Notation in this manualNotation in this manual conforms to familiar conventions.

This manual observes the following conventions in notation and names.v Important ideas are emphasized the first time they appear.

Introducing CPLEX ix

Page 10: Ibm Ilog Cplex User Manual 12.6

v Text that is entered at the keyboard or displayed on the screen as well ascommands and their options available through the Interactive Optimizer appearin this typeface, for example, set preprocessing aggregator n.

v Entries that you must fill in appear in this typeface; for example, write filename.v The names of C routines and parameters in the CPLEX Callable Library begin

with CPX and appear in this typeface, for example, CPXcopyobjnames.v The names of C++ classes in the CPLEX Concert Technology Library begin with

Ilo and appear in this typeface, for example, IloCplex.v The names of Java classes begin with Ilo and appear in this typeface, for

example, IloCplex.v The name of a class or method in .NET is written as concatenated words with

the first letter of each word in upper case, for example, IntVar orIntVar.VisitChildren. Generally, accessors begin with the key word Get.Accessors for Boolean members begin with Is. Modifiers begin with Set.

v Combinations of keys from the keyboard are hyphenated. For example, control-cindicates that you should press the control key and the c key simultaneously.The symbol <return> indicates end of line or end of data entry. On somekeyboards, the key is labeled enter or Enter.

Related documentationAdditional documentation is available for CPLEX.

In addition to this introductory manual, the standard distribution of CPLEX comeswith the CPLEX User’s Manual and the CPLEX Reference Manuals. Alldocumentation is available online. It is delivered with the standard distribution ofthe product and accessible through conventional HTML browsers for customers onmost platforms.v The CPLEX User’s Manual explains the relationship between the Interactive

Optimizer and the Component Libraries. It enlarges on aspects of linearprogramming with CPLEX and shows you how to handle quadraticprogramming (QP) problems, quadratically constrained programming (QCP)problems, second order cone programming (SOCP) problems, and mixed integerprogramming (MIP) problems. It tells you how to control CPLEX parameters,debug your applications, and efficiently manage input and output. It alsoexplains how to use parallel CPLEX optimizers.

v The CPLEX Callable Library Reference Manual documents the Callable Libraryroutines and their arguments. This manual also includes additionaldocumentation about error codes, solution quality, and solution status.

v The CPLEX C++ API Reference Manual documents the C++ API of the ConcertTechnology classes, methods, and functions.

v The CPLEX Java API Reference Manual supplies detailed definitions of theConcert Technology interfaces and CPLEX Java classes.

v The CPLEX .NET Reference Manual documents the .NET API for CPLEX.v The CPLEX Python API Reference Manual documents the Python API for CPLEX.v The reference manual CPLEX Parameters contains documentation of parameters

that can be modified by parameter routines. It is the definitive reference manualfor the purpose and allowable settings of CPLEX parameters.

v The reference manual CPLEX File Formats contains a list of file formats thatCPLEX supports as well as details about using them in your applications.

x Getting Started with CPLEX

Page 11: Ibm Ilog Cplex User Manual 12.6

v The reference manual CPLEX Interactive Optimizer contains the commands of theInteractive Optimizer, along with the command options and links to examples oftheir use in the CPLEX User’s Manual.

v A suite of documentation, including a user's manual and language referencemanual, is available for the CPLEX connector for MATLAB. This documentation isavailable either interactively within a MATLAB session or online.

As you work with CPLEX on a long-term basis, you should read the completeUser’s Manual to learn how to design models and implement solutions to your ownproblems. Consult the reference manuals for authoritative documentation of theComponent Libraries, their application programming interfaces (APIs), and theInteractive Optimizer.

Introducing CPLEX xi

Page 12: Ibm Ilog Cplex User Manual 12.6

xii Getting Started with CPLEX

Page 13: Ibm Ilog Cplex User Manual 12.6

Chapter 1. Setting up CPLEX

To set up CPLEX for your particular platform or integrated developmentenvironment, and to check your set up, follow these steps.

Installing CPLEXCPLEX is installed as a feature of IBM ILOG CPLEX Optimization Studio.

After you successfully install IBM ILOG CPLEX Optimization Studio, all of thefacilities of CPLEX, a feature of IBM ILOG CPLEX Optimization Studio, becomefunctional and are available to you.

This topic directs you to more information about settings specific to your platformor integrated development environment.v “Setting up CPLEX on Windows”v “Setting up Eclipse for the Java API of CPLEX” on page 4v “Setting up the Python API of CPLEX” on page 5

Other topics provide Tutorials in the use of each of the components that CPLEXprovides: the Interactive Optimizer tutorial, the Concert Technology tutorials forC++, Java, and .NET users, the Callable Library tutorial for C and other languagescallable from C, as well as the tutorials for users of Python or the Microsoft SolverFoundation (MSF). More extensive documentation for the CPLEX connector toMicrosoft Excel and for the CPLEX connector to MATLAB is available as onlinehelp inside sessions of those products.

Important:

Remember that most distributions of the product operate correctly only on thespecific platform and operating system for which they are designed. If youupgrade your operating system, you may need to obtain a new distribution of theproduct. In that case, contact your IBM representative for advice.

Setting up CPLEX on WindowsYou can customize your installation of CPLEX for use on Microsoft Windows.

Normally, the installer you receive from IBM installs CPLEX correctly for you; thistopic highlights customization for users of Microsoft Windows.

Tip:

The CPLEX library on Windows is a DLL file. The name of the CPLEX DLL lookslike this: cplexXXX.dll where XXX represents the current version number.

Make sure that your application has read and execute permission for both theCPLEX DLL and the directory where it is located. In other words, set the correctauthorizations on both the CPLEX DLL and the folder where it resides for yourapplication to read and execute.

© Copyright IBM Corp. 1987, 2013 1

Page 14: Ibm Ilog Cplex User Manual 12.6

After your installation of IBM ILOG CPLEX Optimization Studio, if yourapplications are not able to find the DLL for CPLEX at runtime, then you mayneed to identify its location for them. On Windows, there are alternative ways todo so, either through the operating system or in an integrated developmentenvironment (IDE).v At the operating system, you can add the location of cplexXXX.dll to the

environment variable PATH.After you extend the environment variable at the level of the operating systemlike this, all applications that are aware of the PATH environment variable willknow where to find your CPLEX DLL. The topic “Adding your CPLEX DLL tothe environment variable on Windows” explains this alternative in detail.

v In Visual Studio, you can link the location of cplexXXX.dll to the properties ofthe project.After you add your CPLEX DLL to the Linker Path of your Visual Studio projectlike this, your Project will know where to find your CPLEX DLL. The topic“Linking your CPLEX DLL to the properties of your project in Visual Studio”explains this alternative in detail.

Adding your CPLEX DLL to the environment variable onWindows1. From the Start menu, select Control Panel.2. In the Control Panel, select System.3. In the System dialog, select the Advanced tab.4. On the Advanced tab, click the Environment Variables button.5. Add or extend the PATH environment variable. If the PATH environment variable

already exists, extend it, like this:Name: PATHValue: %PATH%;C:\yourCPLEXhome\CPLEXXXX\bin\x86_win32

where XXX represents the current version number and yourCPLEXhome representsthe folder where you installed CPLEX.

6. Restart Visual Studio and other applications for this change in the operatingsystem to take effect.

Linking your CPLEX DLL to the properties of your project inVisual Studio1. In Visual Studio, right-click your project.2. Select Properties of the project.3. Among the Properties of the project, go to the Linker section.4. In the Linker section, add the name of the folder containing the CPLEX DLL

file to the Linker Path.5. Save the properties of your project.

Setting up CPLEX on GNU/LinuxYou can customize your installation of CPLEX for C or C++ applications.

Normally, the installer you receive from IBM installs CPLEX correctly for you. Thistopic highlights customization by users of GNU/Linux, UNIX, and similaroperating systems for C and C++ applications. For similar hints about setting upfor Java applications, see the topic “Setting up Eclipse for the Java API of CPLEX”on page 4. Likewise, for hints about setting up for Python applications, see the

2 Getting Started with CPLEX

Page 15: Ibm Ilog Cplex User Manual 12.6

topic “Setting up the Python API of CPLEX” on page 5. For hints about setting upfor .NET applications in Microsoft Visual Studio, see the topic “Linking yourCPLEX DLL to the properties of your project in Visual Studio” on page 2.

CPLEX is delivered with an assortment of sample make files that accompany theexamples delivered with the product. As you design your own make files for yourCPLEX applications, it is a good idea to start from one of those sample make filesand adapt it as needed.

If you are writing a make file “from scratch” consider these questions:v Where did you install CPLEX? In this topic, for purposes of illustration, assume

the product was installed in /path/to/cplex/cplexXX/ where XX designates theversion number.

v What is your architecture? That is, what is your combination of operating systemand compiler? In this topic, for purposes of illustration, assume the architectureis archi/tecture.

With answers to those questions, now consider options for your compiler andlinker. These options vary slightly according to whether you target C or C++applications because C++ applications need the Concert include files and library aswell as the CPLEX include files and library.

Compiler options

For C applications:v Tell your compiler where to find the include directory for CPLEX Callable

Library (C API) by means of the option -I and the path to the C header files,like this, substituting the correct path of your installation and the correct versionnumber:-I/path/to/cplex/cplexXX/include

v Give your compiler a preprocessor directive by means of the option -D, like this:-DIL_STD

For C++ applications:v Tell your compiler where to find the include directory for both CPLEX C++ API

and Concert C++ API, substituting the correct path of your installation and thecorrect version number, like this:-I/path/to/cplex/cplexXX/include

-I/path/to/cplex/concertYY/include

v Give your compiler a preprocessor directive by means of the option -D, like this:-DIL_STD

Linker options

For C applications:v Tell your linker where to search for the library, like this, substituting the correct

path of your installation and the correct version number:-L/path/to/cplex/cplexXX/lib/archi/tecture

v Specify the library to your linker, like this:-lcplex -lm -lpthread

For C++ applications:

Chapter 1. Setting up CPLEX 3

Page 16: Ibm Ilog Cplex User Manual 12.6

v Tell your linker where to search for both the CPLEX and Concert libraries, likethis, substituting the correct path of your installation and the correct versionnumbers:-L/path/to/cplex/cplexXX/lib/archi/tecture

-L/path/to/cplex/concertYY/lib/archi/tecture

v Specify the libraries to your linker, like this:-lilocplex -lconcert

Here is the correct order of the builds of the libraries:-lilocplex -lconcert -lcplex -lm -lpthread

Setting up Eclipse for the Java API of CPLEXRegardless of platform, you can make Eclipse aware of the Java API of CPLEX.

To make your Eclipse integrated development environment aware of the Java APIof CPLEX, follow these steps.1. Either import an existing project, or create a new Java project.

To import an existing Java project, first click File > Import .... When Selectopens, expand the General folder. Within the General folder, select ExistingProjects into Workspace.To create a new Java project, click File > New ... > Java Project.

2. To include the CPLEX JAR in your project, locate the libraries among theproperties of the project, like this:Project > Properties > Java Build Path > Libraries

3. Click the button Add External JARs.4. Browse to the location of your CPLEX installation and select the file named

cplex.jar.

Tip:

Be sure to point to the CPLEX JAR, cplex.jar, not simply the folder or directorycontaining that file. Conventionally, the CPLEX JAR is in the lib directory of yourCPLEX home, part of the installation of IBM ILOG CPLEX Optimization Studio.

After that procedure, you can create and compile your source code making use ofthe Java API of CPLEX.

Before you can run your compiled code, you must create an appropriate runconfiguration in Eclipse or modify an existing run configuration appropriately. Todo so, follow these steps.1. Create a new run configuration or locate an existing run configuration to

modify, like this:Run > Run Configurations ... > Java Application

2. When the dialog appears, go to the Main tab, and select your main class; thatis, select the class containing the main() function that you want to run.

3. Go to the Arguments tab, select VM arguments, and add the path to theCPLEX library. The CPLEX library is conventionally a DLL file on Windows ora .so file on UNIX or GNU/Linux, with an indication of the version number inits name, like cplexXX.dll or cplexXX.so where XX represents a versionnumber of the product.

Tip:

4 Getting Started with CPLEX

Page 17: Ibm Ilog Cplex User Manual 12.6

Add the path to the directory or folder containing the CPLEX library (not thename of the file itself).For example, on UNIX or GNU/Linux , if the file libcplexXX.so is located inthe directory COSinstallation/cplex/bin/myPlatform/myLibFormat then add apath similar to this example:-Djava.library.path= COSinstallation/cplex/myPlatform/myLibFormat

Similarly, on Windows, if the file cplexXX.dll is located in the folderCOSinstallation\cplex\myPlatform\myLibFormat then add a path similar to thisexample:-Djava.library.path=COSinstallation/cplex/myPlatform/myLibFormat

After these steps, you can run your Java application using CPLEX as you run otherapplications from Eclipse.

Setting up the Python API of CPLEXThe Python API of CPLEX is part of IBM ILOG CPLEX Optimization Studio.

The modules associated with the CPLEX Python API reside in the directoryyourCPLEXhome/python/PLATFORM, (or in the folder yourCPLEXhome\python\PLATFORM)where yourCPLEXhome specifies the location where CPLEX is installed as part ofIBM ILOG CPLEX Optimization Studio, and PLATFORM stands for your combinationof operating system and compiler.

There are two alternative ways to set up the Python API of CPLEX.v The most common way is to use the script setup.py located in the directory

yourCPLEXhome/python/PLATFORM (or in the folder yourCPLEXhome\python\PLATFORM).

v Alternatively, you can set the environment variable PYTHONPATH toyourCPLEXhome/python/PLATFORM and start running Python scripts with CPLEX.

Both of these methods are detailed further in the following paragraphs.

Using the script setup.py

To install the CPLEX-Python modules on your system, use the script setuy.pylocated in yourCplexhome/python/PLATFORM. If you want to install theCPLEX-Python modules in a nondefault location, use the option --home to identifythe installation directory. For example, to install the CPLEX-Python modules in thedefault location, use the following command from the command line:python setup.py install

To install in the directory yourPythonPackageshome/cplex, use the followingcommand from the command line:python setup.py install --home yourPythonPackageshome/cplex

Both of those commands (default and home-specified) invoke the Python packagedistutils. For other options available with that package, consult thedocumentation of Python distutils.

Chapter 1. Setting up CPLEX 5

Page 18: Ibm Ilog Cplex User Manual 12.6

Setting the environment variable PYTHONPATH

If you maintain multiple versions of CPLEX, or if you run multiple versions ofCPLEX side-by-side, then use this way of declaring the location of CPLEX and itsPython API to your Python installation by means of the environment variablePYTHONPATH.

To start using the CPLEX Python API, set the Python path environment variablePYTHONPATH to the value of yourCplexhome/python/PLATFORM. Setting thisenvironment variable enables Python to find the CPLEX modules that it needs torun Python commands and scripts that use the CPLEX Python API.

Next steps

After setting up your Python environment by means of one of those alternativemethods, you can proceed to the topic “Starting the CPLEX Python API” on page97.

Directory structure of CPLEXYour CPLEX home directory is part of your IBM ILOG CPLEX Optimization Studioinstallation.

After you install IBM ILOG CPLEX Optimization Studio, you find CPLEX in astructure (such as folders or directories) like the one in the illustrations Figure 1 onpage 7 and Figure 2 on page 7. This structure is relative to the location where youinstalled IBM ILOG CPLEX Optimization Studio as your COS home, containingyour CPLEX home.

In these illustrations, platform specifies the combination of operating system andchip architecture (such as 32- or 64-bit) Likewise, libformat specifies library formatand compiler options, such as static, position-independent, and so forth.

6 Getting Started with CPLEX

Page 19: Ibm Ilog Cplex User Manual 12.6

Using the Component LibrariesExamples provided with CPLEX help you check your installation.

Figure 1. Structure of the CPLEX directory

Figure 2. Structure of the Concert Technology Directory

Chapter 1. Setting up CPLEX 7

Page 20: Ibm Ilog Cplex User Manual 12.6

After you have completed the installation, you can verify that everything isworking by running one or more of the examples that are provided with thestandard distribution.

Verifying set-up on UNIX

On a UNIX system, go to the subdirectory examples/platform/libformat that matchesyour particular platform of operating system and compiler. In that directory, youwill find a file named Makefile. Execute one of the examples, for instance lpex1.c ,by trying this sequence of commands:

make lpex1

lpex1 -r

This example takes one argument, either -r , -c , or -n .

If your interest is in running one of the C++ examples, try this sequence ofcommands to execute a comparable example in C++:

make ilolpex1

ilolpex1 -r

If your interest is in running one of the Java examples, try this sequence ofcommands:

make LPex1.class

java -Djava.library.path=../../../bin/platform: \

-classpath ../../../lib/cplex.jar: LPex1 -r

where platform represents the machine and library format

Any of these examples, whether C, C++, or Java, should return an optimalobjective function value of 202.5.

Verifying set-up on Windows

On a Windows machine, you can follow a similar process using the facilities ofyour compiler interface to compile and then run any of the examples. A project filefor each example is provided, in a format for Microsoft Visual Studio.

To run the examples on Windows, either you must copy the CPLEX DLL file to thedirectory or folder containing the examples, or you must make sure that thelocation of the DLL file is part of your Windows path, as explained in “Setting upCPLEX on Windows” on page 1.

In case of errors

If an error occurs during the steps to make or to compile, then check that you areable to access the compiler and the necessary linker/loader files and systemlibraries. If an error occurs on the next step, when executing the program createdby make, then the nature of the error message will guide your actions. ForWindows users, if the program has trouble locating cplex XXX .dll or

8 Getting Started with CPLEX

Page 21: Ibm Ilog Cplex User Manual 12.6

ILOG.CPLEX.dll, make sure the DLL file is stored either in the current directory orin a directory listed in your PATH environment variable.

The UNIX Makefile, or Windows project file, contains useful information regardingrecommended flags and other settings for compilation and linking.

Compiling and linking your own applications

The source files for the examples and the makefiles provide guidance for howyour own application can call CPLEX. The following topics give more specificinformation about the necessary header files for compilation, and how to linkCPLEX and Concert Technology libraries into your application.v Chapter 4, “Concert Technology tutorial for C++ users,” on page 49 contains

information and platform-specific instructions for compiling and linking theConcert Technology Library, for C++ users.

v Chapter 5, “Concert Technology tutorial for Java users,” on page 65 containsinformation and platform-specific instructions for compiling and linking theConcert Technology Library, for Java users.

v Chapter 6, “Concert Technology tutorial for .NET users,” on page 75 offers anexample of a C#.NET application.

v Chapter 7, “Callable Library tutorial,” on page 83 contains information andplatform-specific instructions for compiling and linking the Callable Library.

v Chapter 8, “Python tutorial,” on page 97 contains information about usingconventional Python utilities, such as disutils, and instructions for launchingan interactive Python session.

Chapter 1. Setting up CPLEX 9

Page 22: Ibm Ilog Cplex User Manual 12.6

10 Getting Started with CPLEX

Page 23: Ibm Ilog Cplex User Manual 12.6

Chapter 2. Solving an LP with CPLEX

This example solves an LP model to contrast CPLEX components.

OverviewThis example shows ways available in CPLEX to solve a linear programmingproblem.

To help you learn which IBM ILOG CPLEX component best meets your needs, thischapter briefly demonstrates how to create and solve an LP model. It shows you ata glance the Interactive Optimizer and the application programming interfaces(APIs) to CPLEX. Full details of writing a practical program are in the topicscontaining the tutorials.

Problem statementThis linear programming model in a standard formulation can be solved in each ofthe components of CPLEX.

The problem to be solved is:

Maximize x 1 + 2x 2 + 3x 3

subject to–x 1 + x 2 + x 3 ≤ 20

x 1 – 3x 2 + x 3 ≤ 30with these bounds

0 ≤ x1 ≤ 40

0 ≤ x2 ≤ infinity

0 ≤ x3 ≤ infinity

Using the Interactive OptimizerThe Interactive Optimizer solves the model in this way.

The following sample is screen output from a CPLEX Interactive Optimizer sessionwhere the model of an example is entered and solved. CPLEX> indicates the CPLEXprompt, and text following this prompt is user input.Welcome to IBM(R) ILOG(R) CPLEX(R) Interactive Optimizer 12.6.0.0

with Simplex, Mixed Integer & Barrier OptimizersCopyright IBM Corp. 1988, 2013 All Rights Reserved.

Type ’help’ for a list of available commands.Type ’help’ followed by a command name for moreinformation on commands.

CPLEX> enter exampleEnter new problem [’end’ on a separate line terminates]:maximize x1 + 2 x2 + 3 x3subject to -x1 + x2 + x3 <= 20

x1 - 3 x2 + x3 <=30bounds0 <= x1 <= 40

© Copyright IBM Corp. 1987, 2013 11

Page 24: Ibm Ilog Cplex User Manual 12.6

0 <= x20 <= x3endCPLEX> optimizeTried aggregator 1 time.No LP presolve or aggregator reductions.Presolve time = 0.00 sec. (0.00 ticks)

Iteration log . . .Iteration: 1 Dual infeasibility = 0.000000Iteration: 2 Dual objective = 202.500000

Dual simplex - Optimal: Objective = 2.0250000000e+002Solution time = 0.01 sec. Iterations = 2 (1)Deterministic time = 0.00 ticks (3.38 ticks/sec)

CPLEX> display solution variables x1-x3Variable Name Solution Valuex1 40.000000x2 17.500000x3 42.500000CPLEX> quit

Using Concert Technology in C++This C++ application solves the model in this way.

Here is a C++ application using CPLEX in Concert Technology to solve theexample. An expanded form of this example is discussed in detail in Chapter 4,“Concert Technology tutorial for C++ users,” on page 49.#include <ilcplex/ilocplex.h>ILOSTLBEGIN

intmain (int argc, char **argv){

IloEnv env;try {

IloModel model(env);IloNumVarArray vars(env);vars.add(IloNumVar(env, 0.0, 40.0));vars.add(IloNumVar(env));vars.add(IloNumVar(env));

model.add(IloMaximize(env, vars[0] + 2 * vars[1] + 3 * vars[2]));model.add( - vars[0] + vars[1] + vars[2] <= 20);model.add( vars[0] - 3 * vars[1] + vars[2] <= 30);

IloCplex cplex(model);if ( !cplex.solve() ) {

env.error() << "Failed to optimize LP." << endl;throw(-1);

}

IloNumArray vals(env);env.out() << "Solution status = " << cplex.getStatus() << endl;env.out() << "Solution value = " << cplex.getObjValue() << endl;cplex.getValues(vals, vars);env.out() << "Values = " << vals << endl;

}catch (IloException& e) {

cerr << "Concert exception caught: " << e << endl;}catch (...) {

cerr << "Unknown exception caught" << endl;}

12 Getting Started with CPLEX

Page 25: Ibm Ilog Cplex User Manual 12.6

env.end();

return 0;}

Using Concert Technology in JavaThis Java application solves the model in this way.

Here is a Java application using CPLEX with Concert Technology to solve theexample. An expanded form of this example is discussed in detail in Chapter 5,“Concert Technology tutorial for Java users,” on page 65.import ilog.concert.*;import ilog.cplex.*;

public class Example {public static void main(String[] args) {

try {IloCplex cplex = new IloCplex();

double[] lb = {0.0, 0.0, 0.0};double[] ub = {40.0, Double.MAX_VALUE, Double.MAX_VALUE};IloNumVar[] x = cplex.numVarArray(3, lb, ub);

double[] objvals = {1.0, 2.0, 3.0};cplex.addMaximize(cplex.scalProd(x, objvals));

cplex.addLe(cplex.sum(cplex.prod(-1.0, x[0]),cplex.prod( 1.0, x[1]),cplex.prod( 1.0, x[2])), 20.0);

cplex.addLe(cplex.sum(cplex.prod( 1.0, x[0]),cplex.prod(-3.0, x[1]),cplex.prod( 1.0, x[2])), 30.0);

if ( cplex.solve() ) {cplex.output().println("Solution status = " + cplex.getStatus());cplex.output().println("Solution value = " + cplex.getObjValue());

double[] val = cplex.getValues(x);int ncols = cplex.getNcols();for (int j = 0; j < ncols; ++j)

cplex.output().println("Column: " + j + " Value = " + val[j]);}cplex.end();

}catch (IloException e) {

System.err.println("Concert exception ’" + e + "’ caught");}

}}

Using Concert Technology in .NETThis C#.NET application solves the model in this way..

Here is a C#NET application using Concert Technology with CPLEX to solve theexample. A tutorial offering an expanded version of this application is available inChapter 6, “Concert Technology tutorial for .NET users,” on page 75.using ILOG.Concert;using ILOG.CPLEX;public class Example {

public static void Main(string[] args) {

Chapter 2. Solving an LP with CPLEX 13

Page 26: Ibm Ilog Cplex User Manual 12.6

try {Cplex cplex = new Cplex();double[] lb = {0.0, 0.0, 0.0};double[] ub = {40.0, System.Double.MaxValue, System.Double.MaxValue};INumVar[] x = cplex.NumVarArray(3, lb, ub);var[0] = x;double[] objvals = {1.0, 2.0, 3.0};cplex.Add(cplex.Maximize(cplex.ScalProd(x, objvals)));rng[0] = new IRange[2];rng[0][0] = cplex.AddRange(-System.Double.MaxValue, 20.0);rng[0][1] = cplex.AddRange(-System.Double.MaxValue, 30.0);rng[0][0].Expr = cplex.Sum(cplex.Prod(-1.0, x[0]),

cplex.Prod( 1.0, x[1]),cplex.Prod( 1.0, x[2]));

rng[0][1].Expr = cplex.Sum(cplex.Prod( 1.0, x[0]),cplex.Prod(-3.0, x[1]),cplex.Prod( 1.0, x[2]));

x[0].Name = "x1";x[1].Name = "x2";x[2].Name = "x3";rng[0][0].Name = "c1";rng[0][0].Name = "c2";cplex.ExportModel("example.lp");if ( cplex.Solve() ) {

double[] x = cplex.GetValues(var[0]);double[] dj = cplex.GetReducedCosts(var[0]);double[] pi = cplex.GetDuals(rng[0]);double[] slack = cplex.GetSlacks(rng[0]);cplex.Output().WriteLine("Solution status = " + cplex.GetStatus());cplex.Output().WriteLine("Solution value = " + cplex.ObjValue);int nvars = x.Length;for (int j = 0; j < nvars; ++j) {

cplex.Output().WriteLine("Variable " + j +": Value = " + x[j] +" Reduced cost = " + dj[j]);

}int ncons = slack.Length;for (int i = 0; i < ncons; ++i) {

cplex.Output().WriteLine("Constraint " + i +": Slack = " + slack[i] +" Pi = " + pi[i]);

}}cplex.End();

}catch (ILOG.Concert.Exception e) {

System.Console.WriteLine("Concert exception '" + e + "' caught");}

}}

Using the Callable LibraryThis C application solves the model in this way..

Here is a C application using the CPLEX Callable Library to solve the example. Anexpanded form of this example is discussed in detail in Chapter 7, “CallableLibrary tutorial,” on page 83.#include <ilcplex/cplex.h>#include <stdlib.h>#include <string.h>

#define NUMROWS 2#define NUMCOLS 3#define NUMNZ 6

14 Getting Started with CPLEX

Page 27: Ibm Ilog Cplex User Manual 12.6

intmain (int argc, char **argv){

int status = 0;CPXENVptr env = NULL;CPXLPptr lp = NULL;

double obj[NUMCOLS];double lb[NUMCOLS];double ub[NUMCOLS];double x[NUMCOLS];int rmatbeg[NUMROWS];int rmatind[NUMNZ];double rmatval[NUMNZ];double rhs[NUMROWS];char sense[NUMROWS];

int solstat;double objval;

env = CPXopenCPLEX (&status);if ( env == NULL ) {

char errmsg[1024];fprintf (stderr, "Could not open CPLEX environment.\n");CPXgeterrorstring (env, status, errmsg);fprintf (stderr, "%s", errmsg);goto TERMINATE;

}

lp = CPXcreateprob (env, &status, "lpex1");if ( lp == NULL ) {

fprintf (stderr, "Failed to create LP.\n");goto TERMINATE;

}

CPXchgobjsen (env, lp, CPX_MAX);

obj[0] = 1.0; obj[1] = 2.0; obj[2] = 3.0;lb[0] = 0.0; lb[1] = 0.0; lb[2] = 0.0;ub[0] = 40.0; ub[1] = CPX_INFBOUND; ub[2] = CPX_INFBOUND;

status = CPXnewcols (env, lp, NUMCOLS, obj, lb, ub, NULL, NULL);if ( status ) {

fprintf (stderr, "Failed to populate problem.\n");goto TERMINATE;

}

rmatbeg[0] = 0;rmatind[0] = 0; rmatind[1] = 1; rmatind[2] = 2; sense[0] = ’L’;rmatval[0] = -1.0; rmatval[1] = 1.0; rmatval[2] = 1.0; rhs[0] = 20.0;

rmatbeg[1] = 3;rmatind[3] = 0; rmatind[4] = 1; rmatind[5] = 2; sense[1] = ’L’;rmatval[3] = 1.0; rmatval[4] = -3.0; rmatval[5] = 1.0; rhs[1] = 30.0;

status = CPXaddrows (env, lp, 0, NUMROWS, NUMNZ, rhs, sense, rmatbeg,rmatind, rmatval, NULL, NULL);

if ( status ) {fprintf (stderr, "Failed to populate problem.\n");goto TERMINATE;

}

status = CPXlpopt (env, lp);if ( status ) {

fprintf (stderr, "Failed to optimize LP.\n");goto TERMINATE;

}

Chapter 2. Solving an LP with CPLEX 15

Page 28: Ibm Ilog Cplex User Manual 12.6

status = CPXsolution (env, lp, &solstat, &objval, x, NULL, NULL, NULL);if ( status ) {

fprintf (stderr, "Failed to obtain solution.\n");goto TERMINATE;

}printf ("\nSolution status = %d\n", solstat);printf ("Solution value = %f\n", objval);printf ("Solution = [%f, %f, %f]\n\n", x[0], x[1], x[2]);

TERMINATE:

if ( lp != NULL ) {status = CPXfreeprob (env, &lp);if ( status ) {

fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status);}

}

if ( env != NULL ) {status = CPXcloseCPLEX (&env);if ( status ) {

char errmsg[1024];fprintf (stderr, "Could not close CPLEX environment.\n");CPXgeterrorstring (env, status, errmsg);fprintf (stderr, "%s", errmsg);

}}

return (status);

} /* END main */

Using the Python APIThis Python application solves the model in this way.

Here is a Python application using CPLEX to solve the example.execfile("cplexpypath.py")

import cplexfrom cplex.exceptions import CplexErrorimport sys

# data common to all populateby functionsmy_obj = [1.0, 2.0, 3.0]my_ub = [40.0, cplex.infinity, cplex.infinity]my_colnames = ["x1", "x2", "x3"]my_rhs = [20.0, 30.0]my_rownames = ["c1", "c2"]my_sense = "LL"

def populatebyrow(prob):prob.objective.set_sense(prob.objective.sense.maximize)

# since lower bounds are all 0.0 (the default), lb is omitted hereprob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames)

# can query variables like the following bounds and names:

# lbs is a list of all the lower boundslbs = prob.variables.get_lower_bounds()

# ub1 is just the first lower boundub1 = prob.variables.get_upper_bounds(0)

16 Getting Started with CPLEX

Page 29: Ibm Ilog Cplex User Manual 12.6

# names is ["x1", "x3"]names = prob.variables.get_names([0, 2])

rows = [[[0,"x2","x3"],[-1.0, 1.0,1.0]],[["x1",1,2],[ 1.0,-3.0,1.0]]]

prob.linear_constraints.add(lin_expr = rows, senses = my_sense,rhs = my_rhs, names = my_rownames)

# because there are two arguments, they are taken to specify a range# thus, cols is the entire constraint matrix as a list of column vectorscols = prob.variables.get_cols("x1", "x3")

def populatebycolumn(prob):prob.objective.set_sense(prob.objective.sense.maximize)

prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)

c = [[[0,1],[-1.0, 1.0]],[["c1",1],[ 1.0,-3.0]],[[0,"c2"],[ 1.0, 1.0]]]

prob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames,columns = c)

def populatebynonzero(prob):prob.objective.set_sense(prob.objective.sense.maximize)

prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)

prob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames)

rows = [0,0,0,1,1,1]cols = [0,1,2,0,1,2]vals = [-1.0,1.0,1.0,1.0,-3.0,1.0]

prob.linear_constraints.set_coefficients(zip(rows, cols, vals))# can also change one coefficient at a time

# prob.linear_constraints.set_coefficients(1,1,-3.0)# or pass in a list of triples# prob.linear_constraints.set_coefficients([(0,1,1.0), (1,1,-3.0)])

def lpex1(pop_method):try:

my_prob = cplex.Cplex()

if pop_method == "r":handle = populatebyrow(my_prob)

if pop_method == "c":handle = populatebycolumn(my_prob)

if pop_method == "n":handle = populatebynonzero(my_prob)

my_prob.solve()except CplexError, exc:

print excreturn

numrows = my_prob.linear_constraints.get_num()numcols = my_prob.variables.get_num()

print

Chapter 2. Solving an LP with CPLEX 17

Page 30: Ibm Ilog Cplex User Manual 12.6

# solution.get_status() returns an integer codeprint "Solution status = " , my_prob.solution.get_status(), ":",# the following line prints the corresponding stringprint my_prob.solution.status[my_prob.solution.get_status()]print "Solution value = ", my_prob.solution.get_objective_value()slack = my_prob.solution.get_linear_slacks()pi = my_prob.solution.get_dual_values()x = my_prob.solution.get_values()dj = my_prob.solution.get_reduced_costs()for i in range(numrows):

print "Row %d: Slack = %10f Pi = %10f" % (i, slack[i], pi[i])for j in range(numcols):

print "Column %d: Value = %10f Reduced cost = %10f" % (j, x[j], dj[j])

my_prob.write("lpex1.lp")

if __name__ == "__main__":if len(sys.argv) != 2 or sys.argv[1] not in ["-r", "-c", "-n"]:

print "Usage: lpex1.py -X"print " where X is one of the following options:"print " r generate problem by row"print " c generate problem by column"print " n generate problem by nonzero"print " Exiting..."sys.exit(-1)

lpex1(sys.argv[1][1])else:

prompt = """Enter the letter indicating how the problem data should be populated:r : populate by rowsc : populate by columnsn : populate by nonzeros\n ? > """r = ’r’c = ’c’n = ’n’lpex1(input(prompt))

18 Getting Started with CPLEX

Page 31: Ibm Ilog Cplex User Manual 12.6

Chapter 3. Interactive Optimizer tutorial

The major features of the CPLEX Interactive Optimizer are introduced in thistutorial.

Starting CPLEXThe start command launches the Interactive Optimizer.

Procedure

To start the CPLEX Interactive Optimizer, at your operating system prompt typethe command:cplex

A message similar to the following one appears on the screen:Welcome to CPLEX Interactive Optimizer 12.6.0

with Simplex, Mixed Integer, & Barrier OptimizersCopyright (c) IBM 1997-2013CPLEX is a registered trademark of IBM(r)

Type help for a list of available commands.Type help followed by a command name for moreinformation on commands.

CPLEX>

Results

The last line, CPLEX> , is the prompt, showing that the product is running and isready to accept one of the available CPLEX commands. Use the help command tosee a list of these commands.

Using helpThe help command invokes help in the Interactive Optimizer.

About this task

CPLEX accepts commands in several different formats. You can type either the fullcommand name, or any shortened form that uniquely identifies that name.

Procedure

For example, enter help after the CPLEX> prompt, as shown:CPLEX> help

You will see a list of the CPLEX commands on the screen.Since all commands start with a unique letter, you could also enter just the singleletter h .CPLEX> h

© Copyright IBM Corp. 1987, 2013 19

Page 32: Ibm Ilog Cplex User Manual 12.6

CPLEX does not distinguish between upper- and lower-case letters, so you couldenter h , H , help , or HELP. All of these variations invoke the help command. Thesame rules apply to all CPLEX commands. You need to type only enough letters ofthe command to distinguish it from all other commands, and it does not matterwhether you type upper- or lower-case letters. This manual uses lower-case letters.

Results

After you type the help command, a list of available commands with theirdescriptions appears on the screen, like this:add add constraints to the problembaropt solve using barrier algorithmchange change the problemconflict refine a conflict for an infeasible problemdisplay display problem, solution, or parameter settingsenter enter a new problemfeasopt find relaxation to an infeasible problemhelp provide information on CPLEX commandsmipopt solve a mixed integer programnetopt solve the problem using network methodoptimize solve the problempopulate get additional solutions for a mixed integer programprimopt solve using the primal methodquit leave CPLEXread read problem or advanced start information from a fileset set parameterstranopt solve using the dual methodtune try a variety of parameter settingswrite write problem or solution information to a filexecute execute a command from the operating system

Enter enough characters to uniquely identify commands & options. Commands can beentered partially (CPLEX will prompt you for further information) or as

To find out more about a specific command, type help followed by the name ofthat command. For example, to learn more about the primopt command type:help primopt

Typing the full name is unnecessary. Alternatively, you can try:h p

The following message appears to tell you more about the use and syntax of theprimopt command:The PRIMOPT command solves the current problem usinga primal simplex method or crosses over to a basic solutionif a barrier solution exists.

Syntax: PRIMOPT

A problem must exist in memory (from using either theENTER or READ command) in order to use the PRIMOPTcommand.

Sensitivity information (dual price and reduced-costinformation) as well as other detailed information aboutthe solution can be viewed using the DISPLAY command,after a solution is generated.

The syntax for the help command is:help command name

20 Getting Started with CPLEX

Page 33: Ibm Ilog Cplex User Manual 12.6

Entering a problemThe Interactive Optimizer offers a variety of ways to enter a problem.

OverviewThe Interactive Optimizer supports manual entry of data for a problem.

Most users with larger problems enter problems by reading data from formattedfiles. That practice is explained in “Reading problem files” on page 36. For now,you will enter a smaller problem from the keyboard by using the enter command.The process is outlined step-by-step in the following topics.

Entering the exampleThis example appears throughout this tutorial about the Interactive Optimizer.

As an example, this manual uses the following problem:

Maximize x 1 + 2x 2 + 3x 3

subject to–x1 + x2 + x3 ≤ 20

x1 – 3x2 + x3 ≤ 30with these bounds

0 ≤ x1 ≤ 40

0 ≤ x2 ≤ infinity

0 ≤ x3 ≤ infinity

This problem has three variables (x1, x2, and x3) and two less-than-or-equal-toconstraints.

The enter command is used to enter a new problem from the keyboard. Theprocedure is almost as simple as typing the problem on a page. At the CPLEX>prompt type:enter

A prompt appears on the screen asking you to give a name to the problem thatyou are about to enter.

Naming a problem

The problem name may be anything that is allowed as a file name in youroperating system. If you decide that you do not want to enter a new problem, justpress the <return> key without typing anything. The CPLEX> prompt will reappearwithout causing any action. The same can be done at any CPLEX> prompt. If you donot want to complete the command, simply press the <return> key. For now, typein the name example at the prompt.Enter name for problem: example

The following message appears:Enter new problem [’end’ on a separate line terminates]:

and the cursor is positioned on a blank line below it where you can enter the newproblem.

Chapter 3. Interactive Optimizer tutorial 21

Page 34: Ibm Ilog Cplex User Manual 12.6

You can also type the problem name directly after the enter command and avoidthe intermediate prompt.

Summary

The syntax for entering a problem is:enter problem name

Using the LP formatThe Interactive Optimizer supports LP file format to enter a problem.

Entering a new problem is basically like typing it on a page, but there are a fewrules to remember. These rules conform to the CPLEX LP file format and aredocumented in the CPLEX File Formats Reference Manual. LP format appearsthroughout this tutorial.

The problem should be entered in the following order:1. “Objective function”2. “Constraints”3. “Bounds” on page 23

Objective function

Before entering the objective function, you must state whether the problem is aminimization or maximization. For this example, you type:maximizex1 + 2x2 + 3x3

You may type minimize or maximize on the same line as the objective function, butyou must separate them by at least one space.

Variable names

In the example, the variables are named simply x1 , x2 , x3 , but you can giveyour variables more meaningful names such as cars or gallons . The onlylimitations on variable names in LP format are that the names must be no morethan 255 characters long and use only the alphanumeric characters (a-z, A-Z, 0-9)and certain symbols: ! " # $ % & ( ) , . ; ? @ _ ‘ ’ { } ~. Any line with more than 510characters is truncated.

A variable name cannot begin with a number or a period, and there is onecharacter combination that cannot be used: the letter e or E alone or followed by anumber or another e , since this notation is reserved for exponents. Thus, avariable cannot be named e24 nor e9cats nor eels nor any other name with thispattern. This restriction applies only to problems entered in LP format.

Constraints

After you have entered the objective function, you can move on to the constraints.However, before you start entering the constraints, you must indicate that thesubsequent lines are constraints by typing:subject to

or

22 Getting Started with CPLEX

Page 35: Ibm Ilog Cplex User Manual 12.6

st

These terms can be placed alone on a line or on the same line as the first constraintif separated by at least one space. Now you can type in the constraints in thefollowing way:st-x1 + x2 + x3 <= 20x1 - 3x2 + x3 <= 30

Constraint names

In this simple example, it is easy to keep track of the small number of constraints,but for many problems, it may be advantageous to name constraints so that theyare easier to identify. You can do so in CPLEX by typing a constraint name and acolon before the actual constraint. If you do not give the constraints explicit names,CPLEX will give them the default names c1, c2, . . . , cn . In the example, ifyou want to call the constraints time and labor , for example, enter the constraintslike this:sttime: -x1 + x2 + x3 <= 20labor: x1 - 3x2 + x3 <= 30

Constraint names are subject to the same guidelines as variable names. They musthave no more than 255 characters, consist of only allowed characters, and notbegin with a number, a period, or the letter e followed by a positive or negativenumber or another e .

Objective function names

The objective function can be named in the same manner as constraints. Thedefault name for the objective function is obj. CPLEX assigns this name if no otheris entered.

Bounds

Finally, you must enter the lower and upper bounds on the variables. If no boundsare specified, CPLEX will automatically set the lower bound to 0 and the upperbound to +∞. You must explicitly enter bounds only when the bounds differ fromthe default values. In our example, the lower bound on x1 is 0, which is the sameas the default. The upper bound 40, however, is not the default, so you must enterit explicitly. You must type bounds on a separate line before you enter the boundinformation:boundsx1 <= 40

Since the bounds on x2 and x3 are the same as the default bounds, there is no needto enter them. You have finished entering the problem, so to indicate that theproblem is complete, type:end

on the last line.

The CPLEX> prompt returns, indicating that you can again enter a CPLEXcommand.

Chapter 3. Interactive Optimizer tutorial 23

Page 36: Ibm Ilog Cplex User Manual 12.6

Summary

Entering a problem in CPLEX is straightforward, provided that you observe a fewsimple rules:v The terms maximize or minimize must precede the objective function; the term

subject to must precede the constraints section; both must be separated fromthe beginning of each section by at least one space.

v The word bounds must be alone on a line preceding the bounds section.v On the final line of the problem, end must appear.

Entering dataEntering data from the keyboard entails these special considerations.

You can use the <return> key to split long constraints, and CPLEX still interpretsthe multiple lines as a single constraint. When you split a constraint in this way, donot press <return> in the middle of a variable name or coefficient. The followingsequence is acceptable:time: -x1 + x2 + <return>x3 <= 20 <return>labor: x1 - 3x2 + x3 <= 30 <return>

The entry below, however, is incorrect since the <return> key splits a variablename.time: -x1 + x2 + x <return>3 <= 20 <return>labor: x1 - 3x2 + x3 <= 30 <return>

If you type a line that CPLEX cannot interpret, a message indicating the problemwill appear, and the entire constraint or objective function will be ignored. Youmust then re-enter the constraint or objective function.

The final point to remember when you are entering a problem is that after youhave pressed <return> , you can no longer directly edit the characters that precedethe <return>. As long as you have not pressed the <return> key, you can use the<backspace> key to go back and change what you typed on that line. After youpress <return>, you must use the change command to modify the problem. Thechange command is documented in “Changing a problem” on page 41.

Displaying a problemThe Interactive Optimizer displays problems according to your commands.

Verifying a problem with the display commandThe display command in the Interactive Optimizer supports a variety of options.

Now that you have entered a problem using CPLEX, you must verify that theproblem was entered correctly. To do so, use the display command. At the CPLEX>prompt type:display

A list of the items that can be displayed then appears. Some of the options displayparts of the problem description, while others display parts of the problemsolution. Options about the problem solution are not available until after theproblem has been solved. The list looks like this:

24 Getting Started with CPLEX

Page 37: Ibm Ilog Cplex User Manual 12.6

Display Options:

auxiliary display auxiliary information used during optimizationconflict display conflict that demonstrates model infeasibilityproblem display problem characteristicssensitivity display sensitivity analysissettings display parameter settingssolution display existing solution

Display what:

If you type problem in reply to that prompt, that option will list a set of problemcharacteristics, like this:Display Problem Options:

all display entire problembinaries display binary variablesbounds display a set of boundsconstraints display a set of constraints or node supply/demand valuesgenerals display general integer variableshistogram display a histogram of row or column countsindicators display a set of indicator constraintsintegers display integer variablesnames display names of variables or constraintsqpvariables display quadratic variablesqconstraints display quadratic constraintssemi-continuous display semi-continuous and semi-integer variablessos display special ordered setsstats display problem statisticsvariable display a column of the constraint matrix

Display which problem characteristic:

Enter the option all to display the entire problem.Maximizeobj: x1 + 2 x2 + 3 x3Subject Toc1: - x1 + x2 + x3 <= 20c2: x1 - 3 x2 + x3 <= 30Bounds0 <= x1 <= 40All other variables are >= 0.

The default names obj , c1 , c2 , are provided by CPLEX.

If that is what you want, you are ready to solve the problem. If there is a mistake,you must use the change command to modify the problem. The change commandis documented in “Changing a problem” on page 41.

Summary

Display problem characteristics by entering the command:display problem

Displaying problem statisticsThese options for displaying information in the Interactive Optimizer support largeproblems.

When the problem is as small as our example, it is easy to display it on the screen;however, many real problems are far too large to display. For these problems, the

Chapter 3. Interactive Optimizer tutorial 25

Page 38: Ibm Ilog Cplex User Manual 12.6

stats option of the display problem command is helpful. When you select stats ,information about the attributes of the problem appears, but not the entire problemitself. These attributes include:v the number and type of constraintsv variablesv nonzero constraint coefficients

Try this feature by typing:display problem stats

For our example, the following information appears:Problem name: exampleVariables : 3 [Nneg: 2, Box: 1]Objective nonzeros : 3Linear constraints : 2 [Less: 2]

Nonzeros : 6RHS nonzeros : 2

This information tells us that in the example there are two constraints, threevariables, and six nonzero constraint coefficients. The two constraints are both ofthe type less-than-or-equal-to. Two of the three variables have the defaultnonnegativity bounds (0 ≤ x ≤ +∞) and one is restricted to a certain range (a boxvariable). In addition to a constraint matrix nonzero count, there is a count ofnonzero coefficients in the objective function and on the righthand side. Suchstatistics can help to identify errors in a problem without displaying it in itsentirety. The command display problem stats shows this additional informationlike this:Variables : Min LB: 0.000000 Max UB: 40.00000Objective nonzeros : Min : 1.000000 Max : 3.000000Linear constraints :

Nonzeros : Min : 1.000000 Max : 3.000000RHS nonzeros : Min : 20.00000 Max : 30.00000

Another way to avoid displaying an entire problem is to display a specific part ofit by using one of the following three options of the display problem command:v names , documented in “Displaying variable or constraint names” on page 27,

can be used to display a specified set of variable or constraint names;v constraints , documented in “Displaying constraints” on page 28, can be used

to display a specified set of constraints;v bounds , documented in “Displaying bounds” on page 28, can be used to

display a specified set of bounds.

Specifying item rangesThese conventions in notation display ranges of items in the Interactive Optimizer.

For some options of the display command, you must specify the item or range ofitems you want to see. Whenever input defining a range of items is required,CPLEX expects two indices separated by a hyphen (the range character - ). Theindices can be names or matrix index numbers. You simply enter the starting name(or index number), a hyphen ( – ), and finally the ending name (or index number).CPLEX automatically sets the default upper and lower limits defining any range tobe the highest and lowest possible values. Therefore, you have the option ofleaving out either the upper or lower name (or index number) on either side of thehyphen. To see every possible item, you would simply enter –.

26 Getting Started with CPLEX

Page 39: Ibm Ilog Cplex User Manual 12.6

Another way to specify a range of items is to use a wildcard. CPLEX accepts thesewildcards in place of the hyphen to specify a range of items:v question mark (?) for a single character;v asterisk (*) for zero or more characters.

For example, to specify all items, you could enter * (instead of -) if you want.

The sequence of characters c1? matches the name of every constraint in the rangefrom c10 to c19 , for example.

Displaying variable or constraint namesThese options display names of variables or constraints in the InteractiveOptimizer.

You can display a variable name by using the display command with the optionsproblem names variables. If you do not enter the word variables, CPLEX promptsyou to specify whether you wish to see a constraint or variable name.

Type the following command:display problem names variables

In response, CPLEX prompts you to specify a set of variable names to bedisplayed, like this:Display which variable name(s):

Specify these variables by entering the names of the variables or the numberscorresponding to the columns of those variables. A single number can be used or arange such as 1-2 . All of the names can be displayed if you type a hyphen (thecharacter - ). Try this by entering a hyphen at the prompt and pressing the<return> key.Display which variable name(s): -

You could also use a wildcard to display variable names, like this:Display which variable name(s): *

In the example, there are three variables with default names. CPLEX displays thesethree names:x1 x2 x3

If you want to see only the second and third names, you could either enter therange as 2-3 or specify everything following the second variable with 2-. Try thistechnique:display problem names variablesDisplay which variable name(s): 2-x2 x3

If you enter a number without a hyphen, you will see a single variable name:display problem names variablesDisplay which variable name(s): 2x2

Summaryv You can use a wildcard in the display command to specify a range of items.v You can display variable names by entering the command:

Chapter 3. Interactive Optimizer tutorial 27

Page 40: Ibm Ilog Cplex User Manual 12.6

display problem names variables

v You can display constraint names by entering the command:display problem names constraints

Ordering variablesThe Interactive Optimizer respects this internal order among variables.

In the example problem there is a direct correlation between the variable namesand their numbers (x1 is variable 1, x2 is variable 2, etc.); that is not always thecase. The internal ordering of the variables is based on their order of occurrencewhen the problem is entered. For example, if x2 had not appeared in the objectivefunction, then the order of the variables would be x1 , x3 , x2 .

You can see the internal ordering by using the hyphen when you specify the rangefor the variables option. The variables are displayed in the order corresponding totheir internal ordering.

All of the options of the display command can be entered directly after the worddisplay to eliminate intermediate steps. The following command is correct, forexample:display problem names variables 2-3

Displaying constraintsThese options display constraints in the Interactive Optimizer.

To view a single constraint within the matrix, use the command and the constraintnumber. For example, type the following command:display problem constraints 2

The second constraint appears:c2: x1 - 3 x2 + x3 <= 30

You can also use a wildcard to display a range of constraints, like this:display problem constraints *

Displaying the objective functionThese options display an objective function in the Interactive Optimizer.

When you want to display only the objective function, you must enter its name(obj by default) or an index number of 0.display problem constraintsDisplay which constraint name(s): 0Maximize

obj: x1 + 2 x2 + 3 x3

Displaying boundsThese options display bounds of a problem in the Interactive Optimizer.

To see only the bounds for the problem, type the following command (don’t forgetthe hyphen or wildcard):display problem bounds -

or, try a wildcard, like this:

28 Getting Started with CPLEX

Page 41: Ibm Ilog Cplex User Manual 12.6

display problem bounds *

The result is:0 <= x1 <= 40All other variables are >= 0.

Summary

The general syntax of the display command is:display option [option2] identifier - [identifier2]

Displaying a histogram of nonzero countsThese options display a summary of nonzero rows and columns in the InteractiveOptimizer.

For large models, it can sometimes be helpful to see summaries of nonzero countsof the columns or rows of the constraint matrix. This kind of display is known as ahistogram. There are two commands for displaying histograms: one for columns,one for rows.display problem histogram c

display problem histogram r

For the small example in this tutorial, the column histogram looks like this:Column counts (excluding fixed variables):

Nonzero Count: 2Number of Columns: 3

It tells you that there are three columns each having two nonzeroes, and no othercolumns. Similarly, the row histogram of the same small problem looks like this:Row counts (excluding fixed variables):

Nonzero Count: 3Number of Rows: 2

It tells you that there are two rows with three nonzeroes in each of them.

Of course, in a more complex model, there would usually be a wider variety ofnonzero counts than those histograms show. Here is an example in which there aresixteen columns where only one row is nonzero, 756 columns where two rows arenonzero, and so forth.Column counts (excluding fixed variables):Nonzero Count: 1 2 3 4 5 6 15 16Number of Columns: 16 756 1054 547 267 113 2 1

If there has been an error during entry of the problem, perhaps a constraintcoefficient having been omitted by mistake, for example, summaries like these, of amodel where the structure of the constraint matrix is known, may help you findthe source of the error.

Solving a problemThese commands solve a problem in the Interactive Optimizer.

Chapter 3. Interactive Optimizer tutorial 29

Page 42: Ibm Ilog Cplex User Manual 12.6

Where you areTo solve a model and display its solution in the Interactive Optimizer, usecommands and options.

If you have been following this tutorial step by step, the problem is now correctlyentered, and you can now use CPLEX to solve it. This tutorial continues withtopics about solving the problem and displaying solution information. Each ofthese topics introduces commands and options.

Solving the exampleWhile solving a problem, the Interactive Optimizer executes the optimizecommand.

The optimize command tells CPLEX to solve the LP problem. CPLEX uses the dualsimplex optimizer, unless another method has been specified by setting theLPMETHOD parameter (explained more fully in the CPLEX User’s Manual).

Entering the optimize command

At the CPLEX> prompt, type the command:optimize

Preprocessing

First, CPLEX tries to simplify or reduce the problem using its presolver andaggregator. If any reductions are made, a message will appear. However, in oursmall example, no reductions are possible.

Monitoring the iteration log

Next, an iteration log appears on the screen. CPLEX reports its progress as it solvesthe problem. The solution process involves two stages:v during Phase I, CPLEX searches for a feasible solutionv in Phase II, CPLEX searches for the optimal feasible solution.

The iteration log periodically displays the current iteration number and either thecurrent scaled infeasibility during Phase I, or the objective function value duringPhase II. After the optimal solution has been found, the objective function value,solution time, and iteration count (total, with Phase I in parentheses) aredisplayed. This information can be useful for monitoring the rate of progress.

The iteration log display can be modified by the command set simplex displayto display differing amounts of data while the problem is being solved.

Reporting the solution

After it finds the optimal solution, CPLEX reports:v the objective function valuev the problem solution time in secondsv the total iteration countv the Phase I iteration count (in parentheses)

30 Getting Started with CPLEX

Page 43: Ibm Ilog Cplex User Manual 12.6

Optimizing our example problem produces a report like the following one(although the solution times vary with each computer):Tried aggregator 1 time.No LP presolve or aggregator reductions.Presolve Time = 0.00 sec. (0.00 ticks)

Iteration Log . . .Iteration: 1 Dual infeasibility = 0.000000Iteration: 2 Dual objective = 202.500000

Dual simplex - Optimal: Objective = 2.0250000000e+02Solution Time = 0.00 sec. Iterations = 2 (1)Deterministic time = 0.00 ticks (3.38 ticks/sec)

CPLEX>

In our example, CPLEX finds an optimal solution with an objective value of 202.5in two iterations. For this simple problem, 1 Phase I iteration was required.

Summary

To solve an LP problem, use the command:optimize

Solution optionsAfter solving a problem, the Interactive Optimizer supports these additionaloptions.

Here are some of the basic options in solving linear programming problems.Although the example in this tutorial does not make use of these options, you willfind them useful when handling larger, more realistic problems.v “Filing iteration logs”;v “Re-solving”;v “Using alternative optimizers” on page 32;v “Interrupting the optimization” on page 32.

For detailed information about performance options, refer to the CPLEX User’sManual.

Filing iteration logs

Every time CPLEX solves a problem, much of the information appearing on thescreen is also directed into a log file. This file is automatically created by CPLEXwith the name cplex.log . If there is an existing cplex.log file in the directorywhere CPLEX is launched, CPLEX will append the current session data to theexisting file. If you want to keep a unique log file of a problem session, you canchange the default name with the set logfile command. (See the CPLEX User’sManual.) The log file is written in standard ASCII format and can be edited withany text editor.

Re-solving

You may re-solve the problem by reissuing the optimize command. CPLEX restartsthe solution process from the previous optimal basis, and thus requires zeroiterations. If you do not wish to restart the problem from an advanced basis, usethe set advance command to turn off the advanced start indicator.

Chapter 3. Interactive Optimizer tutorial 31

Page 44: Ibm Ilog Cplex User Manual 12.6

Remember that a problem must be present in memory (entered via the entercommand or read from a file) before you issue the optimize command.

Using alternative optimizers

In addition to the optimize command, CPLEX can use the primal simplexoptimizer (primopt command), the dual simplex optimizer (tranopt command), thebarrier optimizer (baropt command) and the network optimizer (netoptcommand). Many problems can be solved faster using these alternative optimizers,which are documented in more detail in the CPLEX User’s Manual. If you want tosolve a mixed integer programming problem, the optimize command is equivalentto the mipopt command.

Interrupting the optimization

Our short example was solved very quickly. However, larger problems, particularlymixed integer problems, can take much longer. Occasionally it may be useful tointerrupt the optimization process. CPLEX allows such interruptions if you usecontrol-c . (The control and c keys must be pressed simultaneously.)Optimization is interrupted, and CPLEX issues a message indicating that theprocess was stopped and displays progress information. If you issue anotheroptimization command in the same session, CPLEX will resume optimization fromwhere it was interrupted.

Displaying post-solution informationFor post-solution information, the Interactive Optimizer supports these options.

After an optimal solution is found, CPLEX can provide many different kinds ofinformation for you to view and analyze the results. You access this information bymeans of the display command and by certain write commands.

Information about the following features of a solution is available with the displaysolution command:v objective function value;v solution values;v numerical quality of the solution;v slack values;v reduced costs;v dual values (shadow prices);v basic rows and columns.

For information about the write commands, see “Writing problem and solutionfiles” on page 34. Sensitivity analysis can also be performed in analyzing results, asexplained in “Performing sensitivity analysis” on page 33.

For example, to view the optimal value of each variable, enter the command:display solution variables -

In response, the list of variable names with the solution value for each variable isdisplayed, like this:Variable Name Solution Valuex1 40.000000x2 17.500000x3 42.500000

32 Getting Started with CPLEX

Page 45: Ibm Ilog Cplex User Manual 12.6

To view the slack values of each constraint, enter the command:display solution slacks -

The resulting message indicates that for this problem the slack variables are allzero.All slacks in the range 1-2 are 0.

To view the dual values (sometimes called shadow prices) for each constraint,enter the command:display solution dual -

The list of constraint names with the solution value for each constraint appears,like this:Constraint Name Dual Pricec1 2.750000c2 0.250000

Summary

Display solution characteristics by entering a command with the syntax:display solution identifier

Performing sensitivity analysisTo perform sensitivity analysis, the Interactive Optimizer supports these options.

Sensitivity analysis of the objective function and righthand side providesmeaningful insight about ways in which the optimal solution of a problem changesin response to small changes in these parts of the problem data.

Sensitivity analysis can be performed on the following features of a solution:v objective function;v righthand side values;v bounds.

To view the sensitivity analysis of the objective function, enter the command:display sensitivity obj -

You can also use a wildcard to query solution information, like this:display sensitivity obj *

For our example, CPLEX displays the following ranges for sensitivity analysis ofthe objective function:

OBJ Sensitivity Ranges

Variable Name Reduced Cost Down Current Upx1 3.5000 -2.5000 1.0000 +infinityx2 zero -5.0000 2.0000 3.0000x3 zero 2.0000 3.0000 +infinity

CPLEX displays each variable, its reduced cost and the range over which itsobjective function coefficient can vary without forcing a change in the optimalbasis. The current value of each objective coefficient is also displayed for reference.Objective function sensitivity analysis is useful to analyze how sensitive theoptimal solution is to the cost or profit associated with each variable.

Chapter 3. Interactive Optimizer tutorial 33

Page 46: Ibm Ilog Cplex User Manual 12.6

Similarly, to view sensitivity analysis of the righthand side, type the command:display sensitivity rhs -

For our example, CPLEX displays the following ranges for sensitivity analysis ofthe righthand side (RHS):

RHS Sensitivity Ranges

Constraint Name Dual Price Down Current Upc1 2.7500 -36.6667 20.0000 +infinityc2 0.2500 -140.0000 30.0000 100.0000

CPLEX displays each constraint, its dual price, and a range over which itsrighthand side coefficient can vary without changing the optimal basis. The currentvalue of each RHS coefficient is also displayed for reference. Righthand sidesensitivity information is useful for analyzing how sensitive the optimal solutionand resource values are to the availability of those resources.

CPLEX can also display lower bound sensitivity ranges with the commanddisplay sensitivity lb

and upper bound sensitivity with the commanddisplay sensitivity ub

Summary

Display sensitivity analysis characteristics by entering a command with the syntax:display sensitivity identifier

Writing problem and solution filesTo write files, the Interactive Optimizer supports a variety of options.

OverviewThe write command of the Interactive Optimizer records information in a file.

The problem or its solution can be saved by using the write command. Thiscommand writes the problem statement or a solution report to a file.

Selecting a write file formatThe Interactive Optimizer writes files in a variety of formats, according to optionsyou specify.

When you type the write command in the Interactive Optimizer, CPLEX displays amenu of options and prompts you for a file format, like this:File type options:

alp LP format problem with generic names and bound annotationsbas INSERT format basis fileclp Conflict filedpe Binary format for dual-perturbed problemdua MPS format of explicit dual of problememb MPS format of (embedded) networkflt Solution pool filterslp LP format problem filemin DIMACS min-cost network-flow format of (embedded) networkmps MPS format problem filemst MIP start file

34 Getting Started with CPLEX

Page 47: Ibm Ilog Cplex User Manual 12.6

net CPLEX network format of (embedded) networkord Integer priority order fileppe Binary format for primal-perturbed problempre Binary format for presolved problemprm Non-default parameter settingsrlp LP format problem with generic namesrew MPS format problem with generic namessav Binary matrix and basis filesol Solution file

File type:

v The BAS format is used for storing basis information and is introduced in“Writing basis files.” See also “Reading basis files” on page 38.

v The LP format was discussed in “Using the LP format” on page 22. Using thisformat is explained in “Writing LP files” and “Reading LP files” on page 37.

v The MPS format is covered in “Reading MPS files” on page 38.

Note:

All these file formats are documented in more detail in the CPLEX File FormatsReference Manual .

Writing LP filesThe command to write LP file format from the Interactive Optimizer prompts foroptions.

When you enter the write command. the following message appears:Name of file to write:

Enter the problem name "example", and CPLEX will ask you to select a type froma list of options. For this example, choose LP. CPLEX displays a confirmationmessage, like this:Problem written to file ’example’.

If you would like to save the file with a different name, you can simply use thewrite command with the new file name as an argument. Try this, using the nameexample2 . This time, you can avoid intermediate prompts by specifying an LPproblem type, like this:write example2 lp

Another way of avoiding the prompt for a file format is by specifying the file typeexplicitly in the file name extension. Try the following example:write example.lp

Using a file extension to indicate the file type is the recommended namingconvention. This makes it easier to keep track of your problem and solution files.

When the file type is specified by the file name extension, CPLEX ignoressubsequent file type information issued within the write command. For example,CPLEX responds to the following command by writing an LP format problem file:write example.lp mps

Writing basis filesThe Interactive Optimizer supports the option to write basis files.

Chapter 3. Interactive Optimizer tutorial 35

Page 48: Ibm Ilog Cplex User Manual 12.6

Another optional file format is BAS. Unlike the LP and MPS formats, this format isnot used to store a description of the problem statement. Rather, it is used to storeinformation about the solution to a problem, information known as a basis. Evenafter changes are made to the problem, using a prior basis to start the optimizationfrom an advanced basis can speed solution time considerably. A basis can bewritten only after a problem has been solved. Try this now with the followingcommand:write example.bas

In response, CPLEX displays a confirmation message, like this:Basis written to file ’example.bas’.

Using path namesThese special considerations with respect to path names apply in the InteractiveOptimizer.

You can also include a full path name to specify to CPLEX on which drive anddirectory to save any file. The following write command is valid if the disk driveon your system contains a root directory named problems:write /problems/example.lp

Summary

The general syntax for the write command is:write filename file_format

orwrite filename.file_extension

where file_extension indicates the format in which the file is to be saved.

Reading problem filesThese commands and options read files into the Interactive Optimizer.

OverviewThe read command supports a variety of file formats in Interactive Optimizer.

When you are using CPLEX to solve linear optimization problems, you mayfrequently enter problems by reading them from files instead of entering themfrom the keyboard. With that practice in view, the following topics continue thetutorial from “Writing problem and solution files” on page 34.

Selecting a read file formatThe Interactive Optimizer reads these files formats.

When you type the read command in the Interactive Optimizer with the name of afile bearing an extension that it does not recognize, CPLEX displays the followingprompt about file formats on the screen:File type options:

alp LP format problem with generic names and bound annotationsbas INSERT format basis fileflt Solution pool filters

36 Getting Started with CPLEX

Page 49: Ibm Ilog Cplex User Manual 12.6

lp LP format problem filemin DIMACS min-cost network-flow format filemps MPS format problem filemst MIP start filenet CPLEX network-flow format fileord Integer priority order fileprm Non-default parameter filesav Binary matrix and basis filesol Solution file

File type:

Note:

All these file formats are documented in more detail in the CPLEX File FormatsReference Manual.

Reading LP filesTo read a formatted LP file into the Interactive Optimizer, use this command withoptions.

At the CPLEX> prompt type:read

The following message appears requesting a file name:Name of file to read:

Four files have been saved at this point in this tutorial:

example

example2

example.lp

example.bas

Specify the file named example that you saved while practicing the writecommand.

You recall that the example problem was saved in LP format, so in response to thefile type prompt, enter:lp

CPLEX displays a confirmation message, like this:Problem ’example’ read.Read Time = 0.03 sec.

The example problem is now in memory, and you can manipulate it with CPLEXcommands.

Tip:

The intermediate prompts for the read command can be avoided by entering theentire command on one line, like this:

Chapter 3. Interactive Optimizer tutorial 37

Page 50: Ibm Ilog Cplex User Manual 12.6

make LPex1.classjava -Djava.library.path=../../../bin/<platform>: \

-classpath ../../../lib/cplex.jar: LPex1 -rread example lp

Using file extensionsSupport for file extensions in the Interactive Optimizer follows these conventions.

If the file name has an extension that corresponds to one of the supported fileformats, CPLEX automatically reads it without your having to specify the format.Thus, the following command automatically reads the problem file example.lp inLP format:read example.lp

Reading MPS filesTo read MPS formatted files in the Interactive Optimizer, follow these conventions.

CPLEX can also read industry-standard MPS formatted files. The problem calledafiro.mps (provided in the CPLEX distribution) serves as an example. If youinclude the .mps extension in the file name, CPLEX recognizes the file as being inMPS format. If you omit the extension, CPLEX attempts to detect whether the fileis of a type that it recognizes.read afiro mps

After the file has been read, the following message appears:Selected objective sense: MINIMIZESelected objective name: objSelected RHS name: rhsProblem 'afiro' read.Read time = 0.01 sec.

CPLEX reports additional information when it reads MPS formatted files. Sincethese files can contain multiple objective function, righthand side, bound, andother information, CPLEX displays which of these is being used for the currentproblem. See Working with MPS files in the CPLEX User’s Manual to learn moreabout special considerations for using MPS formatted files.

Reading basis filesTo read basis files into the Interactive Optimizer, follow these conventions.

In addition to other file formats, the read command is also used to read basis files.These files contain information for CPLEX that tells the simplex method where tobegin the next optimization. Basis files usually correspond to the result of someprevious optimization and help to speed re-optimization. They are particularlyhelpful when you are dealing with very large problems if small changes are madeto the problem data.

“Writing basis files” on page 35 showed you how to save a basis file for theexample after it was optimized. For this tutorial, first read the example.lp file. Thenread this basis file by typing the following command:read example.bas

The message of confirmation:Basis ’example.bas’ read.

38 Getting Started with CPLEX

Page 51: Ibm Ilog Cplex User Manual 12.6

indicates that the basis file was successfully read. If the advanced basis indicator ison, this basis will be used as a starting point for the next optimization, and anynew basis created during the session will be used for future optimizations. If thebasis changes during a session, you can save it by using the write command.

Summary

The general syntax for the read command is:read filename file_format

orread filename.file_extension

where file_extension corresponds to one of the allowed file formats.

Setting CPLEX parametersThe set command controls CPLEX parameters in the Interactive Optimizer.

CPLEX users can vary parameters by means of the set command. This commandis used to set CPLEX parameters to values different from their default values. Theprocedure for setting a parameter is similar to that of other commands. Commandscan be carried out incrementally or all in one line from the CPLEX> prompt.Whenever a parameter is set to a new value, CPLEX inserts a comment in the logfile that indicates the new value.

Setting a parameter

To see the parameters that can be changed, type:set

The parameters that can be changed are displayed with a prompt, like this:Available Parameters:

advance set indicator for advanced starting informationbarrier set parameters for barrier optimizationclocktype set type of clock used to measure timeconflict set parameters for finding conflictsdefaults set all parameter values to defaultsdettimelimit set deterministic time limit in ticksemphasis set optimization emphasisfeasopt set parameters for feasoptlogfile set file to which results are printedlpmethod set method for linear optimizationmip set parameters for mixed integer optimizationnetwork set parameters for network optimizationsoutput set extent and destinations of outputsparallel set parallel optimization modepreprocessing set parameters for preprocessingqpmethod set method for quadratic optimizationrandomseed set seed to initialize the random number generatorread set problem read parameterssifting set parameters for sifting optimizationsimplex set parameters for primal and dual simplex optimizationssolutiontarget set type of solution CPLEX will attempt to computethreads set default parallel thread counttimelimit set time limit in secondstune set parameters for parameter tuning

Chapter 3. Interactive Optimizer tutorial 39

Page 52: Ibm Ilog Cplex User Manual 12.6

workdir set directory for working filesworkmem set memory available for working storage (megabytes)

Parameter to set:

If you press the <return> key without entering a parameter name, the followingmessage is displayed:No parameters changed.

Resetting defaults

After making parameter changes, it is possible to reset all parameters to defaultvalues by issuing one command:set defaults

This resets all parameters to their default values, except for the name of the logfile.

Summary

The general syntax for the set command is:set parameter option new_value

Displaying parameter settings

The current values of the parameters can be displayed with the command:display settings all

A list of parameters with settings that differ from the default values can bedisplayed with the command:display settings changed

For a description of all parameters and their default values, see the referencemanual CPLEX Parameters.

CPLEX also accepts customized system parameter settings via a parameterspecification file. See the CPLEX File Formats Reference Manual for a description ofthe parameter specification file and its use.

Adding constraints and boundsTo add constraints or bounds to a problem in the Interactive Optimizer, use thesecommands and options.

If you wish to add either new constraints or bounds to your problem, use the addcommand. This command is similar to the enter command in the way it is used,but it has one important difference: the enter command is used to start a brandnew problem, whereas the add command only adds new information to the currentproblem.

Suppose that in the example you need to add a third constraint:

x1 + 2x2 + 3x3 ≥ 50

You may do either interactively or from a file.

40 Getting Started with CPLEX

Page 53: Ibm Ilog Cplex User Manual 12.6

Adding interactively

Type the add command, then enter the new constraint on the blank line. Aftervalidating the constraint, the cursor moves to the next line. You are in anenvironment identical to that of the enter command after having issued subjectto . At this point you may continue to add constraints or you may type bounds andenter new bounds for the problem. For the present example, type end to exit theadd command. Your session should look like this:addEnter new constraints and bounds ['end' terminates]:x1 + 2x2 + 3x3 >= 50endProblem addition successful.

When the problem is displayed again, the new constraint appears, like this:display problem all

Maximizeobj: x1 + 2 x2 + 3 x3Subject Toc1: - x1 + x2 + x3 <= 20c2: x1 - 3 x2 + x3 <= 30c3: x1 + 2 x2 + 3 x3 >= 50Bounds0 <= x1 <= 40All other variables are >= 0.end

Adding from a file

Alternatively, you may read in new constraints and bounds from a file. If youenter a file name after the add command, CPLEX will read a file matching thatname. The file contents must comply with standard CPLEX LP format. CPLEXdoes not prompt for a file name if none is entered. Without a file name, interactiveentry is assumed.

Summary

The general syntax for the add command is:

add

or

add filename

Changing a problemTo change a problem, the Interactive Optimizer supports these commands andoptions.

OverviewThe change command modifies a model in the Interactive Optimizer.

The enter and add commands allow you to build a problem from the keyboard,but they do not allow you to change what you have built. You make changes withthe change command.

Chapter 3. Interactive Optimizer tutorial 41

Page 54: Ibm Ilog Cplex User Manual 12.6

The change command can be used for several different tasks, as demonstrated inthe following topics.

What can be changed?Options of the change command determine what you can modify in a problementered in the Interactive Optimizer.

Start out by changing the name of the constraint that you added with the addcommand. In order to see a list of change options, type:change

The elements that can be changed are displayed like this:Change options:

bounds change bounds on a variablecoefficient change a coefficientdelete delete some part of the problemname change a constraint or variable nameobjective change objective function valueproblem change problem typeqpterm change a quadratic objective termrhs change a righthand side or network supply/demand valuesense change objective function or a constraint sensetype change variable typevalues change small values in the problem to zero

Change to make:

Changing constraint or variable namesThese options change the name of a constraint or variable in the InteractiveOptimizer.

Enter name at the Change to make: prompt to change the name of a constraint:Change to make: name

The present name of the constraint is c3 . In the example, you can change thename to new3 to differentiate it from the other constraints using the followingentries:Change a constraint or variable name ['c' or 'v']: cPresent name of constraint: c3New name of constraint: new3The constraint 'c3' now has name 'new3'.

The name of the constraint has been changed.

The problem can be checked with a display command (for example,display problem constraints new3 ) to confirm that the change was made.

This same technique can also be used to change the name of a variable.

Changing senseThis option changes the sense of a constraint in the Interactive Optimizer.

Next, change the sense of the new3 constraint from ≥ to ≤ using the sense option ofthe change command. At the CPLEX> prompt, type:change sense

42 Getting Started with CPLEX

Page 55: Ibm Ilog Cplex User Manual 12.6

CPLEX prompts you to specify a constraint. There are two ways of specifying thisconstraint: if you know the name (for example, new3 ), you can enter the name; ifyou do not know the name, you can specify the index of the constraint. In thisexample, the index is 3 for the new3 constraint. Try the first method and type:Change sense of which constraint: new3Sense of constraint ’new3’ is ’>=’.

CPLEX tells you the current sense of the selected constraint. All that is left now isto enter the new sense, which can be entered as <= , >= , or = . You can also typesimply < (interpreted as ≤) or > (interpreted as ≥). The letters l , g , and e arealso interpreted as ≤, ≥, and = respectively.New sense [’<=’ or ’>=’ or ’=’]: <=Sense of constraint ’new3’ changed to ’<=’.

The sense of the constraint has been changed.

The sense of the objective function may be changed by specifying the objectivefunction name (its default is obj ) or the number 0 when CPLEX prompts you forthe constraint. You are then prompted for a new sense. The sense of an objectivefunction can take the value maximum or minimum or the abbreviation max or min .

Changing boundsThis option changes the bounds of a variable in the Interactive Optimizer.

When the example was entered, bounds were set specifically only for the variablex1 . The bounds can be changed on this or other variables with the bounds option.Again, start by selecting the command and option.change bounds

Select the variable by name or number and then select which bound you wouldlike to change. For the example, change the upper bound of variable x2 from +∞ to50.Change bounds on which variable: x2Present bounds on variable x2: The indicated variable is >= 0.Change lower or upper bound, or both ['l', 'u', or 'b']: uChange upper bound to what ['+inf' for no upper bound]: 50New bounds on variable 'x2': 0 <= x2 <= 50

Removing boundsTo remove a bound in the Interactive Optimizer, use the set command.

To remove a bound, set it to +∞ or –∞. Interactively, use the identifiers inf and -infinstead of the symbols. To change the upper bound of x2 back to +∞, use the oneline command:change bounds x2 u inf

You receive the message:New bounds on variable ’x2’: The indicated variable is >= 0.

The bound is now the same as it was when the problem was originally entered.

Changing coefficients of variablesTo change the coefficient of a variable in a constraint in the Interactive Optimizer,use options of the change command.

Chapter 3. Interactive Optimizer tutorial 43

Page 56: Ibm Ilog Cplex User Manual 12.6

Up to this point all of the changes that have been made could be referenced byspecifying a single constraint or variable. In changing a coefficient, however, aconstraint and a variable must be specified in order to identify the correctcoefficient. As an example, change the coefficient of x3 in the new3 constraint from3 to 30.

As usual, you must first specify which change command option to use:change coefficient

You must now specify both the constraint row and the variable column identifyingthe coefficient you wish to change. Enter both the constraint name (or number) andvariable name (or number) on the same line, separated by at least one space. Theconstraint name is new3 and the variable is number 3, so in response to thefollowing prompt, type new3 and 3 , like this, to identify the one to change:Change which coefficient ['constraint' 'variable']: new3 3Present coefficient of constraint 'new3', variable '3' is 3.000000.

The final step is to enter the new value for the coefficient of x3 .Change coefficient of constraint 'new3', variable '3' to what: 30Coefficient of constraint 'new3', variable '3' changed to 30.000000.

Objective and RHS coefficientsThe Interactive Optimizer also supports modification of a coefficient in theobjective function or righthand side.

To change a coefficient in the objective function, or in the righthand side, use thecorresponding option of the change command: objective or rhs. For example, tospecify the righthand side of constraint 1 to be 25.0, a user enters the followingcommand (but for this tutorial, do not enter this command now):change rhs 1 25.0

Deleting entire constraints or variablesThe Interactive Optimizer supports these options of the delete command.

Another option to the change command is delete. This option is used to removean entire constraint or a variable from a problem. Return the problem to itsoriginal form by removing the constraint you added earlier. Type:change delete

CPLEX displays a list of delete options.Delete options:

constraints delete range of constraintsqconstraints delete range of quadratic constraintsindconstraints delete range of indicator constraintssoss delete range of special ordered setsvariables delete range of variablesfilters delete range of filterssolutions delete range of solutions from the poolequality delete range of equality constraintsgreater-than delete range of greater-than constraintsless-than delete range of less-than constraintsmipstarts delete range of mipstarts

Deletion to make:

At the first prompt, specify that you want to delete a constraint.

44 Getting Started with CPLEX

Page 57: Ibm Ilog Cplex User Manual 12.6

Deletion to make: constraints

At the next prompt, enter a constraint name or number, or a range as you didwhen you used the display command. Since the constraint to be deleted is namednew3, enter that name:Delete which constraint(s): new3Constraint 3 deleted.

Check to be sure that the correct range or number is specified when you performthis operation, since constraints are permanently removed from the problem.Indices of any constraints that appeared after a deleted constraint will bedecremented to reflect the removal of that constraint.

The last message indicates that the operation is complete. The problem can now bechecked to see if it has been changed back to its original form.display problem all

Maximizeobj: x1 + 2 x2 + 3 x3Subject Toc1: - x1 + x2 + x3 <= 20c2: x1 - 3 x2 + x3 <= 30Bounds0 <= x1 <= 40All other variables are >= 0.

When you remove a constraint with the delete option, that constraint no longerexists in memory; however, variables that appear in the deleted constraint are notremoved from memory. If a variable from the deleted constraint appears in theobjective function, it may still influence the solution process. If that is not whatyou want, these variables can be explicitly removed using the delete option.

Changing small values to zeroTo clean data by zeroing out small values, the Interactive Optimizer offers optionsfor the change command.

The change command can also be used to clean up data in situations where youknow that very small values are not really part of your model but instead are theresult of imprecision introduced by finite-precision arithmetic in operations such asround-off.change values

CPLEX then prompts you for a tolerance (epsilon value) within which small valuesshould be changed to 0 (zero).

Summary

The general syntax for the change command is:change option identifier [identifier2] new value

Executing operating system commandsOperating system commands are accessible from the Interactive Optimizer.

Chapter 3. Interactive Optimizer tutorial 45

Page 58: Ibm Ilog Cplex User Manual 12.6

The execute command (xecute) is simple but useful. It executes operating systemcommands outside of the CPLEX environment. By using xecute, you avoid havingto save a problem and quit CPLEX in order to carry out a system function (such asviewing a directory, for example).

As an example, if you wanted to check whether all of the files saved in the lastsession are really in the current working directory, the following CPLEX commandshows the contents of the current directory in a UNIX operating system, using theUNIX command ls:xecute ls -ltotal 7448-r--r--r-- 1 3258 Jul 14 10:34 afiro.mps-rwxr-xr-x 1 3783416 Apr 22 10:32 cplex-rw-r--r-- 1 3225 Jul 14 14:21 cplex.log-rw-r--r-- 1 145 Jul 14 11:32 example-rw-r--r-- 1 112 Jul 14 11:32 example.bas-rw-r--r-- 1 148 Jul 14 11:32 example.lp-rw-r--r-- 1 146 Jul 14 11:32 example2

After the command is executed, the CPLEX> prompt returns, indicating that you arestill in CPLEX. Most commands that can normally be entered from the prompt foryour operating system can also be entered with the xecute command. Thecommand may be as simple as listing the contents of a directory or printing thecontents of a file, or as complex as starting a text editor to modify a file. Anythingthat can be entered on one line after the operating system prompt can also beexecuted from within CPLEX. However, this command differs from other CPLEXcommands in that it must be entered on a single line. No prompt will be issued. Inaddition, the operating system may fail to carry out the command. In that case, nomessage is issued by the operating system, and the result is a return to the CPLEX>prompt.

Summary

The general syntax for the xecute command is:xecute command line

Quitting CPLEXTo terminate a session of the Interactive Optimizer, use the quit command.

When you are finished using CPLEX and want to leave it, type:quit

If a problem has been modified, be sure to save the file before issuing a quitcommand. CPLEX will not prompt you to save your problem.

Advanced features of the Interactive OptimizerFurther reading about advanced features of the Interactive Optimizer is availablein the CPLEX User's Manual.

This introduction to the Interactive Optimizer presents most of the commands andtheir options. There are also other, more advanced features of the InteractiveOptimizer, documented in the CPLEX User's Manual. Here short descriptions ofthose advanced features and links to further information about them.

46 Getting Started with CPLEX

Page 59: Ibm Ilog Cplex User Manual 12.6

The tuning tool can help you discern nondefault parameter settings that lead tofaster solving time. Examples: time limits on tuning in the Interactive Optimizershows how to use the tuning tool in the Interactive Optimizer.

The solution pool stores multiple solutions to a mixed integer programming (MIP)model. With this feature, you can direct the optimizer to generate multiplesolutions in addition to the optimal solution. CPLEX offers facilities to manage thesolution pool and to access members of the solution pool. Solution pool: generatingand keeping multiple solutions describes those facilities and documents thecorresponding commands of the Interactive Optimizer.

The conflict refiner diagnoses the cause of infeasibility in a model or MIP start,whether continuous or discrete, whether linear or quadratic. Diagnosinginfeasibility by refining conflicts documents the conflict refiner generally, and Meetthe conflict refiner in the Interactive Optimizer introduces the conflict refiner as afeature of the Interactive Optimizer.

FeasOpt attempts to repair an infeasibility by modifying the model according topreferences set by the user. FeasOpt accepts an infeasible model and selectivelyrelaxes the bounds and constraints in a way that minimizes a weighted penaltyfunction that you define. Repairing infeasibilities with FeasOpt documents thisfeature and refers throughout to commands available in the Interactive Optimizer.

The user may supply a MIP start, also known as an advanced start or a warmstart, to serve as the first integer solution when CPLEX solves a MIP. Such asolution might come from a MIP problem solved previously or from the user'sknowledge of the problem, for example. MIP starts and the Interactive Optimizerintroduces commands of the Interactive Optimizer to manage MIP starts.

Chapter 3. Interactive Optimizer tutorial 47

Page 60: Ibm Ilog Cplex User Manual 12.6

48 Getting Started with CPLEX

Page 61: Ibm Ilog Cplex User Manual 12.6

Chapter 4. Concert Technology tutorial for C++ users

This tutorial shows you how to write C++ applications using CPLEX with ConcertTechnology. In this tutorial you will learn about:

The design of CPLEX in Concert Technology C++ applicationsCPLEX objects are necessary to an application in C++.

A clear understanding of C++ objects is fundamental to using Concert Technologywith CPLEX to build and solve optimization models. These objects can be dividedinto two categories:1. Modeling objects are used to define the optimization problem. Generally an

application creates multiple modeling objects to specify one optimizationproblem. Those objects are grouped into an IloModel object representing thecomplete optimization problem.

2. IloCplex objects are used to solve the problems that have been created withthe modeling objects. An IloCplex object reads a model and extracts its data tothe appropriate representation for the CPLEX optimizer. Then the IloCplexobject is ready to solve the model it extracted and be queried for solutioninformation.

Thus, the modeling and optimization parts of a user-written application programare represented by a group of interacting C++ objects created and controlled withinthe application. Figure 3 shows a picture of an application using CPLEX withConcert Technology to solve optimization problems.

The CPLEX internals include the computing environment, its communicationchannels, and your problem objects.

This brief tutorial introduces the modeling and solution classes provided byConcert Technology and CPLEX. More information about the algorithm classIloCplex and its nested classes can be found in the CPLEX User’s Manual andCPLEX C++ API Reference Manual.

Figure 3. A View of CPLEX with Concert Technology

© Copyright IBM Corp. 1987, 2013 49

Page 62: Ibm Ilog Cplex User Manual 12.6

Compiling CPLEX in Concert Technology C++ applicationsWhen you compile a C++ application with a C++ library like CPLEX in ConcertTechnology, you need to tell your compiler where to find the CPLEX and Concertinclude files (that is, the header files), and you also need to tell the linker where tofind the CPLEX and Concert libraries. The sample projects and makefiles illustratehow to carry out these crucial steps for the examples in the standard distribution.They use relative path names to indicate to the compiler where the header files are,and to the linker where the libraries are.

Testing your installation on UNIXAfter you install CPLEX on a UNIX platform, you can test the installation.

About this task

To run the test, follow these steps.

Procedure1. First check the file readme.html in the standard distribution to locate the right

subdirectory containing a makefile appropriate for your platform.2. Go to that subdirectory.3. Then use the sample makefile located there to compile and link the examples

that came in the standard distribution.make all compiles and links examples for all of the APIs.make all_cpp compiles and links the examples of the C++ API.

4. Execute one of the compiled examples.make execute_all executes all of the examples.make execute_cpp executes only the C++ examples.

Testing your installation on WindowsAfter you install CPLEX on a Windows platform, you can test the installation.

To run the test on a Windows platform, first consult the file c_cpp.html in thestandard distribution. Then follow the directions you find there.

The examples have been tested repeatedly on all the platforms compatible withCPLEX, so if you successfully compile, link, and execute them, then you can besure that your installation is correct.

In case of problemsCPLEX offers trouble-shooting procedures.

If you encounter difficulty when you try the installation test, then there is aproblem in your installation, and you need to correct it before you begin real workwith CPLEX.

For example, if you get a message from the compiler such as

ilolpex3.cpp 1: Can't find include file ilcplex/ilocplex.h

then you need to verify that your compiler knows where you have installedCPLEX and its include files (that is, its header files).

50 Getting Started with CPLEX

Page 63: Ibm Ilog Cplex User Manual 12.6

If you get a message from the linker, such as

ld: -lcplex: No such file or directory

then you need to verify that your linker knows where the CPLEX library is locatedon your system.

If you successfully compile, link, and execute one of the examples in the standarddistribution, then you can be sure that your installation is correct, and you canbegin to use CPLEX with Concert Technology seriously.

The anatomy of a Concert Technology C++ applicationConcert Technology is a C++ class library, and therefore Concert Technologyapplications consist of interacting C++ objects. This topic gives a short introductionto the most important classes that are usually found in a complete ConcertTechnology CPLEX C++ application.

Constructing the environment: IloEnvThe class IloEnv constructs a CPLEX environment.

An environment, that is, an instance of IloEnv is typically the first object created inany Concert Technology application.

You construct an IloEnv object by declaring a variable of type IloEnv . Forexample, to create an environment named env , you do this:IloEnv env;

Note:

The environment object created in a Concert Technology application is differentfrom the environment created in the CPLEX C library by calling the routineCPXopenCPLEX.

The environment object is of central importance and needs to be available to theconstructor of all other Concert Technology classes because (among other things) itprovides optimized memory management for objects of Concert Technologyclasses. This provides a boost in performance compared to the memorymanagement of the operating system.

As is the case for most Concert Technology classes, IloEnv is a handle class. Thismeans that the variable env is a pointer to an implementation object, which iscreated at the same time as env in the above declaration. One advantage of usinghandles is that if you assign handle objects, all that is assigned is a pointer. So thestatementIloEnv env2 = env;

creates a second handle pointing to the implementation object that env alreadypoints to. Hence there may be an arbitrary number of IloEnv handle objects allpointing to the same implementation object. When terminating the ConcertTechnology application, the implementation object must be destroyed as well. Thismust be done explicitly by the user by callingenv.end();

Chapter 4. Concert Technology tutorial for C++ users 51

Page 64: Ibm Ilog Cplex User Manual 12.6

for just ONE of the IloEnv handles pointing to the implementation object to bedestroyed. The call to env.end is generally the last Concert Technology operation inan application.

Creating a model: IloModelCPLEX C++ offers modeling objects for an application.

After creating the environment, a Concert application is ready to create one ormore optimization models. Doing so consists of creating a set of modeling objectsto define each optimization model.

Modeling objects, like IloEnv objects, are handles to implementation objects.Though you will be dealing only with the handle objects, it is the implementationobjects that contain the data that specifies the optimization model. If you need toremove an implementation object from memory, you need to call the end methodfor one of its handle objects.

Modeling objects are also known as extractables because it is the individualmodeling objects that are extracted one by one when you extract an optimizationmodel to IloCplex . So, extractables are characterized by the possibility of beingextracted to algorithms such as IloCplex . In fact, they all are inherited from theclass IloExtractable . In other words, IloExtractable is the base class of allclasses of extractables or modeling objects.

The most fundamental extractable class is IloModel . Objects of this class are usedto define a complete optimization model that can later be extracted to an IloCplexobject. You create a model by constructing an object of type IloModel. For example,to construct a modeling object named model, within an existing environmentnamed env, you write the following line:IloModel model(env);

At this point, it is important to note that the environment is passed as an argumentto the constructor. There is also a constructor that does not use the environmentargument, but this constructor creates an empty handle, the handle correspondingto a NULL pointer. Empty handles cannot be used for anything but for assigningother handles to them. Unfortunately, it is a common mistake to try to use emptyhandles for other things.

After an IloModel object has been constructed, it is populated with the extractablesthat define the optimization model. The most important classes here are:

IloNumVar representing modeling variables;IloRange defining constraints of the form l <= expr <=

u, where expr is a linear expression; andIloObjective representing an objective function.

You create objects of these classes for each variable, constraint, and objectivefunction of your optimization problem. Then you add the objects to the model bycallingmodel.add(object);

for each extractable object . There is no need to explicitly add the variable objectsto a model, as they are implicitly added when they are used in the rangeconstraints (instances of IloRange ) or the objective. At most one objective can beused in a model with IloCplex .

52 Getting Started with CPLEX

Page 65: Ibm Ilog Cplex User Manual 12.6

Modeling variables are constructed as objects of class IloNumVar , by definingvariables of type IloNumVar . Concert Technology provides several constructors fordoing this; the most flexible form is:IloNumVar x1(env, 0.0, 40.0, ILOFLOAT);

This definition creates the modeling variable x1 with lower bound 0.0, upperbound 40.0 and type ILOFLOAT , which indicates the variable is continuous. Otherpossible variable types include ILOINT for integer variables and ILOBOOL forBoolean variables.

For each variable in the optimization model a corresponding object of classIloNumVar must be created. Concert Technology provides a wealth of ways to helpyou construct all the IloNumVar objects.

After all the modeling variables have been constructed, they can be used to buildexpressions, which in turn are used to define objects of class IloObjective andIloRange . For example,IloObjective obj = IloMinimize(env, x1 + 2*x2 + 3*x3);

This creates the extractable obj of type IloObjective which represents the objectivefunction of the example presented in “Introducing CPLEX” on page v.

Consider in more detail what this line does. The function IloMinimize takes theenvironment and an expression as arguments, and constructs a new IloObjectiveobject from it that defines the objective function to minimize the expression. Thisnew object is returned and assigned to the new handle obj .

After an objective extractable is created, it must be added to the model. As notedabove this is done with the add method of IloModel . If this is all that the variableobj is needed for, it can be written more compactly, like this:model.add(IloMinimize(env, x1 + 2*x2 + 3*x3));

This way there is no need for the program variable obj and the program is shorter.If in contrast, the objective function is needed later, for example, to change it andre-optimize the model when doing scenario analysis, the variable obj must becreated in order to refer to the objective function. (From the standpoint ofalgorithmic efficiency, the two approaches are comparable.)

Creating constraints and adding them to the model can be done just as easily withthe following statement:model.add(-x1 + x2 + x3 <= 20);

The part -x1 + x2 + x3 <= 20 creates an object of class IloRange that isimmediately added to the model by passing it to the method IloModel::add .Again, if a reference to the IloRange object is needed later, an IloRange handleobject must be stored for it. Concert Technology provides flexible array classes forstoring data, such as these IloRange objects. As with variables, Concert Technologyprovides a variety of constructors that help create range constraints.

While those examples use expressions with modeling variables directly formodeling, it should be pointed out that such expressions are themselvesrepresented by yet another Concert Technology class, IloExpr . Like most ConcertTechnology objects, IloExpr objects are handles. Consequently, the method endmust be called when the object is no longer needed. The only exceptions areimplicit expressions, where the user does not create an IloExpr object, such as

Chapter 4. Concert Technology tutorial for C++ users 53

Page 66: Ibm Ilog Cplex User Manual 12.6

when writing (for example) x1 + 2*x2 . For such implicit expressions, the methodend should not be called. The importance of the class IloExpr becomes clear whenexpressions can no longer be fully spelled out in the source code but need insteadto be built up in a loop. Operators like += provide an efficient way to do this.

Solving the model: IloCplexThe class IloCplex solves a model.

After the optimization problem has been created in an IloModel object, it is time tocreate the IloCplex object for solving the problem by creating an instance of theclass IloCplex. For example, to create an object named cplex, write the followingline:IloCplex cplex(env);

again using the environment env as an argument. The CPLEX object can then beused to extract the model to be solved. One way to extract the model is to callcplex.extract(model). However, experienced Concert users practice a shortcut thatperforms the construction of the cplex object and the extraction of the model inone line:IloCplex cplex(model);

This shortcut works because the modeling object model contains within it thereference to the environment named env.

After this line, the object cplex is ready to solve the optimization problem definedby model. To solve the model, call:cplex.solve ();

This method returns an IloBool value, where IloTrue indicates that cplexsuccessfully found a feasible (yet not necessarily optimal) solution, and IloFalsespecifies that no solution was found. More precise information about the outcomeof the last call to the method IloCplex::solve can be obtained by calling:cplex.getStatus ();

The returned value tells you what CPLEX found out about the model: whether itfound the optimal solution or only a feasible solution, whether it proved the modelto be unbounded or infeasible, or whether nothing at all has been proved at thispoint. Even more detailed information about the termination of the solve call isavailable through method IloCplex::getCplexStatus.

Querying resultsQuery methods access information about the solution.

After successfully solving the optimization problem, you probably are interested inaccessing the solution. The following methods can be used to query the solutionvalue for a variable or a set of variables:IloNum IloCplex::getValue (IloNumVar var) const;void IloCplex::getValues (IloNumArray val,

const IloNumVarArray var) const;

For example:IloNum val1 = cplex.getValue(x1);

54 Getting Started with CPLEX

Page 67: Ibm Ilog Cplex User Manual 12.6

stores the solution value for the modeling variable x1 in val1. Other methods areavailable for querying other solution information. For example, the objectivefunction value of the solution can be accessed using:IloNum objval = cplex.getObjValue ();

Handling errorsA robust application of CPLEX in C++ avoids errors with assertions and handlesunforeseeable errors with exceptions.

Concert Technology provides two lines of defense for dealing with errorconditions, suited for addressing two kinds of errors. The first kind covers simpleprogramming errors. Examples of this kind are trying to use empty handle objectsor passing arrays of incompatible lengths to functions.

This kind of error is usually an oversight and should not occur in a correctprogram. In order not to pay any runtime cost for correct programs asserting suchconditions, the conditions are checked using assert statements. The checking isdisabled for production runs if compiled with the -DNDEBUG compiler option.

The second kind of error is more complex and cannot generally be avoided bycorrect programming. An example is memory exhaustion. The data may simplyrequire too much memory, even when the program is correct. This kind of error isalways checked at runtime. In cases where such an error occurs, ConcertTechnology throws a C++ exception.

In fact, Concert Technology provides a hierarchy of exception classes that all derivefrom the common base class IloException . Exceptions derived from this class arethe only kind of exceptions that are thrown by Concert Technology. The exceptionsthrown by IloCplex objects all derive from class IloAlgorithm::Exception orIloCplex::Exception .

To handle exceptions gracefully in a Concert Technology application, include all ofthe code in a try/catch clause, like this:IloEnv env;try {// ...} catch (IloException& e) {cerr << "Concert Exception: " << e << endl;} catch (...) {cerr << "Other Exception" << endl;}env.end();

Note:

The construction of the environment comes before the try/catch clause. In case ofan exception, env.end must still be called. To protect against failure during theconstruction of the environment, you can add another try/catch clause.

If code other than Concert Technology code is used in the part of that sampledenoted by ... , all other exceptions will be caught with the statement catch(...). Doing so is good practice, as it makes sure that no exception is unhandled.

Building and solving a small LP model in C++This sample solves a linear programming model in C++.

Chapter 4. Concert Technology tutorial for C++ users 55

Page 68: Ibm Ilog Cplex User Manual 12.6

OverviewThe sample illustrates three alternative approaches: modeling by rows, columns, ornonzero elements.

This sample offers a complete example of building and solving a small LP model.It demonstrates:v “Modeling by rows” on page 57v “Modeling by columns” on page 57v “Modeling by nonzero elements” on page 58

This example ilolpex1.cpp is one of the sample applications in the standardCPLEX distribution. It is an extension of the example presented in “IntroducingCPLEX” on page v. It shows three different ways of creating a Concert TechnologyLP model, as well as how to solve it using IloCplex, and how to access thesolution. Here is the problem that the example optimizes:

Maximize x1 + 2x2 + 3x3

subject to–x1 + x2 + x 3 ≤ 20

x1 – 3x2 + x 3 ≤ 30with these bounds

0 ≤ x 1 ≤ 40

0 ≤ x 2 ≤ infinity

0 ≤ x 3 ≤ infinity

The first operation is to create the environment object env , and the last operationis to destroy it by calling env.end . The rest of the code is enclosed in a try/catchclause to gracefully handle any errors that may occur.

First the example creates the model object and, after checking the correctness ofcommand line arguments, it creates empty arrays for storing the variables andrange constraints of the optimization model. Then, depending on the commandline argument, the example calls one of the functions populatebyrow,populatebycolumn, or populatebynonzero, to fill the model object with arepresentation of the optimization problem. These functions place the variable andrange objects in the arrays var and con which are passed to them as arguments.

After the model has been populated, the IloCplex algorithm object cplex is createdand the model is extracted to it. The following call of the method solve invokesthe optimizer. If it fails to generate a solution, an error message is issued to theerror stream of the environment, cplex.error() , and the integer -1 is thrown as anexception.

IloCplex provides the output streams out for general logging, warning for warningmessages, and error for error messages. They are preconfigured to cout , cerr ,and cerr respectively. Thus by default you will see logging output on the screenwhen invoking the method solve. This can be turned off by callingcplex.setOut(env.getNullStream()) , that is, by redirecting the out stream of theIloCplex object cplex to the null stream of the environment.

If a solution is found, solution information is output through the channel, env.outwhich is initialized to cout by default. The output operator << is defined for typeIloAlgorithm::Status as returned by the call to getStatus . It is also defined for

56 Getting Started with CPLEX

Page 69: Ibm Ilog Cplex User Manual 12.6

IloNumArray , the Concert Technology class for an array of numerical values, asreturned by the calls to getValues , getDuals , getSlacks , and getReducedCosts. Ingeneral, the output operator is defined for any Concert Technology array ofelements if the output operator is defined for the elements.

The functions named populateby * are purely about modeling and are completelydecoupled from the algorithm IloCplex. In fact, they don’t use the cplex object,which is created only after executing one of these functions.

Modeling by rowsCPLEX supports the approach of modeling by rows in the sample.

The function populatebyrow creates the variables and adds them to the array x.Then the objective function and the constraints are created using expressions overthe variables stored in x. The range constraints are also added to the array ofconstraints c. The objective and the constraints are added to the model.

Modeling by columnsCPLEX also supports the approach of modeling by columns in the sample.

The function populatebycolumn can be viewed as the transpose of populatebyrow.While, for simple examples like this one, population by rows may seem the moststraightforward and natural approach, there are some models where modeling bycolumn is a more natural or more efficient approach.

When an application creates a model by columns, range objects are created withtheir lower and upper bound only. No expression is given since the variables arenot yet created. Similarly, the objective function is created with only its intendedoptimization sense, and without any expression. Next the variables are created andinstalled in the already existing ranges and objective.

Column expressions provide the description of how the newly created variables areto be installed in the ranges and objective. These column expressions arerepresented by the class IloNumColumn. Column expressions consist of objects of theclass IloAddNumVar linked together with the operator +. These IloAddNumVar objectsare created using the operator() of the classes IloObjective and IloRange. Theseoverloaded operators define how to install a new variable to the invoking objectiveor range objects. For example, obj(1.0) creates an instance of IloAddNumVarcapable of adding a new modeling variable with a linear coefficient of 1.0 to theexpression in obj. Column expressions can be built in loops by means of theoperator +=.

Column expressions (objects of the class IloNumColumn) are handle objects, likemost other Concert Technology objects. The method end must therefore be called todelete the associated implementation object when it is no longer needed. However,for implicit column expressions, where no IloNumColumn object is explicitly created,such as the ones used in this example, the method end should not be called.

The column expression is passed as an argument to the constructor of the classIloNumVar. For example the constructor IloNumVar(obj(1.0) + c[0](-1.0) + c[1](1.0), 0.0, 40.0) creates a new modeling variable with lower bound 0.0, upperbound 40.0 and, by default, type ILOFLOAT, and adds it to the objective obj with alinear coefficient of 1.0, to the range c[0] with a linear coefficient of -1.0 and to

Chapter 4. Concert Technology tutorial for C++ users 57

Page 70: Ibm Ilog Cplex User Manual 12.6

c[1] with a linear coefficient of 1.0. Column expressions can be used directly toconstruct numeric variables with default bounds [0, IloInfinity] and typeILOFLOAT, as in the following statement:x.add(obj(2.0) + c[0]( 1.0) + c[1](-3.0));

where IloNumVar does not need to be explicitly written. Here, the C++ compilerrecognizes that an IloNumVar object needs to be passed to the add method andtherefore automatically calls the constructor IloNumVar(IloNumColumn) in order tocreate the variable from the column expression.

Modeling by nonzero elementsCPLEX supports the approach of modeling by nonzero elements in the sample.

The last of the three functions that can be used to build the model ispopulatebynonzero. It creates objects for the objective and the ranges withoutexpressions, and variables without columns. The methodsIloObjective::setLinearCoef, setLinearCoefs, and IloRange::setLinearCoef,setLinearCoefs are used to set individual nonzero values in the expression of theobjective and the range constraints. As usual, the objective and ranges must beadded to the model.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation /examples/src/ilolpex1.cpp.

Writing and reading models and filesCPLEX supports reading models from files and writing models to files in a C++application.

In example ilolpex1.cpp , one line is still unexplained:cplex.exportModel ("lpex1.lp");

This statement causes cplex to write the model it has currently extracted to the filecalled lpex1.lp . In this case, the file will be written in LP format. (That format isdocumented in the reference manual CPLEX File Formats.) Other formats supportedfor writing problems to a file are MPS and SAV (also documented in the referencemanual CPLEX File Formats). IloCplex decides which file format to write based onthe extension of the file name.

IloCplex also supports reading of files through one of its importModel methods. Acall to importModel causes CPLEX to read a problem from the file file.lp andadd all the data in it to model as new objects. (Again, MPS and SAV format filesare also supported.) In particular, CPLEX creates an instance of

IloObjective for the objective function found in file.lp ,IloNumVar for each variable found in file.lp , exceptIloSemiContVar for each semi-continuous or semi-integer

variable found in file.lp,IloRange for each row found in file.lp ,IloSOS1 for each SOS of type 1 found in file.lp ,

andIloSOS2 for each SOS of type 2 found in file.lp .

If you also need access to the modeling objects created by importModel , twoadditional signatures are provided:

58 Getting Started with CPLEX

Page 71: Ibm Ilog Cplex User Manual 12.6

void IloCplex::importModel (IloModel& m,const char* filename,IloObjective& obj,IloNumVarArray vars,IloRangeArray rngs) const;

andvoid IloCplex::importModel (IloModel& m,

const char* filename,IloObjective& obj,IloNumVarArray vars,IloRangeArray rngs,IloSOS1Array sos1,IloSOS2Array sos2) const;

They provide additional arguments so that the newly created modeling objects willbe returned to the caller. Example program ilolpex2.cpp shows how to use themethod importModel.

Selecting an optimizerSelect an optimizer in a C++ application on the basis of the problem type.

IloCplex treats all problems it solves as Mixed Integer Programming (MIP)problems. The algorithm used by IloCplex for solving MIP is known as dynamicsearch or branch and cut (referred to in some contexts as branch and bound) and isdocumented in more detail in the CPLEX User’s Manual. For this tutorial, it issufficient to know that this algorithm consists of solving a sequence of LPs, QPs, orQCPs that are generated in the course of the algorithm. The first LP, QP, or QCP tobe solved is known as the root, while all the others are referred to as nodes andare derived from the root or from other nodes. If the model extracted to the cplexobject is a pure LP, QP, or QCP (no integer variables), then it will be fully solved atthe root.

As mentioned in “Optimizer options” on page vii, various optimizer options areprovided for solving LPs, QPs, and QCPs. While the default optimizer works wellfor a wide variety of models, IloCplex allows you to control which option to usefor solving the root and for solving the nodes, respectively, by the followingmethods:void IloCplex::setParam(IloCplex::RootAlg, alg)void IloCplex::setParam(IloCplex::NodeAlg, alg)

where IloCplex::Algorithm is an enumeration type. It defines the followingsymbols with their meaning:

IloCplex::AutoAlg allow CPLEX to choose the algorithmIloCplex::Dual use the dual simplex algorithmIloCplex::Primal use the primal simplex algorithmIloCplex::Barrier use the barrier algorithmIloCplex::Network use the network simplex algorithm for the

embedded networkIloCplex::Sifting use the sifting algorithmIloCplex::Concurrent allow CPLEX to use multiple algorithms on

multiple computer processors

For QP models, only the AutoAlg, Dual, Primal, Barrier, and Network algorithmsare applicable.

Chapter 4. Concert Technology tutorial for C++ users 59

Page 72: Ibm Ilog Cplex User Manual 12.6

Set the root algorithm argument to select the optimizer that CPLEX uses to solve apure LP or QPs. The example ilolpex2.cpp illustrates this practice.

Reading a problem from a file: example ilolpex2.cppThe sample ilolpex2.cpp illustrates reading a model from a file in a C++application.

OverviewThe sample ilolpex2.cpp reads a model from a file, solves the problem with aspecified optimizer, prints the basis, and accesses quality information about thesolution.

This example shows how to read an optimization problem from a file and solve itwith a specified optimizer. It prints solution information, including a simplex basis,if available. Finally, the application prints the maximum infeasibility of anyvariable of the solution.

The file to read and the optimizer choice are passed to the program via commandline arguments. For example, this command:ilolpex2 example.mps d

reads the file example.mps and solves the problem with the dual simplex optimizer.

Example ilolpex2 demonstrates:v “Reading the model from a file”v “Selecting the optimizer”v “Accessing basis information” on page 61v “Querying quality measures” on page 61

The general structure of this example is the same as for example ilolpex1.cpp . Itstarts by creating the environment and terminates with destroying it by calling theend method. The code in between is enclosed in try/catch statements for errorhandling.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation /examples/src/ilolpex2.cpp .

Reading the model from a fileThe sample reads a model from a file for extraction later.

The model is created by reading it from the file specified as the first command lineargument argv[1] . The method importModel of an IloCplex object reads themodel from the file but it does not extract the model for solution. That is, in thiscase, the IloCplex object is used as a model reader rather than an optimizer.Calling importModel does not extract the model to the invoking cplex object.Consequently, extraction must be done later by a call to cplex.extract(model). Theobjects obj , var , and rng are passed to importModel so that later on, when resultsare queried, the variables will be accessible.

Selecting the optimizerThe sample provides a command line argument for the application user to selectan optimizer.

60 Getting Started with CPLEX

Page 73: Ibm Ilog Cplex User Manual 12.6

The switch statement controlled by the second command line argument selects theoptimizer. A user of the application specifies the optimizer by means of a CPLEXparameter. In the sample, a call to setParam(IloCplex::RootAlg, alg) specifies theselected optimizer as an instance of IloCplex::Algorithm.

Accessing basis informationThe sample may query basis information from the solution, if basis information isavailable.

After the sample solves the model by calling the method solve, it accesses theresults in the same way as in ilolpex1.cpp, with the exception of basis informationfor the variables. Not all optimizers compute basis information. In other words, notall solutions can be queried for basis information. In particular, basis information isnot available when the model is solved by the barrier optimizer(IloCplex::Barrier) without crossover (parameter IloCplex::BarCrossAlg set toIloCplex::NoAlg ).

Querying quality measuresThe sample shows how to access values measuring the quality of a solution.

Finally, the program prints the maximum primal infeasibility or bound violation ofthe solution. To cope with the finite precision of the numerical computations doneon the computer, IloCplex allows some tolerances by which (for instance)optimality conditions may be violated. A long list of other quality measures isavailable.

Modifying and re-optimizingCPLEX offers means to modify the model and re-optimize, using availableinformation from previous optimizations.

In many situations, the solution to a model is only the first step. One of theimportant features of Concert Technology is the ability to modify and then re-solvethe model even after it has been extracted and solved one or more times.

A look back to examples ilolpex1.cpp and ilolpex2.cpp reveals that models havebeen modified all along. Each time an extractable object is added to a model, itchanges the model. However, those examples made all such changes before themodel was extracted to CPLEX.

Concert Technology maintains a link between the model and all IloCplex objectsthat may have extracted it. This link is known as notification. Each time amodification of the model or one of its extractable objects occurs, the IloCplexobjects that extracted the model are notified about the change. They then track themodification in their internal representations.

Moreover, IloCplex tries to maintain as much information from a previous solutionas is possible and reasonable, when the model is modified, in order to have abetter start when solving the modified model. In particular, when solving LPs orQPs with a simplex method, IloCplex attempts to maintain a basis which will beused the next time the method solve is invoked, with the aim of makingsubsequent solves go faster.

Chapter 4. Concert Technology tutorial for C++ users 61

Page 74: Ibm Ilog Cplex User Manual 12.6

Modifying an optimization problem: example ilolpex3.cppThe sample ilolpex3.cpp shows how to modify a model so that CPLEX canre-optimize and re-use any information available from previous optimizations.

OverviewThe example ilolpex3.cpp is based on a network flow model.

This example demonstrates:v “Setting CPLEX parameters” on page 63v “Modifying an optimization problem” on page 63v “Starting from a previous basis” on page 63

Here is the problem that example ilolpex3 solves:

Minimize c^Txsubject to

Hx = d

Ax = b

l ≤ x ≤ uwhere H = ( -1 0 1 0 1 0 0 0

)d = ( -3 )

( 1 -1 0 1 0 0 0 0)

( 1 )

( 0 1 -1 0 0 1 -1 0)

( 4 )

( 0 0 0 -1 0 -1 0 1)

( 3 )

( 0 0 0 0 -1 0 1 -1)

( -5 )

A = ( 2 1 -2 -1 2 -1 -2-3 )

b = ( 4 )

( 1 -3 2 3 -1 2 1 1)

( -2 )

c = (-9 1 4 2 -8 2 8 12)

l = ( 0 0 0 0 0 0 0 0 )u = (50 50 50 50 50

50 50 50 )

The constraints Hx=d represent the flow conservation of a pure network flow. Theexample solves this problem in two steps:1. The CPLEX network optimizer is used to solve

Minimize c^Txsubject to

Hx = d

l ≤ x ≤ u

62 Getting Started with CPLEX

Page 75: Ibm Ilog Cplex User Manual 12.6

2. The constraints Ax=b are added to the problem, and the dual simplex optimizeris used to solve the full problem, starting from the optimal basis of the networkproblem. The dual simplex method is highly effective in such a case becausethis basis remains dual feasible after the slacks (artificial variables) of the addedconstraints are initialized as basic.

Notice that the 0 (zero) values in the data are omitted in the example program.CPLEX makes extensive use of sparse matrix methods and, although CPLEXcorrectly handles any explicit zero coefficients given to it, most programs solvingmodels of more than modest size benefit (in terms of both storage space andspeed) if the natural sparsity of the model is exploited from the very start.

Before the model is solved, the network optimizer is selected by setting theRootAlg parameter to the value IloCplex::Network, as shown in exampleilolpex2.cpp . The simplex display parameter SimDisplay (documented in thereference manual of CPLEX parameters as simplex iteration information display) isset so that the simplex algorithm issues logging information as it executes.

Setting CPLEX parametersThe sample shows how to set CPLEX parameters in a C++ application..

IloCplex provides a variety of parameters that allow you to control the solutionprocess. They can be categorized as Boolean, integer, numeric, and stringparameters. They are represented by the enumeration types IloCplex::BoolParam,IloCplex::IntParam, IloCplex::NumParam, and IloCplex::StringParam, respectively.

Modifying an optimization problemThe sample emphasizes modification with respect to extraction and notification.

After the simple model is solved and the resulting objective value is passed to theoutput channel cplex.out, the remaining constraints are created and added to themodel. At this time the model has already been extracted to the object cplex. As aconsequence, whenever the model is modified by adding a constraint, this additionis immediately reflected in the object cplex via notification.

Starting from a previous basisThe sample illustrates using an optimal basis from a previous solution.

Before solving the modified problem, example ilolpex3.cpp sets the optimizeroption to Dual, as this is the algorithm that can generally take best advantage ofthe optimal basis from the previous solve after the addition of constraints.

Complete programThe sample is available online.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation /examples/src/ilolpex3.cpp .

Chapter 4. Concert Technology tutorial for C++ users 63

Page 76: Ibm Ilog Cplex User Manual 12.6

64 Getting Started with CPLEX

Page 77: Ibm Ilog Cplex User Manual 12.6

Chapter 5. Concert Technology tutorial for Java users

Applications written in the Java programming language use CPLEX with ConcertTechnology in the Java API.

OverviewA typical application with CPLEX in Java includes these features.

Concert Technology allows your application to call IBM ILOG CPLEX directly,through the Java Native Interface (JNI). This Java interface supplies a rich meansfor you to use Java objects to build your optimization model.

The class IloCplex implements the Concert Technology interface for creatingvariables and constraints. It also provides functionality for solving MathematicalPrograming (MP) problems and accessing solution information.

Compiling CPLEX in Concert Technology Java applicationsWhen you compile CPLEX in a Java application, you need to specify the locationof the CPLEX JAR in the classpath.

Paths and JARsYour Java classpath is important to CPLEX in Java applications.

When compiling a Java application that uses Concert Technology, you need toinform the Java compiler where to find the file cplex.jar containing the CPLEXConcert Technology class library. To do this, you add the cplex.jar file to yourclasspath. This is most easily done by passing the command-line option to the Javacompiler javac, like this:

–classpath path_to_cplex.jar

If you need to include other Java class libraries, you should add the correspondingjar files to the classpath as well. Ordinarily, you should also include the currentdirectory (.) to be part of the Java classpath.

At execution time, the same classpath setting is needed. Additionally, since CPLEXis implemented via JNI, you need to instruct the Java Virtual Machine (JVM) whereto find the shared library (or dynamic link library) containing the native code to becalled from Java. You indicate this location with the command line option:

-Djava.library.path=path_to_shared_library

to the java command. Note that, unlike the cplex.jar file, the shared library issystem-dependent; thus the exact path name of the location for the library to beused may differ depending on the platform you are using.

Adapting build procedures to your platformCPLEX makefiles and other aids support Java application development withCPLEX.

© Copyright IBM Corp. 1987, 2013 65

Page 78: Ibm Ilog Cplex User Manual 12.6

About this task

Pre-configured compilation and runtime commands are provided in the standarddistribution, through the UNIX makefiles and Windows javamake file for Nmake .However, these scripts presume a certain relative location for the files alreadymentioned; for application development, most users will have their source files insome other location.

Here are suggestions for establishing build procedures for your application.

Procedure1. First check the readme.html file in the standard distribution, under the

Supported Platforms heading to locate the machine and libformat entry for yourUNIX platform, or the compiler and library-format combination for Windows.

2. Go to the subdirectory in the examples directory where CPLEX is installed onyour machine. On UNIX, this will be machine/libformat, and on Windows it willbe compiler\libformat. This subdirectory will contain a makefile or javamakeappropriate for your platform.

3. Then use this file to compile the examples that came in the standarddistribution by calling make execute_java (UNIX) or nmake -f javamakeexecute (Windows).

4. Carefully note the locations of the needed files, both during compilation and atrun time, and convert the relative path names to absolute path names for use inyour own working environment.

In case problems ariseCPLEX supports trouble-shooting procedures specific to Java applications.

About this task

If a problem occurs in the compilation phase, make sure your Java compiler iscorrectly set up and that your classpath includes the cplex.jar file.

If compilation is successful and the problem occurs when executing yourapplication, there are three likely causes:

Procedure1. If you get a message like java.lang.NoClassDefFoundError your classpath is

not correctly set up. Make sure you use -classpath <path_to_cplex.jar> inyour java command.

2. If you get a message like java.lang.UnsatisfiedLinkError, you need to set upthe path correctly so that the JVM can locate the CPLEX shared library. Makesure you use the following option in your java command:-Djava.library.path=<path_to_shared_library>

66 Getting Started with CPLEX

Page 79: Ibm Ilog Cplex User Manual 12.6

The design of CPLEX in Concert Technology Java applicationsYour Java application includes CPLEX as a component.

Figure 4 illustrates the design of Concert Technology and how a user-applicationuses it. Concert Technology defines a set of interfaces for modeling objects. Suchinterfaces do not actually consume memory. (For this reason, the box in the figurehas a dotted outline.) When a user creates a Concert Technology modeling objectusing CPLEX, an object is created in CPLEX to implement the interface defined byConcert Technology. However, a user application never accesses such objectsdirectly but only communicates with them through the interfaces defined byConcert Technology.

For more detail about these ideas, see the CPLEX User’s Manual, especially thetopic Concert Technology for Java users.

The anatomy of a Concert Technology Java applicationA Java application of CPLEX includes these parts.

Structure of an applicationJava applications using CPLEX observe object-oriented conventions.

To use the CPLEX Java interfaces, you need to import the appropriate packagesinto your application with these lines:import ilog.concert.*;import ilog.cplex.*;

As for every Java application, a CPLEX application is implemented as a method ofa class. In this discussion, the method will be the static main method. The first taskis to create an IloCplex object. It is used to create all the modeling objects neededto represent the model. For example, an integer variable with bounds 0 and 10 iscreated by calling cplex.intVar(0, 10) , where cplex is the IloCplex object.

Figure 4. A View of CPLEX in Concert Technology

Chapter 5. Concert Technology tutorial for Java users 67

Page 80: Ibm Ilog Cplex User Manual 12.6

Since Java error handling in CPLEX uses exceptions, you should include theConcert Technology part of an application in a try /catch statement. All theexceptions thrown by any Concert Technology method are derived fromIloException. Thus IloException should be caught in the catch statement.

In summary, here is the structure of a Java application that calls CPLEX:-classpath <path_to_cplex.jar>

-Djava.library.path=<path_to_shared_library>import ilog.concert.*;import ilog.cplex.*;

import ilog.concert.*;import ilog.cplex.*;static public class Application {

static public main(String[] args) {try {

IloCplex cplex = new IloCplex();// create model and solve it

} catch (IloException e) {System.err.println("Concert exception caught: " + e);

}}

}

Create the modelJava methods create a model in a Java application of CPLEX.

The IloCplex object provides the functionality to create an optimization model thatcan be solved with IloCplex. The class IloCplex implements the ConcertTechnology interface IloModeler and its extensions IloMPModeler andIloCplexModeler. These interfaces define the constructors for modeling objects ofthe following types, which can be used with IloCplex :

IloNumVar modeling variablesIloRange ranged constraints of the type lb <= expr <=

ubIloObjective optimization objectiveIloNumExpr expression using variables

Modeling variables are represented by objects implementing the IloNumVarinterface defined by Concert Technology. Here is how to create three continuousvariables, all with bounds 0 and 100 :IloNumVar[] x = cplex.numVarArray(3, 0.0, 100.0);

There is a wealth of other methods for creating arrays or individual modelingvariables. The documentation for IloModeler, IloCplexModeler, and IloMPModelergives you the complete list.

Modeling variables build expressions, of type IloNumExpr, for use in constraints orthe objective function of an optimization model. For example, the expression:x[0] + 2*x[1] + 3*x[2]

can be created like this:IloNumExpr expr = cplex.sum(x[0],

cplex.prod(2.0, x[1]),cplex.prod(3.0, x[2]));

68 Getting Started with CPLEX

Page 81: Ibm Ilog Cplex User Manual 12.6

Another way of creating an object representing the same expression is to use anexpression of IloLinearNumExpr. Here is how:

IloLinearNumExpr expr = cplex.linearNumExpr();expr.addTerm(1.0, x[0]);expr.addTerm(2.0, x[1]);expr.addTerm(3.0, x[2]);

The advantage of using IloLinearNumExpr over the first way is that you can moreeasily build up your linear expression in a loop, which is what is typically neededin more complex applications. The interface IloLinearNumExpr is an extension ofIloNumExpr and thus can be used anywhere an expression can be used.

As mentioned before, expressions can be used to create constraints or an objectivefunction for a model. Here is how to create a minimization objective for thatexpression:

In addition to your creating an objective, you must also instruct IloCplex to usethat objective in the model it solves. To do so, add the objective to IloCplex likethis:cplex.add(obj);

Every modeling object that is to be used in a model must be added to the IloCplexobject. The variables need not be explicitly added as they are treated implicitlywhen used in the expression of the objective. More generally, every modelingobject that is referenced by another modeling object which itself has been added toIloCplex, is implicitly added to IloCplex as well.

There is a shortcut notation for creating and adding the objective:cplex.addMinimize(expr);This shortcut uses the method addMinimize

Since the objective is not otherwise accessed, it does not need to be stored in thevariable obj .

Adding constraints to the model is just as easy. For example, the constraint

-x[0] + x[1] + x[2] <= 20.0

can be added by calling:cplex.addLe(cplex.sum(cplex.negative(x[0]), x[1], x[2]), 20);

Again, many methods are provided for adding other constraint types, includingequality constraints, greater than or equal to constraints, and ranged constraints.Internally, they are all represented as IloRange objects with appropriate choices ofbounds, which is why all these methods return IloRange objects. Also, note thatthe expressions above could have been created in many different ways, includingthe use of IloLinearNumExpr.

Solve the modelJava methods create the object-oriented optimizer in a Java application of CPLEX.

So far you have seen some methods of IloCplex for creating models. All suchmethods are defined in the interfaces IloModeler and its extension IloMPModelerand IloCplexModeler. However, IloCplex not only implements these interfaces butalso provides additional methods for solving a model and querying its results.

Chapter 5. Concert Technology tutorial for Java users 69

Page 82: Ibm Ilog Cplex User Manual 12.6

After you have created a model as explained in “Create the model” on page 68, theobject IloCplex is ready to solve the problem, which consists of the model and allthe modeling objects that have been added to it. Invoking the optimizer then is assimple as calling the method solve .

That method returns a Boolean value indicating whether the optimizationsucceeded in finding a solution. If no solution was found, false is returned. If trueis returned, then CPLEX found a feasible solution, though it is not necessarily anoptimal solution. More precise information about the outcome of the last call to themethod solve can be obtained from the method getStatus .

The returned value tells you what CPLEX found out about the model: whether itfound the optimal solution or only a feasible solution, whether it proved the modelto be unbounded or infeasible, or whether nothing at all has been proved at thispoint. Even more detailed information about the termination of the optimizer callis available through the method getCplexStatus .

Query the resultsJava methods query results from a Java application of CPLEX.

If the method solve succeeded in finding a solution, you will then want to accessthat solution. The objective value of that solution can be queried using a statementlike this:double objval = cplex.getObjValue();

Similarly, solution values for all the variables in the array x can be queried bycalling:double[] xval = cplex.getValues(x);

More solution information can be queried from IloCplex , including slacks and,depending on the algorithm that was applied for solving the model, duals, reducedcost information, and basis information.

Building and solving a small LP model in JavaAn example shows how to solve a model in a Java application of CPLEX.

Example: LPex1.javaThis example illustrates solving a model in a Java application of CPLEX.

The example LPex1.java , part of the standard distribution of CPLEX, is a programthat builds a specific small LP model and then solves it. This example follows thegeneral structure found in many CPLEX Concert Technology applications, anddemonstrates three main ways to construct a model:v “Modeling by rows” on page 72;v “Modeling by columns” on page 72;v “Modeling by nonzeros” on page 73.

Example LPex1.java is an extension of the example presented in “Entering theexample” on page 21:

Maximize x1 + 2x2 + 3x3

70 Getting Started with CPLEX

Page 83: Ibm Ilog Cplex User Manual 12.6

subject to–x1 + x2 . + x3 ≤ 20

x1 – 3x2 + x3 ≤ 30with these bounds

0 ≤ x1 ≤ 40

0 ≤ x2 ≤ infinity

0 ≤ x3 ≤ infinity

After an initial check that a valid option string was provided as a callingargument, the program begins by enclosing all executable statements that follow ina try/catch pair of statements. In case of an error CPLEX Concert Technology willthrow an exception of type IloException, which the catch statement then processes.In this simple example, an exception triggers the printing of a line stating Concertexception 'e' caught , where e is the specific exception.

First, create the model object cplex by executing the following statement:IloCplex cplex = new IloCplex();

At this point, the cplex object represents an empty model, that is, a model with novariables, constraints, or other content. The model is then populated in one ofseveral ways depending on the command line argument. The possible choices areimplemented in the methodsv populateByRow

v populateByColumn

v populateByNonzero

All these methods pass the same three arguments. The first argument is the cplexobject to be populated. The second and third arguments correspond to thevariables (var ) and range constraints (rng ) respectively; the methods will write tovar[0] and rng[0] an array of all the variables and constraints in the model, forlater access.

After the model has been created in the cplex object, it is ready to be solved by acall to cplex.solve. The solution log will be output to the screen; this is becauseIloCplex prints all logging information to the OutputStream cplex. output, whichby default is initialized to System.out. You can change this by calling the methodcplex. setOut. In particular, you can turn off logging by setting the output streamto null, that is, by calling cplex.setOut(null). Similarly, IloCplex issues warningmessages to cplex. warning, and cplex. setWarning can be used to change (or turnoff) the OutputStream that will be used.

If the solve method finds a feasible solution for the active model, it returns true.The next section of code accesses the solution. The method cplex.getValues(var[0]) returns an array of primal solution values for all the variables.This array is stored as double[]x . The values in x are ordered such that x[j] is theprimal solution value for variable var[0][j] . Similarly, the reduced costs, duals,and slack values are queried and stored in arrays dj, pi, and slack, respectively.Finally, the solution status of the active model and the objective value of thesolution are queried with the methods IloCplex. getStatus and IloCplex.getObjValue, respectively. The program then concludes by printing the values thathave been obtained in the previous steps, and terminates after calling cplex. end to

Chapter 5. Concert Technology tutorial for Java users 71

Page 84: Ibm Ilog Cplex User Manual 12.6

free the memory used by the model object; the catch method of IloExceptionprovides screen output in case of any error conditions along the way.

The remainder of the example source code is devoted to the details of populatingthe model object and the following three sections provide details on how themethods work.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation /examples/src/LPex1.java.

Modeling by rowsJava methods support modeling by rows in this example of a Java application ofCPLEX.

The method populateByRow creates the model by adding the finished constraintsand objective function to the active model, one by one. It does so by first creatingthe variables with the method cplex. numVarArray. Then the minimizationobjective function is created and added to the active model with the methodIloCplex. addMinimize. The expression that defines the objective function iscreated by a method, IloCplex. scalProd, that forms a scalar product using anarray of objective coefficients times the array of variables. Finally, each of the twoconstraints of the model are created and added to the active model with themethod IloCplex. addLe. For building the constraint expression, the methodsIloCplex. sum and IloCplex. prod are used, as a contrast to the approach used inconstructing the objective function.

Modeling by columnsJava methods support modeling by columns in this example of a Java applicationof CPLEX.

While for many examples population by rows may seem most straightforward andnatural, there are some models where population by columns is a more natural ormore efficient approach to implement. For example, problems with networkstructure typically lend themselves well to modeling by column. Readers familiarwith matrix algebra may view the method populateByColumn as producing thetranspose of what is produced by the method populateByRow . In contrast tomodeling by rows, modeling by columns means that the coefficients of theconstraint matrix are given in a column-wise way. As each column represents theconstraint coefficients for a given variable in the linear program, this modelingapproach is most natural where it is easy to access the matrix coefficients byiterating through all the variables, such as in network flow problems.

Range objects are created for modeling by column with only their lower and upperbound. No expressions are given; building them at this point would be impossiblesince the variables have not been created yet. Similarly, the objective function iscreated only with its intended optimization sense, and without any expression.

Next the variables are created and installed in the existing ranges and objective.These newly created variables are introduced into the ranges and the objective bymeans of column objects, which are implemented in the class IloColumn. Objectsof this class are created with the methods IloCplex. column, and can be linkedtogether with the method IloColumn. and to form aggregate IloColumn objects.

An instance of IloColumn created with the method IloCplex. column containsinformation about how to use this column to introduce a new variable into an

72 Getting Started with CPLEX

Page 85: Ibm Ilog Cplex User Manual 12.6

existing modeling object. For example, if obj is an instance of a class thatimplements the interface IloObjective, then cplex.column(obj, 2.0) creates aninstance of IloColumn containing the information to install a new variable in theexpression of the IloObjective object obj with a linear coefficient of 2.0. Similarly,for rng, a constraint that is an instance of a class that implements the interfaceIloRange, the invocation of the method cplex.column(rng, -1.0) creates anIloColumn object containing the information to install a new variable into theexpression of rng , as a linear term with coefficient -1.0.

When you use the approach of modeling by column, new columns are created andinstalled as variables in all existing modeling objects where they are needed. To dothis with Concert Technology, you create an IloColumn object for every modelingobject in which you want to install a new variable, and link them together with themethod IloColumn. and . For example, the first variable in populateByColumn iscreated like this:

The three methods model.column create IloColumn objects for installing a newvariable in the objective obj and in the constraints r0 and r1, with linearcoefficients 1.0 , -1.0, and 1.0, respectively. They are all linked to an aggregatecolumn object by the method and. This aggregate column object is passed as thefirst argument to the method numVar, along with the bounds 0.0 and 40.0 as theother two arguments. The method numVar now creates a new variable andimmediately installs it in the modeling objects obj, r0, and r1 as defined by theaggregate column object. After it has been installed, the new variable is returnedand stored in var[0][0].

Modeling by nonzerosJava methods support modeling by nonzeros in this example of a Java applicationof CPLEX.

The last of the three functions for building the model is populateByNonzero . Thisfunction creates the variables with only their bounds, and the empty constraints,that is, ranged constraints with only lower and upper bound but with noexpression. Only after that are the expressions constructed over these existingvariables, in a manner similar to the ones already described; they are installed inthe existing constraints with the method IloRange. setExpr .

Chapter 5. Concert Technology tutorial for Java users 73

Page 86: Ibm Ilog Cplex User Manual 12.6

74 Getting Started with CPLEX

Page 87: Ibm Ilog Cplex User Manual 12.6

Chapter 6. Concert Technology tutorial for .NET users

CPLEX applications written in C#.NET use Concert Technology in the .NETframework.

Presenting the tutorialCPLEX in the .NET framework supports creating a model, populating it with data,solving the problem, and displaying results of the solution.

This tutorial introduces CPLEX through Concert Technology in the .NETframework. It gives you an overview of a typical application and highlightsprocedures for:v Creating a modelv Populating the model with data, either by rows, by columns, or by nonzerosv Solving that modelv Displaying results after solving

This chapter concentrates on an example using C#.NET. There are also examples ofVB.NET (Visual Basic in the .NET framework) delivered with CPLEX inyourCPLEXhome\examples\src\vb . Because of their .NET framework, thoseVB.NET examples differ from the traditional Visual Basic examples that mayalready be familiar to some CPLEX users.

In the standard distribution of the product, the file dotnet.html offers usefuldetails about installing the product as well as compiling and executing examples.

Note:

This tutorial is based on a procedure-based learning strategy. The tutorial is builtaround a sample problem, available in a file that can be opened in an integrateddevelopment environment, such as Microsoft Visual Studio. As you follow thesteps in the tutorial, you can examine the code and apply concepts explained inthe tutorial. Then you compile and execute the code to analyze the results. Ideally,as you work through the tutorial, you are sitting in front of your computer withCPLEX and Concert Technology for .NET users already installed and available inMicrosoft Visual Studio.

What you need to know: prerequisitesPrerequisites for this tutorial include knowledge of C#.NET, familiarity withlinking, compiling, and executing, as well as a quick test of your installation ofCPLEX.

This tutorial requires a working knowledge of C#.NET.

If you are experienced in mathematical programming or operations research, youare probably already familiar with many concepts used in this tutorial. However,little or no experience in mathematical programming or operations research isrequired to follow this tutorial.

© Copyright IBM Corp. 1987, 2013 75

Page 88: Ibm Ilog Cplex User Manual 12.6

You should have CPLEX and Concert Technology for .NET users installed in yourdevelopment environment before starting this tutorial. In your integrateddevelopment environment, you should be able to compile, link, and execute asample application provided with CPLEX and Concert Technology for .NET usersbefore starting the tutorial.

To check your installation before starting the tutorial, open

yourCPLEXhome \examples\platform\format\examples.net.sln

in your integrated development environment, where yourCPLEXhome specifies theplace you installed CPLEX on your platform, and format specifies one of thesepossibilities: stat_mda, stat_mta, or stat_sta. Your integrated developmentenvironment, Microsoft Visual Studio, will then check for the DLLs of CPLEX andConcert Technology for .NET users and warn you if they are not available to it.

Another way to check your installation is to load the project for one of the samplesdelivered with your product. For example, you might load the following projectinto Microsoft Visual Studio to check a C# example of the diet problem:

yourCPLEXhome\examples\platform\format\Diet.csproj

What you will be doingThis tutorial walks you through building and solving a small linear programmingmodel in C#.NET..

CPLEX can work together with Concert Technology for .NET users, a .NET librarythat allows you to model optimization problems independently of the algorithmsused to solve the problem. It provides an extensible modeling layer adapted to avariety of algorithms ready to use off the shelf. This modeling layer enables you tochange your model, without completely rewriting your application.

To find a solution to a problem by means of CPLEX with Concert Technology for.NET users, you use a three-stage method: describe, model, and solve.

The first stage is to describe the problem in natural language.

The second stage is to use the classes and interfaces of Concert Technology for.NET users to model the problem. The model is composed of data, decisionvariables, and constraints. Decision variables are the unknown information in aproblem. Each decision variable has a domain of possible values. The constraintsare limits or restrictions on combinations of values for these decision variables. Themodel may also contain an objective, an expression that can be maximized orminimized.

The third stage is to use the classes of Concert Technology for .NET users to solvethe problem. Solving the problem consists of finding a value for each decisionvariable while simultaneously satisfying the constraints and maximizing orminimizing an objective, if one is included in the model.

In these tutorials, you will describe, model, and solve a simple problem that alsoappears elsewhere in C, C++, and Java chapters of this manual:v “Building and solving a small LP model in C” on page 90v “Building and solving a small LP model in C++” on page 55

76 Getting Started with CPLEX

Page 89: Ibm Ilog Cplex User Manual 12.6

v “Building and solving a small LP model in Java” on page 70

Describe

The first step is for you to describe the problem in natural language and answerbasic questions about the problem.v What is the known information in this problem? That is, what data is available?v What is the unknown information in this problem? That is, what are the decision

variables?v What are the limitations in the problem? That is, what are the constraints on the

decision variables?v What is the purpose of solving this problem? That is, what is the objective

function?

Note:

Though the Describe step of the process may seem trivial in a simple problem likethis one, you will find that taking the time to fully describe a more complexproblem is vital for creating a successful application. You will be able to code yourapplication more quickly and effectively if you take the time to describe the model,isolating the decision variables, constraints, and objective.

Model

The second stage is for you to use the classes of Concert Technology for .NETusers to build a model of the problem. The model is composed of decision variablesand constraints on those variables. The model of this problem also contains anobjective.

Solve

The third stage is for you to use an instance of the class Cplex to search for asolution and to solve the problem. Solving the problem consists of finding a valuefor each variable while simultaneously satisfying the constraints and minimizingthe objective.

DescribeAsk these questions to describe an optimization problem adequately for applicationdevelopment.

The aim in this tutorial is to see three different ways to build a model: by rows, bycolumns, or by nonzeros. After building the model of the problem in one of thoseways, the application optimizes the problem and displays the solution.

Step One: Describe the problem

Write a natural language description of the problem and answer these questions:v What is known about the problem?v What are the unknown pieces of information (the decision variables) in this

problem?v What are the limitations (the constraints) on the decision variables?v What is the purpose (the objective) of solving this problem?

Chapter 6. Concert Technology tutorial for .NET users 77

Page 90: Ibm Ilog Cplex User Manual 12.6

Building a small LP problem in C#

Here is a conventional formulation of the problem that the example optimizes:

Maximize x1 + 2x2 + 3x3

subject to–x1 + x2 + x3 ≤ 20

x1 – 3x2 + x3 ≤ 30with these bounds

0 ≤ x1 ≤ 40

0 ≤ x2 ≤ infinity

0 ≤ x3 ≤ infinity

v What are the decision variables in this problem?

x1, x2, x3

v What are the constraints?

–x1 + x2 + x3 ≤ 20

x1 – 3x2 + x3 ≤ 30

0 ≤ x1 ≤ 40

0 ≤ x2 ≤ infinity

0 ≤ x3 ≤ infinity

v What is the objective?

Maximize x1 + 2x2 + 3x3

ModelUse classes of Concert Technology for .NET users to build a model for theproblem.

After you have written a description of the problem, you can use classes ofConcert Technology for .NET users with CPLEX to build a model.

Step 2: Open the file

Open the file yourCPLEXhome \examples\src\tutorials\LPex1lesson.cs in yourintegrated development environment, such as Microsoft Visual Studio.

Step 3: Create the model object

Go to the comment Step 3 in that file, and add this statement to create the Cplexmodel for your application.

Cplex cplex = new Cplex();

That statement creates an empty instance of the class Cplex . In the next steps, youwill add methods that make it possible for your application populate the modelwith data, either by rows, by columns, or by nonzeros.

78 Getting Started with CPLEX

Page 91: Ibm Ilog Cplex User Manual 12.6

Step 4: Populate the model by rows

Now go to the comment Step 4 in that file, and add these lines to create a methodto populate the empty model with data by rows.

internal static void PopulateByRow(IMPModeler model,INumVar[][] var,IRange[][] rng) {

double[] lb = {0.0, 0.0, 0.0};double[] ub = {40.0,

System.Double.MaxValue,System.Double.MaxValue};

INumVar[] x = model.NumVarArray(3, lb, ub);var[0] = x;

double[] objvals = {1.0, 2.0, 3.0};model.AddMaximize(model.ScalProd(x, objvals));

rng[0] = new IRange[2];rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, x[0]),

model.Prod( 1.0, x[1]),model.Prod( 1.0, x[2])), 20.0);

rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, x[0]),model.Prod(-3.0, x[1]),model.Prod( 1.0, x[2])), 30.0);

}

Those lines populate the model with data specific to this particular example.However, you can see from its use of the interface IMPModeler how to add rangedconstraints to a model. IMPModeler is the Concert Technology interface typicallyused to build math programming (MP) matrix models. You will see its use again inStep 5 and Step 6.

Step 5: Populate the model by columns

Go to the comment Step 5 in the file, and add these lines to create a method topopulate the empty model with data by columns.

internal static void PopulateByColumn(IMPModeler model,INumVar[][] var,IRange[][] rng) {

IObjective obj = model.AddMaximize();

rng[0] = new IRange[2];rng[0][0] = model.AddRange(-System.Double.MaxValue, 20.0);rng[0][1] = model.AddRange(-System.Double.MaxValue, 30.0);

IRange r0 = rng[0][0];IRange r1 = rng[0][1];

var[0] = new INumVar[3];var[0][0] = model.NumVar(model.Column(obj, 1.0).And(

model.Column(r0, -1.0).And(model.Column(r1, 1.0))),0.0, 40.0);

var[0][1] = model.NumVar(model.Column(obj, 2.0).And(model.Column(r0, 1.0).And(model.Column(r1, -3.0))),0.0, System.Double.MaxValue);

var[0][2] = model.NumVar(model.Column(obj, 3.0).And(model.Column(r0, 1.0).And(model.Column(r1, 1.0))),0.0, System.Double.MaxValue);

}

Chapter 6. Concert Technology tutorial for .NET users 79

Page 92: Ibm Ilog Cplex User Manual 12.6

Again, those lines populate the model with data specific to this problem. Fromthem you can see how to use the interface IMPModeler to add columns to an emptymodel.

While for many examples population by rows may seem most straightforward andnatural, there are some models where population by columns is a more natural ormore efficient approach to implement. For example, problems with networkstructure typically lend themselves well to modeling by column. Readers familiarwith matrix algebra may view the method populateByColumn as the transpose ofpopulateByRow .

In this approach, range objects are created for modeling by column with only theirlower and upper bound. No expressions over variables are given because buildingthem at this point would be impossible since the variables have not been createdyet. Similarly, the objective function is created only with its intended optimizationsense, and without any expression.

Next the variables are created and installed in the existing ranges and objective.These newly created variables are introduced into the ranges and the objective bymeans of column objects, which are implemented in the class IColumn. Objects ofthis class are created with the methods Cplex.Column, and can be linked togetherwith the method IColumn.And to form aggregate IColumn objects.

An IColumn object created with the method ICplex.Column contains informationabout how to use this column to introduce a new variable into an existingmodeling object. For example if obj is an IObjective object, cplex.Column(obj,2.0) creates an IColumn object containing the information to install a new variablein the expression of the IObjective object obj with a linear coefficient of 2.0 .Similarly, for an IRange constraint rng , the method call cplex.Column(rng, -1.0)creates an IColumn object containing the information to install a new variable intothe expression of rng , as a linear term with coefficient -1.0 .

In short, when you use a modeling-by-column approach, new columns are createdand installed as variables in all existing modeling objects where they are needed.To do this with Concert Technology, you create an IColumn object for everymodeling object in which you want to install a new variable, and link themtogether with the method IColumn.And .

Step 6: Populate the model by nonzeros

Go to the comment Step 6 in the file, and add these lines to create a method topopulate the empty model with data by nonzeros.

internal static void PopulateByNonzero(IMPModeler model,INumVar[][] var,IRange[][] rng) {

double[] lb = {0.0, 0.0, 0.0};double[] ub = {40.0, System.Double.MaxValue, System.Double.MaxValue};INumVar[] x = model.NumVarArray(3, lb, ub);var[0] = x;

double[] objvals = {1.0, 2.0, 3.0};model.Add(model.Maximize(model.ScalProd(x, objvals)));

rng[0] = new IRange[2];rng[0][0] = model.AddRange(-System.Double.MaxValue, 20.0);rng[0][1] = model.AddRange(-System.Double.MaxValue, 30.0);

rng[0][0].Expr = model.Sum(model.Prod(-1.0, x[0]),

80 Getting Started with CPLEX

Page 93: Ibm Ilog Cplex User Manual 12.6

model.Prod( 1.0, x[1]),model.Prod( 1.0, x[2]));

rng[0][1].Expr = model.Sum(model.Prod( 1.0, x[0]),model.Prod(-3.0, x[1]),model.Prod( 1.0, x[2]));

}

In those lines, you can see how to populate an empty model with data indicatingthe nonzeros of the constraint matrix. Those lines first create objects for theobjective and the ranges without expressions. They also create variables withoutcolumns; that is, variables with only their bounds. Then those lines createexpressions over the objective, ranges, and variables and add the expressions to themodel.

Step 7: Add an interface

Go to the comment Step 7 in the file, and add these lines to create a method thattells a user how to invoke this application.internal static void Usage() {

System.Console.WriteLine(“usage: LPex1 <option>”);System.Console.WriteLine(“options: -r build model row by row”);System.Console.WriteLine(“options: -c build model column by column”);System.Console.WriteLine(“options: -n build model nonzero by nonzero”);

}

Step 8: Add a command evaluator

Go to the comment Step 8 in the file, and add these lines to create a switchstatement that evaluates the command that a user of your application might enter.

switch ( args[0].ToCharArray()[1] ) {case 'r': PopulateByRow(cplex, var, rng);

break;case 'c': PopulateByColumn(cplex, var, rng);

break;case 'n': PopulateByNonzero(cplex, var, rng);

break;default: Usage();

return;}

SolveAdd the parts of the application that solve the problem.

After you have declared the decision variables and added the constraints andobjective function to the model, your application is ready to search for a solution.

Step 9: Search for a solution

Go to Step 9 in the file, and add this line to make your application search for asolution.

if ( cplex.Solve() ) {

Step 10: Display the solution

Go to the comment Step 10 in the file, and add these lines to enable yourapplication to display any solution found in Step 9.

Chapter 6. Concert Technology tutorial for .NET users 81

Page 94: Ibm Ilog Cplex User Manual 12.6

double[] x = cplex.GetValues(var[0]);double[] dj = cplex.GetReducedCosts(var[0]);double[] pi = cplex.GetDuals(rng[0]);double[] slack = cplex.GetSlacks(rng[0]);

cplex.Output().WriteLine(“Solution status = “+ cplex.GetStatus());

cplex.Output().WriteLine(“Solution value = “+ cplex.ObjValue);

int nvars = x.Length;for (int j = 0; j < nvars; ++j) {

cplex.Output().WriteLine(“Variable :”+ j+” Value = “+ x[j]+” Reduced cost = “+ dj[j]);

}

int ncons = slack.Length;for (int i = 0; i < ncons; ++i) {

cplex.Output().WriteLine(“Constraint:”+ i+” Slack = “+ slack[i]+” Pi = “+ pi[i]);

}}

Step 11: Save the model to a file

If you want to save your model to a file in LP format, go to the comment Step 11in your application file, and add this line.

cplex.ExportModel(“lpex1.lp”);

If you have followed the steps in this tutorial interactively, you now have acomplete application that you can compile and execute.

Complete programA copy of the sample is available on line.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation \examples\src\csharp\LPex1.cs .

82 Getting Started with CPLEX

Page 95: Ibm Ilog Cplex User Manual 12.6

Chapter 7. Callable Library tutorial

Applications written in C use the CPLEX Callable Library (C API).

The design of the CPLEX Callable LibraryThe architecture of the Callable Library (C API) supports user-written applicationsin C and other programming languages callable from C.

Figure 5 shows a picture of the IBM ILOG CPLEX world. The CPLEX CallableLibrary together with the CPLEX internals make up the CPLEX core. The corebecomes associated with your application through Callable Library routines. TheCPLEX environment and all problem-defining data are established inside theCPLEX core.

The CPLEX Callable Library includes several categories of routines:v optimization and result routines for defining a problem, optimizing it, and

getting the results;v utility routines for addressing application programming matters;v problem modification routines to change a problem after it has been created

within the CPLEX internals;v problem query routines to access information about a problem after it has been

created;v file reading and writing routines to move information from the file system into

your application or out of your application to the file system;v parameter setting and query routines to access and modify the values of control

parameters maintained by CPLEX.

Compiling and linking Callable Library applicationsCompilation and linking an application of the C API differ according to platform.

OverviewCallable Library applications follow conventional coding practices for linking andcompiling.

Figure 5. A View of the CPLEX Callable Library

© Copyright IBM Corp. 1987, 2013 83

Page 96: Ibm Ilog Cplex User Manual 12.6

Each Callable Library is distributed as a single library file libcplex.a orcplexXXX.lib . Use of the library file is similar to that with .o or .obj files. Simplysubstitute the library file in the link procedure. This procedure simplifies linkingand makes sure that the smallest possible executable is generated.

The following compilation and linking instructions assume that the example sourceprograms and CPLEX Callable Library files are in the directories associated with adefault installation of the software. If this is not true, additional compile and linkflags would be required to point to the locations of the include file cplex.h orcplexx.h, and Callable Library files respectively.

Note:

The instructions below were current at the time of publication. As compilers,linkers and operating systems are released, different instructions may apply. Besure to check the Release Notes that come with your CPLEX distribution for anychanges. Also check the CPLEX topics among Detailed System Requirements (DSR)at the IBM.com website.

Building Callable Library applications on UNIX platformsStandard conventions for compiling and linking on UNIX platforms apply to yourCallable Library applications.

To compile and execute an example (lpex1) do the following tasks:% cd examples/platform/format

% make lpex1 #to compile and execute the first CPLEX example

In that command, platform specifies the name of the subdirectory corresponding toyour type of machine, and format specifies your particular library format, such asstatic, multithreaded, or other format.

A list of all the examples that can be built this way is to be found in the makefileby looking for C_EX (C examples), or you can view the files listed in examples/src.

The makefile contains recommended compiler flags and other settings for yourparticular computer, which you can find by searching in it for "Compiler options"and use in your applications that call CPLEX.

Building Callable Library applications on Win32 platformsStandard conventions for compiling and linking on various Windows platformsapply to your Callable Library applications.

Building a CPLEX application using Microsoft Visual C++ Integrated DevelopmentEnvironment, or the Microsoft Visual C++ command line compiler are explainedhere.

Microsoft Visual C++ IDE

To make a CPLEX Callable Library application using Visual C++, first create oropen a project in the Visual C++ Integrated Development Environment (IDE).Project files are provided for each of the examples found in the directory or folderexamples\platform\format where platform and format refer to your type of machineand compiler. For details about the build process, refer to the information filemsvc.html, which is found in the top of the installed CPLEX directory structure.

84 Getting Started with CPLEX

Page 97: Ibm Ilog Cplex User Manual 12.6

Note:

The distributed application must be able to locate CPLEXXXX.dll at run time.

Microsoft Visual C++ Command Line Compiler

If the Visual C++ command line compiler is used outside of the IDE, the commandshould resemble the following example. The example command assumes that thefile cplex XXX .lib is in the current directory with the source file lpex1.c , and thatthe line in the source file "#include <ilcplex/cplex.h> " correctly points to thelocation of the include file or else has been modified to do so (or that thedirectories containing these files have been added to the environment variables LIBand INCLUDE respectively).cl lpex1.c cplexXXX.lib

This command will create the executable file lpex1.exe .

Using Dynamic Loading

Some projects require more precise control over the loading and unloading ofDLLs. For information on loading and unloading DLLs without using staticlinking, please refer to the compiler documentation or to a book such as AdvancedWindows by Jeffrey Richter from Microsoft Press. If this is not a requirement, thestatic link implementations already mentioned are easier to use.

How CPLEX worksCPLEX carries out these activities when it is invoked from the Callable Library (CAPI).

OverviewYour C code includes these basic steps in a Callable Library application.

When your application uses routines of the CPLEX Callable Library, it must firstopen the CPLEX environment, then create and populate a problem object before itsolves a problem. Before it exits, the application must also free the problem objectand release the CPLEX environment. The following sections explain those steps.

Opening the CPLEX environmentYour Callable Library application initializes the CPLEX environment.

CPLEX requires a number of internal data structures in order to execute properly.These data structures must be initialized before any call to the CPLEX CallableLibrary. The first call to the CPLEX Callable Library is always to the routineCPXopenCPLEX. This routine returns a pointer to the CPLEX environment. Thispointer is then passed to every CPLEX Callable Library routine, except those, suchas CPXmsg, which do not require an environment.

The application developer must make an independent decision as to whether thevariable containing the environment pointer is a global or local variable. Multipleenvironments are allowed, but extensive opening and closing of environments maycreate significant overhead and degrade performance; typical applications makeuse of only one environment for the entire execution, since a single environmentmay hold as many problem objects as the user wants. After all calls to the CallableLibrary are complete, the environment is released by the routine CPXcloseCPLEX.

Chapter 7. Callable Library tutorial 85

Page 98: Ibm Ilog Cplex User Manual 12.6

This routine specifies to CPLEX that all calls to the Callable Library are complete,any memory allocated by CPLEX is returned to the operating system, and the useof CPLEX is ended for this run.

Instantiating the problem objectYour Callable Library application creates a problem object in the environment.

A problem object is instantiated (created and initialized) by CPLEX when you callthe routine CPXcreateprob. It is destroyed when you call CPXfreeprob. CPLEXallows you to create more than one problem object, although typical applicationswill use only one. Each problem object is referenced by a pointer returned byCPXcreateprob and represents one specific problem instance. Most Callable Libraryfunctions (except parameter setting functions and message handling functions)require a pointer to a problem object.

Note:

An attempt to use a problem object in any environment other than theenvironment (or a child of that environment) where the problem object was createdwill raise an error.

Populating the problem objectYour Callable Library application populates the problem object with data.

The problem object instantiated by CPXcreateprob represents an empty problemthat contains no data; it has zero constraints, zero variables, and an emptyconstraint matrix. This empty problem object must be populated with data. Thisstep can be carried out in several ways.v The problem object can be populated by assembling arrays of data and then

calling CPXcopylp to copy the data into the problem object. (For example, see“Building and solving a small LP model in C” on page 90.)

v Alternatively, you can populate the problem object by sequences of calls to theroutines CPXnewcols, CPXnewrows, CPXaddcols, CPXaddrows, and CPXchgcoeflist ;these routines may be called in any order that is convenient. (For example, see“Adding rows to a problem: example lpex3.c” on page 92.)

v If the data already exist in a file using MPS format or LP format, you can useCPXreadcopyprob to read the file and copy the data into the problem object. (Forexample, see “Reading a problem from a file: example lpex2.c” on page 91.)

Changing the problem objectIf your Callable Library application modifies the problem object, consider theseissues.

A major consideration in the design of CPLEX is the need to re-optimize modifiedlinear programs efficiently. In order to accomplish that, CPLEX must be aware ofchanges that have been made to a linear program since it was last optimized.Problem modification routines are available in the Callable Library.

Do not change the problem by changing the original problem data arrays and thenmaking a call to CPXcopylp. Instead, change the problem using the problemmodification routines, allowing CPLEX to make use of as much solutioninformation as possible from the solution of the problem before the modificationstook place.

86 Getting Started with CPLEX

Page 99: Ibm Ilog Cplex User Manual 12.6

For example, suppose that a problem has been solved, and that the user haschanged the upper bound on a variable through an appropriate call to the CPLEXCallable Library. A re-optimization would then begin from the previous optimalbasis, and if that old basis were still optimal, then that information would bereturned without even the need to refactor the old basis.

Creating a successful Callable Library applicationSuccessful applications of the C API often follow these guidelines.

OverviewThis outline suggests useful steps in developing a Callable Library application.

Callable Library applications are created to solve a wide variety of problems. Eachapplication shares certain common characteristics, regardless of its apparentuniqueness. The following steps can help you minimize development time and getmaximum performance from your programs:

Prototype the modelA small model for prototyping may be helpful, especially in applications to solvevery large models.

Create a small model of the problem to be solved. An algebraic modeling languageis sometimes helpful during this step.

Identify the routines to callThis guideline may help you identify relevant Callable Library routines to use.

By separating the application into smaller components, you can easily identify thetools needed to complete the application. Part of this process consists of identifyingthe Callable Library routines that will be called by your application.

In some applications, the Callable Library is a small part of a larger program. Inthat case, the only CPLEX routines needed may be for:v problem creation;v optimizing;v obtaining results.

In other cases the Callable Library is used extensively in the application. If so,Callable Library routines may also be needed to:v modify the problem;v set parameters;v manage input and output messages and files;v query problem data.

Test procedures in the applicationThe Interactive Optimizer offers a test-bed for Callable Library applications.

It is often possible to test the procedures of an application in the CPLEX InteractiveOptimizer with a small prototype of the model. Doing so will help identify theCallable Library routines required. The test may also uncover any flaws inprocedure logic before you invest significant development effort.

Chapter 7. Callable Library tutorial 87

Page 100: Ibm Ilog Cplex User Manual 12.6

Trying the CPLEX Interactive Optimizer is an easy way to decide the bestoptimization procedure and parameter settings.

Assemble the dataTo populate the model with data, CPLEX offers alternative routines.

You must decide which approach to populating the problem object is best for yourapplication. Reading an MPS or LP file may reduce the coding effort but canincrease the run-time and disk-space requirements of the program. Building theproblem in memory and then calling CPXcopylp avoids time consuming disk-filereading. Using the routines CPXnewcols, CPXnewrows, CPXaddcols, CPXaddrows, andCPXchgcoeflist can lead to modular code that may be more easily maintained thanif you assemble all model data in one step.

Another consideration is that if the Callable Library application reads an MPS orLP formatted file, usually another application is required to generate that file.Particularly in the case of MPS files, the data structures used to generate the filecould almost certainly be used to build the problem-defining arrays for CPXcopylpdirectly. The result would be less coding and a faster, more efficient application.These observations suggest that formatted files may be useful when prototypingyour application, while assembling the arrays in memory may be a usefulenhancement for a production application.

Choose an optimizerAccording to problem type, consider which optimizer to use.

After a problem object has been instantiated and populated, it can be solved usingone of the optimizers provided by the CPLEX Callable Library. The choice ofoptimizer depends on the problem type.v LP and QP problems can be solved by:

– the primal simplex optimizer;– the dual simplex optimizer; and– the barrier optimizer.

v LP and QP problems with a substantial network can also be solved by a specialnetwork optimizer.

v LP problems can also be solved by:– the sifting optimizer; and– the concurrent optimizer.

v If the problem includes integer variables, mixed integer programming (MIP)must be used.

There are also many different possible parameter settings for each optimizer. Thedefault values will usually be the best for linear programs. Integer programmingproblems are more sensitive to specific settings, so additional experimentation willoften be useful.

Choosing the best way to solve the problem can dramatically improveperformance. For more information, refer to the sections about tuning LPperformance and trouble-shooting MIP performance in the CPLEX User’s Manual.

88 Getting Started with CPLEX

Page 101: Ibm Ilog Cplex User Manual 12.6

Observe good programming practicesCPLEX supports standard programming conventions in Callable Libraryapplications.

Using good programming practices will save development time and make theprogram easier to understand and modify. A list of good programming practices isprovided in the CPLEX User’s Manual, in Developing CPLEX applications.

Debug your programCPLEX is compatible with debuggers and other programming tools.

Your program may not run properly the first time you build it. Learn to use asymbolic debugger and other widely available tools that facilitate the creation oferror-free code. Use the list of debugging tips provided in the CPLEX User’sManual to find and correct problems in your Callable Library application.

Test your applicationCPLEX supports testing of performance and correctness.

After an application works correctly, it still may have errors or features that inhibitexecution speed. To get the most out of your application, be sure to test itsperformance as well as its correctness. Again, the Interactive Optimizer can help.Since the Interactive Optimizer uses the same routines as the Callable Library, itshould take the same amount of time to solve a problem as a Callable Libraryapplication.

Use the CPXwriteprob routine with the SAV format to create a binaryrepresentation of the problem object, then read it in and solve it with theInteractive Optimizer. If the application sets optimization parameters, use the samesettings with the Interactive Optimizer. If your application takes significantlylonger than the Interactive Optimizer, performance within your application canprobably be improved. In such a case, possible performance inhibitors includefragmentation of memory, unnecessary compiler and linker options, and codingapproaches that slow the program without causing it to give incorrect results.

Use the examplesCPLEX offers examples to follow.

The CPLEX Callable Library is distributed with a variety of examples that illustratethe flexibility of the Callable Library. The C source of all examples is provided inthe standard distribution. For explanations about the examples of quadraticprogramming problems (QPs), mixed integer programming problems (MIPs) andnetwork flows, see the CPLEX User’s Manual. Explanations of the followingexamples of LPs appear in this manual:

lpex1.c illustrates various ways of generating aproblem object.

lpex2.c demonstrates how to read a problem from afile, optimize it via a choice of several means,and obtain the solution.

lpex3.c demonstrates how to add rows to a problemobject and re-optimize.

Chapter 7. Callable Library tutorial 89

Page 102: Ibm Ilog Cplex User Manual 12.6

It is a good idea to compile, link, and run all of the examples provided in thestandard distribution.

Building and solving a small LP model in CThis application in the C API introduces basic features of the Callable Library.

The example lpex1.c shows you how to use problem modification routines fromthe CPLEX Callable Library in three different ways to build a model. Theapplication in the example takes a single command line argument that indicateswhether to build the constraint matrix by rows, columns, or nonzeros. Afterbuilding the problem, the application optimizes it and displays the solution. Hereis the problem that the example optimizes:

Maximize x1 + 2x2 + 3x3

subject to–x1 + x2 + x3 ≤ 20

x1 – 3x2 + x 3 ≤ 30with these bounds

0 ≤ x1 ≤ 40

0 ≤ x2 ≤ infinity

0 ≤ x3 ≤ infinity

Before any CPLEX Callable Library routine can be called, your application mustcall the routine CPXopenCPLEX to get a pointer (called env) to the CPLEXenvironment. Your application will then pass this pointer to every Callable Libraryroutine. If this routine fails, it returns an error code. This error code can betranslated to a string by the routine CPXgeterrorstring.

After the CPLEX environment is initialized, the CPLEX screen switch parameter(CPX_PARAM_SCRIND) is turned on by the routine CPXsetintparam . This causes alldefault CPLEX output to appear on the screen. If this parameter is not set, thenCPLEX will generate no viewable output on the screen or in a file.

At this point, the routine CPXcreateprob is called to create an empty problemobject. Based on the problem-building method selected by the command-lineargument, the application then calls a routine to build the matrix by rows, bycolumns, or by nonzeros. The routine populatebyrow first calls CPXnewcols tospecify the column-based problem data, such as the objective, bounds, andvariables names. The routine CPXaddrows is then called to supply the constraints.The routine populatebycolumn first calls CPXnewrows to specify the row-basedproblem data, such as the righthand side values and sense of constraints. Theroutine CPXaddcols is then called to supply the columns of the matrix and theassociated column bounds, names, and objective coefficients. The routinepopulatebynonzero calls both CPXnewrows and CPXnewcols to supply all the problemdata except the actual constraint matrix. At this point, the rows and columns arewell defined, but the constraint matrix remains empty. The routine CPXchgcoeflistis then called to fill in the nonzero entries in the matrix.

After the problem has been specified, the application optimizes it by calling theroutine CPXlpopt. Its default behavior is to use the CPLEX dual simplex optimizer.If this routine returns a nonzero result, then an error occurred. If no error occurred,the application allocates arrays for solution values of the primal variables, dualvariables, slack variables, and reduced costs; then it obtains the solution

90 Getting Started with CPLEX

Page 103: Ibm Ilog Cplex User Manual 12.6

information by calling the routine CPXsolution. This routine returns the status ofthe problem (whether optimal, infeasible, or unbounded, and whether a time limitor iteration limit was reached), the objective value and the solution vectors. Theapplication then displays this information on the screen.

As a debugging aid, the application writes the problem to a CPLEX LP file (namedlpex1.lp) by calling the routine CPXwriteprob. This file can be examined to detectwhether any errors occurred in the routines creating the problem. CPXwriteprobcan be called at any time after CPXcreateprob has created the lp pointer.

The label TERMINATE : is used as a place for the program to exit if any type offailure occurs, or if everything succeeds. In either case, the problem objectrepresented by lp is released by the call to CPXfreeprob, and any memory allocatedfor solution arrays is freed. The application then calls CPXcloseCPLEX; it tellsCPLEX that all calls to the Callable Library are complete. If an error occurs whenthis routine is called, then a call to CPXgeterrorstring is needed to retrieve theerror message, since CPXcloseCPLEX causes no screen output.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation/examples/src/lpex1.c .

Reading a problem from a file: example lpex2.cThis application reads the model from a formatted file.

The previous example, lpex1.c , shows a way to copy problem data into aproblem object as part of an application that calls routines from the CPLEXCallable Library. Frequently, however, a file already exists containing a linearprogramming problem in the industry standard MPS format, the CPLEX LPformat, or the CPLEX binary SAV format. In example lpex2.c , CPLEX file-readingand optimization routines read such a file to solve the problem.

Example lpex2.c uses command line arguments to specify the name of the inputfile and the optimizer to call.

Usage: lpex2 filename optimizer

Where: filename is a file with extension MPS, SAV, or LP (lower case is allowed),and optimizer is one of the following letters:

o defaultp primal simplexd dual simplexn network with dual simplex cleanuph barrier with crossoverb barrier without crossovers siftingc concurrent

For example, this command:

lpex2 example.mps d

reads the file example.mps and solves the problem with the dual simplex optimizer.

Chapter 7. Callable Library tutorial 91

Page 104: Ibm Ilog Cplex User Manual 12.6

To illustrate the ease of reading a problem, the example uses the routineCPXreadcopyprob. This routine detects the type of the file, reads the file, and copiesthe data into the CPLEX problem object that is created with a call toCPXcreateprob. The user need not be concerned with the memory management ofthe data. Memory management is handled transparently by CPXreadcopyprob .

After calling CPXopenCPLEX and turning on the screen switch by setting theCPX_PARAM_SCRIND parameter to CPX_ON, the example creates an empty problemobject with a call to CPXcreateprob. This call returns a pointer, lp , to the newproblem object. Then the data is read in by the routine CPXreadcopyprob. After thedata is copied, the appropriate optimization routine is called, based on thecommand line argument.

After optimization, a call to CPXgetstat retrieves the status of the solution . Thecases of infeasibility or unboundedness in the model are handled in a simplefashion here; a more complex application program might treat these cases in moredetail. With these two cases out of the way, the program then calls CPXsolninfo toexamine the nature of the solution. Certain that a solution exists, the applicationthen calls CPXgetobjval to obtain the objective function value for this solution andreport it.

Next, preparations are made to print the solution value and basis status of eachindividual variable, by allocating arrays of appropriate size; these sizes aredetected by calls to the routines CPXgetnumcols and CPXgetnumrows . Note that abasis is not guaranteed to exist, depending on which optimizer was selected at runtime, so some of these steps, including the call to CPXgetbase , are dependent onthe solution type returned by CPXsolninfo .

The primal solution values of the variables are obtained by a call to CPXgetx , andthen these values (along with the basis statuses if available) are printed, in a loop,for each variable. After that, a call to CPXgetdblquality provides a measure of thenumerical roundoff error present in the solution, by obtaining the maximumamount by which any variable's lower or upper bound is violated.

After the TERMINATE: label, the data for the solution (x , cstat , and rstat ) arefreed. Then the problem object is freed by CPXfreeprob. After the problem is freed,the CPLEX environment is freed by CPXcloseCPLEX.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation/examples/src/lpex2.c.

Adding rows to a problem: example lpex3.cThis application adds rows to a model.

This example illustrates how to develop your own solution algorithms withroutines from the Callable Library. It also shows you how to add rows to aproblem object. Here is the problem that lpex3 solves:

Minimize c^Txsubject to

Hx = d

Ax = b

l ≤ x ≤ u

92 Getting Started with CPLEX

Page 105: Ibm Ilog Cplex User Manual 12.6

where H = ( -1 0 1 0 1 0 0 0)

d = ( -3 )

( 1 -1 0 1 0 0 0 0)

( 1 )

( 0 1 -1 0 0 1 -1 0)

( 4 )

( 0 0 0 -1 0 -1 0 1)

( 3 )

( 0 0 0 0 -1 0 1 -1)

( -5 )

A = ( 2 1 -2 -1 2 -1 -2-3 )

b = ( 4 )

( 1 -3 2 3 -1 2 1 1)

( -2 )

c = (-9 1 4 2 -8 2 8 12)

l = ( 0 0 0 0 0 0 0 0 )u = (50 50 50 50 50

50 50 50 )

The constraints Hx=d represent the flow conservation constraints of a purenetwork flow problem. The example solves this problem in two steps:1. The CPLEX network optimizer is used to solve

Minimize c^Txsubject to

Hx = d

l ≤ x ≤ u

2. The constraints Ax=b are added to the problem, and the dual simplex optimizeris used to solve the new problem, starting at the optimal basis of the simplernetwork problem.

The data for this problem consists of the network portion (using variable namesbeginning with the letter H) and the complicating constraints (using variablenames beginning with the letter A).

The example first calls CPXopenCPLEX to create the environment and then turns onthe CPLEX screen switch (CPX_PARAM_SCRIND ). Next it sets the simplex displaylevel (CPX_PARAM_SIMDISPLAY ) to 2 to indicate iteration-by-iteration output, so thatthe progress of each iteration of the optimizer can be observed. Setting thisparameter to 2 is not generally recommended; the example does so only forillustrative purposes.

The example creates a problem object by a call to CPXcreateprob. Then the networkdata is copied via a call to CPXcopylp. After the network data is copied, theparameter CPX_PARAM_LPMETHOD is set to CPX_ALG_NET and the routine CPXlpopt iscalled to solve the network part of the optimization problem using the networkoptimizer. The objective value of this problem is retrieved by CPXgetobjval.

Then the extra rows are added by CPXaddrows. For convenience, the total numberof nonzeros in the rows being added is stored in an extra element of the array

Chapter 7. Callable Library tutorial 93

Page 106: Ibm Ilog Cplex User Manual 12.6

rmatbeg , and this element is passed for the parameter nzcnt . The namearguments to CPXaddrows are NULL , since no variable or constraint names weredefined for this problem.

After the CPXaddrows call, the parameter CPX_PARAM_LPMETHOD is set to CPX_ALG_DUALand the routine CPXlpopt is called to re-optimize the problem using the dualsimplex optimizer. After re-optimization, CPXsolution accesses the solution status,the objective value, and the primal solution. NULL is passed for the other solutionvalues, since the information they provide is not needed in this example.

At the end, the problem is written as a SAV file by CPXwriteprob. This file can thenbe read into the Interactive Optimizer to analyze whether the problem wascorrectly generated. Using a SAV file is recommended over MPS and LP files, asSAV files preserve the full numeric precision of the problem.

After the TERMINATE: label, CPXfreeprob releases the problem object, andCPXcloseCPLEX releases the CPLEX environment.

You can view the complete program online in the standard distribution of theproduct at yourCPLEXinstallation/examples/src/lpex3.c.

Performing sensitivity analysisThis application demonstrates sensitivity analysis in the C API.

In “Performing sensitivity analysis” on page 33, there is a discussion of how toperform sensitivity analysis in the Interactive Optimizer. As with most interactivefeatures of CPLEX, there is a direct approach to this task from the Callable Library.This section modifies the example lpex1.c in “Building and solving a small LPmodel in C” on page 90 to show how to perform sensitivity analysis with routinesfrom the Callable Library.

To begin, make a copy of lpex1.c , and edit this new source file. Among thedeclarations (for example, immediately after the declaration for dj ) insert theseadditional declarations:double *lowerc = NULL, *upperc = NULL;double *lowerr = NULL, *upperr = NULL;

At some point after the call to CPXlpopt, (for example, just before the call toCPXwriteprob), perform sensitivity analysis on the objective function and on therighthand side coefficients by inserting this fragment of code:upperc = (double *) malloc (cur_numcols * sizeof(double));lowerc = (double *) malloc (cur_numcols * sizeof(double));status = CPXobjsa (env, lp, 0, cur_numcols-1, lowerc, upperc);if ( status ) {

fprintf (stderr, "Failed to obtain objective sensitivity.\n");goto TERMINATE;

}printf ("\nObjective coefficient sensitivity:\n");for (j = 0; j < cur_numcols; j++) {

printf ("Column %d: Lower = %10g Upper = %10g\n",j, lowerc[j], upperc[j]);

}

upperr = (double *) malloc (cur_numrows * sizeof(double));lowerr = (double *) malloc (cur_numrows * sizeof(double));status = CPXrhssa (env, lp, 0, cur_numrows-1, lowerr, upperr);if ( status ) {

fprintf (stderr, "Failed to obtain RHS sensitivity.\n");

94 Getting Started with CPLEX

Page 107: Ibm Ilog Cplex User Manual 12.6

goto TERMINATE;}printf ("\nRight-hand side coefficient sensitivity:\n");for (i = 0; i < cur_numrows; i++) {

printf ("Row %d: Lower = %10g Upper = %10g\n",i, lowerr[i], upperr[i]);

}

This sample is familiarly known as “throw away” code. For production purposes,you probably want to observe good programming practices such as freeing theseallocated arrays at the TERMINATE label in the application.

A bound value of 1e+20 (CPX_INFBOUND) is treated as infinity within CPLEX, so thisis the value printed by our sample code in cases where the upper or lowersensitivity range on a row or column is infinite; a more sophisticated programmight print a string, such as -inf or +inf, when negative or positive CPX_INFBOUNDis encountered as a value.

Similar code could be added to perform sensitivity analysis with respect to boundsvia CPXboundsa.

Chapter 7. Callable Library tutorial 95

Page 108: Ibm Ilog Cplex User Manual 12.6

96 Getting Started with CPLEX

Page 109: Ibm Ilog Cplex User Manual 12.6

Chapter 8. Python tutorial

Use CPLEX interactively in a Python session, or write an application using thePython API for CPLEX.

Design of CPLEX in a Python applicationAn application of CPLEX in the Python programming language uses Pythonobjects.

The Python API of CPLEX consists of files in the directory where you installed theproduct (referred to here as yourCPLEXHome).

The primary class in the module cplex is the class Cplex. It encapsulates themathematical formulation of an optimization problem together with informationthat you, the user, specify about how CPLEX should solve the problem. The classCplex provides methods for modifying a problem, solving the problem, andquerying both the problem itself and its solution. The methods of the class Cplexare grouped into categories of related functionality. For example, methods foradding, modifying, and querying data related to variables are contained in themember variables of the class Cplex.

Starting the CPLEX Python APIUse the Python environment variable PYTHONPATH to get started with the CPLEXPython API on your system.

In this tutorial, the directory where you find the CPLEX Python API (for example,as a feature of your installation of IBM ILOG CPLEX Optimization Studio) isknown as yourCPLEXhome. In a path name such as yourCPLEXhome/python/PLATFORM/, the term PLATFORM represents the name of one of the various platformson which the CPLEX Python API is available. In this context, a platform is acombination of operating system (such as a Microsoft Windows designation or aGNU/Linux distribution) and chip-type (such as 32- or 64-bit architecture) forwhich CPLEX is distributed as a feature. In that directory, you find these elements:v a subdirectory named cplex

v a file named setup.py

Before you start this tutorial, you need to use that script to make your Pythoninstallation aware of your CPLEX installation. For more detail about using thatscript (and for an alternative to it), see “Setting up the Python API of CPLEX” onpage 5.

Accessing the module cplexInvoke CPLEX in a Python session.

After you have installed the CPLEX Python API on your system, you accessCPLEX from the Python programming language through the cplex module. To doso, you may use any of the following commands either from a script written in thePython programming language or from within the Python interpreter:import cplex

© Copyright IBM Corp. 1987, 2013 97

Page 110: Ibm Ilog Cplex User Manual 12.6

orfrom cplex import *

orimport cplex as NAME

where NAME is any Python name of your choice.

Building and solving a small LP with PythonSolve a linear programming model using the CPLEX Python API.

After you have installed the CPLEX Python API on your system and opened aPython interactive session, you can actually build and solve a small LP model as ademonstration. The demonstration shows how to:v model by rows;v model by columns;v model by nonzero elements.

The code sample, lpex1.py, is one of the examples in the standard distribution ofthe product. It is an extension of the example presented in Getting Started withCPLEX as “Problem statement” on page 11. The demonstration shows threedifferent ways to define an LP problem through the CPLEX Python API, how tosolve it, and how to access the solution. Here is the model that the sampleoptimizes:Maximizex1 + 2x2 + 3x3subject to–x1 + x2 + x3 <= 20x1 – 3x2 + x3 <= 30with these bounds0 <= x1 <= 400 <= x2 <= infinity0 <= x3 <= infinity

First, the example checks the correctness of command-line arguments. If thecommand-line arguments are valid, the example creates and solves the problemwithin a try/except clause to handle any errors that may occur. Then, dependingon the command line argument, the example calls one of the functionspopulatebyrow, populatebycolumn, or populatebynonzero, to fill the Cplex objectwith a representation of the optimization problem. These functions generate listscontaining the data that define the LP problem. After the Cplex object has beenpopulated by one of these three functions, its method solve invokes the optimizerin this sample.

If the optimizer fails to generate a solution, CPLEX raises an exception.

If a solution is found, CPLEX prints solution information to sys.stdout when auser's application invokes print statements.

Reading and writing CPLEX models to files with PythonRead models from files and write models to files in an application using theCPLEX Python API.

98 Getting Started with CPLEX

Page 111: Ibm Ilog Cplex User Manual 12.6

In general, the methods of the class Cplex query, add, or modify data comprisingan optimization problem.

Moreover, the class Cplex provides output streams for general log messages,results, warning messages, and error messages. A user sets those output streams bymeans of the methods set_log_stream, set_results_stream, set_warning_stream,and set_error_stream. These methods take either a file object or a filename as anargument; they also accept the argument None to disable their output.

These methods can also take, as an optional second argument, a parsing functionthat takes a string as input and returns a string as output. If the user specifies aparsing function, CPLEX uses that function to process the output to that stream.

By default, the log and results streams are set to sys.stdout and the error andwarning streams are set to sys.stderr.

The sample lpex1.py contains one more line that deserves explanation in thecontext of reading and writing files:my_prob.write("lpex1.lp")

That statement causes my_prob to write the data it has stored to the file namedlpex1.lp. In this sample, the file is written in LP format. The reference manual,File formats supported by CPLEX, documents that file format with respect toCPLEX in the topic LP file format: algebraic representation.

Other formats supported for writing problems to a file are MPS and SAV (alsodocumented by the reference manual, File formats supported by CPLEX, in the topicMPS file format: industry standard and in SAV.

The CPLEX Python API decides which file format to write based on the extensionof the file name; you can also use an optional format string as an additionalargument to specify a file format.

The class Cplex also supports reading of files through its method read and throughits constructor. For example, if cpx is an instance of the class Cplex, then a call likethis:cpx.read("file.lp")

or like this:cpx = cplex.Cplex("file.lp")

causes the CPLEX Python API to read a problem from the formatted file namedfile.lp.

Note:

The method read replaces all data currently stored in the object cpx.

MPS and SAV format files are also supported in a similar way.

Selecting an optimizer in PythonSelect an optimizer using the CPLEX Python API, according to these criteria.

Chapter 8. Python tutorial 99

Page 112: Ibm Ilog Cplex User Manual 12.6

The CPLEX Python API provides a single method, solve, to optimize problems.That method uses the features of the model to deduce the appropriate algorithmfor solving the problem. While the default optimizer works well for a wide varietyof models, the CPLEX Python API allows you to control which algorithm to invokefor certain types of problems by your changing the values of certain parameters.

For example, if cpx is an instance of the class Cplex encapsulating a MIP (mixedinteger programming) problem, you can specify which linear programmingalgorithm is used for solving the root problem and the node subproblems, like this:cpx.parameters.mip.strategy.startalgorithm.set(start)cpx.parameters.mip.strategy.subalgorithm.set(sub)

where start is one of the attributes ofcplex.parameters.mip.strategy.startalgorithm.values for the root node and subis one of the attributes of cplex.parameters.mip.strategy.subalgorithm.values forthe subproblem nodes.

Example: reading a problem from a file lpex2.pyThe sample lpex2.py illustrates reading a problem from a file.

The sample lpex2.py shows how to read an optimization problem from a file, andsolve the problem with a specified optimizer option. If solution information or asimplex basis are available, the sample application prints them. Finally the sampleprints the maximum infeasibility of any variable of the solution.

The user passes the name of the file to read and the choice of optimizers asarguments on the command line. For example, this command:$ python lpex2.py example.mps d

reads the file example.mps and solves the problem with the dual simplex optimizer.

Alternatively, you may execute the statement:import lpex2

within the Python interpreter and specify the problem file and optimizerinteractively.

In summary, this example shows how to:v read a model from a formatted file;v select the optimizer;v access basis information;v query quality measures of the solution.

The general structure of this sample is similar to the sample lpex1.py. It starts bycreating an instance of the class Cplex. A try/except statement encloses the codethat follows to handle errors gracefully. You can see the complete applicationonline in the standard distribution of the product at yourCPLEXHome/examples/src/lpex2.py.

Modifying and re-optimizing in the CPLEX Python APIModify a model and re-optimize in the CPLEX Python API to see the effect.

100 Getting Started with CPLEX

Page 113: Ibm Ilog Cplex User Manual 12.6

In many situations, the solution to a model is only the first step. One of theimportant features of the CPLEX Python API is the ability to modify and thenre-optimize the model even after it has been created and solved one or more times.

After CPLEX solves a problem, you can add, remove, or modify constraints toproduce a different but related model. When you modify a problem, CPLEX triesto maintain as much information from the previous solution as reasonable andpossible, in order to have a better start when it solves the modified problem. Inparticular, when solving LPs or QPs with a simplex optimmizer, CPLEX attemptsto maintain a basis which will be used the next time the method solve is invoked,with the aim of making subsequent solves go faster.

Example: modifying a model lpex3.pyModify the model in the sample lpex3.py.

The sample lpex3.py demonstrates how to:v set CPLEX parameters;v modify an optimization model;v start optimization from an existing basis.

The problem that lpex3.py solves looks like this:Minimizec^Txsubject toHx = dAx = bl <= x <= uwhereH = ( -1 0 1 0 1 0 0 0 )d =( -3 )( 1 -1 0 1 0 0 0 0 )( 1 )( 0 1 -1 0 0 1 -1 0 )( 4 )( 0 0 0 -1 0 -1 0 1 )( 3 )( 0 0 0 0 -1 0 1 -1 )( -5 )A = ( 2 1 -2 -1 2 -1 -2 -3 )b =( 4 )( 1 -3 2 3 -1 2 1 1 )( -2 )c = (-9 1 4 2 -8 2 8 12 )l = ( 0 0 0 0 0 0 0 0 )u =(50 50 50 50 50 50 50 50 )

The constraints Hx=d represent the flow conservation of a pure network flowproblem. The sample solves this problem in two steps:v First, the CPLEX network optimizer solves:

Minimizec^Txsubject toHx = dl <= x <= u

Chapter 8. Python tutorial 101

Page 114: Ibm Ilog Cplex User Manual 12.6

v Second, the sample adds the constraints Ax=b to the model, and invokes the dualsimplex optimizer to solve the full problem, starting from the optimal basis ofthe network problem.

The dual simplex optimizer is highly effective in such a case because this basisremains dual feasible after the slacks (artificial variables) of the added constraintsare initialized as basic.

The 0 (zero) values in the data are omitted in the sample. CPLEX makes extensiveuse of sparse matrix methods and, although CPLEX correctly handles any explicitzero coefficients given to it, most programs solving models of more than modestsize benefit (in terms of both storage space and speed) if the natural sparsity of themodel is exploited from the very start.

Before solving the model, the sample selects the network optimizer by setting theparameter lpmethod to the value parameters.lpmethod.values.network.

The sample also sets the simplex display parameter so that the simplex optimizerlogs information as it executes.

For an introduction to CPLEX parameters in the CPLEX Python API, see also thetopic “Using CPLEX parameters in the CPLEX Python API.”

Using CPLEX parameters in the CPLEX Python APIManage CPLEX parameters in the CPLEX Python API.

For CPLEX users familiar with the Interactive Optimizer, setting and queryingparameters in the CPLEX Python API is similar to parameter handling in theInteractive Optimizer. The class Cplex offers a data member named parameterscontaining names of parameters (such as lpmethod and threads) and names ofgroups of related parameters (such as barrier and output). These groups can inturn contain individual parameters and groups of parameters themselves. Thehierarchy is the same as that found in the Interactive Optimizer, with the exceptionof parameters such as output dialog; their functionality is handled by other partsof the CPLEX Python API.

Tip:

If you are already familiar with the names of parameters in the InteractiveOptimizer, then you quickly recognize names of parameters in the Python API. Forexample, the command “set mip limits nodes 1” in the Interactive Optimizercorresponds to “c.parameters.mip.limits.nodes.set(1)” in a Python session.

For users whose first contact with CPLEX is through the CPLEX Python API, thefollowing topics introduce setting parameters, querying their current value, andusing groups of parameters.

Setting and querying parameters in the CPLEX Python API

As objects themselves, parameters offer the following methods:v get() returns the current value of the parameter.v set(value) sets the invoking parameter to value. If value is of the wrong type

for the invoking parameter, or if value is less than the minimum value or greaterthan the maximum value for the parameter, CPLEX raises an exception.

102 Getting Started with CPLEX

Page 115: Ibm Ilog Cplex User Manual 12.6

v reset() sets the parameter to its default value.v default() returns the default value of the parameter.v type() returns the type of the parameter.v help() returns a brief description of the parameter.

Numerical parameters offer these additional methods:v min() returns the minimum value allowed for the parameter.v max() returns the maximum value allowed for the parameter.

Parameters of type float with no restrictions on their value return 0.0 (zero) whenyou invoke the method min() or max().

Certain integer parameters, such as lpmethod, have values with a special meaning.Such parameters also have a data attribute named values, which has as itsattributes the values that the parameter can take. For example, if cpx is an instanceof the class Cplex encapsulating an LP problem, then:>>> cpx.parameters.lpmethod.set(cpx.parameters.lpmethod.values.primal)>>> cpx.solve()

results in CPLEX solving the problem by the primal simplex optimizer.

Parameter groups

For your convenience, CPLEX parameters are organized into groups of parametersthat you can manage simultaneously. A parameter group is an instance of the classParameterGroup.

The class ParameterGroup offers these methods:v reset sets all parameters within the group to their default value.v get_changed returns a list of pairs (parameter, current value) for the members of

the group not currently at their default value.

The parameter group that encompasses all parameters is an instance of the classRootParameterGroup, a subclass of the class ParameterGroup. It offers thesemethods:v read(filename) reads a set of parameters from the named file.v write(filename) writes a set of parameters to the named file.v tune_problem(fixed_parameters_and_values=[]) tunes the parameters to

improve performance on an instance of the class Cplex. The argumentfixed_parameters_and_values is a sequence of pairs (parameter, value) asreturned by the method ParameterGroup.get_changed.

v tune_problem_set(filenames, filetypes=[], fixed_parameters_and_values=[])tunes the parameters to improve performance on a set of problems. Again, theargument fixed_parameters_and_values is a sequence of pairs (parameter, value)as returned by the method ParameterGroup.get_changed.

Chapter 8. Python tutorial 103

Page 116: Ibm Ilog Cplex User Manual 12.6

104 Getting Started with CPLEX

Page 117: Ibm Ilog Cplex User Manual 12.6

Index

Aaccessing

basic rows and columns of solution inInteractive Optimizer 32

basis information (C++ API) 61dual values in Interactive

Optimizer 32dual values in Interactive Optimizer

(example) 32module of Python API 97objective function value in Interactive

Optimizer 32quality of solution in Interactive

Optimizer 32reduced cost (Java API) 70reduced costs in Interactive

Optimizer 32slack values in Interactive

Optimizer 32solution values (C++ API) 54solution values in Interactive

Optimizer 32add Interactive Optimizer command 40,

41file name and 41syntax 41

add(obj) method (Java API) 68adding

bounds in Interactive Optimizer 40constraint to model (C++ API) 62constraints in Interactive

Optimizer 40from a file in Interactive

Optimizer 41interactively in Interactive

Optimizer 41objective (shortcut) (Java API) 68objective function to model (C++

API) 52rows to a problem (C API) 92

addLe method (Java API) 72addMinimize method (Java API) 68, 72advanced basis

advanced start indicator in InteractiveOptimizer 31

algorithmcreating object (C++ API) 54role in application (C++ API) 56

and method (Java API) 72application

and Callable Library viand Concert Technology vicompiling and linking (C++ API) 50compiling and linking Callable

Library (C API) 83compiling and linking Component

Libraries 9development steps (C API) 87error handling (C API) 89error handling (C++ API) 55

Bbaropt Interactive Optimizer

command 32barrier optimizer

availability in InteractiveOptimizer 32

BAS file formatreading from Interactive

Optimizer 38writing from Interactive

Optimizer 36basis

accessing information (C++ API) 61basis information (Java API) 70starting from previous (C++ API) 63

basis filereading in Interactive Optimizer 38writing in Interactive Optimizer 36

Boolean parameter (C++ API) 63Boolean variable

representing in model (C++ API) 52bound

adding in Interactive Optimizer 40changing in Interactive Optimizer 43default values in Interactive

Optimizer 23displaying in Interactive

Optimizer 28entering in LP format in Interactive

Optimizer 23removing in Interactive Optimizer 43sensitivity analysis in Interactive

Optimizer 33box variable in Interactive Optimizer 25

CC++ API

compiler options 2linker options 2

Callable Librarydescription viexample model 14

Callable Library (C API) 83application development steps 87compiler options 2compiling and linking

applications 83conceptual design 83CPLEX operation 85distribution file 84error handling 89linker options 2opening CPLEX 85

change Interactive Optimizercommand 41

bounds 43change options 42coefficient 44delete 44

change Interactive Optimizer command(continued)

delete options 44objective 44rhs 44sense 42syntax 45

changingbounds in Interactive Optimizer 43coefficients in Interactive

Optimizer 44constraint names in Interactive

Optimizer 42objective in Interactive Optimizer 44parameters (C++ API) 63parameters in Interactive

Optimizer 39problem in Interactive Optimizer 41righthand side (rhs) in Interactive

Optimizer 44sense in Interactive Optimizer 42variable names in Interactive

Optimizer 42choosing

optimizer (C API) 88optimizer (C++ API) 59optimizer in Interactive Optimizer 32

class library (Java API) 65classpath (Java API) 66

command line option 65clean up data 45coefficient

changing in Interactive Optimizer 44column

expressions (C++ API) 57command

executing from operating system inInteractive Optimizer 46

input formats in InteractiveOptimizer 19

Interactive Optimizer list 19compiler

-DNDEBUG option (C++ API) 55error messages (C++ API) 50Microsoft Visual C++ Command Line

(C API) 85using with CPLEX (C++ API) 50

compiler option 2compiling

applications 9applications (C API) 83applications (C++ API) 50

Component Librariesdefined virunning examples 8verifying installation 8

Concert TechnologyC++ classes 51C++ objects 49compiling and linking applications

(C++ API) 50

© Copyright IBM Corp. 1987, 2013 105

Page 118: Ibm Ilog Cplex User Manual 12.6

Concert Technology (continued)CPLEX design in (C++ API) 49error handling (C++ API) 55running examples (C++ API) 50

Concert Technology (C++ API) 49, 63Concert Technology Library

description viexample model 12

constraintadding (C++ API) 62adding in Interactive Optimizer 40changing names in Interactive

Optimizer 42changing sense in Interactive

Optimizer 42creating (C++ API) 57default names in Interactive

Optimizer 23deleting in Interactive Optimizer 44displaying in Interactive

Optimizer 28displaying names in Interactive

Optimizer 27displaying nonzero coefficients in

Interactive Optimizer 25displaying number in Interactive

Optimizer 25displaying type in Interactive

Optimizer 25entering in LP format in Interactive

Optimizer 22name limitations in Interactive

Optimizer 23naming in Interactive Optimizer 23range (C++ API) 57

constraintsadding to a model (Java API) 68

continuous variablerepresenting (C++ API) 52

CPLEXcompatible platforms viiComponent Libraries videscription vdirectory structure 6problem types vquitting in Interactive Optimizer 46setting up 1starting in Interactive Optimizer 19technologies vi

cplex command in InteractiveOptimizer 19

cplex.jar (location) 65cplex.log file in Interactive Optimizer 31CPXaddcols routine

example in C API 90modular data in C API 88populating problem (C API) 86

CPXaddrows routineLP example in C API 90modular data in C API 88network example in C API 92populating model in C API 86

CPXchgcoeflist routineexample in C API 90modular data in C API 88populating model in C API 86

CPXcloseCPLEX routineLP example in C API 90MPS example in C API 91network example in C API 92purpose in C API 85

CPXcopylp routinebuilding model in memory for C

API 88efficient arrays in C API 88example in C API 92not for changing model in C API 86populating model in C API 86

CPXcreateprob routineLP example in C API 91network example in C API 92purpose in C API 86use in C API 86

CPXfreeprob routinefile format example in C API 91LP example in C API 90network example in C API 92purpose in C API 86

CPXgeterrorstring routineclosing LP example in C API 90opening LP example in C API 90

CPXgetobjval routine 92CPXlpopt routine

LP example in C API 90network example in C API 92

CPXmsg routine 85CPXnewcols routine

LP example in C API 90modular data in C API 88populating model in C API 86

CPXnewrows routine 90example in C API 90modular data in C API 88populating model in C API 86

CPXopenCPLEX routinefile format example in C API 91LP example in C API 90network example in C API 92purpose in C API 85

CPXreadcopyprob routineexample in C API 91formatted data files in C API 86

CPXsetintparam routine 90CPXsolution routine

LP example in C API 90network example in C API 92

CPXwriteprob routineLP example in C API 90network example in C API 92testing in CAPI 89

creatingalgorithm object (C++ API) 54, 56automatic log file in Interactive

Optimizer 31binary problem representation (C

API) 89constraint (C++ API) 57environment (C API) 92environment object (C++ API) 51, 56model (IloModel) (C++ API) 52model (Java API) 68model objects (C++ API) 56objective function (C++ API) 57

creating (continued)optimization model (C++ API) 52problem files in Interactive

Optimizer 34problem object (C API) 86, 92

Ddata

entering in Interactive Optimizer 24entry options viii

deletingconstraints in Interactive

Optimizer 44problem options in Interactive

Optimizer 44variables in Interactive Optimizer 44

directory structure 6display Interactive Optimizer

command 24, 42options 24problem 24

bounds 28constraints 28names 27, 28options 24stats 25syntax 25

sensitivity 33syntax 34

settings 40solution 32

syntax 33specifying item ranges 26syntax 29

displayingbasic rows and columns in Interactive

Optimizer 32bounds in Interactive Optimizer 28constraint names in Interactive

Optimizer 27constraints in Interactive

Optimizer 28nonzero constraint coefficients in

Interactive Optimizer 25number of constraints in Interactive

Optimizer 25objective function in Interactive

Optimizer 28optimal solution in Interactive

Optimizer 30parameter settings in Interactive

Optimizer 40post-solution information in

Interactive Optimizer 32problem in Interactive Optimizer 24problem options in Interactive

Optimizer 24problem part in Interactive

Optimizer 25problem statistics in Interactive

Optimizer 25sensitivity analysis (C API) 94sensitivity analysis in Interactive

Optimizer 33slack values in Interactive

Optimizer 32

106 Getting Started with CPLEX

Page 119: Ibm Ilog Cplex User Manual 12.6

displaying (continued)solution values in Interactive

Optimizer 32type of constraint in Interactive

Optimizer 25variable names in Interactive

Optimizer 27variables in Interactive Optimizer 25

dual simplex optimizeras default in Interactive

Optimizer 30availability in Interactive

Optimizer 32finding a solution (C API) 90

dual valuesaccessing (Java API) 70accessing in Interactive Optimizer 32

EEclipse

configuring for CPLEXapplications 4

enter Interactive Optimizer command 21bounds 23maximize 22minimize 22subject to 22, 41syntax 22

enteringbounds in Interactive Optimizer 23constraint names in Interactive

Optimizer 23constraints in Interactive

Optimizer 22example problem in Interactive

Optimizer 21item ranges in Interactive

Optimizer 26keyboard data in Interactive

Optimizer 24objective function in Interactive

Optimizer 22, 23objective function names in Interactive

Optimizer 23problem in Interactive Optimizer 21,

22problem name in Interactive

Optimizer 21variable bounds in Interactive

Optimizer 23variable names in Interactive

Optimizer 22environment object

creating (C++ API) 51, 56destroying (C++ API) 51memory management and (C++

API) 51equality constraints

adding to a model (Java API) 68error

invalid encrypted key (Java API) 66NoClassDefFoundError (Java API) 66UnsatisfiedLinkError (Java API) 66

error handlingcompiler (C++ API) 50linker (C++ API) 50

error handling (continued)programming errors (C++ API) 55runtime errors (C++ API) 55testing installation 8testing installation (C++ API) 50

exampleadding rows to a problem (C API) 92entering a problem in Interactive

Optimizer 21entering and optimizing a problem (C

API) 90entering and optimizing a problem in

C# 78ilolpex2.cpp (C++ API) 60ilolpex3.cpp (C++ API) 62lpex1.c (C API) 90lpex1.cs 78lpex2.c (C API) 91lpex2.py 100lpex3.c (C API) 92lpex3.py 101modifying an optimization problem

(C++ API) 62reading a problem file (C API) 91reading a problem from a file (C++

API) 60running (C++ API) 50running Callable Library (C API) 84running Component Libraries 8running from standard distribution (C

API) 84solving a problem in Interactive

Optimizer 30exception handling (C++ API) 55executing operating system commands in

Interactive Optimizer 46exportModel method

IloCplex class (C++ API) 58expression

column 57

Ffalse return value of IloCplex.solve (Java

API) 69feasible solution (Java API) 69file format

read options in InteractiveOptimizer 36

write options in InteractiveOptimizer 34

file nameextension 58extension in Interactive

Optimizer 35, 38

GgetCplexStatus method

IloCplex class (C++ API) 54getCplexStatus method (Java API) 69getDuals method

IloCplex class (C++ API) 56getObjValue method

IloCplex class (C++ API) 54

getReducedCosts methodIloCplex class (C++ API) 56

getSlacks methodIloCplex class (C++ API) 56

getStatus methodIloCplex class (C++ API) 54, 56

getStatus method (Java API) 69getValue method

IloCplex class (C++ API) 54getValues method

IloCplex class (C++ API) 56greater than equal to constraints

adding to a model (Java API) 68

Hhandle class

definition (C++ API) 51empty handle (C++ API) 52

handlingerrors (C API) 89errors (C++ API) 55exceptions (C++ API) 55

help Interactive Optimizer command 19histogram in Interactive Optimizer 29

IIloAddNumVar class (C++ API) 57IloColumn.and method (Java API) 72IloCplex class (C++ API) 49

exportModel method 58getCplexStatus method 54getDuals method 56getObjValue method 54getReducedCosts method 56getSlacks method 56getStatus method 54, 56getValue method 54getValues method 56importModel method 58, 60setParam method 59setRootAlgorithm method 61solve method 54, 56, 61solving with 54

IloCplex class (Java API) 65add modeling object 68addLe method 72addMinimize method 72numVarArray method 72prod method 72scalProd method 72sum method 72

IloEnv class (C++ API) 51end method 51

IloException class (C++ API) 55IloExpr class (C++ API) 52IloExtractable class (C++ API) 52IloLinearNumExpr class (Java API) 68IloMinimize function (C++ API) 52IloModel class (C++ API)

add method 52extractable 52role 49

IloModel class (Java API)column method 72

Index 107

Page 120: Ibm Ilog Cplex User Manual 12.6

IloModel class (Java API) (continued)numVar method 72

IloNumArray class (C++ API) 56IloNumColumn class (C++ API) 57IloNumExpr class (Java API) 68IloNumVar class (C++ API) 57

columns and 57IloObjective class (C++ API) 57

setLinearCoef method 58IloRange class (C++ API)

casting operator for 57example 52setLinearCoef method 58

IloRange class (Java API)setExpr method 73

importModel methodIloCplex class (C++ API) 58, 60

infeasible (Java API) 69installing

Python API 97installing CPLEX

testing installation 8integer parameter (C++ API) 63integer variable

optimizer used (C API) 88representing in model (C++ API) 52

Interactive Optimizer 19, 46command formats 19commands 19description viexample model 11quitting 46starting 19starting (tutorial) 19

invalid encrypted key (Java API) 66iteration log in Interactive Optimizer 30,

31

JJava API

setting up Eclipse 4Java Native Interface (JNI) 65Java Virtual Machine (JVM) 65javamake for Windows 66

Llibformat (Java API) 66linear optimization vlinker

error messages (C++ API) 50using with CPLEX (C++ API) 50

linker option 2linking

applications 9applications (C++ API) 50Callable Library (C API)

applications 83log file

adding to in Interactive Optimizer 39cplex.log in Interactive Optimizer 31creating in Interactive Optimizer 31iteration log in Interactive

Optimizer 30, 31

LPcreating a model 11node (C++ API) 59problem format vroot (C++ API) 59solving a model 11solving pure (C++ API) 59

LP fileformat in Interactive Optimizer 22reading in Interactive Optimizer 37writing in Interactive Optimizer 35

lpex1.cexample (C API) 90

LPex1.java example 70lpex2.py example 100lpex3.py example 101LPMETHOD parameter in Interactive

Optimizer 30

Mmake file target 2makefile (Java API) 66maximization in LP problem in

Interactive Optimizer 22memory management

by environment object (C++ API) 51minimization in LP problem in

Interactive Optimizer 22MIP

description voptimizer in Interactive Optimizer 32solving (C++ API) 59

mipopt Interactive Optimizercommand 32

modeladding constraints (C++ API) 62creating (C++ API) 52creating IloModel (C++ API) 52creating objects in (C++ API) 56extracting (C++ API) 56modifying (C++ API) 61reading from file (C++ API) 58, 60solving (C++ API) 61writing to file (C++ API) 58

modelingby columns (C++ API) 57by columns (Java API) 72by nonzeros (C++ API) 58by nonzeros (Java API) 73by rows (Java API) 72objects (C++ API) 49variables (Java API) 68

modeling by rows (C++ API) 57modifying

problem object (C API) 86monitoring iteration log in Interactive

Optimizer 30MPS file format in Interactive

Optimizer 38

Nnetopt Interactive Optimizer

command 32

networkdescription v

network flow (C++ API) 62network optimizer

availability in InteractiveOptimizer 32

solving with (C++ API) 62Nmake (Java API) 66NoClassDefFoundError (Java API) 66node LP

solving (C++ API) 59nonzeros

modeling (C++ API) 58modeling (Java API) 73

notation in this manual ixnotification (C++ API) 61numeric parameter (C++ API) 63numVarArray method (Java API) 72

Oobjective function

accessing value in InteractiveOptimizer 32

adding to model (C++ API) 52changing coefficient in Interactive

Optimizer 44changing sense in Interactive

Optimizer 42creating (C++ API) 57default name in Interactive

Optimizer 23displaying in Interactive

Optimizer 28entering in Interactive Optimizer 23entering in LP format in Interactive

Optimizer 22name in Interactive Optimizer 23sensitivity analysis in Interactive

Optimizer 33operator() (C++ API) 57operator+ (C++ API) 57optimal solution (Java API) 69optimization model

creating (C++ API) 52defining extractable objects (C++

API) 52extracting (C++ API) 52

optimization probleminterrupting in Interactive

Optimizer 32reading from file (C++ API) 60representing (C++ API) 56solving with IloCplex (C++ API) 54

optimize Interactive Optimizercommand 30

re-solving 31syntax 31

optimizerchoosing (Python API) 100choosing by problem type (C API) 88choosing by switch in application

(C++ API) 61choosing in Interactive Optimizer 32options viisyntax for choosing (C++ API) 59

108 Getting Started with CPLEX

Page 121: Ibm Ilog Cplex User Manual 12.6

ordering variables in InteractiveOptimizer 28

output method (Java API) 70OutputStream (Java API) 70

Pparallel

choosing optimizers for viiiparameter

Boolean (C++ API) 63changing (C++ API) 63changing in Interactive Optimizer 39displaying settings in Interactive

Optimizer 40in Python API 102integer (C++ API) 63list of settable in Interactive

Optimizer 39numeric (C++ API) 63resetting to defaults in Interactive

Optimizer 40string (C++ API) 63

parameter group (Python API) 103parameter specification file in Interactive

Optimizer 40path names in Interactive Optimizer 36populateByColumn method (Java

API) 70populateByNonzero method (Java

API) 73populateByNonzero method(Java

API) 70populateByRow (Java API) 70primal simplex optimizer

availability in InteractiveOptimizer 32

primopt Interactive Optimizercommand 32

problemchange options in Interactive

Optimizer 42changing in Interactive Optimizer 41creating binary representation (C

API) 89data entry options viiidisplaying a part in Interactive

Optimizer 25displaying in Interactive

Optimizer 24displaying options in Interactive

Optimizer 24displaying statistics in Interactive

Optimizer 25entering from the keyboard in

Interactive Optimizer 21entering in LP format in Interactive

Optimizer 22naming in Interactive Optimizer 21reading files (C API) 91solving (C API) 90solving in Interactive Optimizer 30verifying entry in Interactive

Optimizer 24, 42problem file

reading in Interactive Optimizer 36writing in Interactive Optimizer 34

problem formulationilolpex1.cpp (C++ API) 56Interactive Optimizer and 21lpex1.c (C API) 90lpex1.cs 78LPex1.java (Java API) 70standard notation for v

problem objectcreating (C API) 86modifying (C API) 86

problem types solved by CPLEX vPython

tutorial 97Python API 97

accessing cplex module 97modifying model 101paramters in 102re-optimizing problem 101reading files in 99selecting optimizer 100setting up on GNU/Linux 5setting up on UNIX 5setting up on Windows 5writing files from 99

QQCP

description voptimizer for vii

QPapplicable algorithms (C++ API) 59description vsolving pure (C++ API) 59

queryingparameters (Python API) 102

quit Interactive Optimizer command 46quitting

CPLEX in Interactive Optimizer 46Interactive Optimizer 46

Rrange constraint

adding to a model (Java API) 68range constraint (C++ API) 57re-solving in Interactive Optimizer 31read Interactive Optimizer command 36,

37, 38basis files and 38file type options 36syntax 39

readingfile format in Interactive

Optimizer 36LP files in Interactive Optimizer 37model from file (C++ API) 58, 60MPS files in Interactive Optimizer 38problem files (C API) 91problem files in Interactive

Optimizer 36reduced cost

accessing (Java API) 70accessing in Interactive Optimizer 32

removing bounds in InteractiveOptimizer 43

representing optimization problem (C++API) 56

righthand side (RHS)changing coefficient in Interactive

Optimizer 44sensitivity analysis in Interactive

Optimizer 33root LP

solving (C++ API) 59

SSAV file format (C API) 92saving

problem files in InteractiveOptimizer 34

solution files in InteractiveOptimizer 34

scalProd method (Java API) 72sense

changing in Interactive Optimizer 42sensitivity analysis

performing (C API) 94performing in Interactive

Optimizer 33set Interactive Optimizer command 39

advance 31available parameters 39defaults 40logfile 31simplex 30syntax 40

setOut method (Java API) 70setRootAlgorithm method

IloCplex class (C++ API) 61setting

parameters (C++ API) 63parameters (Python API) 102parameters in Interactive

Optimizer 39parameters to default in Interactive

Optimizer 40setting up CPLEX 1

GNU/Linux 2setWarning method (Java API) 70shadow price

accessing in Interactive Optimizer 32slack

accessing (Java API) 70accessing in Interactive Optimizer 32accessing values in Interactive

Optimizer 32SOCP

description voptimizer for vii

solutionaccessing basic rows and columns in

Interactive Optimizer 32accessing values (C++ API) 54accessing values in Interactive

Optimizer 32displaying basic rows and columns in

Interactive Optimizer 32displaying in Interactive

Optimizer 32outputting (C++ API) 56process in Interactive Optimizer 30

Index 109

Page 122: Ibm Ilog Cplex User Manual 12.6

solution (continued)querying results (C++ API) 54reporting optimal in Interactive

Optimizer 30restarting in Interactive Optimizer 31sensitivity analysis (C API) 94sensitivity analysis in Interactive

Optimizer 33solution file

writing in Interactive Optimizer 34solve method

IloCplex class (C++ API) 54, 56, 61solve method (Java API) 69, 70solving

model (C++ API) 54, 61node LP (C++ API) 59problem (C API) 90problem in Interactive Optimizer 30root LP (C++ API) 59with network optimizer (C++

API) 62sparse matrix (C++ API) 62starting

CPLEX in Interactive Optimizer 19from previous basis (C++ API) 63Interactive Optimizer 19new problem in Interactive

Optimizer 21string parameter (C++ API) 63structure of a CPLEX application (Java

API) 67Supported Platforms (Java API) 66System.out method (Java API) 70

Ttranopt Interactive Optimizer

command 32

Uunbounded (Java API) 69UNIX

building Callable Library (C API)applications 84

executing commands in InteractiveOptimizer 46

testing CPLEX (C++ API) 50verifying set-up 8

UnsatisfiedLinkError (Java API) 66

Vvariable

Boolean (C++ API) 52box in Interactive Optimizer 25changing bounds in Interactive

Optimizer 43changing names in Interactive

Optimizer 42continuous (C++ API) 52deleting in Interactive Optimizer 44displaying in Interactive

Optimizer 25displaying names in Interactive

Optimizer 27

variable (continued)entering bounds in Interactive

Optimizer 23entering names in Interactive

Optimizer 22integer (C++ API) 52modeling (Java API) 68name limitations in Interactive

Optimizer 22ordering in Interactive Optimizer 28removing bounds in Interactive

Optimizer 43

Wwarning method (Java API) 70wildcard

displaying ranges of items inInteractive Optimizer 26

solution information in InteractiveOptimizer 33

wildcard in Interactive Optimizer 26Windows

building Callable Library (C API)applications 84

dynamic loading (C API) 85Microsoft Visual C++ compiler (C

API) 85Microsoft Visual C++ IDE (C API) 84setting up CPLEX 1testing CPLEX (C++ API) 50verifying set-up 8

write Interactive Optimizercommand 34, 35

file type options 34syntax 36

writingbasis files in Interactive Optimizer 36file format for Interactive

Optimizer 34LP files in Interactive Optimizer 35model to file (C++ API) 58problem files in Interactive

Optimizer 34solution files in Interactive

Optimizer 34

Xxecute Interactive Optimizer

command 46syntax 46

110 Getting Started with CPLEX

Page 123: Ibm Ilog Cplex User Manual 12.6
Page 124: Ibm Ilog Cplex User Manual 12.6

����

Printed in USA