applications of optimization with xpress-mp › ~moretti › mt503 › syllabus.pdf · sion (s-11)...

55
Applications of optimization with Xpress-MP Syllabus and teaching material Last update 25 October, 2006

Upload: others

Post on 08-Jun-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Applications of optimizationwith Xpress-MP

Syllabus and teaching material

Last update 25 October, 2006

Page 2: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Published by Dash Optimization Ltdc©Copyright Dash Associates 2007. All rights reserved.

All trademarks referenced in this manual that are not the property of Dash Associates are acknowledged.

All companies, products, names and data contained within this book are completely fictitious and are used solely toillustrate the use of Xpress-MP. Any similarity between these names or data and reality is purely coincidental.

How to Contact Dash

USA, Canada and all Americas

Dash Optimization Inc

Information and Sales: [email protected]: [email protected] Support: [email protected]

Tel: +1 (201) 567 9445Fax: +1 (201) 567 9443

Dash Optimization Inc.560 Sylvan AvenueEnglewood CliffsNJ 07632USA

Japan

Dash Optimization Japan

Information and Sales: [email protected]: [email protected] Support: [email protected]

Tel: +81 43 297 8836Fax: +81 43 297 8827

WBG Marive-East 21F FASuC B21242-6 Nakase Mihama-ku261-7121 ChibaJapan

Worldwide

Dash Optimization Ltd

Information and Sales: [email protected]: [email protected] Support: [email protected]

Tel: +44 1926 315862Fax: +44 1926 315854

Leam House, 64 Trinity StreetLeamington SpaWarwickshire CV32 5YNUK

For the latest news and Xpress-MP software and documentation updates, please visit the Xpress-MP website athttp://www.dashoptimization.com or subscribe to our mailing list.

Page 3: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Contents

1 Syllabus: Modeling with Mosel 11.1 Introduction unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Thematical units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 Additional examples 32.1 Binary variables: Location of firestations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2.1.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.1.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.1.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.1.4 Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2.2 Semi-continuous variables: Contract allocation . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.3 SOS-1: Manpower planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.3.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.4 SOS-2: Purchasing with price breaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.4.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.4.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.4.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.5 Development of a model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.5.1 A first model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.5.2 Improved model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.5.3 Time-indexed model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.5.4 Complete model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.5.5 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.6 Programming with Mosel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.6.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.6.2 Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.7 Branch-and-Cut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242.7.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.7.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262.7.3 Cutting plane algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262.7.4 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.8 Column generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292.8.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292.8.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.8.3 Column generation algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.8.4 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

2.9 Goal Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342.9.1 Example problem: Family holiday planning . . . . . . . . . . . . . . . . . . . . . . . . 342.9.2 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342.9.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

2.10 Recursion – SLP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382.10.1 Model formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382.10.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392.10.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392.10.4 Recursion algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.10.5 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

i Applications of optimization with Xpress-MP

Page 4: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

3 Teaching material 423.1 Model APS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

