You are on page 1of 66

‫به‌‌نام‌خدا‬

‫آموزش نرمافزار بهینهسازی ‪CPLEX‬به‬


‫برنامه‌نویسی‌ریاضی‌و‌برنامهریزی‌محدودیت‌ها‬

‫درس‌برنامه‌ریزی‌تصادفی‬

‫ارائه‌دهنده‪‌:‬مریم‌رادمان‬

‫آبان‌ماه‌‪1396‬‬
‫فهرست‌عناوین‬
‫‪ ‬معرفی نرم‌افزار‬
‫‪ ‬برنامه‌ریزی ریاضی‬
‫• معرفی محیط نرم‌افزار و نحوه ایجاد پروژه جدید‬
‫• مثال برنامه‌ریزی تولید‬
‫• تعریف داده‌ها‬
‫• تعریف متغیرها‬
‫• تعریف تابع هدف‬
‫• تعریف محدودیت‌ها‬
‫• بررسی خروجی‌های مدل‬
‫• معرفی آرایه‌های چند بعدی‬
‫• معرفی ‪filtering indexes‬‬
‫‪ ‬برنامه‌ریزی محدودیت‌ها‬
‫• معرفی عملگرهای ریاضی‪ ،‬منطقی‪ ،‬سازگاری و اختصاصی‬
‫• بررسی مثال ‪n-queen‬‬
‫• بررسی مثال فروشنده دوره‌گرد‬
‫‪ ‬نحوه تبادل داده‌ها بین ‪ Cplex‬و ‪Excel‬‬
‫نرم‌افزار‌‪CPLEX‬‬
‫‪ CPLEX ‬یک بسته‌ی نرم‌افزاری شامل مجموعه‌ای از برنامه‌های مدل‌سازی ریاضی است‪ .‬این برنامه‬
‫توسط ‪ Robert E. Bixby‬توسعه یافت‪ .‬در سال ‪ 1997‬شرکت ‪ CPLEX‬توسط شرکت ‪ILOG‬‬
‫خریداری شد‪.‬‬
‫‪ ‬این برنامه بیشتر به یک ‪ Solver‬صنعتی است تا یک ‪ Solver‬آکادمیک و تحقیقاتی‪ .‬به همین علت قیمت‬
‫‪ License‬این نرم‌افزار بسیار باالست‪.‬‬
‫‪ ‬نکته‌ی قابل‌توجه دیگر این است که شرکت ‪ ILOG‬هیچ نسخه‌ی ‪ Trial‬یا ‪ Student Version‬از این‬
‫نرم‌افزار را ارایه نمی‌کند‪ .‬که این باعث می‌شود تا بسیاری از افراد در ایران نتوانند آن را آزمایش کنند‪.‬‬
‫نرم‌افزار‌‪CPLEX‬‬

