یفداصتیزیرهمانبسرد - sharifie.sharif.edu/~sp/cplex tutorial-sp-radman_96.pdf ·...
TRANSCRIPT
به
بهنامخدا
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بهاتصال).بگیرندبهرهآناتصالقابلیتهایازتامیدهندترجیححرفهای
matlab،C#و...)
مثلمجموعههاییGAMSوLingo/LindoَحساببهریاضیمدلتوسعهمحیطعمدتایکCPLEXولی.میگیرندبهرهخوددروندرهاsolverازمجموعهایازومیآیند
solverاست.یبرنامهدرراریاضیمدلیکاستممکنشمامثال،عنوانبهGAMSسپسوبنویسید
.کنیدحلراآنCPLEXتوسط
GAMSنرمافزار
Mathematical Programming
Optimization modeling with IBM ILOG OPL
IBM ILOG CPLEX optimization
IBM: IBM (International Business Machines) is by far the world's largestinformation technology company.
ILOG: ILOG was an international software company purchased andincorporated into IBM announced in January, 2009. It created enterprisesoftware products for supply chain, business rule management,visualization and optimization.
OPL: OPL (Optimization Programming Language) is a modelinglanguage for combinatorial optimization, designed to substantiallysimplify optimization problems.
OPL combines the strengths of mathematical programming andconstraint programming modeling languages.
Definitions…
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 somecontinuous decision variables, and so it is more common to use Mixed IntegerProgramming (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
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
OPL projects are located inside directories, typically with the same nameas the project, on the computer's file system. These directories typicallycontain:
• Model files (.mod)
• Data files (.dat)
• Settings files (.ops)
Model files contain data declarations, as well as the model definition interms of decision variables, the objective function and constraints. Modelfiles may also contain IBM ILOG Script statements.
Data files initialize the data declared in the model files. Data can beinitialized directly in the .dat file, or imported from external sources.
Setting files are used to change the default settings in OPL, for exampleparameters that define solution algorithm behavior, display options, andso forth.
More about OPL projects
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
𝑚𝑎𝑥
𝑖=1
12
𝑑𝑖𝑧𝑖
𝑠. 𝑡
𝑗=1
6
𝑐𝑗𝑦𝑗 ≤ 𝐵
𝑧𝑖 ≤
𝑗=1
6
𝑎𝑖𝑗𝑦𝑗 ∀𝑖
𝑧𝑖, 𝑦𝑗 = 0,1
An other example
Data file
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;
The choice of solver engine
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, anarray, or a tuple.
Examples:
• float unitProfit = ...;
• int a[i][j]=...;
Data
• 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- Ranges
{int} myIntegerSet = ...;
setof (int) myIntegerSet = ...;
both declare a set called myIntegerSet containing elements of typeinteger.
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 beencreated.
• Functions and operations applied to ordered sets preserve the order.
A set is often used as an array index in an array declaration. Forexample, 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 overthe set of Products
Data- sets
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 asupported database. Spreadsheet or database read and writestatementsare 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
Data-initialization
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 atuple.
Optionally, the domain, which is the set of possible values the variablecan take.
Examples:
dvar float+ production in 0..maxCapacity;
Decision variables
OPL decision variable expressions can be used to write more complexexpressions 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, andnonzeros at execution time and can impact both the solution time and thememory consumption.
Decision variable expressions
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. Theobjective
expression can be very complex or very simple, depending on yourproblem.
Objective function
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 toresolve infeasibilities.
Instead of writing constraints within subject to {...}, you can use constraints{...}. These are equivalent.
Constraints
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];
Filtering indexes
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];
Aggregators:
• 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- Initializing 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, forexample:
int numberOfWorkers[Days][1..3] = ...;
Arrays- multidimensional arrays
Operators- numeric
Constrained Programming
• Some optimization problems are solved very effectively using a techniquecalled Constraint Programming (CP).
• IBM® ILOG® CP Optimizer is a constraint programming optimizer forsolving detailed scheduling problems as well as certain combinatorialoptimization problems that cannot be easily linearized and solved usingtraditional mathematical programming methods.
• This powerful CP engine is easily accessible through OPL, where the usercan take full advantage of OPLs development, debugging and tuning featuresto solve complex real-world CP problems.
• In addition, it provides easy-to-use representations for specializedconstraints. These simplified representations are particularly useful whentackling, 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 fortraditional 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 timeduring which, for example, a task occurs
Certain combinatorial optimization problems not well-suited for MP Theseproblems contain only discrete decision variables
Constrained Programming
CP methodology, in general, has two phases:
1. Write a model representation of a problem in a computer programminglanguage
2. Describe a search strategy for solving the problem
A typical CP search uses the following techniques iteratively until a solution isfound:
• Domain reduction: The process of eliminating possible values from avariable domain by considering the constraints on that variable and relatedvariables.
• Constraint propagation: The process of communicating the domain reductionof a decision variable to all of the constraints on this variable. This can resultin more domain reductions.
How does CP Optimizer work?
How does CP Optimizer work?
The OPL keyword using at the beginning of a model file invokes the solutionengine 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
Constrained Programming
operations
Constrained Programming
expressions
Constrained Programming
Arithmetic constraints
Constrained Programming
Logical operator
Constrained ProgrammingCompatibility 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");