3.1.1 LP models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423.1.2 MIP models (1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.1.3 MIP models (2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

3.2 Model Food . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Contents ii Applications of optimization with Xpress-MP

Page 5: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Chapter 1

Syllabus: Modeling with Mosel

This document suggests a syllabus for a course “Modeling with Mosel” based on the book “Applicationsof optimization with Xpress-MP” (http://www.dashoptimization.com/applications_book.html).

The cours layout is organized in several units: the first (8-10 hours) unit gives the necessary foundationsand should be taught at the start of the course. The other units are formed around themes. They buildon the first unit but are largely independent of each other. The teacher may make a choice among theseunits according to the background and interests of the students. It should be noticed however that someof the units overlap.

After the first 2-3 hours of introduction the students are able to write simple LP models and implementand solve them using Xpress-MP. A "hands-on" course or guided practical work (see examples “T-1 APS”and “T-2 Food” under “Teaching Material”) accompanying the lectures from the first lesson taught isrecommended.

All chapter and section references in the following refer to the book “Applications of optimization withXpress-MP”. Examples A-1 to J-6 are in this book. Examples S-1 to S-11 are described below under “Addi-tional examples” and examples T-1 and T-2 under “Teaching Material”.

1.1 Introduction unit

Teaching time: 8-10 hours

1. What is “modeling” (Sections 1.1, 1.5)

2. Basics of LP: the Chess problem (Sections 1.2, 1.3)

3. Getting started with Mosel (Chapter 5)

4. Examples of LP constraint/problem types: resource constraints (Chess problem), blending (A-1),flow/material balance (C-2, C-5, or J-1), assignment (F-1)

5. Programming with Mosel: dynamic arrays, sets, loops, subroutines (examples: “S-6 Prime numbers”and “S-7 Quick sort”, see below Section “Additional examples”) — at this place for Computer Sci-ence students, may go to the end (after 8.) of the introduction unit for others

6. Introduction of MIP: the algorithm of Branch-and-Bound (Sections 3.1, 3.2)

7. MIP variable types: modeling logical relations with binaries (Section 3.3, two variable cases only)and examples using different variable types (Section 3.4; Chess problem, D-5, H-2: integer, D-4, G-6,S-1: binary, H-3, S-2: semi-continuous, B-2, S-3, S-4: SOS)

8. Development of a model: “S-5 Coco problem” (see below Section “Additional examples”) — thisitem could also be moved before as a motivation for discrete variables

9. “Extras” (optional): Branch-and-Cut (S-8), column generation (S-9), Goal Programming (S-10), recur-sion (S-11) → simple algorithms looping around optimization statements, extension to other typesof Mathematical Programming problems (see below Section “Additional examples”)

1.2 Thematical units

Teaching time: 4-6 hours per unit (choice of 5-6 examples out of those given below)

1 Applications of optimization with Xpress-MP

Page 6: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

• Telecom: Chapter 12 (G-1 to G-6)

• Transport: loading (D-1 to D-3), network layout (E-3, J-1, F-4, G-6, J-5), route choice (E-2, E-4, E-5,F-5, G-3, J-4), timing (F-1, F-3), fleet (E-1, E-6)

• Services: safety/surveillance (J-2), gritting roads (J-4), income tax offices (J-5), efficiency of hospitals(J-6), scheduling nurses (I-2), college timetable (I-3), telephone network (reliability: G-1, coverage:G-6), car rental (E-1), passenger transfer (F-1)

• Finance: Chapter 13 (H-1 to H-7)

• Personnel: assignment (I-1, I-5), timetabling/scheduling/planning (I-2, I-3, I-6), efficiency (J-6), flightcrews (F-2), early retirement (H-4)

• Aspects of production: blending (A-2), loading (D-1 to D-3), inventory (C-1 or C-4), cutting stock(D-6), dispatching (A-6), sequencing/scheduling (B-2 to B-5), delivery (E-2, E-4), routing (G-3)

• Aspects of scheduling: project (B-1), flow shop (B-2), job shop (B-3), parallel machines (D-1), timewindows (F-3), preemptive open shop (G-5), personnel (I-2)

• Aspects of planning: short-term (A-6, B-2, B-6, C-6), mid-term (B-1, C-2, C-3, E-6), long-term (A-5,E-3, J-5, J-1, G-2, G-6), finance (H-4, H-5), personnel/timetabling (I-2, I-3, I-6)

• Aspects of management: Production (C-3, C-2 or C-5), Project scheduling (B-1), Resources (J-1),Transport (E-3 or F-4), Personnel (I-6), Finance (H-6, H-3 or H-1), Service (J-5), Marketing (H-2)

• Problems in graphs: minimum cost flow (A-4, A-5, E-2), transport (E-1), facility location (E-3, F-4), VRP (E-4), Bipartite matching (F-2), TSP (F-5, B-5), maximum flow (G-1, J-1), multi-commoditynetwork flow (G-3), minimum weigth spanning tree (G-4), Chinese postman (J-4), p-median (J-5),multi-period production as flow (C-5)

• Solution algorithms and heuristics: Heuristic with sorting algorithm (D-1), heuristic solution (I-1),TSP subtour elimination (F-5), model cuts (E-4), data preprocessing (J-3), looping over optimization(G-5), all-pairs shortest path (J-5), Eulerian circuit (J-4), DEA method (J-6)

• “Classical” problem types: Cutting-stock (D-6), TSP (F-5), Facility location (E-3), Minimum cost flow(A-5 or E-2), Scheduling (one of B-1 to B-4), Assignment (F-1, I-1, or C-6), Covering (D-5, G-6)

• “Historical” and “new” application areas: flight crews (F-2), refinery (A-3), sequencing/scheduling(B-1, B-4), mobile phone network/transmitters (G-2, G-6), CCTV (J-2), portfolio selection (H-3, H-7)

• Working with a problem, studying different objectives and improving the problem formulation:incremental problem definition (D-2, I-1, I-5), experiment with solutions (H-6), symmetry breaking(D-4, I-4), model reformulation (D-4, F-4), two problems (B-1, F-2), several objectives (B-4, D-3)

Syllabus: Modeling with Mosel 2 Applications of optimization with Xpress-MP

Page 7: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Chapter 2

Additional examples

The examples in this chapter may be used in addition to those provided in the book “Applications ofoptimization with Xpress-MP” in the introduction unit of a course on modeling with Mosel. They coverthe following topics:

• MIP variable types: binary, semi-continuous, SOS-1, SOS-2 (Sections 2.1 - 2.4)

• Development of a model (Section 2.5)

• Programming with Mosel: prime numbers, quick sort (Section 2.6)

• “Extras”: Branch-and-Cut, column generation, Goal Programming, recursion/SLP (Sections 2.7 -2.10)

2.1 Binary variables: Location of firestations

Six neighboring towns have decided to organize their rescues services jointly to reduce the total cost. Atthe present, every town has got its own firestation. A town must be no more than 20 minutes from theclosest firestation. Which is the minimum number of firestations that need to be maintained?

The traveling times between the towns are giving in Table 2.1.

Table 2.1: Traveling times between towns

tofrom 1 2 3 4 5 6

1 0 15 25 35 35 25

2 15 0 30 40 25 15

3 25 30 0 20 30 25

4 35 40 20 0 20 30

5 35 25 35 20 0 19

6 25 15 25 30 19 0

2.1.1 Model formulation

Let TOWNS be the set of town. The traveling time between towns t and s is denoted by TIMEts. TIMELIMITis the maximum traveling time allowed to reach any town. The decision about the location of firestationscan be represented by binary variables opent that take the value 0 if the station is closed and 1 iff itremains open. The mathematical model of our problem may then be written as follows:

minimize∑

t∈TOWNS

opent (2.1.1)

∀t ∈ TOWNS :∑

s∈TOWNSTIMEts≤TIMELIMIT

opens ≥ 1 (2.1.2)

∀t ∈ TOWNS : opent ∈ {0, 1} (2.1.3)

The objective function (2.1.1) counts the number of open firestations. The constraints (2.1.2) state thatevery town must be reachable from at least one open firestation. All variables opent are binaries (2.1.3).

3 Applications of optimization with Xpress-MP

Page 8: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.1.2 Implementation

The following Mosel program implements the mathematical model.

model "S-1 Firestations"uses "mmxprs"

declarationsTOWNS = 1..6 ! Set of townsTIMELIMIT = 20 ! Max. time allowed to reach any townTIME: array(TOWNS,TOWNS) of integer ! Traveling time between townsSERVE: array(TOWNS,TOWNS) of boolean ! "true" if town reachable

open: array(TOWNS) of mpvar ! 1 if firestation at town; 0 if notend-declarations

initializations from ’s1fire.dat’TIME

end-initializations

forall(t,s in TOWNS)SERVE(t,s):= TIME(t,s) <= TIMELIMIT

! Objective function: number of open fire stationsMinSta:= sum(t in TOWNS) open(t)

! Serve each town t by an open station sforall(t in TOWNS) sum(s in TOWNS | SERVE(s,t)) open(s) >= 1

forall(t in TOWNS) open(t) is_binary

! Solve the problemminimize(MinSta)

end-model

In this implementation we have introduced the table SERVE of type boolean that indicates which townscan be reached within the given time limit. An alternative formulation of the constraints without thisintermediate table SERVE is as follows:

forall(t in TOWNS) sum(s in TOWNS | TIME(t,s) <= TIMELIMIT) open(s) >= 1

2.1.3 Results

The minimum number of stations to be maintained is 2. The firestation in town 2 serves towns 1, 2, and6 and the firestation in town 4 the remaining towns.

2.1.4 Extension

There may be additional constraints in this example such as the following logical relations:

1. There must be a firestation either in town 1 or in town 2, but not in both towns.

open1 + open2 = 1

2. If there is a firestation in town 3, then there is none in town 4.

open3 ≤ 1− open4

3. In towns 1,2,5,6 there must be at least 2 firestations.∑t∈{1,2,5,6}

opent ≥ 2

4. If there is no firestation in town 6, then there must be one in towns 3 or 4.

1− open6 ≤ open3 + open4

Additional examples 4 Applications of optimization with Xpress-MP

Page 9: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.2 Semi-continuous variables: Contract allocation

A public utility, which is divided into six regional districts, wishes to allocate ten power generation con-tracts to its regions as cheaply as possible. The cost per unit of power generated by each region for eachcontract is known (see Table 2.2). If part of a contract is allocated to a region than it must be at least asbig as a certain minimum size (5 units). For reliability reasons, no contract may be placed exclusively withonly one district. Each district has a limited power generation capacity. The contract volumes are listed inTable 2.3.

Table 2.2: Production capacities and costs

District Max. output Cost/unitin MW in kBC

1 50 50

2 40 20

3 10 25

4 20 30

5 70 45

6 50 40

Table 2.3: Contract volume

Contract 1 2 3 4 5 6 7 8 9 10

Size in MW 20 10 30 15 20 30 10 50 10 20

2.2.1 Model formulation

We write DISTRICT for the set of bidding districts and CONTRACT for the set of contracts to be allocated.Every district d has a maximum output of OUTPUTd MW and a production cost of COSTd per MW. The sizeof a contract c is given by VOLUMEc.

To count the numbers of bidders allocated a contract and to account for the allocated contract volumeswe introduce two sets of decision variables. The binary variables allocdc indicate whether distrct d isallocated a part of contract c. The variables quantdc are the quantities of contracts allocated to thedistricts. These variables are either 0 or lie between 5 and an upper bound given by the maximum outputof the district:

∀d ∈ DISTRICT, c ∈ CONTRACT : quantdc = 0 ∨ 5 ≤ quantdc ≤ OUTPUTd (2.2.1)

This type of variables is known as semi-continuous variables.

For every contract we need to establish two sets of constraints: the entire contract volume must beallocated to the bidders (2.2.2) and at least two districts must share the contract (2.2.3).

∀c ∈ CONTRACT :∑

d∈DISTRICT

quantdc ≥ VOLUMEc (2.2.2)

∀c ∈ CONTRACT :∑

d∈DISTRICT

allocdc ≥ 2 (2.2.3)

In addition, we have the constraints (2.2.4) that ensure that the allocated contract volume remains withinthe output capacity of the districts.

∀d ∈ DISTRICT :∑

c∈CONTRACT

quantdc ≤ OUTPUTd (2.2.4)

Completed with the objective function to minimize the total cost (2.2.5), we obtain the following math-ematical model:

minimize∑

d∈DISTRICT

∑c∈CONTRACT

COSTd · quantdc (2.2.5)

Additional examples 5 Applications of optimization with Xpress-MP

Page 10: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

∀c ∈ CONTRACT :∑

d∈DISTRICT

quantdc ≥ VOLUMEc (2.2.6)

∀c ∈ CONTRACT :∑

d∈DISTRICT

allocdc ≥ 2 (2.2.7)

∀d ∈ DISTRICT :∑

c∈CONTRACT

quantdc ≤ OUTPUTd (2.2.8)

∀d ∈ DISTRICT, c ∈ CONTRACT : allocdc ∈ {0, 1} (2.2.9)

∀d ∈ DISTRICT, c ∈ CONTRACT : quantdc = 0 ∨ 5 ≤ quantdc ≤ OUTPUTd (2.2.10)

2.2.2 Implementation

The Mosel implementation of the mathematical model is given by the following. The semi-continuousvariables are marked with the keyword is_semcont, followed by the limit value (lower bound of thecontinuous part).

model "S-2 Contract allocation"uses "mmxprs"

declarationsDISTRICT = 1..6 ! DistrictsCONTRACT = 1..10 ! ContractsOUTPUT: array(DISTRICT) of integer ! Maximum output per districtCOST : array(DISTRICT) of integer ! Cost per districtVOLUME: array(CONTRACT) of integer ! Volume of contracts

alloc: array(DISTRICT,CONTRACT) of mpvar ! 1 if a bid is chosen, 0 otherwisequant: array(DISTRICT,CONTRACT) of mpvar ! Quantities allocated to contractors

end-declarations

initializations from ’s2contract.dat’OUTPUT COST VOLUME

end-initializations

! Objective function: total costCost:= sum(d in DISTRICT, c in CONTRACT) COST(d)*quant(d,c)

forall(c in CONTRACT) dosum(d in DISTRICT) quant(d,c) >= VOLUME(c) ! Cover the req. contract volumesum(d in DISTRICT) alloc(d,c) >= 2 ! At least 2 districts per contract

end-do

! Do not exceed maximum output of any districtforall(d in DISTRICT) sum(c in CONTRACT) quant(d,c) <= OUTPUT(d)

! If a contract is allocated to a district, then at least 1 unit is! allocated to itforall(d in DISTRICT, c in CONTRACT) alloc(d,c) <= quant(d,c)

forall(d in DISTRICT, c in CONTRACT) doalloc(d,c) is_binaryquant(d,c) is_semcont 5quant(d,c) <= OUTPUT(d)

end-do

! Solve the problemminimize(Cost)

end-model

2.2.3 Results

The total cost of the contract allocation is BC 8,050,000. Table 2.4 shows the distribution of contracts tobidding districts (there are several different distributions with the same cost). All but the first districtoperate at their capacity limit. A graphical representation of the result generated with IVE is shown inFigure 2.1.

Additional examples 6 Applications of optimization with Xpress-MP

Page 11: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Table 2.4: Contract volume

ContractsDistrict 1 2 3 4 5 6 7 8 9 10 Total

1 5 5 5 5 5 25

2 5 20 5 5 5 40

3 10 10

4 5 15 20

5 15 5 25 10 15 70

6 45 5 50

Figure 2.1: Solution display with mmive

Additional examples 7 Applications of optimization with Xpress-MP

Page 12: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.3 SOS-1: Manpower planning

Over the next 6 months we have three projects which can be done. Each of these projects has a profileof manpower requirements over its lifetime, and a benefit which accrues each month when the projecthas been completed. Our problem is to determine when each project is to start, subject to the constraintthat in no month can we try to use more manpower than is available. The data are as follows:

Table 2.5: Project-related data

Project Duration Profile Benefit/monthin kBC

1 3 3,4,2 10.2

2 3 4,1,5 12.3

3 4 3,2,1,2 11.2

For example, project 1 takes 3 months. In its first month it uses 3 people, in its second, 4 people, and inits third, 2 people.

The total manpower availability per month is shown in Table 2.6.

Table 2.6: Manpower availability

Month 1 2 3 4 5 6

Personnel 5 6 7 7 6 6

2.3.1 Model formulation

We write PROJ for the set of projects and TIME = {1, . . . , NT} for the set of time periods. Let further DURp

denote the duration of project p, BENp its monthly benefit once the project is finished, and RESUSEps

the resource usage of project p in its sth month. The available manpower per time period t is given byRESMAXt.

We define variables xpt that indicate whether project p starts in month t (xpt = 1) or not (xpt = 0). Sincea project is to start in a single month, exactly one vairable xpt per project p must be 1 and all others 0(constraints (2.3.1)). The starting time startp of every project is then given by the constraints (2.3.2). If allprojects are to finish within the planning period, then the latest start time for every project is NT−DURp+1(constraints (2.3.3)).

∀p ∈ PROJ :∑

t∈TIME

xpt = 1 (2.3.1)

∀p ∈ PROJ :∑

t∈TIME

t · xpt = startp (2.3.2)

∀p ∈ PROJ : 0 ≤ startp ≤ NT − DURp + 1 (2.3.3)

Strictly speaking, it is not required to introduce the variables startp in this model, these are merely ac-counting variables that make the model formulation clearer.

The formulation of the resource constraints and of the objective function is a bit tricky. The resourceusage of a project p in a given month t depends on its start time. If it starts in month s (s ≤ t), it is in itst − s + 1st month in month t, and hence, we may calculate the resource usage of p in t as

t∑s=1

RESUSEp,t−s+1 · xps (2.3.4)

In any month t, the resource usage by all projects must not exceed the available manpower RESMAXt,leading to the constraints (2.3.5).

∀t ∈ TIME :∑

p∈PROJ

t∑s=1

RESUSEp,t−s+1 · xps ≤ RESMAXt (2.3.5)

The objective is to maximize the total benefit obtained through the projects once they are finished. Inother words, if project p starts in month t, it finishes in month t + DURp − 1 and contributes a benefit of

Additional examples 8 Applications of optimization with Xpress-MP

Page 13: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

BENp for the remaining NT − (t + DURp − 1) months. The total benefit from a project is therefore givenby the sum

NT−DURp∑t=1

(BENp · (NT − t − DURp + 1)) · xpt (2.3.6)

Summing up over all projects, we obtain the objective function (2.3.7). For completeness’ sake we repeathere the complete mathematical model:

maximize∑

p∈PROJ

NT−DURp∑t=1

(BENp · (NT − t − DURp + 1)) · xpt (2.3.7)

∀t ∈ TIME :∑

p∈PROJ

t∑s=1

RESUSEp,t−s+1 · xps ≤ RESMAXt (2.3.8)

∀p ∈ PROJ :∑

t∈TIME

xpt = 1 (2.3.9)

∀p ∈ PROJ :∑

t∈TIME

t · xpt = startp (2.3.10)

∀p ∈ PROJ : 0 ≤ startp ≤ NT − DURp + 1 (2.3.11)

∀p ∈ PROJ, t ∈ TIME : xpt ∈ {0, 1} (2.3.12)

2.3.2 Implementation

The following implementation with Mosel of the mathematical model shows two different possibilitiesof stating that the variables xpt only take values in {0, 1} and that for every project p exactly one xpt takesthe value 1. If the parameter USESOS is set to false, the variables xpt are defined as standard binaryvariables. With USESOS = true we define SOS-1 (Special Ordered Sets of Type 1) that ensure that atmost one xpt is non-zero (and hence 1, due to the constraints sum(t in TIME) x(p,t) = 1) for eachproject p. The month index is used to order the variables in the sets. Especially in larger problems, usingSOS instead of binary variables may be advantageous in the Branch-and-Bound search.

model "S-3 Manpower planning"uses "mmxprs"

parametersUSESOS = false ! Set to true to use formulation with SOS

end-parameters

declarationsPROJ = 1..3 ! ProjectsNT = 6 ! Time horizonTIME = 1..NT ! Months to plan forDUR: array(PROJ) of integer ! Duration of projectsRESUSE: array(PROJ,TIME) of integer ! Resource usage per projectRESMAX: array(TIME) of integer ! Resource available per monthBEN: array(PROJ) of real ! Benefit per month once project finished

x: array(PROJ,TIME) of mpvar ! 1 if project p starts in month t, else 0start: array(PROJ) of mpvar ! Starting time of project t

end-declarations

initializations from ’s3pplan.dat’DUR RESMAX BEN RESUSE

end-initializations

! Objective: Maximize BenefitMaxBen:=sum(p in PROJ,t in 1..NT-DUR(p)) (BEN(p)*(NT-t-DUR(p)+1)) * x(p,t)

! Resource availabilityforall(t in TIME)sum(p in PROJ,s in 1..t) RESUSE(p,t-s+1)*x(p,s) <= RESMAX(t)

! Each project starts once and only onceforall(p in PROJ) sum(t in TIME) x(p,t) = 1

! Connect variables x(p,t) and start(p)

Additional examples 9 Applications of optimization with Xpress-MP

Page 14: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

forall(p in PROJ) sum(t in TIME) t*x(p,t) = start(p)

! Finish everything by the end of the planning periodforall(p in PROJ) start(p) <= NT-DUR(p)+1

if not USESOS then ! Turn variables x into binariesforall(p in PROJ,t in TIME) x(p,t) is_binary

else ! Define SOS-1 setsforall(p in PROJ) sum(t in TIME) t*x(p,t) is_sos1end-if

! Solve the problemmaximize(MaxBen)

end-model

2.3.3 Results

The total benefit is BC 48,100. Project 1 starts in month 4, project 2 in month 1, and project 3 in month 2.As shown in Figure 2.2, in months 3 and 5 all available personnel is employed, in the other months thereis some remaining free capacity.

Figure 2.2: Resource use diagram

2.4 SOS-2: Purchasing with price breaks

There are three suppliers of a good, and they have quoted various prices for various quantities of product.We want to buy at least total cost, yet not buy too much from any one supplier. Each supplier offersdecreasing prices for increased lot size, in the form of incremental discounts. We wish to buy 600 itemsin total. The rest of the data is:

Table 2.7: Price profile

Supplier Max. percentage Unit price Breakpoint Unit price Breakpoint Unit price Breakpoint

1 40% 9.2 100 9 200 7 1000

2 35% 9 50 8.5 250 8.3 2000

3 40% 11 100 8.5 300 7.5 4000

For example, if you buy 150 items from supplier 1, you pay 9. 2 · 100 + 9 · 50. If you buy 250 items fromsupplier 1, you pay 9. 2 · 100 + 9 · 100 + 7 · 50. We can buy at most 40% of the requirement from supplier1, so in fact we cannot buy more than (40 / 100) · 600 = 240 items.

Additional examples 10 Applications of optimization with Xpress-MP

Page 15: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

B10 xB11 B12 B13

COST12

COST11

CBR

Cost

CBR

CBR

11

12

13

COST13

Figure 2.3: Price curve of supplier 1

2.4.1 Model formulation

Let SUPPL be the set of suppliers, BREAK0 the set of breakpoints including 0, and BREAK1 the set ofbreakpoints starting with the first point where unit cost changes, that is without 0. For every supplier s,BRsb (b ∈ BREAK1) denotes the breakpoint where the unit cost changes from COSTsb to COSTs,b+1; BRs0

is always 0. Let furthermore REQ be the total amount we wish to buy, and MAXPERCs the maximumpercentage that may be bought from supplier s.

To formulate this problem, we introduce two sets of variables. buys represents the quantity bought fromsupplier s. These quantities are calculated via weight variables wsb associated with the breakpoints. Theweight variables for every supplier s form an SOS-2 (Special Ordered Set of Type 2), that means that atmost two neighboring variables wsb in the order induced by the coefficients BRbs may be non-zero. Underthe condition that the weight variables sum up to 1 for every supplier (2.4.2) we can use these variablesto linearly interpolate between the breakpoints to obtain the quantities bought (constraints (2.4.1)).

∀s ∈ SUPPL :∑

b∈BREAK0

BRsb ·wsb = buys (2.4.1)

∀s ∈ SUPPL :∑

b∈BREAK0

wsb = 1 (2.4.2)

Furthermore, we need to express the constraints that the total requirement must be met (2.4.3) and thatno more than a certain given percentage may be bought of each supplier (2.4.4).∑

s∈SUPPL

buys ≥ REQ (2.4.3)

∀s ∈ SUPPL : buy(s) <= MAXPERC(s) ∗ REQ / 100. 0 (2.4.4)

The total cost at the breakpoints, CBRsb, is given by the following recursive formula:

CBRs0 = 0 (2.4.5)

∀b ∈ BREAK1 : CBRsb = CBRs,b−1 + COSTsb · (BRsb − BRs,b−1) (2.4.6)

With these total cost values we can formulate the objective function (2.4.7) and obtain the followingmathematical model (see Section 3.5.4 of the book for further explanation).

maximize∑

s∈SUPPL

∑b∈BREAK0

CBRsb ·wsb (2.4.7)

∀s ∈ SUPPL :∑

b∈BREAK0

BRsb ·wsb = buys (2.4.8)

∀s ∈ SUPPL :∑

b∈BREAK0

wsb = 1 (2.4.9)∑s∈SUPPL

buys ≥ REQ (2.4.10)

∀s ∈ SUPPL : buy(s) <= MAXPERC(s) ∗ REQ / 100. 0 (2.4.11)

Additional examples 11 Applications of optimization with Xpress-MP

Page 16: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

∀s ∈ SUPPL :⋃

b∈BREAK0

{wsb} SOS-2 with coefficients BRsb (2.4.12)

2.4.2 Implementation

The Mosel implementation of the mathematical model looks as follows.

model "S-4 Purchase"uses "mmxprs"

declarationsNB = 3BREAK1 = 1..NB ! Price breaksBREAK0 = 0..NB ! Price breaks including 0SUPPL = 1..3 ! Suppliers

COST: array(SUPPL,BREAK1) of real ! Unit costBR: array(SUPPL,BREAK0) of real ! Breakpoints (quantities at which unit

! cost changes)CBR: array(SUPPL,BREAK0) of real ! Total cost at break pointsMAXPERC: array(SUPPL) of real ! Maximum percentages for each supplierREQ: real ! Total quantity required

buy: array(SUPPL) of mpvar ! Quantity to purchase from supplier sw: array(SUPPL,BREAK0) of mpvar ! Weights at breakpoint k for supplier s

end-declarations

initializations from ’s4purch.dat’COST BR MAXPERC REQ

end-initializations

! Calculate total cost at breakpointsforall(s in SUPPL) doCBR(s,0):= 0forall(b in BREAK1) CBR(s,b):= CBR(s,b-1) + COST(s,b)*(BR(s,b)-BR(s,b-1))

end-do

! Objective: sum of costs*weightsMinCost:= sum(s in SUPPL, b in BREAK0) CBR(s,b) * w(s,b)

! Define buy and also order the weight variables by breakpoint quantitiesforall(s in SUPPL) sum(b in BREAK0) BR(s,b) * w(s,b) = buy(s)

! The convexity row (w sum to 1)forall(s in SUPPL) sum(b in BREAK0) w(s,b) = 1

! The minimum quantity that must be boughtsum(s in SUPPL) buy(s) >= REQ

! No more than the maximum percentage from each supplierforall(s in SUPPL) buy(s) <= MAXPERC(s)*REQ/100.0

! Define the w as SOS-2forall(s in SUPPL)makesos2(union(b in BREAK0) {w(s,b)}, sum(b in BREAK0) BR(s,b)*w(s,b))

minimize(MinCost) ! Solve the MIP-problem

end-model

In the model above we use the procedure makesos2 for the definition of the SOS-2. Alternatively, if wewish to use is_sos2, then the weight coefficients BR(s,b) all need to be augmented by some non-zeroconstant EPS since Mosel does not accept 0-valued weights with is_sos2.

forall(s in SUPPL) sum(b in BREAK0) (BR(s,b)+EPS) * w(s,b) is_sos2

2.4.3 Results

The minimum cost of BC 5,435 is obtained by buying 240 items from supplier 1, 210 from supplier 2, and150 items from supplier 3.

Additional examples 12 Applications of optimization with Xpress-MP

Page 17: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.5 Development of a model

The company Coco has two plants that can produce two types of cocoa powder. The first factory has a to-tal capacity of 400 tons per month and the second of 500 tons per month. The marketing department hasprovided estimations for the maximum amount of every product that may be sold and the contributionto profit of every product at the two factories. Which quantities of cocoa powder should be produced atthe two plants to maximize the total profit?

Table 2.8: Maximum sales quantities

Product Quantity

1 650

2 600

Table 2.9: Profit generated by products

FactoryProduct 1 2

1 50 47

2 125 132

2.5.1 A first model

As a first attempt, we may write down the following naive model formulation, where make11 denotesthe quantity of product 1 made at factory 1, make21 the quantity of product 2made at factory 1, and soon:

maximize 50 ·make11 + 127 ·make21 + 47 ·make12 + 134 ·make22 (2.5.1)

make11 + make21 ≤ 400 (2.5.2)

make12 + make22 ≤ 500 (2.5.3)

make11 + make12 ≤ 650 (2.5.4)

make21 + make22 ≤ 600 (2.5.5)

make11 ≥ 0, make12 ≥ 0, make21 ≥ 0, make22 ≥ 0 (2.5.6)

The objective function (2.5.1) is to maximize the total profit. Constraints (2.5.2) and (2.5.3) are the capac-ity limits at factory 1 and 2 respectively, and constraints (2.5.4) and (2.5.5) the limits on the amount ofproducts 1 and 2 that may be sold. Constraints (2.5.6) express that we cannot produce negative quantities.

With Mosel, the implementation of this model is straightforward (the non-negativity constraints areimplicitly added by Mosel):

model "S-5 Coco1"uses "mmxprs"

declarationsmake11: mpvar ! Amount of product 1 to make at factory 1make21: mpvar ! Amount of product 2 to make at factory 1make12: mpvar ! Amount of product 1 to make at factory 2make22: mpvar ! Amount of product 2 to make at factory 2

end-declarations! Objective: maximize total profit

MaxProfit:= 50*make11 + 127*make21 + 47*make12 + 134*make22

make11 + make21 <= 400 ! Capacity limit at factory 1make12 + make22 <= 500 ! Capacity limit at factory 2make11 + make12 <= 650 ! Limit on the amount of prod. 1 to be soldmake21 + make22 <= 600 ! Limit on the amount of prod. 2 to be sold

maximize(MaxProfit) ! Solve the problem

! Solution printingwriteln("Solution:\n Objective: ", getobjval)

Additional examples 13 Applications of optimization with Xpress-MP

Page 18: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

writeln(" make11: ", getsol(make11), " make12: ", getsol(make12)," make21: ", getsol(make21), " make22: ", getsol(make22))

end-model

This formulation integrates all data immediately in the model. Any change to the data values, the numberof products or factories leads to modifications directly in the model. Maintaining such a model is relativelyerror-prone and time-consuming.

2.5.2 Improved model

To separate the data from the model, we now modify the previous model by:

• making use of indexation

• definition of data tables

• reading data tables from a file

The profit contribution of every product is calculated from its sales revenues, minus the cost of rawmaterials used in its production and the production cost:

Profit = Revenue− Rawmaterialcost − Productioncost

Table 2.10 contains the raw material requirements per unit of finished products and the prices of the rawmaterial that are necessary to calculate the raw material cost.

Table 2.10: Raw material use and buying prices

Raw materialProduct 1 2 3

Use 1 0.8 0.2 0.5

2 1.0 0.3 0.4

Price 110 60 200

The unit production costs of the products at the different factories are given in Table 2.11.

Table 2.11: Production costs

FactoryProduct 1 2

1 150 153

2 75 68

Let PRODS be the set of finished products, FACT the set of factories, and RAW the set of raw materials.The profit PROFITpf per product and factory is calculated from the sales revenues REVp, the raw materialrequirement REQpr, the raw material price CBUYr and the production cost CMAKEpf . Let further MXSELLp

be the maximum sales quantity of product p and MXMAKEf the capacity limit of factory f .

With makepf representing the quantity of product p made at factory f , we obtain the following short-term planning model :

maximize∑

p∈PRODS

∑f∈FACT

PROFITpf ·makepf (2.5.7)

∀p ∈ PRODS :∑

f∈FACT

sellpf ≤ MXSELLp (2.5.8)

∀f ∈ FACT :∑

p∈PRODS

makepf ≤ MXMAKEf (2.5.9)

∀p ∈ PRODS,∀f ∈ FACT : makepf ≥ 0 (2.5.10)

This model can be implemented with Mosel as shown below:

Additional examples 14 Applications of optimization with Xpress-MP

Page 19: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

model "S-5 Coco2"uses "mmxprs"

parametersNPROD = 2NFACT = 2NRAW = 3

end-parameters

declarationsPRODS = 1..NPROD ! Range of products (p)FACT = 1..NFACT ! factories (f)RAW = 1..NRAW ! raw materials (r)REV: array(PRODS) of real ! Unit selling price of productsCMAKE: array(PRODS,FACT) of real ! Unit cost to make product p at factory fCBUY: array(RAW) of real ! Unit cost to buy raw material rREQ: array(PRODS,RAW) of real ! Requirement by unit of product p

! for raw material rMXSELL: array(PRODS) of real ! Maximum amount of p that can be soldMXMAKE: array(FACT) of real ! Maximum amount factory f can make

! over all productsPROFIT: array(PRODS,FACT) of real ! Profit contribution of product p

! at factory f

make: array(PRODS,FACT) of mpvar ! Amount of products made at factoriesend-declarations

initializations from ’s5coco.dat’REV CMAKE CBUY REQ MXSELL MXMAKE

end-initializations

! Calculate the profitforall(p in PRODS, f in FACT) PROFIT(p,f):=

REV(p) - sum(r in RAW) REQ(p,r)*CBUY(r) - CMAKE(p,f)

! Objective: maximize total profitMaxProfit:= sum(p in PRODS,f in FACT) PROFIT(p,f) * make(p,f)

! Limit on the amount of product p to be soldforall(p in PRODS) sum(f in FACT) sell(p,f) <= MXSELL(p)

! Capacity limit at factory fforall(f in FACT) sum(p in PRODS) make(p,f) <= MXMAKE(f)

! Solve the problemmaximize(MaxProfit)

! Solution printingwriteln("Solution:\n Objective: ", getobjval)forall(p in PRODS, f in FACT)write(" make(", p, ",", f, "): ", getsol(make(p,f)))

writelnend-model

2.5.3 Time-indexed model

Having solved this problem successfully, the company now wishes to extend the model to consider severaltimes periods at a time. This extension also involves the introduction of the possibility to store rawmaterials and finished product from one time period to the next. Raw material prices, sales revenues,and the maximum amount that may be sold depend on the time period (Tables 2.12 and 2.13).

Table 2.12: Estimated revenues and maximum sales quantities

Time periodsProduct 1 2 3 4

Revenue 1 400 380 405 350

2 410 397 412 397

Max. quantity 1 650 600 500 400

2 600 500 300 250

Additional examples 15 Applications of optimization with Xpress-MP

Page 20: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Table 2.13: Raw material prices

Time periodsRaw mat. 1 2 3 4

1 110 108 107 111

2 60 59 58 58

3 200 195 198 200

Storing product between time periods incurs storage costs (2 euros per period for finished products and 1euro per period for raw materials). Some product is held in stock at the beginning of the planning period(Table 2.14). The raw material storage capacity is limited to 300 units at both plants.

Table 2.14: Initial stock levels

Factory1 2

Product 1 50 100

2 50 50

Raw mat. 1 100 150

2 30 20

3 50 100

Let IPSTOCKpf be the quantity of product p initially held in stock at factory f and IRSTOCKrf the ini-tial stock level of raw material r. We denote by CPSTOCK and CRSTOCK respectively the unit costfor storing finished product and raw material, and MXRSTOCK the raw material storage capacity. LetTIMES = {1, . . . , NT} be the set of time periods under consideration. We need to add a time index tothe production variables makepft. Furthermore, to model the transition from one time period to the nextand to account for the different types of cost incurred, we need several other sets of variables: sellpft, theamount of product p sold at factory f in period t; buyrft the amount of raw material r bought at f in t;and finally pstockpft and rstockrft (both defined for t=1,...,NT+1) respectively the amount of product andraw material held in stock at factory f at the beginning of period t.

The objective function of maximizing the total profit now is to maximize the sales revenues, minus thecost of production, buying raw material, and storing finished products and raw material.

maximize∑

p∈PRODS

∑f∈FACT

∑t∈TIME

REVpt · sellpft

−∑

p∈PRODS

∑f∈FACT

∑t∈TIME

CMAKEpf ·makepft −∑

p∈RAW

∑f∈FACT

∑t∈TIME

CBUYrt · sellpft

−∑

p∈PRODS

∑f∈FACT

NT+1∑t=2

CPSTOCK · pstockpft −∑

r∈RAW

∑f∈FACT

NT+1∑t=2

CRSTOCK · rstockrft(2.5.11)

The introduction of multiple time periods and the possibility to store products between time periods givesrise to three sets of new constraints: the inventory balance constraints for finished products (2.5.12) andfor raw material (2.5.13), and the limit on the raw material storage capacity (2.5.14). The stock pstockp,f,t+1

of product p at the beginning of t + 1 is given by the stock at the beginning of t plus the production in treduced by the amount sold on t. The stock rstockr,f,t+1 of raw material r at the beginning of t + 1 is givenby the corresponding stock at the beginning of t plus the amount bought in t reduced by the quantityused in production during t.

∀p ∈ PRODS,∀f ∈ FACT,∀t ∈ TIME : pstockp,f,t+1 = pstockpft + makepft − sellpft (2.5.12)

∀r ∈ RAW,∀f ∈ FACT,∀t ∈ TIME : rstockr,f,t+1 = rstockrft + buyrft −∑

p∈PRODS

REQpr ·makepft(2.5.13)

∀f ∈ FACT,∀t ∈ {2, . . . , NT + 1} :∑

r∈RAW

rstockrft ≤ MXRSTOCK (2.5.14)

Below the complete mathematical model is given. The constraints imposing limits on the productioncapacity (2.5.18) and on the quantities to sell (2.5.19) now apply to every time period separately. In

Additional examples 16 Applications of optimization with Xpress-MP

Page 21: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

addition, now the variables sellpft are used in the sales limit constraints and not the production variablesany more. We also fix the initial stock levels of finished products (2.5.21) and raw material (2.5.22).

maximize∑

p∈PRODS

∑f∈FACT

∑t∈TIME

REVpt · sellpft

−∑

p∈PRODS

∑f∈FACT

∑t∈TIME

CMAKEpf ·makepft −∑

p∈RAW

∑f∈FACT

∑t∈TIME

CBUYrt · sellpft

−∑

p∈PRODS

∑f∈FACT

NT+1∑t=2

CPSTOCK · pstockpft −∑

r∈RAW

∑f∈FACT

NT+1∑t=2

CRSTOCK · rstockrft (2.5.15)

∀p ∈ PRODS,∀f ∈ FACT,∀t ∈ TIME : pstockp,f,t+1 = pstockpft + makepft − sellpft (2.5.16)

∀r ∈ RAW,∀f ∈ FACT,∀t ∈ TIME : rstockr,f,t+1 = rstockrft + buyrft −∑

p∈PRODS

REQpr ·makepft(2.5.17)

∀p ∈ PRODS,∀t ∈ TIME :∑

f∈FACT

makepft ≤ MXMAKEp (2.5.18)

∀f ∈ FACT,∀t ∈ TIME :∑

p∈PRODS

sellpft ≤ MXSELLf (2.5.19)

∀f ∈ FACT,∀t ∈ {2, . . . , NT + 1} :∑

r∈RAW

rstockrft ≤ MXRSTOCK (2.5.20)

∀p ∈ PRODS,∀f ∈ FACT : pstockpf1 = IPSTOCKpf (2.5.21)

∀r ∈ RAW,∀f ∈ FACT : rstockrf1 = IRSTOCKrf (2.5.22)

∀p ∈ PRODS,∀f ∈ FACT,∀t ∈ TIME : makepft ≥ 0, sellpft ≥ 0 (2.5.23)

∀r ∈ RAW,∀f ∈ FACT,∀t ∈ TIME : buyrft ≥ 0 (2.5.24)

∀p ∈ PRODS,∀f ∈ FACT,∀t ∈ {1, . . . , NT + 1} : pstockpft ≥ 0 (2.5.25)

∀r ∈ RAW,∀f ∈ FACT,∀t ∈ {1, . . . , NT + 1} : rstockrft ≥ 0 (2.5.26)

This mid-term planning model is implemented by the following Mosel model.

model "S-5 Coco3"uses "mmxprs"

parametersNPROD = 2NFACT = 2NRAW = 3NT = 4

end-parameters

declarationsPRODS = 1..NPROD ! Range of products (p)FACT = 1..NFACT ! factories (f)RAW = 1..NRAW ! raw materials (r)TIME = 1..NT ! time periods (t)

REV: array(PRODS,TIME) of real ! Unit selling price of productsCMAKE: array(PRODS,FACT) of real ! Unit cost to make product p

! at factory fCBUY: array(RAW,TIME) of real ! Unit cost to buy raw materialsREQ: array(PRODS,RAW) of real ! Requirement by unit of product p

! for raw material rMXSELL: array(PRODS,TIME) of real ! Max. amount of p that can be soldMXMAKE: array(FACT) of real ! Max. amount factory f can make

! over all productsIPSTOCK: array(PRODS,FACT) of real ! Initial product stock levelsIRSTOCK: array(RAW,FACT) of real ! Initial raw material stock levelsCPSTOCK = 2.0 ! Unit cost to store any product pCRSTOCK = 1.0 ! Unit cost to store any raw mat. rMXRSTOCK = 300 ! Raw material storage capacity

make: array(PRODS,FACT,TIME) of mpvar ! Amount of products made at factoriessell: array(PRODS,FACT,TIME) of mpvar ! Amount of product sold from factoriesbuy: array(RAW,FACT,TIME) of mpvar ! Amount of raw material boughtpstock: array(PRODS,FACT,1..NT+1) of mpvar ! Product stock levels at start

! of period t

Additional examples 17 Applications of optimization with Xpress-MP

Page 22: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

rstock: array(RAW,FACT,1..NT+1) of mpvar ! Raw material stock levels! at start of period t

end-declarations

initializations from ’s5coco.dat’CMAKE REQ MXMAKE REV as "REVT" CBUY as "CBUYT" MXSELL as "MXSELLT"IPSTOCK IRSTOCK

end-initializations

! Objective: maximize total profitMaxProfit:=sum(p in PRODS,f in FACT,t in TIME) REV(p,t) * sell(p,f,t) - ! revenuesum(p in PRODS,f in FACT,t in TIME) CMAKE(p,f) * make(p,f,t) - ! prod. costsum(r in RAW,f in FACT,t in TIME) CBUY(r,t) * buy(r,f,t) - ! raw mat.sum(p in PRODS,f in FACT,t in 2..NT+1) CPSTOCK * pstock(p,f,t) - ! p storagesum(r in RAW,f in FACT,t in 2..NT+1) CRSTOCK * rstock(r,f,t) ! r storage

! Product stock balanceforall(p in PRODS,f in FACT,t in TIME)pstock(p,f,t+1) = pstock(p,f,t) + make(p,f,t) - sell(p,f,t)

! Raw material stock balanceforall(r in RAW,f in FACT,t in TIME)rstock(r,f,t+1) =rstock(r,f,t) + buy(r,f,t) - sum(p in PRODS) REQ(p,r)*make(p,f,t)

! Capacity limit at factoriesforall(f in FACT,t in TIME) sum(p in PRODS) make(p,f,t) <= MXMAKE(f)

! Limit on the amount of prod. p to be soldforall(p in PRODS,t in TIME) sum(f in FACT) sell(p,f,t) <= MXSELL(p,t)

! Raw material stock limitforall(f in FACT,t in 2..NT+1) sum(r in RAW) rstock(r,f,t) <= MXRSTOCK

! Initial product and raw material stock levelsforall(p in PRODS,f in FACT) pstock(p,f,1) = IPSTOCK(p,f)forall(r in RAW,f in FACT) rstock(r,f,1) = IRSTOCK(r,f)

! Solve the problemmaximize(MaxProfit)

end-model

The data file s5coco.dat used by s5coco2.mos, s5coco3.mos, and s5coco4.mos looks as follows.Instead of renaming the time-indexed tables in this file to avoid duplicate data labels, it is also possibleto read these data entries from a second data file.

CMAKE: [150 15375 68]

REQ: [0.8 0.2 0.51.0 0.3 0.4]

MXMAKE: [400 500]

REV: [400 410]REVT: [400 380 405 350

410 397 412 397]

CBUY: [110 60 200]CBUYT: [110 108 107 111

60 59 58 58200 195 198 200]

MXSELL: [650 600]MXSELLT:[650 600 500 400

600 500 300 250]

IPSTOCK: [50 10050 50]

IRSTOCK: [100 150

Additional examples 18 Applications of optimization with Xpress-MP

Page 23: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

30 2050 100]

COPEN: [50000 63000]

2.5.4 Complete model

The company Coco now wishes to complete the model of the previous section with strategic decisionsabout the opening or closing of its plants, leading to a long-term planning model).Two cases are to be studied:4: A plant may be closed for one (or several) time periods. This reduces the fix cost to BC 20,000 (fix costwhen open BC 50,000 for plant 1, BC 63,000 for plant 2).5: If a plant is closed down, it stays closed for all following time periods.

In both cases we have to model the decision whether a factory f is open during time period t or not.To this aim we add binary variables openft to our model. These variables need to be added to the plantcapacity constraints (2.5.27): production only takes place if a factory is open during a given time period.

∀f ∈ FACT,∀t ∈ TIME :∑

p∈PRODS

makepft ≤ MXMAKEf · openft (2.5.27)

For case 4, to model the reduction of the fix cost of keeping a plant open, COPENf , we add the followingterm to the objective function:

NFACT · NT · 20000−∑

f∈FACT

∑t∈TIME

(COPENf − 20000) · openft (2.5.28)

The fix cost of BC 20,000 is incurred in any case, that is during all NT time periods in the NFACT factories.If a factory is open in t (openft = 1) then this cost increases to COPENf .

In case 5, we only incur the fix cost COPENf if the plant f is open during period t, hence the followingterm that needs to be deduced from the total profit:∑

f∈FACT

∑t∈TIME

COPENf · openft (2.5.29)

To model case 5, we also need additional constraints (2.5.30) that express the condition ‘once closed,always closed’.

∀f ∈ FACT,∀t ∈ {1, . . . , NT − 1} : openf,t+1 ≤ openft (2.5.30)

Both cases, 4 and 5, can be implemented in a single Mosel model, with the parameter PHASE allowing theuser to switch between the two different options. The implementation builds on the model presented inthe previous section.

model "S-5 Coco4"uses "mmxprs"

parametersPHASE = 5

(! PHASE = 4: Factories open/closed freely; when closed reduced fix costsPHASE = 5: Once closed always closed; larger saving

!)

NPROD = 2NFACT = 2NRAW = 3NT = 4

end-parameters

declarationsPRODS = 1..NPROD ! Range of products (p)FACT = 1..NFACT ! factories (f)RAW = 1..NRAW ! raw materials (r)TIME = 1..NT ! time periods (t)

REV: array(PRODS,TIME) of real ! Unit selling price of productsCMAKE: array(PRODS,FACT) of real ! Unit cost to make product p

! at factory f

Additional examples 19 Applications of optimization with Xpress-MP

Page 24: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

CBUY: array(RAW,TIME) of real ! Unit cost to buy raw materialsCOPEN: array(FACT) of real ! Fixed cost of factory being

! open for one periodREQ: array(PRODS,RAW) of real ! Requirement by unit of product p

! for raw material rMXSELL: array(PRODS,TIME) of real ! Max. amount of p that can be soldMXMAKE: array(FACT) of real ! Max. amount factory f can make

! over all productsIPSTOCK: array(PRODS,FACT) of real ! Initial product stock levelsIRSTOCK: array(RAW,FACT) of real ! Initial raw material stock levelsCPSTOCK = 2.0 ! Unit cost to store any productCRSTOCK = 1.0 ! Unit cost to store any raw mat.MXRSTOCK = 300 ! Raw material storage capacity

make: array(PRODS,FACT,TIME) of mpvar ! Amount of products made at factoriessell: array(PRODS,FACT,TIME) of mpvar ! Amount of product sold from factoriesbuy: array(RAW,FACT,TIME) of mpvar ! Amount of raw material boughtpstock: array(PRODS,FACT,1..NT+1) of mpvar ! Product stock levels at start

! of period trstock: array(RAW,FACT,1..NT+1) of mpvar ! Raw material stock levels

! at start of period topen: array(FACT,TIME) of mpvar ! 1 if factory f is open in t, else 0

end-declarations

initializations from ’s5coco.dat’CMAKE REQ MXMAKE REV as "REVT" CBUY as "CBUYT" MXSELL as "MXSELLT"IPSTOCK IRSTOCK COPEN

end-initializations

! Objective: maximize total profitMaxProfit:=sum(p in PRODS,f in FACT,t in TIME) REV(p,t) * sell(p,f,t) - ! revenuesum(p in PRODS,f in FACT,t in TIME) CMAKE(p,f) * make(p,f,t) - ! prod. costsum(r in RAW,f in FACT,t in TIME) CBUY(r,t) * buy(r,f,t) - ! raw mat.sum(p in PRODS,f in FACT,t in 2..NT+1) CPSTOCK * pstock(p,f,t) - ! p storagesum(r in RAW,f in FACT,t in 2..NT+1) CRSTOCK * rstock(r,f,t) ! r storage

! Factory fixed costif PHASE=4 thenMaxProfit += NF*NT*20000 -

sum(f in FACT,t in TIME) (COPEN(f)-20000)*open(f,t)elif PHASE=5 thenMaxProfit -= sum(f in FACT,t in TIME) COPEN(f)* open(f,t)

end-if

! Product stock balanceforall(p in PRODS,f in FACT,t in TIME)pstock(p,f,t+1) = pstock(p,f,t) + make(p,f,t) - sell(p,f,t)

! Raw material stock balanceforall(r in RAW,f in FACT,t in TIME)rstock(r,f,t+1) =rstock(r,f,t) + buy(r,f,t) - sum(p in PRODS) REQ(p,r)*make(p,f,t)

! Capacity limit at factory fforall(f in FACT,t in TIME) sum(p in PRODS) make(p,f,t) <= MXMAKE(f)*open(f,t)

! Limit on the amount of prod. p to be soldforall(p in PRODS,t in TIME) sum(f in FACT) sell(p,f,t) <= MXSELL(p,t)

! Raw material stock limitforall(f in FACT,t in 2..NT+1) sum(r in RAW) rstock(r,f,t) <= MXRSTOCK

if PHASE=5 then ! Once closed, always closedforall(f in FACT,t in 1..NT-1) open(f,t+1) <= open(f,t)

end-if

! Initial product and raw material stock levelsforall(p in PRODS,f in FACT) pstock(p,f,1) = IPSTOCK(p,f)forall(r in RAW,f in FACT) rstock(r,f,1) = IRSTOCK(r,f)

forall(f in FACT,t in TIME) open(f,t) is_binary

! Solve the problem

Additional examples 20 Applications of optimization with Xpress-MP

Page 25: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

maximize(MaxProfit)

end-model

2.5.5 Results

Short-term model: The total profit is BC 94,700, with the production plan shown in Table 2.15.

Table 2.15: Short-term plan

Factory1 2

Product 1 300 –

2 100 500

Mid-term model: The total profit is BC 428,809, with the production and sales plan shown in Table 2.16.

Table 2.16: Mid-term plan

Time periodsFactory Product 1 2 3 4

1 1 Prod. 400 400 400 250

Sale 450 400 400 250

2 Prod. – – – –

Sale 50 – – –

2 1 Prod. – – 100 –

Sale 100 – 100 –

2 Prod. 500 500 335.7 214.3

Sale 550 500 300 250

Long-term model:Case 4: The total profit is BC 390,000. Factory 1 is closed in period 4 and factory 2 closes in periods 2-4. Thecorresponding production and sales plan is shown in Table 2.17.

Table 2.17: Long-term plan for case 4

Time periodsFactory Product 1 2 3 4

1 1 Prod. – 150 – –

Sale – – 200 –

2 Prod. 400 250 400 –

Sale 200 500 150 250

2 1 Prod. – – – –

Sale – – 100 –

2 Prod. 500 – – –

Sale 400 – 150 –

Case 5: The total profit is BC 164,350. Both factories are closed starting from time period 2. The corre-sponding production and sales plan is shown in Table 2.18.

2.6 Programming with Mosel

This section presents two examples of how Mosel may be used for programming tasks. The topics dis-cussed involve different types of loops, the working with sets, and the definition of subroutines.

2.6.1 Sets

Sets in Mosel are a powerful facility for programming as in the following example that calculates allprime numbers between 2 and some given limit.

Additional examples 21 Applications of optimization with Xpress-MP

Page 26: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Table 2.18: Long-term plan for case 4

Time periodsFactory Product 1 2 3 4

1 1 Prod. – – – –

Sale – – 50 –

2 Prod. 400 – – –

Sale 450 – – –

2 1 Prod. – – – –

Sale – – 100 –

2 Prod. 500 – – –

Sale 150 100 300 –

Starting with the smallest one, the algorithm takes every element of a set of numbers SNumbers (positivenumbers between 2 and some upper limit that may be specified when running the model), adds it to theset of prime numbers SPrime and removes the number and all its multiples from the set SNumbers:

Repeat

• Find the smallest n in SNumbers

• A prime number is found, add n to the set SPrime

• Remove n and all its multiples from SNumbers

until SNumbers is empty

With Mosel, we may implement this algorithm as shown below:

model "S-6 Prime"

parametersLIMIT=100 ! Search for prime numbers in 2..LIMIT

end-parameters

declarationsSNumbers: set of integer ! Set of numbers to be checkedSPrime: set of integer ! Set of prime numbers

end-declarations

SNumbers:={2..LIMIT}

writeln("Prime numbers between 2 and ", LIMIT, ":")

n:=2repeat

while (not(n in SNumbers)) n+=1SPrime += {n} ! n is a prime numberi:=nwhile (i<=LIMIT) do ! Remove n and all its multiples

SNumbers-= {i}i+=n

end-dountil SNumbers={}

writeln(SPrime)writeln(" (", getsize(SPrime), " prime numbers.)")

end-model

This example uses the function getsize, that if applied to a set returns the number of elements of theset. The condition in the while loop is the logical negation of an expression, marked with not: the loopis repeated as long as the condition n in SNumbers is not satisfied.

The example also introduces the operator += to add sets to a set (there is also an operator -= to removesubsets from a set). Another set operator used in the example is in denoting that a single object iscontained in a set. We have already encountered this operator in the enumeration of indices for theforall loop. Mosel also defines the standard operators for comparing sets: subset (<=), superset (>=),difference (<>), end equality (=).

Additional examples 22 Applications of optimization with Xpress-MP

Page 27: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

The example ‘Prime’ also employs different types of loops. Whilst the forall loop (used in MathematicalProgramming models) repeats a statement or block of statements for all values of an index or counter, awhile loop is typically employed if the number of times that the loop needs to be executed is not knowbeforehand but depends on the evaluation of some condition: a set of statements is repeated while acondition holds. As with forall, the while statement exists in two versions, an inline version (while)and a version (while-do) that is to be used with a block of program statements. The repeat-untilstructure is similar to the while statement with the difference that the actions in the loop are executedonce before the termination condition is tested for the first time. Note that there is no limit to thenumber of nested levels of loops and/or selections in Mosel.

2.6.2 Subroutines

Subroutines in Mosel may be employed in the form of procedures or functions. Procedures are called as aprogram statement, they have no return value, functions must be called in an expression that uses theirreturn value. User defined subroutines in Mosel have to be marked with procedure /end-procedureand function /end-function respectively. The return value of a function has to be assigned to returned.

The structure of subroutines being very similar to the one of model, they may also include declarationssections for declaring local parameters that are only valid in the corresponding subroutine.

The following example implements a quick sort algorithm for sorting a randomly generated array ofnumbers (a number may appear repeatedly) into ascending order. The procedure qsort that starts thesorting algorithm is defined at the very end of the program, it therefore needs to be declared at thebeginning, before it is called. Procedure qsort_start calls the main sorting routine, qsort. Since thedefinition of this procedure precedes the place where it is called there is no need to declare it (but it stillcould be done). Procedure qsort calls yet again another subroutine, swap.

The idea of the quick sort algorithm is to partition the array that is to be sorted into two parts. The ‘left’part containing all values smaller than the partitioning value and the ‘right’ part all the values that arelarger than this value. The partitioning is then applied to the two subarrays, and so on, until all valuesare sorted.

model "S-7 Quick sort 1"

parametersLIM=50

end-parameters

forward procedure qsort_start(L:array(range) of integer)

declarationsT:array(1..LIM) of integer

end-declarations

forall(i in 1..LIM) T(i):=round(.5+random*LIM)writeln(T)qsort_start(T)writeln(T)

! Swap the positions of two numbers in an arrayprocedure swap(L:array(range) of integer,i,j:integer)k:=L(i)L(i):=L(j)L(j):=k

end-procedure

! Main sorting routineprocedure qsort(L:array(range) of integer,s,e:integer)v:=L((s+e) div 2) ! Determine the partitioning valuei:=s; j:=erepeat ! Partition into two subarrayswhile(L(i)<v) i+=1while(L(j)>v) j-=1if i<j thenswap(L,i,j)i+=1; j-=1end-if

until i>=j! Recursively sort the two subarrays

if j<e and s<j then qsort(L,s,j); end-if

Additional examples 23 Applications of optimization with Xpress-MP

Page 28: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

if i>s and i<e then qsort(L,i,e); end-ifend-procedure

! Start of the sorting processprocedure qsort_start(L:array(r:range) of integer)qsort(L,getfirst(r),getlast(r))

end-procedure

end-model

This example demonstrates typical uses of subroutines, namely regrouping actions that are executedrepeatedly (qsort) and isolating subtasks (swap) in order to structure a program and increase its read-ability.

The calls to the procedures in this example are nested (procedure swap is called from qsort which iscalled from qsort_start): in Mosel there is no limit as to the number of nested calls to subroutines (itis not possible, though, to define subroutines within a subroutine).

In Mosel, it is possible to re-use the names of subroutines, provided that every version has a differentnumber and/or types of parameters. This functionality is commonly referred to as overloading.

Using the possibility to overload subroutines, we may rewrite the preceding example ‘Quick sort’ asfollows.

model "S-7 Quick sort 2"

parametersLIM=50

end-parameters

forward procedure qsort(L:array(range) of integer)

declarationsT:array(1..LIM) of integer

end-declarations

forall(i in 1..LIM) T(i):=round(.5+random*LIM)writeln(T)qsort(T)writeln(T)

procedure swap(L:array(range) of integer,i,j:integer)(...) (same procedure body as in the preceding example)

end-procedure

procedure qsort(L:array(range) of integer,s,e:integer)(...) (same procedure body as in the preceding example)

end-procedure

! Start of the sorting processprocedure qsort(L:array(r:range) of integer)qsort(L,getfirst(r),getlast(r))

end-procedure

end-model

The procedure qsort_start is now also called qsort. The procedure bearing this name in the firstimplementation keeps its name too; it has got two additional parameters which suffice to ensure thatthe right version of the procedure is called. To the contrary, it is not possible to give procedure swapthe same name qsort because it takes exactly the same parameters as the original procedure qsort andhence it would not be possible to differentiate between these two procedures any more.

2.7 Branch-and-Cut

In this section we introduce the economic lot sizing problem (ELS) and show how to implement a config-urable cutting plane algorithm for this problem with Mosel.

ELS considers production planning over a given planning horizon, in our example 20 time periods. Inevery period, there is a given demand for every product (see Table 2.19) that must be satisfied by theproduction in this period and by inventory carried over from previous periods.

Additional examples 24 Applications of optimization with Xpress-MP

Page 29: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Table 2.19: Demand data (in tons)

Time periodsProduct 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

1 2 3 5 3 4 2 5 4 1 3 4 2 3 5 2 3 1 2 3 5

2 3 1 2 3 5 3 1 2 3 3 4 5 1 4 1 3 1 2 3 3

3 3 5 2 1 2 1 3 3 5 2 2 1 3 2 3 4 2 5 4 1

4 2 2 1 3 2 1 2 2 3 3 2 2 3 1 2 3 2 1 2 1

A set-up cost is associated with production in a period, and the total production capacity per period islimited (Table 2.20).

Table 2.20: Set-up costs and production capacities

Time periods1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Set-up cost (kBC) 17 14 11 6 9 6 15 10 8 7 12 9 10 8 12 6 10 12 7 9

Capacity (tons) 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12

The unit production cost per product and time period is given in Table 2.21. There is no inventory orstock-holding cost.

Table 2.21: Unit production costs (in 1000 BC)

Time periodsProduct 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

1 5 3 2 1 3 1 4 3 2 2 3 1 2 3 2 3 3 2 2 1

2 1 4 2 3 1 3 1 2 3 3 3 4 4 2 2 4 2 3 1 3

3 3 3 3 4 4 3 3 3 2 2 1 1 3 3 3 2 2 3 3 3

4 2 2 2 3 3 3 4 4 4 3 3 2 2 2 3 3 3 4 4 3

2.7.1 Model formulation

Let TIMES = 1, . . . , NT be the set of planning periods and PRODUCTS the set of products. In period t(t ∈ TIMES), the demand for every product p in the set PRODUCTS is given by DEMANDpt. We alsodefine SETUPCOSTt, the set-up up cost associated with production in period t, and PRODCOSTpt, the unitproduction cost of product p in period t. CAPt denotes the limit on the total production capacity in periodt.

We introduce the decision variables producept for the amount of product p made in period t and thebinary variables setuppt indicating whether a setup takes place for product p in period t (setuppt = 1) ornot (setuppt = 0).

We may then formulate the following mathematical model for this problem:

minimize∑

t∈TIMES

(SETUPCOSTt ·

∑p∈PRODUCTS

setuppt +∑

p∈PRODUCTS

PRODCOSTpt · producept

)(2.7.1)

∀p ∈ PRODUCTS, t ∈ TIMES :t∑

s=1

produceps ≥t∑

s=1

DEMANDps (2.7.2)

∀p ∈ PRODUCTS, t ∈ TIMES : producept ≤ Dp,t,NT · setuppt (2.7.3)

∀t ∈ TIMES :∑

p∈PRODUCTS

producept ≤ CAPt (2.7.4)

∀p ∈ PRODUCTS, t ∈ TIMES : setuppt ∈ {0, 1}, producept ≥ 0 (2.7.5)

The objective function in line (2.7.1) is to minimize the total cost. Constraints (2.7.2) formulate the re-quirement that the production of p in periods 0 to t must satisfy the total demand for this product duringthis period of time. The constraints (2.7.3) establish the implication ‘if there is production during t thenthere is a setup in t’ where Dptl stands for the demand of product p in periods t to l. The productioncapacity per period t is limited (constraints (2.7.4)). And finally, the setuppt variables are binaries.

Additional examples 25 Applications of optimization with Xpress-MP

Page 30: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.7.2 Implementation

The transformation into a Mosel model is straightforward:

model "S-8 ELS"uses "mmxprs"

declarationsTIMES = 1..20 ! Range of timePRODUCTS = 1..4 ! Set of products

DEMAND: array(PRODUCTS,TIMES) of integer ! Demand per periodSETUPCOST: array(TIMES) of integer ! Setup cost per periodPRODCOST: array(PRODUCTS,TIMES) of real ! Production cost per periodCAP: array(TIMES) of integer ! Production capacity per periodD: array(PRODUCTS,TIMES,TIMES) of integer ! Total demand in periods t1 - t2

produce: array(PRODUCTS,TIMES) of mpvar ! Production in period tsetup: array(PRODUCTS,TIMES) of mpvar ! Setup in period t

end-declarations

initializations from "s8els.dat"DEMAND SETUPCOST PRODCOST CAP

end-initializations

forall(p in PRODUCTS,s,t in TIMES) D(p,s,t):= sum(k in s..t) DEMAND(p,k)

! Objective: minimize total costMinCost:= sum(t in TIMES) (SETUPCOST(t) * sum(p in PRODUCTS) setup(p,t) +

sum(p in PRODUCTS) PRODCOST(p,t) * produce(p,t) )

! Satisfy the total demandforall(p in PRODUCTS,t in TIMES)

sum(s in 1..t) produce(p,s) >= sum (s in 1..t) DEMAND(p,s)

! If there is production during t then there is a setup in tforall(p in PRODUCTS, t in TIMES)produce(p,t) <= D(p,t,getlast(TIMES)) * setup(p,t)

! Capacity limitsforall(t in TIMES) sum(p in PRODUCTS) produce(p,t) <= CAP(t)

! Variables setup are 0/1forall(p in PRODUCTS, t in TIMES) setup(p,t) is_binary

2.7.3 Cutting plane algorithm

A well-known class of valid inequalities for ELS are the so-called (l, S)-inequalities [?]. Let Dptl denotethe total demand of p in periods t to l and setuppt be a binary variable indicating whether there is anyproduction of p in period t. For each period l and each subset of periods S of 1 to l, the (l, S)-inequality is

l∑t=1t∈S

producept +l∑

t=1t 6∈S

Dptl · setuppt ≥ Dp1l

It says that actual production producept in the periods included in S plus the maximum potential produc-tion Dptl · setuppt in the remaining periods (those not in S) must at least equal the total demand in periods1 to l. Note that in period t at most Dptl production is required to meet demand up to period l.

Based on the observation thatl∑

t=1t∈S

producept +l∑

t=1t 6∈S

Dptl · setuppt ≥l∑

t=1

min(producept, Dptl · setuppt) ≥ Dp1l

it is possible to develop a separation algorithm and thus the following cutting plane algorithm based onthese (l, S)-inequalities:

1. Solve the LP.

Additional examples 26 Applications of optimization with Xpress-MP

Page 31: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2. Identify violated (l, S)-inequalities by testing violations of

l∑t=1

min(producept, Dptl · setuppt) ≥ Dp1l

3. Add violated inequalities as cuts to the problem.

4. Re-solve the LP problem.

There are numerous options for how to configure this algorithm. For instance:

• Generation of cuts only in the root node or also during the search (Cut-and-Branch versus Branch-and-Cut),

• Number of cut generation passes at a node (e.g. one pass or looping around steps 2.-4. until nomore cuts are generated),

• Search tree depth for cut generation (up to a given depth or at all nodes)

• Exclusive use of (l, S)-cuts or combination with others (e.g. default cuts generated by the solver)

The implementation of the (l, S)-cut generation algorithm shown below may be configured to generatecuts at the top node only (TOPONLY = true) or up to a given tree depth (parameter CUTDEPTH), and togenerate one or several rounds of cuts (SEVERALROUNDS = true).

function cb_node:booleandeclarationsncut:integer ! Counter for cutscut: array(range) of linctr ! Cutscutid: array(range) of integer ! Cut type identificationtype: array(range) of integer ! Cut constraint typeobjval,ds: real

end-declarations

depth:=getparam("XPRS_NODEDEPTH")

if((TOPONLY and depth<1) or (not TOPONLY and depth<=CUTDEPTH)) thenncut:=0

! Get the solution valuessetparam("XPRS_SOLUTIONFILE",0)forall(t in TIMES, p in PRODUCTS) do

solprod(p,t):=getsol(produce(p,t))solsetup(p,t):=getsol(setup(p,t))

end-dosetparam("XPRS_SOLUTIONFILE",1)

! Search for violated constraintsforall(p in PRODUCTS,l in TIMES) dods:=0forall(t in 1..l)

if(solprod(p,t) < D(p,t,l)*solsetup(p,t) + EPS) then ds += solprod(p,t)else ds += D(p,t,l)*solsetup(p,t)end-if

! Generate the violated inequalityif(ds < D(p,1,l) - EPS) then

cut(ncut):= sum(t in 1..l)if(solprod(p,t)<(D(p,t,l)*solsetup(p,t))+EPS, produce(p,t),

D(p,t,l)*setup(p,t)) - D(p,1,l)cutid(ncut):= 1type(ncut):= CT_GEQncut+=1

end-ifend-do

returned:=false ! Call this function once per node

! Add cuts to the problemif(ncut>0) thenaddcuts(cutid, type, cut);

Additional examples 27 Applications of optimization with Xpress-MP

Page 32: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

writeln("Cuts added : ", ncut, " (depth ", depth, ", node ",getparam("XPRS_NODES"), ", obj. ", getparam("XPRS_LPOBJVAL"), ")")

if SEVERALROUNDS thenreturned:=true ! Repeat until no new cuts generated

end-ifend-ifend-if

end-function

We need to add the following declarations to the start of our model:

uses "mmsystem"

parametersALG = 0 ! Default algorithm: no user cutsCUTDEPTH = 10 ! Maximum tree depth for cut generationEPS = 1e-6 ! Zero tolerance

end-parameters

forward function cb_node:booleanforward procedure tree_cut_gen

declarationssolprod: array(PRODUCTS,TIMES) of real ! Sol. values for var.s producesolsetup: array(PRODUCTS,TIMES) of real ! Sol. values for var.s setupstarttime: real

end-declarations

The cutting plane algorithm is set up after the definition of the problem, followed by the start of theoptimization algorithm:

starttime:=gettimeSEVERALROUNDS:=false; TOPONLY:=false

case ALG of1: setparam("XPRS_CUTSTRATEGY", 0) ! No cuts2: setparam("XPRS_PRESOLVE", 0) ! No presolve3: tree_cut_gen ! User Branch-and-Cut + automatic cuts4: do ! User Branch-and-Cut (several rounds),

tree_cut_gen ! no automatic cutssetparam("XPRS_CUTSTRATEGY", 0)SEVERALROUNDS:=true

end-do5: do ! User Cut-and-Branch (several rounds)

tree_cut_gen ! + automatic cutsSEVERALROUNDS:=trueTOPONLY:=true

end-do6: do ! User Branch-and-Cut (several rounds)

tree_cut_gen ! + automatic cutsSEVERALROUNDS:=true

end-doend-case

minimize(MinCost) ! Solve the problem

writeln("Time: ", gettime-starttime, "sec, Nodes: ", getparam("XPRS_NODES"),", Solution: ", getobjval)

The following subroutine defines some Xpress-Optimizer settings for the cutting plane algorithm; mostimportantly it defines the cut-manager callback so that our function cb_node will be called from theoptimizer at every node:

procedure tree_cut_gensetparam("XPRS_PRESOLVE", 0) ! Switch presolve offsetparam("XPRS_EXTRAROWS", 5000) ! Reserve extra rows in matrixsetcallback(XPRS_CB_CM, "cb_node") ! Set the cut-manager callback function

end-procedure

Additional examples 28 Applications of optimization with Xpress-MP

Page 33: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.7.4 Results

For a rough evaluation of the different versions of the cutting plane algorithm, our algorithm has beenrun with the different settings of ALG. The results of the runs (times measured on PIII, 550MHz, 640Mb)are summarized in Table 2.22. Column ‘First’ lists the value of the first solution and column ‘Best’ the valueof the best solution found. The entries in the column ‘Opt./Best bound’ indicate the best lower boundon the optimal solution (all runs were stopped after 1800 seconds) or are marked ‘Opt.’ if optimality wasproven. In parentheses after the solution values every time the corresponding running times and numberof nodes are given. The (l, S)-cut generation in the tree was in all cases limited to a maximum depth of10.

Whereas the automatically generated cuts in Xpress help finding a good first solution, our cutting planealgorithm works better for closing the integrality gap (that is, proving optimality) once the best solutionhas been found. The best version seems to be a combination of both; it was even possible to proveoptimality when generating many (l, S)-cuts (several rounds) together with the default cuts.

Table 2.22: Results of different executions of the ELS model

ALG First Best Opt./Best bound

0 817 (2s/53) 788 (703s/187933) 774.75 (1800s/358969)

1 852 (0s/77) 800 (592s/244761) 723.13 (1800s/440753)

2 845 (0s/77) 803 (235s/121778) 727.95 (1800s/412300)

3 818 (1s/50) 788 (271s/27653) 783.06 (1800s/190171)

4 831 (1s/62) 788 (253s/19834) 779.95 (1800s/146871)

5 809 (0s/45) 790 (984s/118846) 784.07 (1800s/214400)

6 793 (1s/32) 788 (476s/45495) Opt. (1571s/168820)

The following production plan listing the production and initial stock levels per time period has theminimium cost of BC 788,000.

Table 2.23: Optimal production plan

Time periods1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

1 Production 2 3 7 5 – 12 – – – 9 – – 12 – 12 – – – – –

Stock – – – 2 4 – 10 5 1 – 6 2 – 9 4 14 11 10 8 5

2 Production 4 – 5 – 9 – – 12 – – – 6 – 11 – – – – 6 –

Stock – 1 – 3 – 4 1 – 10 7 4 – 1 – 7 6 3 2 – 3

3 Production 4 6 – 4 – – 6 – 7 – 12 – – – – 3 12 – – –

Stock – 1 2 – 3 1 – 3 – 2 – 10 9 6 4 1 – 10 5 1

4 Production 2 3 – 3 3 – 6 – 5 3 – 6 – – – 9 – – – –

Stock – – 1 – – 1 – 4 2 4 4 2 6 3 2 – 6 4 3 1

2.8 Column generation

The example in this section shows how to implement a column generation algorithm for a simple cutting-stock problem (a slightly more complicated version of the problem is described in Section 9.6 of the book).

A paper mill produces rolls of paper of a fixed width MAXWIDTH that are subsequently cut into smallerrolls according to the customer orders. The rolls can be cut into NWIDTHS different sizes. The orders aregiven as demands for each width i (DEMANDi). The objective of the paper mill is to satisfy the demandwith the smallest possible number of paper rolls in order to minimize the losses.

2.8.1 Model formulation

We express the objective of minimizing the total number of rolls as choosing the best set of cuttingpatterns for the current set of demands. To avoid having to calculate all possible cutting patterns byhand, we start off with a basic set of patterns (PATTERN1,..., PATTERNNWIDTH), that consists of cutting smallrolls all of the same width as many times as possible out of the large roll. Let variables usej denote thenumber of times a cutting pattern j (j ∈ WIDTHS = {1, . . . , NWIDTH}) is used. The objective then becomes

Additional examples 29 Applications of optimization with Xpress-MP

Page 34: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

to minimize the sum of these variables (2.8.1), subject to the constraints that the demand for every sizehas to be met (2.8.2). (Function ceil means rounding to the next larger integer value.)

minimize∑

j∈WIDTHS

usej (2.8.1)

∑j∈WIDTHS

PATTERNij · usej ≥ DEMANDi (2.8.2)

∀j ∈ WIDTHS : usej ≤ ceil(DEMANDj / PATTERNjj), usej ∈ IN (2.8.3)

2.8.2 Implementation

The transformation of the mathematical model into a Mosel program is fairly straightforward. However,the implementation uses some specific features:

Decision variables use: The index range is not known at the start of the program, the array of variableswill grow dynamically during the column generation.

Constraints: Here all the constraints are named for further reference (we need to add new terms duringthe column generation).

model "S-9 Papermill"uses "mmxprs"

parametersDATAFILE="cutdat.dat"NWIDTHS = 15

end-parameters

forward procedure column_genforward function knapsack(C:array(range) of real,

A:array(range) of real,B:real,xbest:array(range) of integer,pass: integer): real

forward procedure print_pat(dj:real, vx: array(range) of integer)

declarationsWIDTHS = 1..NWIDTHS ! Range of widthsRP: range ! Range of cutting patternsMAXWIDTH: integer ! Maximum roll widthEPS = 0.001 ! Zero tolerance

WIDTH: array(WIDTHS) of real ! Possible widthsDEMAND: array(WIDTHS) of integer ! Demand per widthPATTERN: array(WIDTHS, RP) of integer ! (Basic) cutting patterns

use: array(RP) of mpvar ! Rolls per patternsoluse: array(RP) of real ! Solution values for variables ‘use’Dem: array(WIDTHS) of linctr ! Demand constraintsMinRolls: linctr ! Objective function

KnapCtr, KnapObj: linctr ! Knapsack constraint+objectivex: array(WIDTHS) of mpvar ! Knapsack variables

end-declarations

initializations from DATAFILEWIDTH DEMAND MAXWIDTH

end-initializations! Make basic patterns

forall(j in WIDTHS) PATTERN(j,j) := floor(MAXWIDTH/WIDTH(j))

forall(j in WIDTHS) docreate(use(j)) ! Create NWIDTHS variables ‘use’use(j) is_integer ! Variables are integer and boundeduse(j) <= integer(ceil(DEMAND(j)/PATTERN(j,j)))

end-do

! Objective: minimize the number of rollsMinRolls:= sum(j in WIDTHS) use(j)

Additional examples 30 Applications of optimization with Xpress-MP

Page 35: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

! Satisfy all demandsforall(i in WIDTHS)Dem(i):= sum(j in WIDTHS) PATTERN(i,j) * use(j) >= DEMAND(i)

column_gen ! Column generation at top node

minimize(MinRolls) ! Compute the best integer solution! for the current problem (including! the new columns)

writeln("Best integer solution: ", getobjval, " rolls")write(" Rolls per pattern: ")forall(i in RP) write(getsol(use(i)),", ")writeln

The column generation algorithm requires the solution of a knapsack problem. We define the constraintsof the knapsack problem (KnapCtr and KnapObj) globally because Mosel does not delete them at theend of a function (due to its principle of incremental model formulation).

2.8.3 Column generation algorithm

The column generation algorithm is implemented as a loop over the following four steps that is repeatedas long as new cutting patterns are generated:

1. Solve the LP and save the basis.

2. Get the solution values.

3. Generate a new column (=cutting pattern) by solving a knapsack problem on the dual values.

4. Load the modified problem and load the saved basis.

Re-starting the solution of the LP problem with the basis of the previous optimal solution reduces thenumber of simplex iterations required to solve the problem and hence leads to shorter running times.Mosel completes the saved basis according to the additions made to the problem.

procedure column_gen

declarationsdualdem: array(WIDTHS) of realxbest: array(WIDTHS) of integerubnd, zbest, objval: realbas: basis

end-declarations

setparam("XPRS_CUTSTRATEGY", 0) ! Disable automatic cutssetparam("XPRS_PRESOLVE", 0) ! Switch presolve offnpatt:=NWIDTHSnpass:=1

while(true) dominimize(XPRS_LIN, MinRolls) ! Solve the LP

savebasis(bas) ! Save the current basisobjval:= getobjval ! Get the objective value

! Get the solution valuesforall(j in 1..npatt) soluse(j):=getsol(use(j))forall(i in WIDTHS) dualdem(i):=getdual(Dem(i))

! Solve a knapsack problemzbest:= knapsack(dualdem, WIDTH, MAXWIDTH, xbest, npass) - 1.0

write("Pass ", npass, ": ")if(zbest < EPS) then

writeln("no profitable column found.\n")break

elseprint_pat(zbest, xbest) ! Print the new patternnpatt+=1create(use(npatt)) ! Create a new var. for this patternuse(npatt) is_integer

MinRolls+= use(npatt) ! Add new var. to the objective

Additional examples 31 Applications of optimization with Xpress-MP

Page 36: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

ubnd:=0forall(i in WIDTHS)

if(xbest(i) > 0) thenDem(i)+= xbest(i)*use(npatt) ! Add new var. to demand constr.subnd:= maxlist(ubnd, ceil(DEMAND(i)/xbest(i) ))

end-ifuse(npatt) <= ubnd ! Set upper bound on the new var.

loadprob(MinRolls) ! Reload the problemloadbasis(bas) ! Load the saved basis

end-ifnpass+=1

end-do

writeln("Solution after column generation: ", objval, " rolls, ",getsize(RP), " patterns")

write(" Rolls per pattern: ")forall(i in RP) write(soluse(i),", ")writeln

end-procedure

The knapsack problem solved to generate a new column is an independent optimization problem that isdefined and solved in the same Mosel model as the main cutting stock problem. The knapsack problemhas the following form:

maximize∑

j∈WIDTHS

Cj · xj (2.8.4)

∑j∈WIDTHS

Aj · xj ≤ B (2.8.5)

∀j ∈ WIDTHS : xj ∈ IN (2.8.6)

where the coefficients Cj of the objective function (2.8.4) are given by the dual values of the demandconstraints, the constraint coefficients Aj are the width values WIDTHj, and the constant term B of theconstraint (2.8.5) is the maximum width MAXWIDTH.

function knapsack(C:array(range) of real,A:array(range) of real,B:real,xbest:array(range) of integer,pass: integer):real

! Hide the demand constraintsforall(j in WIDTHS) sethidden(Dem(j), true)

! Define the knapsack problemKnapCtr := sum(j in WIDTHS) A(j)*x(j) <= BKnapObj := sum(j in WIDTHS) C(j)*x(j)

! Integrality conditionif(pass=1) thenforall(j in WIDTHS) x(j) is_integer

end-if

maximize(KnapObj)returned:=getobjvalforall(j in WIDTHS) xbest(j):=round(getsol(x(j)))

! Reset knapsack constraint and objective, unhide demand constraintsKnapCtr := 0KnapObj := 0forall(j in WIDTHS) sethidden(Dem(j), false)

end-function

In this implementation, the knapsack constraints are reset to 0 at the end of this function so that they donot unnecessarily increase the size of the main problem. The same is true in the other sense: hiding the

Additional examples 32 Applications of optimization with Xpress-MP

Page 37: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

demand constraints while solving the knapsack problem makes life easier for the Optimizer, but is notessential for getting the correct solution.

To complete the model, the following procedure print_pat is used to display every new pattern foundby the column generation heuristic.

procedure print_pat(dj:real, vx: array(range) of integer)declarationsdw: real

end-declarations

writeln("New pattern found with marginal cost ", dj)write(" Widths distribution: ")dw:=0forall(i in WIDTHS) do

write(WIDTH(i), ":", vx(i), " ")dw += WIDTH(i)*vx(i)

end-dowriteln("Total width: ", dw)

end-procedure

end-model

2.8.4 Results

We have tried the column generation heuristic with several sets of bin packing benchmark problems(between 50 and 1000 items of up to 350 different widths), see [?]. For up to about 100 different widthsthe algorithm is very efficient, taking on the average only a few seconds on a standard PC. In mostcases the optimal solution is found, but sometimes the best solution found is 1-2 rolls (bins) worse thanthe optimum (mainly due to the tolerance and time limit on the knapsack problem, and probably alsoto rounding errors). For a few instances where the optimal solution was previously not known, ouralgorithm has found the optimal solution or improved the value of the best solution. For instances witha larger number of widths the results (obtained by limiting the solving time per knapsack problem to2 seconds and the time for solving the MIP of the main problem to 2 minutes without any limit on thenumber of patterns (= new columns) generated) are often 5-10 rolls (bins) worse than the best solution.They can be improved with longer running times, but specialized heuristics may be a better choice.

To speed up the implementation, a greedy-type heuristic (based on the LPT heuristic [?]) may be addedbefore the start of the column generation: at every iteration the heuristic places the largest unassigneditem into the bin (=roll) with the least load. The number of bins is initially set to the theoretical lowerbound (ceil(

∑i∈WIDTHS DEMANDi · WIDTHi / MAXWIDTH)). Whenever an item no longer fits into the

existing bins, a new bin is added. The patterns (=distribution of items to bins) generated by this heuristicare completed to non-dominated patterns and added as new columns to the problem. Some instancesare solved immediately by this heuristic, otherwise the new columns provide an improved starting pointfor the MIP-based column generation.

Additional examples 33 Applications of optimization with Xpress-MP

Page 38: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.9 Goal Programming

Goal Programming is an extension of Linear Programming in which targets are specified for a set ofconstraints. In Goal Programming there are two basic models: the pre-emptive (lexicographic) model andthe Archimedian model. In the pre-emptive model, goals are ordered according to priorities. The goalsat a certain priority level are considered to be infinitely more important than the goals at the next level.With the Archimedian model weights or penalties for not achieving targets must be specified, and weattempt to minimize the sum of the weighted infeasibilities.

If constraints are used to construct the goals, then the goals are to minimize the violation of the con-straints. The goals are met when the constraints are satisfied. Alternatively, goals may be given in theform of multiple objective functions. This type of problem is also known as multiple criteria optimizationproblem.

The example in this section demonstrates how Mosel can be used for implementing pre-emptive GoalProgramming with constraints. We try to meet as many goals as possible, taking them in priority order.

2.9.1 Example problem: Family holiday planning

At the beginning of the year a family is discussing the holiday plans for the year. Five destinations areunder consideration: skiing in the Alpes, a round trip through Andalusia, beach holidays in the Antilles, acity trip to London, and sightseeing in Brittany. The family needs to take a decision where to go and howmuch time to spend at a destination. The total holiday budget is limited to BC 6,500. The holidays shouldpreferably last between four and five weeks. Parents and children have expressed their preferences (seeTable 2.24) for the different destinations: they should be equally satisfied with a minimum preferencerating of 100 points. The family would like to have at least 21 sunny days. Furthermore, they have fixeda maximum duration for every destination.

Table 2.24: Destination-related data

Cost/day Rating Rating Sun Duration

(in BC) parents children probability (days)

Alpes 235 4 5 0.65 3–10

Andalusia 210 5 4 0.8 4–12

Antilles 250 2 4 0.85 7–14

London 300 4 3 0.2 3–5

Brittany 170 4 2 0.3 3–12

2.9.2 Model formulation

Let DEST be the set of holiday destinations the family is looking at. The data given per destinationd includes the daily cost COSTd, the preference rating by parents (PREFAd) and children (PREFCd), theexpected rate of sunny days SUNd, and the maximum duration of stay MAXDURd. Furthermore, we writeMINSAT for the minimum total preference rating and MINSUN for the desired minimum number of sunnydays. For every destination d in DEST we define a variable stayd that denotes the length of their stay atd in days.

We formulate the model with two types of constraints: “hard” constraints that need to be satisfied in allcases and goal constraints that express preferences and should be satisfied as far as possible.

The hard constraints in our example are the budget limit (2.9.1), the maximum duration of the stay atevery destination (2.9.2) and the integrality condition for variables stayd (2.9.3).∑

d∈DEST

COSTd · stayd ≤ BUDGET (2.9.1)

∀d ∈ DEST : stayd ≤ MAXDURd (2.9.2)

∀d ∈ DEST : stayd ∈ IN (2.9.3)

In addition, we have the following goal constraints: the total duration of the holidays should lie between28 and 35 days (constraints (2.9.4) and (2.9.5)). The preferences of children and parents should be equallytaken into account (2.9.6) and be above a certain threshold value (2.9.7). And finally, the expected

Additional examples 34 Applications of optimization with Xpress-MP

Page 39: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

number of sunny days should be sufficiently large (2.9.8).∑d∈DEST

stayd ≥ 28 (2.9.4)∑d∈DEST

stayd ≥ 35 (2.9.5)∑d∈DEST

PREFAd · stayd = PREFCd · stayd (2.9.6)∑d∈DEST

PREFCd · stayd ≥ MINSAT (2.9.7)∑d∈DEST

SUNd · stayd ≥ MINSUN (2.9.8)

(2.9.9)

In the following we assume that this order of the goal constraints corresponds to their priorities.

2.9.3 Implementation

To increase readability, the implementation of the Mosel model is organized into three blocks: the prob-lem is stated in the main part, procedure preemptive implements the solution strategy via preemptiveGoal Programming, and procedure print_sol produces a nice solution printout.

model "S-10 Holiday planning"uses "mmxprs"

forward procedure printsol(i:integer)forward procedure preemptive

declarationsNGOALS = 5 ! Number of goalsGOALS = 1..NGOALSDEST: set of string ! Holiday destionationsCOST: array(DEST) of real ! Daily costBUDGET: real ! Budget limitPREFA, PREFC: array(DEST) of integer ! Preferences of adults and childrenMINSAT: integer ! Minimum total ratingSUN: array(DEST) of real ! Probability of sunny daysMINSUN: real ! Min. number of sunny daysMINDUR, MAXDUR: array(DEST) of integer ! Minimum & maximum stay

stay: array(DEST) of mpvar ! Variablesdev: array(1..2*NGOALS) of mpvar ! Deviation from goalsMinDev: linctr ! Objective functionGoal: array(GOALS) of linctr ! Goal constraints

end-declarations

initializations from ’s10holid.dat’COST BUDGET [PREFA,PREFC] as "PREF" SUN MINSUN [MINDUR,MAXDUR] as "DUR" MINSAT

end-initializations

forall(d in DEST) create(stay(d)) ! Create the decision variables

! Define a (hard) constraint: budget limitsum(d in DEST) COST(d)*stay(d) <= BUDGET

! Define the goal constraints:Goal(1):= sum(d in DEST) stay(d) >= 28 ! Min. total holiday durationGoal(2):= sum(d in DEST) stay(d) <= 35 ! Max. total holiday durationGoal(3):= sum(d in DEST) PREFA(d)*stay(d) = sum(d in DEST) PREFC(d)*stay(d)

! Consider preferences equallyGoal(4):= sum(d in DEST) PREFC(d)*stay(d) >= MINSAT

! Min. total satisfactionGoal(5):= sum(d in DEST) SUN(d)*stay(d) >= MINSUN

! Min. number of sunny days

forall(d in DEST) dostay(d) <= MAXDUR(d)

Additional examples 35 Applications of optimization with Xpress-MP

Page 40: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

stay(d) is_integerend-do

preemptive ! Pre-emptive Goal Programming

At the end of the model definition, we call procedure preemptive to solve this problem by pre-emptiveGoal Programming. In this procedure, the goals are at first entirely removed from the problem (‘hidden’).We then add them successively to the problem and re-solve it until the problem becomes infeasible, thatis, the deviation variables forming the objective function are not all 0. Depending on the constraint type(obtained with gettype) of the goals, we need one (for inequalities) or two (for equalities) deviationvariables.

Let us have a closer look at the first goal (Goal1), a ≥ constraint: the left hand side (all terms with decisionvariables) must be at least 28 to satisfy the constraint. To ensure this, we add a dev2. The goal constraintbecomes ∑

d∈DEST

stayd + dev2 ≥ 28 (2.9.10)

and the objective function is to minimize dev2. If this is feasible (0-valued objective), then we remove thedeviation variable from the goal, thus turning it into a hard constraint. It is not required to remove thedeviation variables from the objective since minimization will always force this variable to take the value0.

We then continue with Goal2, a≤ constraint: in this case we need to add a variable for positive deviations,dev3. We add −dev3 to the constraint, turning it into∑

d∈DEST

stayd − dev3 ≤ 35 (2.9.11)

and the objective now is to minimize dev3.

We then continue with Goal3: since this is an equation, we need variables for positive and negativedeviations, dev5 and dev6. We add dev6 − dev5 to the constraint, turning it into∑

d∈DEST

PREFAd · stayd + dev6 − dev5 =∑

d∈DEST

PREFCd · stayd (2.9.12)

and the objective now is to minimize the absolute deviation dev6 + dev5. And so on.

procedure preemptive

! Remove (=hide) goal constraint from the problemforall(g in GOALS) sethidden(Goal(g), true)

i:=0while (i<NGOALS) do

i+=1sethidden(Goal(i), false) ! Add (=unhide) the next goal

case gettype(Goal(i)) of ! Add deviation variable(s)CT_GEQ: do

Deviation:= dev(2*i)MinDev += Deviation

end-doCT_LEQ: do

Deviation:= -dev(2*i-1)MinDev += dev(2*i-1)

end-doCT_EQ : do

Deviation:= dev(2*i) - dev(2*i-1)MinDev += dev(2*i) + dev(2*i-1)end-do

else writeln("Wrong constraint type")break

end-caseGoal(i)+= Deviation

minimize(MinDev) ! Solve the LP-problemwriteln(" Solution(", i,"): Total cost ",

getsol(sum(d in DEST) COST(d)*stay(d)))

Additional examples 36 Applications of optimization with Xpress-MP

Page 41: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

forall(d in DEST) write(" ", d, ": ", getsol(stay(d)))writeln

if(getobjval>0) thenwriteln("Cannot satisfy goal ",i)break

end-ifGoal(i)-= Deviation ! Remove deviation variable(s) from goal

end-do

print_sol(i) ! Solution printoutend-procedure

The procedure sethidden(c:linctr, b:boolean) is used to remove constraints (‘hide’) from theproblem solved by the Optimizer without deleting them in the problem definition. So effectively, theOptimizer solves a subproblem of the problem originally stated in Mosel.

To complete the model, below is the procedure print_sol for printing the results.

procedure print_sol(i:integer)declarationsSTypes={CT_GEQ, CT_LEQ, CT_EQ}ATypes: array(STypes) of string

end-declarations

ATypes:: ([CT_GEQ, CT_LEQ, CT_EQ])[">=", "<=", "="]

writeln(" Goal", strfmt("Target",11), strfmt("Value",7))forall(g in 1..i)writeln(strfmt(g,4), strfmt(ATypes(gettype(Goal(g))),4),

strfmt(-getcoeff(Goal(g)),6),strfmt( getact(Goal(g))-getsol(dev(2*g))+getsol(dev(2*g-1)) ,8))

forall(g in GOALS)if(getsol(dev(2*g))>0) thenwriteln(" Goal(",g,") deviation from target: -", getsol(dev(2*g)))elif(getsol(dev(2*g-1))>0) thenwriteln(" Goal(",g,") deviation from target: +", getsol(dev(2*g-1)))

end-ifend-procedure

end-model

When running the program, one finds that the first four goals can be satisfied, but the last not quite.

Solution(1): Total cost 6360Alpes: 0 Andalusia: 12 Antilles: 14 London: 0 Brittany: 2

Solution(2): Total cost 6360Alpes: 0 Andalusia: 12 Antilles: 14 London: 0 Brittany: 2

Solution(3): Total cost 6120Alpes: 0 Andalusia: 12 Antilles: 11 London: 0 Brittany: 5

Solution(4): Total cost 6120Alpes: 0 Andalusia: 12 Antilles: 11 London: 0 Brittany: 5

Solution(5): Total cost 6340Alpes: 2 Andalusia: 12 Antilles: 10 London: 0 Brittany: 5

Cannot satisfy goal 5Goal Target Value

1 >= 28 292 <= 35 293 = -0 04 >= 100 1085 >= 21 20.9

Goal(5) deviation from target: -0.1

The total duration of the holidays is 29 days, out of which 2 are spent in the Alpes, 12 in Andalusia, 10 inthe Antilles, and 5 in Brittany. Both, parents and children are satisfied with the choice of the destinations,but the number of expected sunny days remains under the limit value of 21 days.

Spending 2 days in the Alpes may not be realistic due to the traveling times. We therefore now definethe variables stayd as semi-continuous integers that either take the value 0 or and integer value between

Additional examples 37 Applications of optimization with Xpress-MP

Page 42: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

a given limit value and their upper bound:

∀d ∈ DEST : stayd = 0 ∨MINDURd ≤ stayd ≤ MAXDURd (2.9.13)

In the model, the keyword is_integer needs to be replaced by is_semint and the limit value:

forall(d in DEST) stay(d) is_semint MINDUR(d)

With this modification, we obtain the following output:

Solution(1): Total cost 6475Alpes: 3 Andalusia: 12 Antilles: 13 London: 0 Brittany: 0

Solution(2): Total cost 6475Alpes: 3 Andalusia: 12 Antilles: 13 London: 0 Brittany: 0

Solution(3): Total cost 6120Alpes: 0 Andalusia: 12 Antilles: 11 London: 0 Brittany: 5

Solution(4): Total cost 6120Alpes: 0 Andalusia: 12 Antilles: 11 London: 0 Brittany: 5

Solution(5): Total cost 6360Alpes: 6 Andalusia: 12 Antilles: 7 London: 0 Brittany: 4

Cannot satisfy goal 5Goal Target Value

1 >= 28 292 <= 35 293 = -0 04 >= 100 1145 >= 21 20.65

Goal(5) deviation from target: -0.35

2.10 Recursion – SLP

Recursion, more properly known as Successive Linear Programming, is a technique whereby LP may beused to solve certain non-linear problems. Some coefficients in an LP problem are defined to be functionsof the optimal values of LP variables. When an LP problem has been solved, the coefficients are re-evaluated and the LP re-solved. Under some assumptions this process may converge to a local (thoughnot necessarily a global) optimum.

Consider the following financial planning problem:We wish to determine the yearly interest rate rate so that for a given set of payments we obtain the finalbalance of 0. Interest is paid quarterly according to the following formula:

interestt = 92 / 365 · balancet · rate

where balancet is the balance at the beginning of period t.

The balance at time t (t ∈ QUARTERS = {1, . . . , NT}) results from the balance of the previous period t − 1and the net of payments and interest:

nett = Paymentst − interestt

balancet = balancet−1 − nett

2.10.1 Model formulation

We may formulate the following mathematical model for this problem (there is no objective function,we only wish to obtain a feasible solution):

∀t ∈ QUARTERS : nett = Paymentst − interestt (2.10.1)

balance1 = −net1 (2.10.2)

∀t ∈ {2, . . . , NT} : balancet = balancet−1 − nett (2.10.3)

∀t ∈ {2, . . . , NT} : interestt = 92 / 365 · balancet−1 · rate (2.10.4)

∀t ∈ QUARTERS : interest ≥ 0 (2.10.5)

interest1 = 0, balanceNT = 0, rate ≥ 0 (2.10.6)

Additional examples 38 Applications of optimization with Xpress-MP

Page 43: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

The constraints 2.10.4 are non-linear due to the products

balancet · rate

Notice further that we have not stated any non-negativity constraints for the variables balancet and nett,meaning that these variables are allowed to take negative values.

2.10.2 Implementation

For the implementation of this problem we use the Xpress-SLP solver instead of Xpress-Optimizer. Sincethe aim is simply to get feasible, there is no objective function in this problem (hence the argument 0 forprocedure SLPloadprob in the Mosel model below).

The fact that the variables balancet and nett are unconstrained is expressed by the keyword is_free (bydefault Mosel interprets all decision variables of type mpvar as non-negative variables).

model "S-11 Recursion"uses "mmxslp" ! Use Xpress-SLP

declarationsNT=6 ! Time horizonQUARTERS=1..NT ! Range of time periodsM,P,V: array(QUARTERS) of real ! Payments

interest: array(QUARTERS) of mpvar ! Interestnet: array(QUARTERS) of mpvar ! Netbalance: array(QUARTERS) of mpvar ! Balancerate: mpvar ! Interest rate

end-declarations

M:: [-1000, 0, 0, 0, 0, 0]P:: [206.6, 206.6, 206.6, 206.6, 206.6, 0]V:: [-2.95, 0, 0, 0, 0, 0]

SLPDATA("IV", rate, 0) ! Set initial values for variablesforall(t in QUARTERS) SLPDATA("IV", balance(t), 1)

! net = payments - interestforall(t in QUARTERS) net(t) = (M(t)+P(t)+V(t)) - interest(t)

! Money balance across periodsforall(t in QUARTERS) balance(t) = if(t>1, balance(t-1), 0) - net(t)

! Interest rateforall(t in 2..NT) interest(t) = (92/365) * balance(t-1) * rate

interest(1) = 0 ! Initial interest is zeroforall (t in QUARTERS) net(t) is_freeforall (t in 1..NT-1) balance(t) is_freebalance(NT) = 0 ! Final balance is zero

SLPloadprob(0) ! Load the problem (no objective)SLPminimize ! Solve the problem (get feasible)

end-model

In this implementation we use the procedure SLPDATA to set initial values ("IV") for the variables rateand balancet. Setting such start values based on reasonable guesses of feasible solution values may speedup the convergence of the SLP algorithm.

2.10.3 Results

With the initial guesses 0 for rate and 1 for all Bt the model converges to an interest rate of 5.94413%(rate = 0.0594413). It takes four SLP iterations to converge to a solution (both with and without specifi-cation of initial values). — To see the detailed output of the SLP algorithm add the following parametersetting before the start of the solution process:

setparam("XSLP_VERBOSE",true)

Additional examples 39 Applications of optimization with Xpress-MP

Page 44: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.10.4 Recursion algorithm

Let us now have a closer look at this example to understand how an SLP algorithm proceeds to solve anon-linear problem.

As has been mentioned earlier, this problem cannot be modeled just by LP because we have the NT − 1products

balancet · rate

which are non-linear. To express an approximation of the original problem by LP we replace the interestrate variable rate by a (constant) guess R of its value and a deviation variable dr:

rate = R + dr

The formula for the quarterly interest payment interestt therefore becomes

interestt = 92 / 365 · (balancet−1 · rate)

= 92 / 365 · (balancet−1 · (R + dr))

= 92 / 365 · (balancet−1 · R + balancet−1 · dr)

where balancet is the balance at the beginning of period t.

We now also replace the balance balancet−1 in the product with dr by a guess Bt−1 and a deviation dbt−1

interestt = 92 / 365 · (balancet−1 · R + (Bt−1 + dbt−1) · dr)

= 92 / 365 · (balancet−1 · R + Bt−1 · dx + dbt−1 · dr)

which can be approximated by dropping the product of the deviation variables

interestt = 92 / 365 · (balancet−1 · R + Bt−1 · dr)

To ensure feasibility we add penalty variables eplust and eminust for positive and negative deviations inthe formulation of the constraint:

interestt = 92 / 365 · (balancet−1 · R + Bt−1 · dr + eplust − eminust)

The objective of the problem is to get feasible, that is to minimize the deviations (2.10.7). We henceobtain the following complete mathematical model:

minimize∑

t∈QUARTERS

(eplust + eminust) (2.10.7)

∀t ∈ QUARTERS : nett = paymentst − interestt (2.10.8)

balance1 = −net1 (2.10.9)

∀t ∈ {2, . . . , NT} : balancet = balancet−1 − nett (2.10.10)

∀t ∈ {2, . . . , NT} : interestt = 92 / 365 · (balancet−1 · R + Bt−1 · dr + eplust − eminust) (2.10.11)

R + dr = rate (2.10.12)

∀t ∈ QUARTERS : eplust ≥ 0, eminust ≥ 0, interest ≥ 0 (2.10.13)

interest1 = 0, balanceNT = 0, rate ≥ 0 (2.10.14)

With this model, we can define a recursion procedure that is repeated until the solution has converged(i.e. the change in the deviation variables gets close to 0). The recursion on rate and the balancet

(t = 1, . . . , T − 1) is implemented by the following steps:

1. Solve the problem.

2. If the solution has not converged:

• The Bt−1 in constraints (2.10.11) get the prior solution value of balancet−1

• The R in constraints (2.10.11) get the prior solution value of rate

• The R in constraint (2.10.12) gets the prior solution value of rate

• Continue with 1.

Additional examples 40 Applications of optimization with Xpress-MP

Page 45: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

2.10.5 Exercise

In the implementation with Xpress-SLP, the linearization of the problem is done by the solver and ofcourse, we do not have to program the recursion algorithm ourselves. However, as an exercise the re-cursion procedure for this particular problem can be implemented with Mosel, solving the resulting LPproblems with Xpress-Optimizer.

Additional examples 41 Applications of optimization with Xpress-MP

Page 46: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Chapter 3

Teaching material

The following material are examples of “hands-on” work accompanying the taught course “Modelingwith Mosel”.

3.1 Model APS

3.1.1 LP models

1. A company wants to plan the production of several products (PRODUCT = {‘a′, ‘b′, ‘c′, ‘d′}). Thedemands for the next 4 months are known (Dem1p, Dem2p, Dem3p, and Dem4p), as are the monthlycapacity limits (MAXMAKEp) for every product p in PRODUCT . Is the production capacity sufficientlylarge to satisfy the demand every month?The following model may be used to answer this question.

model "T-1 APS0f"uses "mmxprs" ! Load the Optimizer library

parametersDEMDATA="Dem1"end-parameters

declarationsPRODUCT: set of string ! Product namesDEMAND: array(PRODUCT) of real ! DemandMAXMAKE: array(PRODUCT) of real ! Production capacity limitend-declarations

initializations from ’t1aps0.dat’MAXMAKEDEMAND as DEMDATAend-initializations

! Formulate the problemdeclarationsmake: array(PRODUCT) of mpvar ! Production of product p

end-declarations

! Objective functionMinProd:= sum(p in PRODUCT) make(p)

! Satisfy the demandforall(p in PRODUCT) make(p) >= DEMAND(p)

! Production has limited capacityforall(p in PRODUCT) make(p) <= MAXMAKE(p)

minimize(MinProd) ! Solve the problem

! Solution printingdeclarationsstatus:array({XPRS_OPT,XPRS_UNF,XPRS_INF,XPRS_UNB,XPRS_OTH}) of string

end-declarations

42 Applications of optimization with Xpress-MP

Page 47: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

status(XPRS_OPT):="Optimum found"; status(XPRS_UNF):="Unfinished"status(XPRS_INF):="Infeasible"; status(XPRS_UNB):="Unbounded"status(XPRS_OTH):="Failed"

writeln("Problem status: ", status(getprobstat))

if(getprobstat=XPRS_OPT) thenwriteln("Total production: ", getobjval)writeln("Product Quantity made")forall(p in PRODUCT)writeln(strfmt(p,-8), strfmt(getsol(make(p)),9))

end-ifend-model

2. Model APS0: Let us now consider the 4 months of the planning period all at once. It is possible tostore an unlimited quantity of every product from one month to the next at a unit cost of HCOSTp

per product p and per month. The initial and final stocks are empty. Determine a production planthat minimizes the total cost of storage.This new model may be developed based on the model APS0f above. It introduces a new constrainttype, namely stock balance constraints. For every product and every months t we have:stock at beginning of t + production in t = demand in t + stock at the beginning of t + 1

The following data file t1aps0.dat contains all the necessary data for the models APS0f and APS0(some data items like HCOST are listed twice to show different ways of formating data; other entrieslike TimeData may be used for output printing):

HCOST: [(a) 35 (b) 39 (c) 45 (d) 85]MAXMAKE: [(a) 8000 (b) 5000 (c) 8000 (d) 15000]

Dem1: [(a) 5000 (b) 900 (c) 6000 (d) 10000]Dem2: [(a) 6000 (b) 1000 (c) 9000 (d) 11000]Dem3: [(a) 3000 (b) 4000 (c) 4000 (d) 14000]Dem4: [(a) 10000 (b) 5000 (c) 2000 (d) 16000]

NT: 4

TimeData: [(1) Jan (2) Feb (3) Mar (4) Apr]

ProductData: [ !PROD [HCOST MAXMAKE](a) [35 8000](b) [39 5000](c) [45 8000](d) [85 15000] ]

DemandData: [ ! (PROD TIME) DEMAND(a 1) 5000(a 2) 6000(a 3) 3000(a 4) 10000(b 1) 900(b 2) 1000(b 3) 4000(b 4) 5000(c 1) 6000(c 2) 9000(c 3) 4000(c 4) 2000(d 1) 10000(d 2) 11000(d 3) 14000(d 4) 16000 ]

StockData: [ !PROD [ISTOCK FSTOCK]] ! All at zero

3.1.2 MIP models (1)

1. Model APS1: we continue to work with the previous model APS0.The company now also wishes to take into account the cost of setting up the production (SUCOSTp).This cost applies every month during which a product p is made.

Teaching material 43 Applications of optimization with Xpress-MP

Page 48: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

To model this cost, we need to introduce 0/1 variables (ifmakept) that indicate whether the productp is made in month t.We then have to establish the following relation between the decision about the production andthe quantities produced: if the quantity produced is non-zero (that is, positive), then the variablefor the production decision must be 1 (for ‘yes’). Conversely, if there is no production (0 for ‘no’),then the produced quantity must be 0. This relation can be expressed by adding the new variablesifmakept to the capacity constraints:make(p,t) <= MAXMAKE(p)*ifmake(p,t)

2. Model APS2: Satisfying all demands leads to the fairly unprofitable production of small quanti-ties in certain months. The company’s marketing department has made an estimation of the cost(OPCOSTp) per unit of unsatisfied demand of p.We introduce new variables xdempt for the quantity of unsatisfied demand of p in month t. Thesevariables must be added to the objective function and also to the stock balance constraints. Forevery product and every month t we have:stock at the beginning of t + production in t = demand in t - quantity of unsatisfied demand in t +stock at the beginning of t + 1Display the result separately for every cost category.

Data file t1aps1.dat for model APS1:

NT: 4TimeData: [(1) Jan (2) Feb (3) Mar (4) Apr]

HCOST: [(a) 35 (b) 39 (c) 45 (d) 85]SUCOST: [(a) 500000 (b) 900000 (c) 800000 (d) 900000]MAXMAKE: [(a) 8000 (b) 5000 (c) 8000 (d) 15000]

ProductData: [ !PROD [HCOST SUCOST MAXMAKE](a) [35 500000 8000](b) [39 900000 5000](c) [45 800000 8000](d) [85 900000 15000] ]

DemandData: [ ! (PROD TIME) DEMAND(a 1) 5000(a 2) 6000(a 3) 3000(a 4) 10000(b 1) 900(b 2) 1000(b 3) 4000(b 4) 5000(c 1) 6000(c 2) 9000(c 3) 4000(c 4) 2000(d 1) 10000(d 2) 11000(d 3) 14000(d 4) 16000 ]

StockData: [ !PROD [ISTOCK FSTOCK]] ! All at zero

Data file t1aps2.dat for model APS2:

NT: 4TimeData: [(1) Jan (2) Feb (3) Mar (4) Apr]

HCOST: [(a) 35 (b) 39 (c) 45 (d) 85]SUCOST: [(a) 500000 (b) 900000 (c) 800000 (d) 900000]OPCOST: [(a) 1000 (b) 800 (c) 1000 (d) 900]MAXMAKE: [(a) 8000 (b) 5000 (c) 8000 (d) 15000]

ProductData: [ !PROD [HCOST SUCOST OPCOST MAXMAKE](a) [35 500000 1000 8000](b) [39 900000 800 5000](c) [45 800000 1000 8000](d) [85 900000 900 15000] ]

Teaching material 44 Applications of optimization with Xpress-MP

Page 49: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

DemandData: [ ! (PROD TIME) DEMAND(a 1) 5000(a 2) 6000(a 3) 3000(a 4) 10000(b 1) 900(b 2) 1000(b 3) 4000(b 4) 5000(c 1) 6000(c 2) 9000(c 3) 4000(c 4) 2000(d 1) 10000(d 2) 11000(d 3) 14000(d 4) 16000 ]

StockData: [ !PROD [ISTOCK FSTOCK]] ! All at zero

3.1.3 MIP models (2)

1. Model APS3: we continue to work with the previous model APS2.To obtain a more detailed production plan, the company now wishes to consider its two pro-duction sites separately. Every factory l has different setup costs (SUCOSTpl) and capacity limits(MAXMAKEpl), and in addition a specific production cost (cost per unit of product, PCOSTpl)The storage costs (HCOSTp) and the cost for unsatisfied demand (OPCOSTp) do not depend on theproduction site.Besides the data, we have to modify the index sets of all variables linked to production.

2. Model APS4: Variations in the level of factory utilization are expensive (overtime hours to be paidor under-utilization of available resources). For this reason, the production manager decides todefine a cost MDEVCOST for every change (positive or negative) to the level of production (= sumof the quantities made of all products) from one month to the next.For every factory l and every time period (except the first) the following equation represents thechanges to the production level:increase - decrease = total production in t - total production in t − 1Note that it is required to introduce two seperate variables for increase and decrease of the pro-duction level because in every case we have to account for a positive cost.

3. Improving the performance of model APS4: Display the output log of the Optimizer by adding thefollowing line before calling the optimization:setparam("XPRS_VERBOSE",true)

The logging frequency can be modified: for example to reduce it to every 500 branch-and-bounditerations:setparam("XPRS_MIPLOG",-500)

Try to speed up the branch-and-bound search by modifying, for instance, the following parameters:XPRS_PRESOLVE (0/1), XPRS_MIPPRESOLVE (0/1), XPRS_CUTSTRATEGY (0/1/2),XPRS_NODESELECTION (1/2/3/4), XPRS_BACKTRACK (1/2/3)and/or by adding branching priorities and directives for the prefered branching direction with theprocedure setmipdir (consult the Mosel Language Reference Manual for the arguments of thissubroutine).Display the total number of node (parameter XPRS_NODES) and the running time (for instance byusing the function gettime of the module mmsystem)

Data file t1aps3.dat for model APS3:

NT: 4TimeData: [(1) Jan (2) Feb (3) Mar (4) Apr]

HCOST: [(a) 35 (b) 39 (c) 45 (d) 85]OPCOST: [(a) 1000 (b) 800 (c) 1000 (d) 900]

ProductData: [! PROD [OPCOST HCOST](a) [1000 35](b) [800 39]

Teaching material 45 Applications of optimization with Xpress-MP

Page 50: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

(c) [1000 45](d) [900 85] ]

SUCOST: [(a Detroit) 450000 (a Seattle) 550000(b Detroit) 950000 (b Seattle) 850000(c Detroit) 750000 (c Seattle) 850000(d Detroit) 1000000 (d Seattle) 800000 ]

PCOST: [(a Detroit) 600 (a Seattle) 650(b Detroit) 400 (b Seattle) 370(c Detroit) 450 (c Seattle) 380(d Detroit) 500 (d Seattle) 350 ]

MAXMAKE: [(a Detroit) 3000 (a Seattle) 5000(b Detroit) 2000 (b Seattle) 3000(c Detroit) 5000 (c Seattle) 3000(d Detroit) 10000 (d Seattle) 5000 ]

ProductPlantData: [ ! (PROD PLANT) [PCOST SUCOST MAXMAKE](a Detroit) [600 450000 3000](b Detroit) [400 950000 2000](c Detroit) [450 750000 5000](d Detroit) [500 1000000 10000](a Seattle) [650 550000 5000](b Seattle) [370 850000 3000](c Seattle) [380 850000 3000](d Seattle) [350 800000 5000] ]

DemandData: [ ! (PROD TIME) DEMAND(a 1) 5000(a 2) 6000(a 3) 3000(a 4) 10000(b 1) 900(b 2) 1000(b 3) 4000(b 4) 5000(c 1) 6000(c 2) 9000(c 3) 4000(c 4) 2000(d 1) 10000(d 2) 11000(d 3) 14000(d 4) 16000 ]

StockData: [ !PROD [ISTOCK FSTOCK]] ! All at zero

Data file t1aps4.dat for model APS4:

NT: 4TimeData: [(1) Jan (2) Feb (3) Mar (4) Apr]

HCOST: [(a) 35 (b) 39 (c) 45 (d) 85(e) 23 (f) 34 (g) 21 (h) 67]

OPCOST: [(a) 1000 (b) 800 (c) 1000 (d) 900(e) 1500 (f) 1200 (g) 700 (h) 1100]

ProductData: [ ! PROD [OPCOST HCOST](a) [1000 35](b) [800 39](c) [1000 45](d) [900 85](e) [1500 23]

(f) [1200 34](g) [700 21]

(h) [1100 67] ]

SUCOST: [(a Detroit) 450000 (a Seattle) 550000(b Detroit) 950000 (b Seattle) 850000(c Detroit) 750000 (c Seattle) 850000(d Detroit) 100000 (d Seattle) 800000(e Detroit) 400000 (e Seattle) 600000

Teaching material 46 Applications of optimization with Xpress-MP

Page 51: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

(f Detroit) 500000 (f Seattle) 750000(g Detroit) 700000 (g Seattle) 750000(h Detroit) 800000 (h Seattle) 700000 ]

PCOST: [(a Detroit) 600 (a Seattle) 650(b Detroit) 400 (b Seattle) 370(c Detroit) 450 (c Seattle) 380(d Detroit) 500 (d Seattle) 350(e Detroit) 700 (e Seattle) 900(f Detroit) 570 (f Seattle) 350(g Detroit) 300 (g Seattle) 400(h Detroit) 500 (h Seattle) 600 ]

MAXMAKE: [(a Detroit) 3000 (a Seattle) 5000(b Detroit) 2000 (b Seattle) 3000(c Detroit) 5000 (c Seattle) 3000(d Detroit) 10000 (d Seattle) 5000(e Detroit) 2500 (e Seattle) 3000(f Detroit) 3800 (f Seattle) 4500(g Detroit) 3000 (g Seattle) 5000(h Detroit) 3500 (h Seattle) 4300 ]

ProductPlantData: [ ! (PROD PLANT) [PCOST SUCOST MAXMAKE](a Detroit) [600 450000 3000](b Detroit) [400 950000 2000](c Detroit) [450 750000 5000](d Detroit) [500 100000 10000](e Detroit) [700 400000 2500](f Detroit) [570 500000 3800](g Detroit) [300 700000 3000](h Detroit) [500 800000 3500](a Seattle) [650 550000 5000](b Seattle) [370 850000 3000](c Seattle) [380 850000 3000](d Seattle) [350 800000 5000](e Seattle) [900 600000 3000](f Seattle) [350 750000 4500](g Seattle) [400 750000 5000](h Seattle) [600 700000 4300] ]

DemandData: [ ! (PROD TIME) DEMAND(a 1) 5000(a 2) 6000(a 3) 3000(a 4) 10000(b 1) 900(b 2) 1000(b 3) 4000(b 4) 5000(c 1) 6000(c 2) 9000(c 3) 4000(c 4) 2000(d 1) 10000(d 2) 11000(d 3) 14000(d 4) 16000(e 1) 1000(e 2) 6000(e 3) 3000(e 4) 10000(f 1) 5000(f 2) 6000(f 3) 8000(f 4) 7000(g 1) 5000(g 2) 6000(g 3) 3000(g 4) 2000(h 1) 5000(h 2) 12000(h 3) 4000(h 4) 10000 ]

Teaching material 47 Applications of optimization with Xpress-MP

Page 52: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

StockData: [ !PROD [ISTOCK FSTOCK]] ! All at zero

MDEVCOST: 10000

Implementation of the complete model APS4:

model "T-1 APS4"uses "mmxprs" ! Load the Optimizer library

declarationsTIME:range ! Range of time periodsTIME2: range ! Time periods without first periodPRODUCT: set of string ! Product namesPLANT: set of string ! Plant namesMONTH: array(TIME) of string ! Time period namesFirst,Last: integer

PCOST: array(PRODUCT,PLANT) of real ! Production costHCOST: array(PRODUCT) of real ! Holding costSUCOST: array(PRODUCT,PLANT) of real ! Setup costOPCOST: array(PRODUCT) of real ! Opportunity costMDEVCOST: real ! Deviation costDEMAND: array(PRODUCT,TIME) of real ! DemandMAXMAKE: array(PRODUCT,PLANT) of real ! Production capacity limitISTOCK,FSTOCK: array(PRODUCT) of real ! Initial and final stock levels

end-declarations

initializations from ’t1aps4.dat’MONTH as "TimeData"OPCOST HCOST[PCOST,SUCOST,MAXMAKE] as "ProductPlantData"DEMAND as "DemandData"MDEVCOST

end-initializations

First:=getfirst(TIME); Last:=getlast(TIME)TIME2:= First+1..Last

! Formulate the problemdeclarationsmake: array(PRODUCT,PLANT,TIME) of mpvar

! Production in period tifmake: array(PRODUCT,PLANT,TIME) of mpvar ! 1 if production of p in time t,

! 0 otherwisestore: array(PRODUCT,TIME2) of mpvar ! Stock at start period txdem: array(PRODUCT,TIME) of mpvar ! Excess demand (not met)mpdev: array(PLANT,TIME2) of mpvar ! Make deviation +ve from t-1 to tmndev: array(PLANT,TIME2) of mpvar ! Make deviation -ve from t-1 to thcost: mpvar ! Total holding costsucost: mpvar ! Total set-up costmdcost: mpvar ! Total missed demand costpcost: mpvar ! Total production costmdevcost: mpvar ! Total deviation cost

end-declarations

! Objective functionMinCost:= hcost + sucost + mdcost + pcost + mdevcost

hcost = sum(p in PRODUCT,t in TIME2) HCOST(p)*store(p,t)sucost = sum(p in PRODUCT,l in PLANT,t in TIME) SUCOST(p,l)*ifmake(p,l,t)mdcost = sum(p in PRODUCT,t in TIME) OPCOST(p)*xdem(p,t)pcost = sum(p in PRODUCT,l in PLANT,t in TIME) PCOST(p,l)*make(p,l,t)mdevcost = MDEVCOST * sum(l in PLANT,t in TIME2) (mpdev(l,t) + mndev(l,t))

! Deviation of production levelforall(l in PLANT,t in TIME2)mpdev(l,t) - mndev(l,t) = sum(p in PRODUCT) (make(p,l,t) - make(p,l,t-1))

! Inventory balanceforall(p in PRODUCT,t in TIME)if(t>First, store(p,t), ISTOCK(p)) + sum(l in PLANT) make(p,l,t) =DEMAND(p,t) + if(t<Last, store(p,t+1), FSTOCK(p)) - xdem(p,t)

Teaching material 48 Applications of optimization with Xpress-MP

Page 53: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

! Production requires setup and has limited capacityforall(p in PRODUCT,l in PLANT,t in TIME)make(p,l,t) <= MAXMAKE(p,l)*ifmake(p,l,t)

forall(p in PRODUCT,l in PLANT,t in TIME) ifmake(p,l,t) is_binary

! Set branching directivesforall(p in PRODUCT,l in PLANT) dosetmipdir(ifmake(p,l,First), XPRS_PR, 1)setmipdir(ifmake(p,l,First+1), XPRS_PR, 2)setmipdir(ifmake(p,l,First+2), XPRS_PR, 3)

end-do

! Algorithm settingssetparam("XPRS_PRESOLVE",1)

! Output controlsetparam("XPRS_verbose",true)setparam("XPRS_miplog",-500)

minimize(MinCost) ! Solve the problem

if(getprobstat=XPRS_INF) thenwriteln("Problem is infeasible")exit(0)

end-if

! Solution printingwriteln("Total cost: ", getobjval/1e6, "Million")writeln("(Holding: ", getsol(hcost)/1e6, "M, setup: ", getsol(sucost)/1e6,

"M, missed demand: ", getsol(mdcost)/1e6, "M,\n production: ",getsol(pcost)/1e6, "M, deviation: ", getsol(mdevcost)/1e6, "M)")

write("Plant Product")forall(t in TIME) write(strfmt(MONTH(t),9))forall(l in PLANT) dowrite("\n", l, ":")forall(p in PRODUCT) dowrite("\n ", p, " ")forall(t in TIME) write(strfmt(round(getsol(make(p,l,t))),6),

"(",round(getsol(ifmake(p,l,t))), ")")end-do

writelnend-do

write("\nProduct ")forall(t in TIME) write(strfmt(MONTH(t),9))forall(p in PRODUCT) dowrite("\n", p, " Store ", strfmt(ISTOCK(p),9))forall(t in TIME2) write(strfmt(round(getsol(store(p,t))),9))write(strfmt(FSTOCK(p),9))write("\n Missed")forall(t in TIME) write(strfmt(round(getsol(xdem(p,t))),9))

end-dowriteln

end-model

3.2 Model Food

A company produces two types of food (granules and powder) for farm animals by blending oat, maize,and molasses. Every food product needs to fulfill certain nutritional requirements, expressed as per-centages of proteins, lipids and fibers. There are limits on the availability of raw materials and we arealso given their respective prices. Every production step (grinding, blending, granulating, sieving) hasa known cost per unit. With a daily demand of nine tonnes of granules and twelve tonnes of powder,which quantities of raw materials are required and how should they be blended to minimize the totalcost?

A solution to this problem is implemented by the following model t2food.mos. For further detail on themodel formulation for this problem see the section Animal food production of the book “Applications of

Teaching material 49 Applications of optimization with Xpress-MP

Page 54: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

optimization with Xpress-MP” (http://www.dashoptimization.com/applications_book.html)

The following data file t2food.dat contains all the necessary data for models Food to Food4.

P: [(oat 1) 13.6 7.1 7 ! Composition of raw materials (percentages)(maize 1) 4.1 2.4 3.7(molasses 1) 5 0.3 25 ]

REQ: [9.5 2 6] ! Nutritional requirements

AVAIL: [(oat) 11900 (maize) 23500 (molasses) 750] ! Raw mat. availabilities

COST: [(oat) 0.13 (maize) 0.17 (molasses) 0.12] ! Raw mat. prices

! Cost of processing operationsPCOST: [(grinding) 0.25 (blending) 0.05 (granulating) 0.42 (sieving) 0.17]

DEM: [9000 12000] ! Demands for food types

1. Model t2food1.mos: Display the production costs for each step of the production process. Whatis the total cost for each product?

2. Model t2food2.mos: Which is the effect of an increase of the oat price? Display the results for anincrease of 1% to 10%.

3. With IVE: Display the results for the preceding question graphically, using the module mmive. Usethe function IVEaddplot to define a new graph, for example:Graph:= IVEaddplot("Effect of oat price increase", IVE_BLUE)and the procedure IVEdrawpoint to draw a point, such as: IVEdrawpoint(Graph, x, y)

4. Model t2food3.mos: To simplify the production process, the company wishes to restrict the num-ber of raw material types used by any product to 2.To model these new constraints we need to introduce 0/1 variables (ifuserf ) that indicate whetherproduct f uses raw material r.We then have to set a bound of 2 on the sum of the ifuserf for every final product. We also needto establish the following relation: if the quantity of r is non-zero (i.e., positive), then the decisionvariable ifuserf must be at 1 (for “yes”). Inversely, if r is not used (ifuserf at 0 for “no”), then thequantity of this raw material is 0. This relation can be formulated by associating the new variableifuserf with the available quantities of raw material:AVAIL(r)*ifuse(r,f) >= use(r,f)

5. Does this model have a solution? Display the optimizer log (control parameter XPRS_verbose) andcheck the value of the Mosel problem status (function getprobstat).

6. Model t2food4.mos: In the model t2food1 add output printing to compare (a) the demands andthe actual production and (b) the available quantities of raw material and the quantities that areused (using functions getsol and getact). Which would be the effect of an increase or decreaseof the demands on the total cost (use function getrcost)?

7. Model t2food3b.mos: The company has the possibility to buy extra raw material for the doubleprice. Modify the model t2food3 by adding variables buyr to the objective function and to theconstraints on the availability of raw material (Quantity(f)). Which quantities of raw materialhave to be bought?

8. Model t2food5.mos: Whilst the demands are stable the raw material costs are subject to somevariation over time. The company has estimated the raw material costs for the next six time periodsand now wishes to establish a production plan for the whole planning period at once. It is possibleto store an unlimited quantity of every finished product from one time period to the next at a unitcost of SCOSTf per product f and per time period. The initial stock levels ISTOCKf are known andalso the final stock levels to be attained (FSTOCKf ).Extend the model t2food1 to a multi-period model by replacing the lower bounds on the pro-duction (given through the demands) by stock balance constraints. For every finished product andevery time period t we have:stock at beginning of t + production in t = demand in t + stock at the beginning of t + 1The formulation of these constraints makes necessary the introduction of additional decision vari-ables, storeft, for the amount of product f held in stock at the beginning of time period t. Fur-thermore, we need to add a time index to the other decision variables of our model (userft andproduceft) and to the constraints.

Teaching material 50 Applications of optimization with Xpress-MP

Page 55: Applications of optimization with Xpress-MP › ~moretti › MT503 › syllabus.pdf · sion (S-11) → simple algorithms looping around optimization statements, extension to other

Data file t2food5.dat for the model t2food5.mos:

P: [(oat 1) 13.6 7.1 7 ! Composition of raw materials (percentages)(maize 1) 4.1 2.4 3.7(molasses 1) 5 0.3 25 ]

REQ: [9.5 2 6] ! Nutritional requirements

AVAIL: [(oat) 11900 (maize) 23500 (molasses) 750] ! Raw mat. availabilities

! Cost of processing operationsPCOST: [(grinding) 0.25 (blending) 0.05 (granulating) 0.42 (sieving) 0.17]

DEM: [9000 12000] ! Demands for food types

COST: [(oat 1) 0.13 0.15 0.15 0.16 0.17 0.17 ! Raw mat. cost per period(maize 1) 0.17 0.16 0.16 0.17 0.17 0.18(molasses 1) 0.12 0.13 0.11 0.11 0.12 0.11]

ISTOCK: [1000 1000] ! Initial stock levelsFSTOCK: [1000 1000] ! Final stock levels

SCOST: [0.05 0.07] ! Stock holding cost

Teaching material 51 Applications of optimization with Xpress-MP