‫‪ CPLEX ‬در حقیقت یک موتور حالل (‪ )solver‬است که قابلیت اتصال به اکثر محیط‌های‬
‫برنامه‌نویسی و بهینه‌سازی مدل‌های ریاضی را دارا می‌باشد‪ .‬هر چند شرکت ‪ ILOG‬یک‬
‫محیط ساده برای ویرایش و توسعه‌ی مدل‌ها در برنامه قرار داده‌است‪ ،‬ولی اکثر کاربران‬
‫حرفه‌ای ترجیح می‌دهند تا از قابلیت‌های اتصال آن بهره بگیرند‪( .‬اتصال به ‪،GAMS‬‬
‫‪ C# ، matlab‬و ‪)...‬‬
‫‪ ‬مجموعه‌هایی مثل ‪ GAMS‬و ‪ Lingo/Lindo‬عمدتاَ محیط توسعه مدل ریاضی به حساب‬
‫می‌آیند و از مجموعه‌ای از ‪ solver‬ها در درون خود بهره می‌گیرند‪ .‬ولی ‪ CPLEX‬یک‬
‫‪ solver‬است‪.‬‬
‫‪ ‬به عنوان مثال‪ ،‬شما ممکن است یک مدل ریاضی را در برنامه ی ‪ GAMS‬بنویسید و سپس‬
‫توسط ‪ CPLEX‬آن را حل کنید‪.‬‬

‫نرم‌افزار‌‪GAMS‬‬
Mathematical Programming
Definitions…

Optimization modeling with IBM ILOG OPL


IBM ILOG CPLEX optimization

 IBM: IBM (International Business Machines) is by far the world's largest


information technology company.
 ILOG: ILOG was an international software company purchased and
incorporated into IBM announced in January, 2009. It created enterprise
software products for supply chain, business rule management,
visualization and optimization.
 OPL: OPL (Optimization Programming Language) is a modeling
language for combinatorial optimization, designed to substantially
simplify optimization problems.
OPL combines the strengths of mathematical programming and
constraint programming modeling languages.
Optimization techniques in OPL

The optimization techniques available in OPL are:


 Mathematical Programming (MP), specifically (using CPLEX)
 Linear Programming (LP)
 Integer Programming (IP)
In practice, many models that require integer decision variables also require some
continuous decision variables, and so it is more common to use Mixed Integer
Programming (MIP) than pure IP.
 Quadratic Programming (QP)
 Network flow programming

 Constraint Programming (CP), typically used for (using CP)


 Detailed scheduling
 Certain combinatorial problems not well-suited for MP
Optimization techniques in OPL
Optimization techniques in OPL

In the case of MP problems, OPL can represent the following types of


objective functions, data, decision variables, and constraints:
Optimization techniques in OPL

In the case of CP, OPL can represent the following types of objective
functions, data, decision variables, and constraints:
CPLEX Programming Environment

‫برنامه‌های‌پیشین‬
CPLEX Programming Environment

‫ایجاد‌برنامه‌جدید‬
‫‪CPLEX Programming Environment‬‬

‫نام‌برنامه‌جدید‬
‫انتخاب‌مکان‌ذخیره‌برنامه‬

‫توضیح‌در‌مورد‌برنامه‌در‌‬
‫صورت‌نیاز‬

‫فعال‌کردن‌هر‌‪ 4‬گزینه‪:‬‬
‫‪ -1‬ایجاد‌فایل‌اجرای‌برنامه‬
‫‪ -2‬ایجاد‌فایل‌نوشتن‌مدل‬
‫‪ -3‬ایجاد‌فایل‌تنظیمات‌مدل‬
‫‪ -4‬ایجاد‌فایل‌داده‌‌های‌مدل‬
More about OPL projects
OPL projects are located inside directories, typically with the same name
as the project, on the computer's file system. These directories typically
contain:
• Model files (.mod)
• Data files (.dat)
• Settings files (.ops)
Model files contain data declarations, as well as the model definition in
terms of decision variables, the objective function and constraints. Model
files may also contain IBM ILOG Script statements.
Data files initialize the data declared in the model files. Data can be
initialized directly in the .dat file, or imported from external sources.
Setting files are used to change the default settings in OPL, for example
parameters that define solution algorithm behavior, display options, and
so forth.
‫‪CPLEX Programming Environment‬‬

‫ایجاد‌فایل‌مدل‬ ‫ایجاد‌فایل‌داده‬ ‫ایجاد‌فایل‌تنظیمات‬

‫ایجاد‌برنامه‌جدید‬
‫‪CPLEX Programming Environment‬‬

‫با‌دابل‌کلید‌بر‌روی‬
‫برنامه‌جدید‪‌،‬نیز‌هر‌‬
‫چهار‌فایل‌را‌مشاهده‌‬
‫می‌کنید‪.‬‬
CPLEX Programming Environment

‌‫برنامه‌خود‌را‌در‌فایل‬
‌‫)‌وارد‬.mod(‌‫مدل‬
.‫می‌کنید‬
‫‪CPLEX Programming Environment‬‬

‫داده‌های‌برنامه‌را‌در‌‬
‫فایل‌(‪‌).dat‬وارد‌‬
‫می‌کنید‪.‬‬
‫‪CPLEX Programming Environment‬‬

‫تنظیمات‌مربوط‌به‌حل‌برنامه‪‌،‬شامل نوع‌‬
‫الگوریتم‌و‌تنظیمات‌مربوط‌به‌مشخصات‌‬
‫آن‌الگوریتم‌را‌در‌فایل‌تنظیمات‌(‪‌).ops‬‬
‫اجرا‌نمایید‪.‬‬
‫‪CPLEX Programming Environment‬‬

‫این‌قسمت‌مربوط‌به‌تنظیمات‌مدل‌‬
‫برنامه‌ریزی‌ریاضی‌است‪.‬‬

‫این‌قسمت‌مربوط‌به‌تنظیمات‌مدل‌‬
‫برنامه‌ریزی‌محدودیت‌ها‌است‪.‬‬

‫انتقال‌به‌محیط‌نرم‌افزار‬
‫‪CPLEX Programming Environment‬‬

‫پس‌از‌نوشتن‌مدل‌و‌وارد‌کردن‌داده‌های‬
‫مربوط‌به‌آن‌از‌روی‌فایل‌اجرایی‪‌،‬مدل‬
‫را‌اجرا‌نمایید‪.‬‬
‫‪CPLEX Programming Environment‬‬

‫اطالعات‌اجمالی‌‬
‫در‌مورد‌مدل‬

‫داده‌ها‌و‌متغیرهای‌‬ ‫نتایج‌خروجی‌مدل‬
‫تصمیم‌گیری‬

‫زمان‌اجرای‌مدل‬

‫انتقال‌به‌محیط‌نرم‌افزار‌برای‌توضیح‌خروجی‌ها‬ ‫در‌صورت‌عدم‌وجود‌فضای‌موجه‌برای‌مساله‪‌،‬برخی‌متغیرها‌که‌با‌اسم‌‬
‫مشخص‌شده‌اند‪‌،‬آزادسازی‌می‌شوند‌که‌در‌این‌قسمت‌بیان‌می‌شود‪.‬‬
A simple example:
a production planning problem

Problem description
Consider a typical production planning problem where a company produces
a number of products. Each product has a unit profit associated with it, and
is made up of different components. The company's objective is to
maximize the profit while using only the available stock of components.
The data
The following table shows the data for this problem, together with the OPL
data type and OPL data declaration:
A simple example:
a production planning problem

The decision variables

dvar float+ production[Products];

• Here, dvar is the OPL keyword used to declare decision variables.


• float is the OPL keyword used for real numbers, and the + is added to
denote that the quantities are non-negative.
• production is our choice of variable name, and it is defined as an array
over the set of Products.

Note that all declarations in OPL end with a semicolon.


A simple example:
a production planning problem

The objective function

maximize sum(p in Products) profit[p] * production[p];

• Here, maximize is the OPL keyword used to declare an objective to be


maximized.
• sum is the OPL keyword to compute the summation of a collection of
expressions, in this case to sum up the profit over all products.
• Note that we use normal parentheses, as in (p in Products), to denote
the selection to sum over.
• p is an index used to access each element of the set of Products.
A simple example:
a production planning problem

The constraints
subject to{
Forall(c in Components)
sum(p in Products) usageFactor[p][c] * production[p] <= stock[c];
}

• In the OPL, constraints are written inside a block starting with subject
to {, and ending with }
• Here, forall is the OPL keyword used when expressions are similar,
except for their indices. In this case, it's used to write only one constraint
for all components, seeing that the constraints only differ according to
the product or component they refer to.
• c is an index used to access each element of the set of Components.
A simple example:
a production planning problem

Complete problem formulation


A simple example:
a production planning problem

Data instance

‫انتقال‌به‌محیط‌نرم‌افزار‌برای‌بررسی‌مثالی‌دیگر‬
An other example
Model file
12

𝑚𝑎𝑥 𝑑𝑖 𝑧𝑖
𝑖=1
𝑠. 𝑡
6

𝑐𝑗 𝑦𝑗 ≤ 𝐵
𝑗=1
6

𝑧𝑖 ≤ 𝑎𝑖𝑗 𝑦𝑗 ∀𝑖
𝑗=1
𝑧𝑖 , 𝑦𝑗 = 0,1
An other example
Data file
The choice of solver engine
The following two solver engines are available in OPL:

 CPLEX for Mathematical Programming (MP) problems.


 CP Optimizer for Constraint Programming (CP) problems, specifically:
 Detailed scheduling problems
 Certain combinatorial problems not well-suited for MP

OPL uses CPLEX by default. To specify that CP Optimizer should be used,


start your model with the following text:
using CP;
Data

When declaring data, you need to decide:


The name for the data item
The data type:
 Integer (OPL keyword int)
 Real (OPL keyword float)
 String (OPL keyword string)
The data structure, which can be a scalar, a range, a set, an
array, or a tuple.
Examples:
• float unitProfit = ...;
• int a[i][j]=...;
Data- Ranges
• range Rows = 1..10;

• int n = 8;
range Rows = n+1..2*n+1

• range R = 1..100;
int A[R]; // A is an array of 100 integers

• range R = 1..100;
forall(i in R) {
//element of a loop
{;

• range float myFloatRange = 1.2..2.2;


Data- sets
{int} myIntegerSet = ...;
setof (int) myIntegerSet = ...;

both declare a set called myIntegerSet containing elements of type


integer.
Sets may be ordered, sorted, or reversed. By default, sets are ordered,
which means that:
• Their elements are considered in the order in which they have been
created.
• Functions and operations applied to ordered sets preserve the order.
A set is often used as an array index in an array declaration. For
example, in the following code, we first declare a set called Products,
and then use that set as an index for the decision variable array production.

{string} Products = {”product1”,”product2”,”product3”};


dvar float production[Products]; // production is a decision variable array indexed over
the set of Products
Data-initialization
Data can be initialized:
 in the model (.mod file) or the data (.dat file) files
 read from spreadsheets and databases.
Data can also be exported from OPL to an Excel spreadsheet or a
supported database. Spreadsheet or database read and write
statementsare written in .dat files.
Examples:
float unitProfit = 2.5; in the .mod file
Or
float unitProfit =…; in the .mod file & unitProfit = 2.5; in the .dat file

{int} myIntegerSet = {1, 3, 5, 7}; in the .mod file


Or
{int} myIntegerSet = …; in the .mod file & myIntegerSet = {1, 3, 5, 7}; in the
.dat file
Decision variables
When declaring decision variables, you need to decide:
The name of the variable
The variable type:
 Integer (OPL keyword int)
 Real (OPL keyword float, for MP only)
 Boolean (OPL keyword boolean)
 Interval (OPL keyword interval, for CP only)
 Sequence (OPL keyword sequence, for CP only)
The data structure, which can be a scalar, a range, a set, an array, or a
tuple.
Optionally, the domain, which is the set of possible values the variable
can take.
Examples:
dvar float+ production in 0..maxCapacity;
Decision variable expressions

OPL decision variable expressions can be used to write more complex


expressions in a compact way.

Dexpr float+ profit = production*unitProfit;


 dexpr is the OPL keyword used to declare decision expressions
 profit is the name of this particular decision expression
 this expression defines profit to equal the production decision variable
multiplied by the unitProfit associated with each unit produced.

Using decision expressions modifies the number of variables, constraints, and


nonzeros at execution time and can impact both the solution time and the
memory consumption.
Objective function

maximize profit;

 maximize is the OPL keyword used for maximization problems.


minimize is
used for minimization problems.
 profit is the decision expression to be maximized, in this case. The
objective
expression can be very complex or very simple, depending on your
problem.
Constraints

Constraints in OPL are written in a block starting with subject to { and ending
with }.
subject to {
productionConstraint: production <= capacity;
}
 productionConstraint is the name, or constraint label, of this constraint.
Labeling constraints is optional.

OPL considers only labeled constraints for relaxation when attempting to


resolve infeasibilities.
Instead of writing constraints within subject to {...}, you can use constraints
{...}. These are equivalent.
Filtering indexes
You can filter the index using a filtering condition:
p in Products : filtering condition
Example:
subject to {
forall (p in ProductNumbers)
production[p] <= capacity[p];
}
forall (p in ProductNumbers : p <= 2)
production[p] <= capacity[p];
Aggregators:
maximize sum (p in Products) profit[p] * production[p];

• Here is an example of quantifier and aggregator in use together:

forall (p in products) sales[p] == sum (l in locations) locSales[l][p];


Arrays- Initializing arrays
• In the model file:
int myIntegerArray[1..4] = [1, 3, 5, 7];
• In the data file:
myIntegerArray = [1, 3, 5, 7];
• In a generic way:
int anotherIntegerArray[i in 1..10] = [i+1];
• range R = 1..4;
int a[R]=[1,2,3,4];
Arrays- multidimensional arrays
• a two-dimensional array declaration and initialization:
int my2DArray[1..2][1..3] = [ [5, 2,5], [4, 4,6] ];
• declaration in the model file:
int my2DArray[1..2][1..3] = ...;
initialization in the data file:
my2DArray = [[5, 2,5], [4, 4,6] ];
• A three-dimensional array declaration and initialization:
int my3DArray[1..2][1..3][1..4] =
[ [[1,2,3,4] ,[5,6,7,8], [9,10,11,12]], [[13,14,15,16], [17,18,19,20], [21,22,23,24]] ];
• You can combine different types of indices in multidimensional arrays, for
example:
int numberOfWorkers[Days][1..3] = ...;
Operators- numeric
Constrained Programming
Constrained Programming

• Some optimization problems are solved very effectively using a technique


called Constraint Programming (CP).
• IBM® ILOG® CP Optimizer is a constraint programming optimizer for
solving detailed scheduling problems as well as certain combinatorial
optimization problems that cannot be easily linearized and solved using
traditional mathematical programming methods.
• This powerful CP engine is easily accessible through OPL, where the user
can take full advantage of OPLs development, debugging and tuning features
to solve complex real-world CP problems.
• In addition, it provides easy-to-use representations for specialized
constraints. These simplified representations are particularly useful when
tackling, for example, complex scheduling problems.
Constrained Programming
• It is a technique that is very effective in solving, for example:
 Detailed scheduling problems
 Routing problems
 Satisfiability problems
 Certain other combinatorial optimization problems not well-suited for
traditional Mathematical Programming (MP) methods

• IBM ILOG CP Optimizer is intended for the following two categories of problems:
 Detailed scheduling problems
 Decision variables are of type interval and describe an interval of time
during which, for example, a task occurs
 Certain combinatorial optimization problems not well-suited for MP These
problems contain only discrete decision variables
How does CP Optimizer work?

CP methodology, in general, has two phases:


1. Write a model representation of a problem in a computer programming
language
2. Describe a search strategy for solving the problem
A typical CP search uses the following techniques iteratively until a solution is
found:
• Domain reduction: The process of eliminating possible values from a
variable domain by considering the constraints on that variable and related
variables.
• Constraint propagation: The process of communicating the domain reduction
of a decision variable to all of the constraints on this variable. This can result
in more domain reductions.
How does CP Optimizer work?
Constrained Programming

The OPL keyword using at the beginning of a model file invokes the solution
engine to be used. To call IBM ILOG CP Optimizer as the optimization engine,
use the command:
using CP;
as the first line of your .mod file.
Constrained Programming
operations
Constrained Programming
expressions
Constrained Programming
Arithmetic constraints
Constrained Programming
Logical operator
Constrained Programming
Compatibility Constraints

• allowedAssignments
• forbiddenAssignments

The purpose of these constraints is to define combinations of allowed or forbidden


values for multiple integer decision variables.
using CP;
tuple C {
int a;
int b;
};
{C} possibles = {<1,1>, <2,4>};
{C} forbidden = {<3,5>};
dvar int+ x;
dvar int+ y;
constraints {
allowedAssignments(possibles, x, y);
or
forbiddenAssignments(forbidden, x, y);
}
Constrained Programming
Specialized constraints
A specialized constraint is equivalent to a set of arithmetic or logical constraints.
They express complicated relations between decision variables that would
otherwise require a large number of arithmetic constraint.

𝑥 = 3,1,2
𝑦 = [2,3,1]
Constrained Programming
Specialized constraints
Constrained Programming
Example 1

n Queens

Place 𝑛-queens on an
𝑛  𝑛 board so that no
pair of queens attacks
each other
Constrained Programming
Example 1

n Queens
using CP;
int n=8;
dvar int x[1..n]in 1..n;
subject to{
allDifferent(all(i in 1..n) x[i]);

forall(i in 1..n-1)
forall(j in i+1..n)
abs(x[i]-x[j])!=j-i;
}
Constrained Programming
Example 2

Traveling sales person (TSP)


Exchanging data with a spreadsheet

To exchange data with a spreadsheet:

1. Establish a connection between the OPL application and


the spreadsheet using SheetConnection
• SheetConnection takes a handle – OPL will use
this as the “pipeline.”
2. Read data from the spreadsheet using SheetRead.
• You can read from one or more sheets in an Excel file.
• You can define a range of cells to read.
3. Write data to the spreadsheet using SheetWrite.
• You can write to one or more sheets in an Excel file.
• You can define a range of cells to write to.
Exchanging data with a spreadsheet
Connecting to a spreadsheet
Before an OPL model can read from and/or write to a spreadsheet, it must connect to
the spreadsheet using the SheetConnection instruction.
This is not done in the .mod file but in the .dat file.
Steps:
1. Write your model in the .mod file exactly as you would any model in a project
with independent data.
2. To initialize the data, use links to the spreadsheet in the .dat file.

Syntax:
SheetConnection <handle> ("filename.xls");
Example:
SheetConnection connex ("mySheet.xls");

Establishes a connection connex to a spreadsheet named mySheet.xls in read/write


mode.
Exchanging data with a spreadsheet
Reading from a spreadsheet

Once the model is connected to the spreadsheet, data can be read into these data
elements using the SheetRead command:
• One-dimensional arrays
• Two-dimensional arrays or sets

Steps:
1. In the .mod file, declare the array or set, <dataElement>, that you want to fill
with data from the spreadsheet;
2. In the .dat file, call the data to be read using the syntax:
<dataElement> from SheetRead (<handle>,“<SheetName>!<startCell>:<endCell>”;

<SheetName> is optional. If no <SheetName> is given, and the Excel workbook


has more than one sheet, the currently active sheet is read.
Exchanging data with a spreadsheet
Reading from a spreadsheet
Example:
Streets from SheetRead (connex,”addresses!A1:C13”)
Reads the range of cells from A1 to C13 into a data element named Streets
from the
sheet named addresses that is located in the spreadsheet that uses the
connex
connection.

• <dataElement> is the array or set, declared in the model file, that you
want to fill
• <SheetName> is the name of the sheet inside the Excel file that you
want to read from.
• <startCell> is the first cell, in the spreadsheet called by the connection
<handle>, of the range that you want to use to fill <dataElement>.
• <endCell> is the last cell, in the spreadsheet called by the connection
<handle>, of the range that you want to use to fill <dataElement>.
Exchanging data with a spreadsheet
Writing to a spreadsheet

You can write into spreadsheets using the SheetWrite command. As with
SheetRead, you write the SheetWrite command in the .dat file.
Steps:
1. You must already have an array or set declared in the .mod file and
instantiated, from which you will write to the spreadsheet. This is
represented here by the token <dataElement>.
2. In the .dat file, write the data to a range in the spreadsheet, using the
syntax:

<dataElement> to SheetWrite (<handle>, “<SheetName>!<startCell>:<endCell>”;


Exchanging data with a spreadsheet
example
1. In the model file, declare the data and variables.
{string} Products =...;
{int} TimePeriods =...;
float rate[Products] =...;

dvar float+ Make[Products][TimePeriods];


dvar float+ Sell[Products][TimePeriods];

2. In the data file, declare the connection to the spreadsheet.


SheetConnection sheet("xsteel.xls");
3. In the data file, write how to read the data values in the spreadsheet.
Products from SheetRead(sheet,"data!A2:A3");
TimePeriods from SheetRead(sheet,"data!A17:A20");
rate from SheetRead(sheet,"data!B2:B3");
4. Also in the data file, add the statements that write the result into the spreadsheet.
Make to SheetWrite(sheet,"RESULT!A2:D3");
Sell to SheetWrite(sheet,"RESULT!A8:D9");

You might also like