Red Hat JBoss BRMS 6.3 Business Resource Planner Guide

advertisement
Red Hat JBoss BRMS 6.3
Business Resource Planner
Guide
For JBoss Developers
Red Content ServicesGemma Sheldon
Marek Czernek
Tomas Radej
Klara Kufova
Vidya Iyengar
Red Hat JBoss BRMS 6.3 Business Resource Planner Guide
For JBoss Developers
Red Content Services
Gemma Sheldon
gsheldon@redhat.com
Klara Kufova
kkufova@redhat.com
Marek Czernek
mczernek@redhat.com
Tomas Radej
tradej@redhat.com
Vidya Iyengar
viyengar@redhat.com
Legal No tice
Copyright © 2016 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a
Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An
explanation of CC-BY-SA is available at
http://creativecommons.org/licenses/by-sa/3.0/
. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it,
you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees
not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable
law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, OpenShift, Fedora,
the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United
States and other countries.
Linux ® is the registered trademark of Linus Torvalds in the United States and other
countries.
Java ® is a registered trademark of Oracle and/or its affiliates.
XFS ® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the
United States and/or other countries.
MySQL ® is a registered trademark of MySQL AB in the United States, the European
Union and other countries.
Node.js ® is an official trademark of Joyent. Red Hat Software Collections is not
formally related to or endorsed by the official Joyent Node.js open source or
commercial project.
The OpenStack ® Word Mark and OpenStack logo are either registered
trademarks/service marks or trademarks/service marks of the OpenStack
Foundation, in the United States and other countries and are used with the
OpenStack Foundation's permission. We are not affiliated with, endorsed or
sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
Abstract
This guide provides the steps needed for installing Business Resource Planner and
instructions for using it.
T able o f Co nt e nt s
T able o f Co ntents
.CHAPT
. . . . . ER
. . .1.
. .BUSINESS
. . . . . . . . .RESO
. . . . .URCE
. . . . .PLANNER
. . . . . . . .INT
. . . RO
. . .DUCT
. . . . .IO
. .N. . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . .
1.1. WHAT IS BUSINESS RESO URC E P LANNER
5
1.2. DO WNLO AD BUSINESS RESO URC E P LANNER
6
1.3. RUN THE EXAMP LES
8
.CHAPT
. . . . . ER
. . .2.
. .Q
. UICK
. . . . .ST
. . ART
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10
..........
2.1. C LO UD BALANC ING TUTO RIAL
10
.CHAPT
. . . . . ER
. . .3.
. .USE
. . . .CASES
. . . . . .AND
. . . .EXAMPLES
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24
..........
3.1. EXAMP LES O VERVIEW
24
3.2. BASIC EXAMP LES
27
3.3. REAL EXAMP LES
35
3.4. DIFFIC ULT EXAMP LES
54
. . . . . . ER
CHAPT
. . .4. .. PLANNER
. . . . . . . . .CO
. . NFIGURAT
. . . . . . . . .IO
. .N
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71
..........
4.1. O VERVIEW
4.2. SO LVER C O NFIGURATIO N
4.3. MO DEL A P LANNING P RO BLEM
4.4. USE THE SO LVER
71
71
77
108
.CHAPT
. . . . . ER
. . .5.
. .SCO
. . . .RE
. . CALCULAT
. . . . . . . . . IO
. .N
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .116
...........
5.1. SC O RE TERMINO LO GY
116
5.2. C HO O SE A SC O RE DEFINITIO N
5.3. C ALC ULATE THE SC O RE
125
127
5.4. SC O RE C ALC ULATIO N P ERFO RMANC E TRIC KS
5.5. EXP LAINING THE SC O RE: USING SC O RE C ALC ULATIO N O UTSIDE THE SO LVER
140
146
. . . . . . ER
CHAPT
. . .6. .. O
. .PT
. .IMIZAT
. . . . . . IO
. .N
. .ALGO
. . . . .RIT
. . .HMS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14
. .8. . . . . . . . .
6.1. SEARC H SP AC E SIZ E IN THE REAL WO RLD
6.2. DO ES P LANNER FIND THE O P TIMAL SO LUTIO N?
6.3. ARC HITEC TURE O VERVIEW
148
149
150
6.4. O P TIMIZ ATIO N ALGO RITHMS O VERVIEW
6.5. WHIC H O P TIMIZ ATIO N ALGO RITHMS SHO ULD I USE?
6.6. P O WER TWEAKING O R DEFAULT P ARAMETER VALUES
6.7. SO LVER P HASE
6.8. SC O P E O VERVIEW
151
154
155
155
157
6.9. TERMINATIO N
6.10. SO LVEREVENTLISTENER
6.11. C USTO M SO LVER P HASE
158
163
164
.CHAPT
. . . . . ER
. . .7.
. .MO
. . .VE
. . AND
. . . . .NEIGHBO
. . . . . . . .RHO
...O
. .D. .SELECT
. . . . . . IO
. .N
. . . . . . . . . . . . . . . . . . . . . . . . . . .16
. .8. . . . . . . . .
7.1. MO VE AND NEIGHBO RHO O D INTRO DUC TIO N
168
7.2. GENERIC MO VESELEC TO RS
7.3. C O MBINING MULTIP LE MO VESELEC TO RS
7.4. ENTITYSELEC TO R
7.5. VALUESELEC TO R
7.6. GENERAL SELEC TO R FEATURES
170
179
181
182
182
7.7. C USTO M MO VES
197
.CHAPT
. . . . . ER
. . .8. .. EXHAUST
. . . . . . . . IVE
. . . SEARCH
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20
. .4. . . . . . . . .
8.1. O VERVIEW
204
8.2. BRUTE FO RC E
204
8.3. BRANC H AND BO UND
205
8.4. SC ALABILITY O F EXHAUSTIVE SEARC H
208
1
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
8.4. SC ALABILITY O F EXHAUSTIVE SEARC H
208
.CHAPT
. . . . . ER
. . .9. .. CO
. . .NST
. . . RUCT
. . . . . IO
. .N
. .HEURIST
. . . . . . . ICS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .211
...........
9.1. O VERVIEW
211
9.2. FIRST FIT
211
9.3. FIRST FIT DEC REASING
212
9.4. WEAKEST FIT
9.5. WEAKEST FIT DEC REASING
9.6. STRO NGEST FIT
9.7. STRO NGEST FIT DEC REASING
9.8. ALLO C ATE ENTITY FRO M Q UEUE
213
214
214
215
216
9.9. ALLO C ATE TO VALUE FRO M Q UEUE
9.10. C HEAP EST INSERTIO N
9.11. REGRET INSERTIO N
9.12. ALLO C ATE FRO M P O O L
221
222
223
224
. . . . . . ER
CHAPT
. . .10
. . .. LO
. . .CAL
. . . SEARCH
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .226
...........
10.1. O VERVIEW
10.2. LO C AL SEARC H C O NC EP TS
226
226
10.3. HILL C LIMBING (SIMP LE LO C AL SEARC H)
10.4. TABU SEARC H
232
234
10.5. SIMULATED ANNEALING
10.6. LATE AC C EP TANC E
236
238
10.7. STEP C O UNTING HILL C LIMBING
239
10.8. STRATEGIC O SC ILLATIO N
240
10.9. USING A C USTO M TERMINATIO N, MO VESELEC TO R, ENTITYSELEC TO R, VALUESELEC TO R
O R AC C EP TO R
241
. . . . . . ER
CHAPT
. . .11.
. . .EVO
. . . .LUT
. . .IO
. .NARY
. . . . . ALGO
. . . . .RIT
. . .HMS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24
. .2. . . . . . . . .
11.1. O VERVIEW
11.2. EVO LUTIO NARY STRATEGIES
242
242
11.3. GENETIC ALGO RITHMS
242
. . . . . . ER
CHAPT
. . .12.
. . .HYPERHEURIST
. . . . . . . . . . . . . ICS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24
. .3. . . . . . . . .
12.1. O VERVIEW
243
.CHAPT
. . . . . ER
. . .13.
. . .PART
. . . . .IT
. .IO
. .NED
. . . .SEARCH
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24
. .4. . . . . . . . .
13.1. O VERVIEW
244
. . . . . . ER
CHAPT
. . .14
. . .. BENCHMARKING
. . . . . . . . . . . . . . AND
. . . . .T.WEAKING
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24
. .5. . . . . . . . .
14.1. FIND THE BEST SO LVER C O NFIGURATIO N
14.2. BENC HMARK C O NFIGURATIO N
245
245
14.3. BENC HMARK REP O RT
252
14.4. SUMMARY STATISTIC S
14.5. STATISTIC P ER DATASET (GRAP H AND C SV)
253
256
14.6. STATISTIC P ER SINGLE BENC HMARK (GRAP H AND C SV)
263
14.7. ADVANC ED BENC HMARKING
268
.CHAPT
. . . . . ER
. . .15.
. . .REPEAT
. . . . . . .ED
. . PLANNING
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .273
...........
15.1. INTRO DUC TIO N TO REP EATED P LANNING
273
15.2. BAC KUP P LANNING
15.3. O VERC O NSTRAINED P LANNING
273
273
15.4. C O NTINUO US P LANNING (WINDO WED P LANNING)
274
15.5. REAL-TIME P LANNING
278
.CHAPT
. . . . . ER
. . .16
. . .. INT
. . . EGRAT
. . . . . . IO
. .N
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28
. .3. . . . . . . . .
16.1. O VERVIEW
283
2
T able o f Co nt e nt s
16.1. O VERVIEW
283
16.2. P ERSISTENT STO RAGE
16.3. SO A AND ESB
283
287
16.4. O THER ENVIRO NMENTS
287
16.5. INTEGRATIO N WITH HUMAN P LANNERS (P O LITIC S)
289
.CHAPT
. . . . . ER
. . .17.
. . .DESIGN
. . . . . . .PAT
. . . .T.ERNS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
. .1. . . . . . . . .
17.1. DESIGN P ATTERNS INTRO DUC TIO N
291
17.2. ASSIGNING TIME TO P LANNING ENTITIES
291
17.3. MULTI-STAGE P LANNING
294
.CHAPT
. . . . . ER
. . .18
. . .. DEVELO
. . . . . . .PMENT
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
. .5. . . . . . . . .
18.1. METHO DO LO GY O VERVIEW
295
18.2. DEVELO P MENT GUIDELINES
296
.CHAPT
. . . . . ER
. . .19
. . .. MIGRAT
. . . . . . .IO
. .N
. .GUIDE
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
. .7. . . . . . . . .
19.1. ABO UT THE BUSINESS RESO URC E P LANNER MIGRATIO N
297
19.2. P LANNING VALUES AND VALUE RANGES
301
19.3. BENC HMARK
19.4. SO LVER C O NFIGURATIO N
304
307
19.5. O P TIMIZ ATIO N
309
. . . . . . ER
CHAPT
. . .20
. . .. REALT
. . . . . .IME
. . . DECISIO
. . . . . . .N
. .SERVER
. . . . . . .FUNCT
. . . . . .IO
. .NALIT
. . . . .Y
. . . . . . . . . . . . . . . . . . . . .314
...........
20.1. INTRO DUC TIO N
20.2. BUSINESS RESO URC E P LANNER REST AP I
314
314
. . . . . . . . . .A.
APPENDIX
. .REVISIO
. . . . . . .N. HIST
. . . . .O. RY
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .322
...........
3
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
4
CHAPT ER 1. BUSINESS RESO URCE PLANNER INT RO DUCT IO N
CHAPTER 1. BUSINESS RESOURCE PLANNER
INTRODUCTION
1.1. WHAT IS BUSINESS RESOURCE PLANNER
Business Resource Planner is a lightwe ight, e mbe ddable planning e ngine that
optimiz e s planning proble ms . It he lps normal Java TM programme rs s olve planning
proble ms e fficie ntly, and it combine s optimiz ation he uris tics and me tahe uris tics
with ve ry e fficie nt s core calculations .
Bus ine s s Re s ource Planne r he lps s olve various us e cas e s like the following:
Employee/Patient Rosters. It he lps cre ate time table s for nurs e s and ke e ps track
of patie nt be d manage me nt.
Educational Timetables. It he lps s che dule le s s ons , cours e s , e xams , and
confe re nce pre s e ntations .
Shop Schedules: It tracks car as s e mbly line s , machine que ue planning, and
workforce tas k planning.
Cutting Stock: It minimiz e s was te by re ducing the cons umption of re s ource s
s uch as pape r and s te e l.
Eve ry organiz ation face s planning proble ms ; that is , the y provide products and
s e rvice s with a limite d s e t of cons traine d re s ource s (e mploye e s , as s e ts , time ,
and mone y).
Figure 1.1. Use Case Overview
5
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Bus ine s s Re s ource Planne r is ope n s ource s oftware unde r the Apache Software
Lice ns e 2.0. It is 100% pure Java TM and runs on any Java virtual machine .
1.2. DOWNLOAD BUSINESS RESOURCE PLANNER
Bus ine s s Re s ource Planne r is production re ady. The API is s table but backward
incompatible change s can occur. With the re cipe calle d
Upgrade FromPre vious Ve rs ionRe cipe .txt, you can e as ily upgrade to a ne we r
ve rs ion and quickly de al with any backwards incompatible change s . This re cipe file
is include d in e ve ry re le as e .
Pro cedure: Get t he release zip and run t he examples
1. Navigate to the Re d Hat Cus tome r Portal and log in with your us e r
cre de ntials .
2. Se le ct Do wnlo ads → Red Hat JBo ss Middleware → Do wnlo ad
So f t ware.
3. From the Pro duct s drop-down me nu, s e le ct BPM Suit e or BRMS
Plat f o rm.
4. From the Versio n drop-down me nu, s e le ct the product ve rs ion 6.3.
5. Se le ct the St andalo ne or Deplo yable file and the n click do wnlo ad.
6. Unz ip the file s .
7. Ope n the dire ctory examples and run the following s cript:
6
CHAPT ER 1. BUSINESS RESO URCE PLANNER INT RO DUCT IO N
Linux or Mac:
$ cd examples
$ ./runExamples.sh
Windows :
$ cd examples
$ runExamples.bat
Figure 1.2. Do wnlo ad Business Reso urce Planner
The Example s GUI application will ope n. Jus t pick an e xample :
7
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
Bus ine s s Re s ource Planne r its e lf has no GUI de pe nde ncie s . It runs jus t as
we ll on a s e rve r or a mobile JVM as it doe s on the de s ktop.
1.3. RUN T HE EXAMPLES
Pro cedure: T o run t he examples in yo ur f avo rit e IDE:
1. Configure your IDE:
In Inte lliJ and Ne tBe ans , jus t ope n the file examples/sources/pom.xml as
a ne w proje ct, the Mave n inte gration will take care of the re s t.
In Eclips e , ope n a ne w proje ct for the dire ctory examples/sources.
Add all the jars to the clas s path from the dire ctory binaries and the
dire ctory examples/binaries , e xce pt for the file
examples/binaries/optaplanner-examples-*.jar.
Add the Java s ource dire ctory src/main/java and the Java re s ource s
dire ctory src/main/resources.
2. Ne xt, cre ate a run configuration:
Main clas s : org.optaplanner.examples.app.OptaPlannerExamplesApp
VM parame te rs (optional): -Xmx512M -server
8
CHAPT ER 1. BUSINESS RESO URCE PLANNER INT RO DUCT IO N
Working dire ctory: examples (this is the dire ctory that contains the
dire ctory data)
3. Run that run configuration.
Pro cedure: Use Business Reso urce Planner wit h Maven, Gradle, Ivy, Buildr
o r ANT :
1. Ge t the Bus ine s s Re s ource Planne r jars at the ce ntral mave n re pos itory
(and als o at the JBos s mave n re pos itory).
2. If you us e Mave n, add a de pe nde ncy to optaplanner-core in your proje ct’s
pom.xml :
<dependency>
<groupId>org.optaplanner</groupId>
<artifactId>optaplanner-core</artifactId>
<version>...</version>
</dependency>
To ide ntify the late s t ve rs ion, che ck the ce ntral mave n re pos itory. This is
s imilar for Gradle , Ivy, and Buildr.
3. If you’re s till us ing ANT (without Ivy), copy all the jars from the download
z ip’s binaries dire ctory and manually ve rify that your clas s path doe s n’t
contain duplicate jars .
No t e
The download z ip’s binaries dire ctory contains far more jars the n
optaplanner-core actually us e s . It als o contains the jars us e d by othe r
module s , s uch as optaplanner-benchmark.
Che ck the Mave n re pos itory pom.xml file s to de te rmine the minimal
de pe nde ncy s e t for a s pe cific ve rs ion of a s pe cific module .
No t e
Bus ine s s Re s ource Planne r will be known as Planne r for the re s t of this
book.
9
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 2. QUICK START
2.1. CLOUD BALANCING T UT ORIAL
2.1.1. Problem Descript ion
Suppos e your company owns a numbe r of cloud compute rs and ne e ds to run a
numbe r of proce s s e s on thos e compute rs . As s ign e ach proce s s to a compute r
unde r the following four cons traints .
The following hard cons traints mus t be fulfille d:
Eve ry compute r mus t be able to handle the minimum hardware re quire me nts of
the s um of its proce s s e s :
The CPU powe r of a compute r mus t be at le as t the s um of the CPU powe r
re quire d by the proce s s e s as s igne d to that compute r.
The RAM me mory of a compute r mus t be at le as t the s um of the RAM
me mory re quire d by the proce s s e s as s igne d to that compute r.
The ne twork bandwidth of a compute r mus t be at le as t the s um of the
ne twork bandwidth re quire d by the proce s s e s as s igne d to that compute r.
The following s oft cons traints s hould be optimiz e d:
Each compute r that has one or more proce s s e s as s igne d, incurs a mainte nance
cos t (which is fixe d pe r compute r).
Minimiz e the total mainte nance cos t.
This proble m is a form of bin packing. The following is a s implifie d e xample , whe re
we as s ign four proce s s e s to two compute rs with two cons traints (CPU and RAM)
with a s imple algorithm:
10
CHAPT ER 2. Q UICK ST ART
The s imple algorithm us e d he re is the First Fit Decreasing algorithm, which as s igns
the bigge r proce s s e s firs t and as s igns the s malle r proce s s e s to the re maining
s pace . As you can s e e , it is not optimal, as it doe s not le ave e nough room to
as s ign the ye llow proce s s "D".
Planne r doe s find the more optimal s olution fas t by us ing additional, s marte r
algorithms . It als o s cale s : both in data (more proce s s e s , more compute rs ) and
cons traints (more hardware re quire me nts , othe r cons traints ). So s e e how Planne r
can be us e d in this s ce nario.
2.1.2. Problem Size
T able 2.1. Clo ud Balancing Pro blem Size
Pr o ble m Siz e
Co mput e r s
Pr o c e s s e s
Se ar c h Spac e
2com puters6processes
2
6
64
3com puters9processes
3
9
10^4
11
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Pr o ble m Siz e
Co mput e r s
Pr o c e s s e s
Se ar c h Spac e
4com puters012processes
4
12
10^7
100com puters300processes
100
300
10^600
200com puters600processes
200
600
10^1380
400com puters1200processes
400
1200
10^3122
800com puters2400processes
800
2400
10^6967
2.1.3. Domain Model Design
Be ginning with the domain mode l:
Computer: re pre s e nts a compute r with ce rtain hardware (CPU powe r, RAM
me mory, ne twork bandwidth) and mainte nance cos t.
Process: re pre s e nts a proce s s with a de mand. Ne e ds to be as s igne d to a
Computer by Planne r.
CloudBalance: re pre s e nts a proble m. Contains e ve ry Computer and Process
for a ce rtain data s e t.
12
CHAPT ER 2. Q UICK ST ART
In the UML clas s diagram above , the Planne r conce pts are alre ady annotate d:
Planning e ntity: the clas s (or clas s e s ) that change s during planning. In this
e xample , it is the clas s Process.
Planning variable : the prope rty (or prope rtie s ) of a planning e ntity clas s that
change s during planning. In this e xample , it is the prope rty computer on the
clas s Process.
Solution: the clas s that re pre s e nts a data s e t and contains all planning e ntitie s .
In this e xample that is the clas s CloudBalance.
2.1.4. Main Met hod
Try it yours e lf. Download and configure the e xample s in your pre fe rre d IDE. Run
org.optaplanner.examples.cloudbalancing.app.CloudBalancingHelloWorld.
By de fault, it is configure d to run for 120 s e conds . It will e xe cute this code :
Example 2.1. Clo udBalancingHello Wo rld.java
public class CloudBalancingHelloWorld {
public static void main(String[] args) {
// Build the Solver
SolverFactory<CloudBalance> solverFactory =
SolverFactory.createFromXmlResource(
13
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
"org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolve
rConfig.xml");
Solver<CloudBalance> solver = solverFactory.buildSolver();
// Load a problem with 400 computers and 1200 processes
CloudBalance unsolvedCloudBalance = new
CloudBalancingGenerator().createCloudBalance(400, 1200);
// Solve the problem
CloudBalance solvedCloudBalance =
solver.solve(unsolvedCloudBalance);
// Display the result
System.out.println("\nSolved cloudBalance with 400
computers and 1200 processes:\n"
+ toDisplayString(solvedCloudBalance));
}
...
}
The code e xample doe s the following:
Build the Solver bas e d on a s olve r configuration (in this cas e an XML file from
the clas s path).
SolverFactory<CloudBalance> solverFactory =
SolverFactory.createFromXmlResource(
"org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolve
rConfig.xml");
Solver solver<CloudBalance> = solverFactory.buildSolver();
Load the proble m. CloudBalancingGenerator ge ne rate s a random proble m:
you will re place this with a clas s that loads a re al proble m, for e xample from a
databas e .
CloudBalance unsolvedCloudBalance = new
CloudBalancingGenerator().createCloudBalance(400, 1200);
Solve the proble m.
CloudBalance solvedCloudBalance =
solver.solve(unsolvedCloudBalance);
Dis play the re s ult.
System.out.println("\nSolved cloudBalance with 400
computers and 1200 processes:\n"
+ toDisplayString(solvedCloudBalance));
The only complicate d part is building the Solver, as de taile d in the ne xt s e ction.
2.1.5. Solver Conf igurat ion
14
CHAPT ER 2. Q UICK ST ART
2.1.5. Solver Conf igurat ion
Take a look at the s olve r configuration:
Example 2.2. clo udBalancingSo lverCo nf ig.xml
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<!-- Domain model configuration -->
<scanAnnotatedClasses/>
<!-- Score configuration -->
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.s
olver.score.CloudBalancingEasyScoreCalculator</easyScoreCalculatorC
lass>
<!-<scoreDrl>org/optaplanner/examples/cloudbalancing/solver/cloudBalan
cingScoreRules.drl</scoreDrl>-->
</scoreDirectorFactory>
<!-- Optimization algorithms configuration -->
<termination>
<secondsSpentLimit>30</secondsSpentLimit>
</termination>
</solver>
This s olve r configuration cons is ts of thre e parts :
Domain model configuration: What can Planne r change ? We ne e d to make
Planne r aware of our domain clas s e s . In this configuration, it will automatically
s can all clas s e s in your clas s path (for an @PlanningEntity or
@PlanningSolution annotation):
<scanAnnotatedClasses/>
Score configuration: How s hould Planne r optimiz e the planning variable s ? What
is our goal? Since we have hard and s oft cons traints , we us e a HardSoftScore.
But we als o ne e d to te ll Planne r how to calculate the s core , de pe nding on our
bus ine s s re quire me nts . Furthe r down, we will look into two alte rnative s to
calculate the s core : us ing an e as y Java imple me ntation, or us ing Drools DRL.
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.s
olver.score.CloudBalancingEasyScoreCalculator</easyScoreCalculatorC
lass>
<!-<scoreDrl>org/optaplanner/examples/cloudbalancing/solver/cloudBalan
cingScoreRules.drl</scoreDrl>-->
</scoreDirectorFactory>
15
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Optimization algorithms configuration: How s hould Planne r optimiz e it? In this
cas e , we us e the de fault optimiz ation algorithms (be caus e no e xplicit
optimiz ation algorithms are configure d) for 30 s e conds :
<termination>
<secondsSpentLimit>30</secondsSpentLimit>
</termination>
Planne r s hould ge t a good re s ult in s e conds (and e ve n in le s s than 15
millis e conds with re al-time planning), but the more time it has , the be tte r the
re s ult will be . Advance d us e cas e s will like ly us e a diffe re nt te rmination crite ria
than a hard time limit.
The de fault algorithms will alre ady e as ily s urpas s human planne rs and mos t inhous e imple me ntations . Us e the Be nchmarke r to powe r twe ak to ge t e ve n
be tte r re s ults .
Le t’s e xamine the domain mode l clas s e s and the s core configuration.
2.1.6. Domain Model Implement at ion
2.1.6.1. T he Comput er Class
The Computer clas s is a POJO (Plain Old Java Obje ct). Us ually, you will have more of
this kind of clas s e s .
Example 2.3. Clo udCo mput er.java
public class CloudComputer ... {
private
private
private
private
int
int
int
int
cpuPower;
memory;
networkBandwidth;
cost;
... // getters
}
2.1.6.2. T he Process Class
The Process clas s is particularly important. We ne e d to te ll Planne r that it can
change the fie ld computer, s o we annotate the clas s with @PlanningEntity and
the ge tte r getComputer() with @PlanningVariable:
Example 2.4. Clo udPro cess.java
@PlanningEntity(...)
public class CloudProcess ... {
16
CHAPT ER 2. Q UICK ST ART
private int requiredCpuPower;
private int requiredMemory;
private int requiredNetworkBandwidth;
private CloudComputer computer;
... // getters
@PlanningVariable(valueRangeProviderRefs = {"computerRange"})
public CloudComputer getComputer() {
return computer;
}
public void setComputer(CloudComputer computer) {
computer = computer;
}
//
*******************************************************************
*****
// Complex methods
//
*******************************************************************
*****
...
}
The value s that Planne r can choos e from for the fie ld computer, are re trie ve d
from a me thod on the Solution imple me ntation:
CloudBalance.getComputerList(), which re turns a lis t of all compute rs in the
curre nt data s e t. The valueRangeProviderRefs prope rty is us e d to pas s this
information to the Planne r.
No t e
Ins te ad of ge tte r annotations , it is als o pos s ible to us e fie ld annotations .
2.1.6.3. T he CloudBalance Class
The CloudBalance clas s imple me nts the Solution inte rface . It holds a lis t of all
compute rs and proce s s e s . We ne e d to te ll Planne r how to re trie ve the colle ction
of proce s s e s that it can change , the re fore we mus t annotate the ge tte r
getProcessList with @PlanningEntityCollectionProperty.
The CloudBalance clas s als o has a prope rty score, which is the Score of that
Solution ins tance in its curre nt s tate :
Example 2.5. Clo udBalance.java
17
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
@PlanningSolution
public class CloudBalance ... implements Solution<HardSoftScore> {
private List<CloudComputer> computerList;
private List<CloudProcess> processList;
private HardSoftScore score;
@ValueRangeProvider(id = "computerRange")
public List<CloudComputer> getComputerList() {
return computerList;
}
@PlanningEntityCollectionProperty
public List<CloudProcess> getProcessList() {
return processList;
}
...
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
//
*******************************************************************
*****
// Complex methods
//
*******************************************************************
*****
public Collection<? extends Object> getProblemFacts() {
List<Object> facts = new ArrayList<Object>();
facts.addAll(computerList);
// Do not add the planning entity's (processList) because
that will be done automatically
return facts;
}
...
}
The getProblemFacts() me thod is only ne e de d for s core calculation with Drools .
It is not ne e de d for the othe r s core calculation type s .
2.1.7. Score Conf igurat ion
18
CHAPT ER 2. Q UICK ST ART
Planne r will s e arch for the Solution with the highe s t Score. This e xample us e s a
HardSoftScore, which me ans Planne r will look for the s olution with no hard
cons traints broke n (fulfill hardware re quire me nts ) and as little as pos s ible s oft
cons traints broke n (minimiz e mainte nance cos t).
Of cours e , Planne r ne e ds to be told about the s e domain-s pe cific s core cons traints .
The re are s e ve ral ways to imple me nt s uch a s core function:
Eas y Java
Incre me ntal Java
Drools
Le t’s take a look at two diffe re nt imple me ntations :
2.1.7.1. Easy Java Score Conf igurat ion
One way to de fine a s core function is to imple me nt the inte rface
EasyScoreCalculator in plain Java.
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.sol
ver.score.CloudBalancingEasyScoreCalculator</easyScoreCalculatorClass
>
</scoreDirectorFactory>
19
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Jus t imple me nt the calculateScore(Solution) me thod to re turn a
HardSoftScore ins tance .
Example 2.6. Clo udBalancingEasySco reCalculat o r.java
public class CloudBalancingEasyScoreCalculator implements
EasyScoreCalculator<CloudBalance> {
/**
* A very simple implementation. The double loop can easily be
removed by using Maps as shown in
* {@link
CloudBalancingMapBasedEasyScoreCalculator#calculateScore(CloudBalan
ce)}.
*/
public HardSoftScore calculateScore(CloudBalance cloudBalance)
{
int hardScore = 0;
int softScore = 0;
for (CloudComputer computer :
cloudBalance.getComputerList()) {
int cpuPowerUsage = 0;
int memoryUsage = 0;
int networkBandwidthUsage = 0;
boolean used = false;
// Calculate usage
for (CloudProcess process :
cloudBalance.getProcessList()) {
if (computer.equals(process.getComputer())) {
cpuPowerUsage += process.getRequiredCpuPower();
memoryUsage += process.getRequiredMemory();
networkBandwidthUsage +=
process.getRequiredNetworkBandwidth();
used = true;
}
}
// Hard constraints
int cpuPowerAvailable = computer.getCpuPower() cpuPowerUsage;
if (cpuPowerAvailable < 0) {
hardScore += cpuPowerAvailable;
}
int memoryAvailable = computer.getMemory() memoryUsage;
if (memoryAvailable < 0) {
hardScore += memoryAvailable;
}
int networkBandwidthAvailable =
computer.getNetworkBandwidth() - networkBandwidthUsage;
if (networkBandwidthAvailable < 0) {
hardScore += networkBandwidthAvailable;
}
20
CHAPT ER 2. Q UICK ST ART
// Soft constraints
if (used) {
softScore -= computer.getCost();
}
}
return HardSoftScore.valueOf(hardScore, softScore);
}
}
Eve n if we optimiz e the code above to us e Mapsto ite rate through the
processList only once , it is still slow be caus e it doe s not do incre me ntal s core
calculation. To fix that, e ithe r us e an incre me ntal Java s core function or a Drools
s core function. Le t’s take a look at the latte r.
2.1.7.2. Drools Score Conf igurat ion
To us e the Drools rule e ngine as a s core function, s imply add a scoreDrl
re s ource in the clas s path:
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<scoreDrl>org/optaplanner/examples/cloudbalancing/solver/cloudBalanci
ngScoreRules.drl</scoreDrl>
</scoreDirectorFactory>
Firs t, we want to make s ure that all compute rs have e nough CPU, RAM and ne twork
bandwidth to s upport all the ir proce s s e s , s o we make the s e hard cons traints :
Example 2.7. clo udBalancingSco reRules.drl - Hard Co nst raint s
...
import
org.optaplanner.examples.cloudbalancing.domain.CloudBalance;
import
org.optaplanner.examples.cloudbalancing.domain.CloudComputer;
import
org.optaplanner.examples.cloudbalancing.domain.CloudProcess;
global HardSoftScoreHolder scoreHolder;
//
#################################################################
###########
// Hard constraints
//
#################################################################
###########
21
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
rule "requiredCpuPowerTotal"
when
$computer : CloudComputer($cpuPower : cpuPower)
$requiredCpuPowerTotal : Number(intValue > $cpuPower)
from accumulate(
CloudProcess(
computer == $computer,
$requiredCpuPower : requiredCpuPower),
sum($requiredCpuPower)
)
then
scoreHolder.addHardConstraintMatch(kcontext, $cpuPower $requiredCpuPowerTotal.intValue());
end
rule "requiredMemoryTotal"
...
end
rule "requiredNetworkBandwidthTotal"
...
end
Ne xt, if thos e cons traints are me t, we want to minimiz e the mainte nance cos t, s o
we add that as a s oft cons traint:
Example 2.8. clo udBalancingSco reRules.drl - So f t Co nst raint s
//
#################################################################
###########
// Soft constraints
//
#################################################################
###########
rule "computerCost"
when
$computer : CloudComputer($cost : cost)
exists CloudProcess(computer == $computer)
then
scoreHolder.addSoftConstraintMatch(kcontext, - $cost);
end
If you us e the Drools rule e ngine for s core calculation, you can inte grate with othe r
Drools te chnologie s , s uch as de cis ion table s (XLS or we b bas e d), the KIE
Workbe nch, …​
2.1.8. Beyond t his T ut orial
22
CHAPT ER 2. Q UICK ST ART
Now that this s imple e xample works , try going furthe r. Enrich the domain mode l
and add e xtra cons traints s uch as the s e :
Each Process be longs to a Service. A compute r might cras h, s o proce s s e s
running the s ame s e rvice s hould be as s igne d to diffe re nt compute rs .
Each Computer is locate d in a Building. A building might burn down, s o
proce s s e s of the s ame s e rvice s s hould be as s igne d to compute rs in diffe re nt
buildings .
23
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 3. USE CASES AND EXAMPLES
3.1. EXAMPLES OVERVIEW
Planne r has s e ve ral e xample s . In this manual we e xplain mainly us ing the n
que e ns e xample and cloud balancing e xample . So it’s advis able to re ad at le as t
thos e s e ctions .
The s ource code of all the s e e xample s is available in the dis tribution z ip unde r
examples/sources and als o in git unde r optaplanner/optaplanner-examples.
T able 3.1. Examples Overview
Example
N queens
Do main
1 entity
class
1 variable
Siz e
Entity ⇐ 256
Value ⇐ 256
Co mpe t it io n
?
P ointless
(cheatable)
Spe c ial
f e at ur e s
us e d
None
Search
space ⇐
10^616
C loud
balancing
1 entity
class
Entity ⇐
No
1 variable
Value ⇐ 800
Defined by
us
2400
Real-tim e
planning
Search
space ⇐
10^6967
Traveling
salesm an
1 entity
class
1 chained
variable
Entity ⇐ 980
Unrealistic
Value ⇐ 980
TSP web
Real-tim e
planning
Search
space ⇐
10^2927
Dinner party
1 entity
class
1 variable
Entity ⇐ 144
Value ⇐ 72
Search
space ⇐
10^310
24
Unrealistic
Decision
Table
spreadshee
t (XLS) for
score
constraints
CHAPT ER 3. USE CASES AND EXAMPLES
Example
Tennis club
scheduling
Do main
1 entity
class
1 variable
Siz e
Co mpe t it io n
?
Entity ⇐ 72
No
Value ⇐ 7
Defined by
us
Search
space ⇐
1 entity
class
2 variables
Fairness
score
constraints
Im m ovable
entities
10^60
Meeting
scheduling
Spe c ial
f e at ur e s
us e d
Entity ⇐ 10
No
Value ⇐ 320
and ⇐ 5
Defined by
us
Tim eGrain
pattern
Search
space ⇐
10^320
C ourse
tim etabling
1 entity
class
2 variables
Entity ⇐ 434
Realistic
Value ⇐ 25
and ⇐ 20
ITC 2007
track 3
Im m ovable
entities
Search
space ⇐
10^1171
Machine
reassignm ent
1 entity
class
Entity ⇐
50000
Nearly
realistic
1 variable
Value ⇐
5000
RO ADEF
2012
Real-tim e
planning
Search
space ⇐
10^184948
Vehicle
routing
1 entity
class
1 chained
variable
1 shadow
entity class
1 autom atic
shadow
variable
Entity ⇐ 134
Unrealistic
Value ⇐ 141
VRP web
Search
space ⇐
10^285
Shadow
variable
Real-tim e
planning
Nearby
selection
Real road
distances
25
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Example
Do main
Vehicle
routing with
tim e windows
Extra on
Vehicle
routing:
1 shadow
variable
Siz e
Entity ⇐
1000
Co mpe t it io n
?
Unrealistic
VRP web
Value ⇐
1250
Spe c ial
f e at ur e s
us e d
Extra on
Vehicle
routing:
C ustom
VariableList
ener
Search
space ⇐
10^3000
P roject job
scheduling
1 entity
class
Entity ⇐ 640
2 variables
Value ⇐ ?
and ⇐ ?
1 shadow
variable
Search
space ⇐ ?
Nearly
realistic
Bendable
score
MISTA 2013
C ustom
VariableList
ener
ValueRange
Factory
Hospital bed
planning
1 entity
class
Entity ⇐
1 nullable
variable
Value ⇐ 471
2750
Unrealistic
Kaho P AS
O verconstr
ained
planning
Search
space ⇐
10^6851
Exam
tim etabling
2 entity
classes
(sam e
hierarchy)
2 variables
Entity ⇐
1096
Value ⇐ 80
and ⇐ 49
realistic
ITC 2007
track 1
C ustom
VariableList
ener
Search
space ⇐
10^3374
Em ployee
rostering
1 entity
class
1 variable
Entity ⇐ 752
realistic
Value ⇐ 50
INRC 2010
Search
space ⇐
10^1277
26
C ontinuous
planning
Real-tim e
planning
CHAPT ER 3. USE CASES AND EXAMPLES
Example
Do main
Traveling
tournam ent
Siz e
1 entity
class
Entity ⇐
1 variable
Value ⇐ 78
Co mpe t it io n
?
TTP
C ustom
MoveListFa
ctory
Nearly
realistic
Field
annotations
IC O N
Energy
ValueRange
Factory
Entity ⇐ 11
No
Value =
1000
Defined by
us
ValueRange
Factory
1560
Unrealistic
Spe c ial
f e at ur e s
us e d
Search
space ⇐
10^2951
C heap tim e
scheduling
1 entity
class
2 variables
Entity ⇐ 500
Value ⇐ 100
and ⇐ 288
Search
space ⇐
10^20078
Investm ent
1 entity
class
1 variable
Search
space ⇐
10^4
A realistic competition is an official, inde pe nde nt compe tition:
that cle arly de fine s a re al-word us e cas e
with re al-world cons traints
with multiple , re al-world datas e ts
that e xpe cts re producible re s ults within a s pe cific time limit on s pe cific
hardware
that has had s e rious participation from the acade mic and/or e nte rpris e
Ope rations Re s e arch community
The s e re alis tic compe titions provide an obje ctive comparis on of Planne r with
compe titive s oftware and acade mic re s e arch.
3.2. BASIC EXAMPLES
3.2.1. N Queens
3.2.1.1. Problem Descript ion
27
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Place n que e ns on a n s iz e d che s s board s o no 2 que e ns can attack e ach othe r.
The mos t common n que e ns puz z le is the 8 que e ns puz z le , with n = 8:
Cons traints :
Us e a che s s board of n columns and n rows .
Place n que e ns on the che s s board.
No 2 que e ns can attack e ach othe r. A que e n can attack any othe r que e n on the
s ame horiz ontal, ve rtical or diagonal line .
This docume ntation he avily us e s the 4 que e ns puz z le as the primary e xample .
A propos e d s olution could be :
Figure 3.1. A Wro ng So lut io n f o r t he 4 Queens Puzzle
28
CHAPT ER 3. USE CASES AND EXAMPLES
The above s olution is wrong be caus e que e ns A1 and B0 can attack e ach othe r (s o
can que e ns B0 and D0). Re moving que e n B0 would re s pe ct the "no 2 que e ns can
attack e ach othe r" cons traint, but would bre ak the "place n que e ns " cons traint.
Be low is a corre ct s olution:
Figure 3.2. A Co rrect So lut io n f o r t he 4 Queens Puzzle
All the cons traints have be e n me t, s o the s olution is corre ct. Note that mos t n
que e ns puz z le s have multiple corre ct s olutions . We ’ll focus on finding a s ingle
corre ct s olution for a give n n, not on finding the numbe r of pos s ible corre ct
s olutions for a give n n.
3.2.1.2. Problem Size
4queens
8queens
16queens
32queens
64queens
256queens
has
4
has
8
has 16
has 32
has 64
has 256
queens
queens
queens
queens
queens
queens
with
with
with
with
with
with
a
a
a
a
a
a
search
search
search
search
search
search
space
space
space
space
space
space
of
256.
of
10^7.
of 10^19.
of 10^48.
of 10^115.
of 10^616.
The imple me ntation of the N que e ns e xample has not be e n optimiz e d be caus e it
functions as a be ginne r e xample . Ne ve rthe le s s , it can e as ily handle 64 que e ns .
With a fe w change s it has be e n s hown to e as ily handle 5000 que e ns and more .
3.2.1.3. Domain Model
Us e a good domain mode l: it will be e as ie r to unde rs tand and s olve your planning
proble m. This is the domain mode l for the n que e ns e xample :
public class Column {
private int index;
// ... getters and setters
}
public class Row {
private int index;
29
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
// ... getters and setters
}
public class Queen {
private Column column;
private Row row;
public int getAscendingDiagonalIndex() {...}
public int getDescendingDiagonalIndex() {...}
// ... getters and setters
}
A Queen ins tance has a Column (for e xample : 0 is column A, 1 is column B, …​) and
a Row (its row, for e xample : 0 is row 0, 1 is row 1, …​). Bas e d on the column and the
row, the as ce nding diagonal line as we ll as the de s ce nding diagonal line can be
calculate d. The column and row inde xe s s tart from the uppe r le ft corne r of the
che s s board.
public class NQueens implements Solution<SimpleScore> {
private int n;
private List<Column> columnList;
private List<Row> rowList;
private List<Queen> queenList;
private SimpleScore score;
// ... getters and setters
}
A s ingle NQueens ins tance contains a lis t of all Queen ins tance s . It is the Solution
imple me ntation which will be s upplie d to, s olve d by and re trie ve d from the Solve r.
Notice that in the 4 que e ns e xample , NQue e ns ’s getN() me thod will always re turn
4.
T able 3.2. A So lut io n f o r 4 Queens Sho wn in t he Do main Mo del
30
CHAPT ER 3. USE CASES AND EXAMPLES
A s o lut io n
Q ue e n
c o lumnInd
ex
r o wInde x
as c e nding
Diago nalI
nde x
(c o lumnIn
de x +
r o wInde x)
de s c e ndi
ngDiago n
alInde x
(c o lumnIn
de x r o wInde x)
A1
0
1
1 (**)
-1
B0
1
0 (*)
1 (**)
1
C2
2
2
4
0
D0
3
0 (*)
3
3
Whe n 2 que e ns s hare the s ame column, row or diagonal line , s uch as (*) and (**),
the y can attack e ach othe r.
3.2.2. Cloud Balancing
This e xample is e xplaine d in a tutorial.
3.2.3. T raveling Salesman (T SP - T raveling Salesman Problem)
3.2.3.1. Problem Descript ion
Give n a lis t of citie s , find the s horte s t tour for a s ale s man that vis its e ach city
e xactly once .
The proble m is de fine d by Wikipe dia. It is one of the mos t inte ns ive ly s tudie d
proble ms in computational mathe matics . Ye t, in the re al world, it’s ofte n only part
of a planning proble m, along with othe r cons traints , s uch as e mploye e s hift
ros te ring cons traints .
3.2.3.2. Problem Size
dj38
europe40
st70
pcb442
lu980
has 38 cities
has 40 cities
has 70 cities
has 442 cities
has 980 cities
with
with
with
with
with
a
a
a
a
a
search
search
search
search
search
space
space
space
space
space
of
10^58.
of
10^62.
of 10^126.
of 10^1166.
of 10^2927.
3.2.3.3. Problem Dif f icult y
31
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
De s pite TSP’s s imple de finition, the proble m is s urpris ingly hard to s olve . Be caus e
it’s an NP-hard proble m (like mos t planning proble ms ), the optimal s olution for a
s pe cific proble m datas e t can change a lot whe n that proble m datas e t is s lightly
alte re d:
3.2.4. Dinner Part y
3.2.4.1. Problem Descript ion
Mis s Manne rs is throwing anothe r dinne r party.
This time s he invite d 144 gue s ts and pre pare d 12 round table s with 12 s e ats
e ach.
Eve ry gue s t s hould s it ne xt to s ome one (le ft and right) of the oppos ite ge nde r.
And that ne ighbour s hould have at le as t one hobby in common with the gue s t.
At e ve ry table , the re s hould be 2 politicians , 2 doctors , 2 s ocialite s , 2 coache s , 2
te ache rs and 2 programme rs .
And the 2 politicians , 2 doctors , 2 coache s and 2 programme rs s houldn’t be the
s ame kind at a table .
Drools Expe rt als o has the normal Mis s Manne rs e xample (which is much s malle r)
and e mploys an e xhaus tive he uris tic to s olve it. Planne r’s imple me ntation is far
more s calable be caus e it us e s he uris tics to find the be s t s olution and Drools
Expe rt to calculate the s core of e ach s olution.
32
CHAPT ER 3. USE CASES AND EXAMPLES
3.2.4.2. Problem Size
wedding01 has 18 jobs, 144 guests, 288 hobby practicians, 12 tables
and 144 seats with a search space of 10^310.
3.2.5. T ennis Club Scheduling
3.2.5.1. Problem Descript ion
Eve ry we e k the te nnis club has 4 te ams playing round robin agains t e ach othe r.
As s ign thos e 4 s pots to the te ams fairly.
Hard cons traints :
Conflict: A te am can only play once pe r day.
Unavailability: Some te ams are unavailable on s ome date s .
Me dium cons traints :
Fair as s ignme nt: All te ams s hould play an (almos t) e qual numbe r of time s .
Soft cons traints :
Eve nly confrontation: Each te am s hould play agains t e ve ry othe r te am an e qual
numbe r of time s .
3.2.5.2. Problem Size
munich-7teams has 7 teams, 18 days, 12 unavailabilityPenalties and
72 teamAssignments with a search space of 10^60.
3.2.5.3. Domain Model
33
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
3.2.6. Meet ing Scheduling
3.2.6.1. Problem Descript ion
As s ign e ach me e ting to a s tarting time and a room. Me e tings have diffe re nt
durations .
Hard cons traints :
Room conflict: 2 me e tings mus t not us e the s ame room at the s ame time .
Re quire d atte ndance : A pe rs on cannot have 2 re quire d me e tings at the s ame
time .
Me dium cons traints :
Pre fe rre d atte ndance : A pe rs on cannot have 2 pre fe rre d me e tings at the s ame
time , nor a pre fe rre d and a re quire d me e ting at the s ame time .
Soft cons traints :
Soone r rathe r than late r: Sche dule all me e tings as s oon as pos s ible .
3.2.6.2. Problem Size
34
CHAPT ER 3. USE CASES AND EXAMPLES
50meetings-160timegrains-5rooms has 50 meetings, 160 timeGrains
and 5 rooms with a search space of 10^145.
100meetings-320timegrains-5rooms has 100 meetings, 320 timeGrains
and 5 rooms with a search space of 10^320.
3.3. REAL EXAMPLES
3.3.1. Course T imet abling (IT C 2007 T rack 3 - Curriculum Course
Scheduling)
3.3.1.1. Problem Descript ion
Sche dule e ach le cture into a time s lot and into a room.
Hard cons traints :
Te ache r conflict: A te ache r mus t not have 2 le cture s in the s ame pe riod.
Curriculum conflict: A curriculum mus t not have 2 le cture s in the s ame pe riod.
Room occupancy: 2 le cture s mus t not be in the s ame room in the s ame pe riod.
Unavailable pe riod (s pe cifie d pe r datas e t): A s pe cific le cture mus t not be
as s igne d to a s pe cific pe riod.
Soft cons traints :
Room capacity: A room’s capacity s hould not be le s s than the numbe r of
s tude nts in its le cture .
Minimum working days : Le cture s of the s ame cours e s hould be s pre ad out into
a minimum numbe r of days .
Curriculum compactne s s : Le cture s be longing to the s ame curriculum s hould be
adjace nt to e ach othe r (s o in cons e cutive pe riods ).
Room s tability: Le cture s of the s ame cours e s hould be as s igne d the s ame
room.
The proble m is de fine d by the Inte rnational Time tabling Compe tition 2007 track 3.
3.3.1.2. Problem Size
comp01 has 24 teachers,
30 periods, 6 rooms and
search space of 10^360.
comp02 has 71 teachers,
25 periods, 16 rooms and
search space of 10^736.
comp03 has 61 teachers,
25 periods, 16 rooms and
search space of 10^653.
comp04 has 70 teachers,
25 periods, 18 rooms and
search space of 10^758.
14 curricula, 30 courses, 160 lectures,
53 unavailable period constraints with a
70 curricula, 82 courses, 283 lectures,
513 unavailable period constraints with a
68 curricula, 72 courses, 251 lectures,
382 unavailable period constraints with a
57 curricula, 79 courses, 286 lectures,
396 unavailable period constraints with a
35
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
comp05 has 47 teachers, 139 curricula, 54 courses, 152 lectures,
36 periods, 9 rooms and 771 unavailable period constraints with
search space of 10^381.
comp06 has 87 teachers, 70 curricula, 108 courses, 361 lectures,
25 periods, 18 rooms and 632 unavailable period constraints with
search space of 10^957.
comp07 has 99 teachers, 77 curricula, 131 courses, 434 lectures,
25 periods, 20 rooms and 667 unavailable period constraints with
search space of 10^1171.
comp08 has 76 teachers, 61 curricula, 86 courses, 324 lectures,
25 periods, 18 rooms and 478 unavailable period constraints with
search space of 10^859.
comp09 has 68 teachers, 75 curricula, 76 courses, 279 lectures,
25 periods, 18 rooms and 405 unavailable period constraints with
search space of 10^740.
comp10 has 88 teachers, 67 curricula, 115 courses, 370 lectures,
25 periods, 18 rooms and 694 unavailable period constraints with
search space of 10^981.
comp11 has 24 teachers, 13 curricula, 30 courses, 162 lectures,
45 periods, 5 rooms and
94 unavailable period constraints with
search space of 10^381.
comp12 has 74 teachers, 150 curricula, 88 courses, 218 lectures,
36 periods, 11 rooms and 1368 unavailable period constraints with
search space of 10^566.
comp13 has 77 teachers, 66 curricula, 82 courses, 308 lectures,
25 periods, 19 rooms and 468 unavailable period constraints with
search space of 10^824.
comp14 has 68 teachers, 60 curricula, 85 courses, 275 lectures,
25 periods, 17 rooms and 486 unavailable period constraints with
search space of 10^722.
3.3.1.3. Domain Model
36
a
a
a
a
a
a
a
a
a
a
CHAPT ER 3. USE CASES AND EXAMPLES
3.3.2. Machine Reassignment (Google ROADEF 2012)
3.3.2.1. Problem Descript ion
As s ign e ach proce s s to a machine . All proce s s e s alre ady have an original
(unoptimiz e d) as s ignme nt. Each proce s s re quire s an amount of e ach re s ource
(s uch as CPU, RAM, …​). This is a more comple x ve rs ion of the Cloud Balancing
e xample .
Hard cons traints :
Maximum capacity: The maximum capacity for e ach re s ource for e ach machine
mus t not be e xce e de d.
Conflict: Proce s s e s of the s ame s e rvice mus t run on dis tinct machine s .
Spre ad: Proce s s e s of the s ame s e rvice mus t be s pre ad out acros s locations .
De pe nde ncy: The proce s s e s of a s e rvice de pe nding on anothe r s e rvice mus t
run in the ne ighborhood of a proce s s of the othe r s e rvice .
Trans ie nt us age : Some re s ource s are trans ie nt and count towards the
maximum capacity of both the original machine as the ne wly as s igne d machine .
Soft cons traints :
Load: The s afe ty capacity for e ach re s ource for e ach machine s hould not be
e xce e de d.
37
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Balance : Le ave room for future as s ignme nts by balancing the available
re s ource s on e ach machine .
Proce s s move cos t: A proce s s has a move cos t.
Se rvice move cos t: A s e rvice has a move cos t.
Machine move cos t: Moving a proce s s from machine A to machine B has
anothe r A-B s pe cific move cos t.
The proble m is de fine d by the Google ROADEF/EURO Challe nge 2012.
3.3.2.2. Problem Size
model_a1_1 has 2 resources, 1 neighborhoods,
machines,
79 services,
100 processes and 1
with a search space of
10^60.
model_a1_2 has 4 resources, 2 neighborhoods,
machines,
980 services, 1000 processes and 0
with a search space of
10^2000.
model_a1_3 has 3 resources, 5 neighborhoods,
machines,
216 services, 1000 processes and 0
with a search space of
10^2000.
model_a1_4 has 3 resources, 50 neighborhoods,
machines,
142 services, 1000 processes and 1
with a search space of
10^1698.
model_a1_5 has 4 resources, 2 neighborhoods,
machines,
981 services, 1000 processes and 1
with a search space of
10^1079.
model_a2_1 has 3 resources, 1 neighborhoods,
machines, 1000 services, 1000 processes and 0
with a search space of
10^2000.
model_a2_2 has 12 resources, 5 neighborhoods,
machines,
170 services, 1000 processes and 0
with a search space of
10^2000.
model_a2_3 has 12 resources, 5 neighborhoods,
machines,
129 services, 1000 processes and 0
with a search space of
10^2000.
model_a2_4 has 12 resources, 5 neighborhoods,
machines,
180 services, 1000 processes and 1
with a search space of
10^1698.
model_a2_5 has 12 resources, 5 neighborhoods,
machines,
153 services, 1000 processes and 0
with a search space of
10^1698.
model_b_1 has 12 resources, 5 neighborhoods,
machines, 2512 services, 5000 processes and 0
with a search space of 10^10000.
model_b_2 has 12 resources, 5 neighborhoods,
machines, 2462 services, 5000 processes and 1
with a search space of 10^10000.
model_b_3 has 6 resources, 5 neighborhoods,
machines, 15025 services, 20000 processes and 0
with a search space of 10^40000.
model_b_4 has 6 resources, 5 neighborhoods,
machines, 1732 services, 20000 processes and 1
with a search space of 10^53979.
38
4 locations,
4
balancePenalties
4 locations, 100
balancePenalties
25 locations, 100
balancePenalties
50 locations,
50
balancePenalties
4 locations,
12
balancePenalties
1 locations, 100
balancePenalties
25 locations, 100
balancePenalties
25 locations, 100
balancePenalties
25 locations,
50
balancePenalties
25 locations,
50
balancePenalties
10 locations, 100
balancePenalties
10 locations, 100
balancePenalties
10 locations, 100
balancePenalties
50 locations, 500
balancePenalties
CHAPT ER 3. USE CASES AND EXAMPLES
model_b_5 has 6 resources, 5 neighborhoods, 10 locations, 100
machines, 35082 services, 40000 processes and 0 balancePenalties
with a search space of 10^80000.
model_b_6 has 6 resources, 5 neighborhoods, 50 locations, 200
machines, 14680 services, 40000 processes and 1 balancePenalties
with a search space of 10^92041.
model_b_7 has 6 resources, 5 neighborhoods, 50 locations, 4000
machines, 15050 services, 40000 processes and 1 balancePenalties
with a search space of 10^144082.
model_b_8 has 3 resources, 5 neighborhoods, 10 locations, 100
machines, 45030 services, 50000 processes and 0 balancePenalties
with a search space of 10^100000.
model_b_9 has 3 resources, 5 neighborhoods, 100 locations, 1000
machines, 4609 services, 50000 processes and 1 balancePenalties
with a search space of 10^150000.
model_b_10 has 3 resources, 5 neighborhoods, 100 locations, 5000
machines, 4896 services, 50000 processes and 1 balancePenalties
with a search space of 10^184948.
3.3.2.3. Domain Model
3.3.3. Vehicle Rout ing
3.3.3.1. Problem Descript ion
39
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Us ing a fle e t of ve hicle s , pick up the obje cts of e ach cus tome r and bring the m to
the de pot. Each ve hicle can s e rvice multiple cus tome rs , but it has a limite d
capacity.
Be s ide s the bas ic cas e (CVRP), the re is als o a variant with time windows
(CVRPTW).
Hard cons traints :
Ve hicle capacity: a ve hicle cannot carry more ite ms than its capacity.
Time windows (only in CVRPTW):
Trave l time : Trave ling from one location to anothe r take s time .
Cus tome r s e rvice duration: a ve hicle mus t s tay at the cus tome r for the
le ngth of the s e rvice duration.
Cus tome r re ady time : a ve hicle may arrive be fore the cus tome r’s re ady
time , but it mus t wait until the re ady time be fore s e rvicing.
Cus tome r due time : a ve hicle mus t arrive on time , be fore the cus tome r’s
due time .
40
CHAPT ER 3. USE CASES AND EXAMPLES
Soft cons traints :
Total dis tance : minimiz e the total dis tance drive n (fue l cons umption) of all
ve hicle s .
The capacitate d ve hicle routing proble m (CVRP) and its time windowe d variant
(CVRPTW) are de fine d by the VRP we b.
3.3.3.2. Problem Size
CVRP ins tance s (without time windows ):
A-n32-k5 has 1 depots, 5
space of 10^46.
A-n33-k5 has 1 depots, 5
space of 10^48.
A-n33-k6 has 1 depots, 6
space of 10^48.
A-n34-k5 has 1 depots, 5
space of 10^50.
A-n36-k5 has 1 depots, 5
space of 10^54.
A-n37-k5 has 1 depots, 5
space of 10^56.
A-n37-k6 has 1 depots, 6
space of 10^56.
A-n38-k5 has 1 depots, 5
space of 10^58.
A-n39-k5 has 1 depots, 5
space of 10^60.
A-n39-k6 has 1 depots, 6
space of 10^60.
A-n44-k7 has 1 depots, 7
space of 10^70.
A-n45-k6 has 1 depots, 6
space of 10^72.
A-n45-k7 has 1 depots, 7
space of 10^72.
A-n46-k7 has 1 depots, 7
space of 10^74.
A-n48-k7 has 1 depots, 7
space of 10^78.
A-n53-k7 has 1 depots, 7
space of 10^89.
A-n54-k7 has 1 depots, 7
space of 10^91.
A-n55-k9 has 1 depots, 9
space of 10^93.
A-n60-k9 has 1 depots, 9
space of 10^104.
A-n61-k9 has 1 depots, 9
space of 10^106.
A-n62-k8 has 1 depots, 8
space of 10^108.
A-n63-k10 has 1 depots, 10
space of 10^111.
vehicles and
31 customers with a search
vehicles and
32 customers with a search
vehicles and
32 customers with a search
vehicles and
33 customers with a search
vehicles and
35 customers with a search
vehicles and
36 customers with a search
vehicles and
36 customers with a search
vehicles and
37 customers with a search
vehicles and
38 customers with a search
vehicles and
38 customers with a search
vehicles and
43 customers with a search
vehicles and
44 customers with a search
vehicles and
44 customers with a search
vehicles and
45 customers with a search
vehicles and
47 customers with a search
vehicles and
52 customers with a search
vehicles and
53 customers with a search
vehicles and
54 customers with a search
vehicles and
59 customers with a search
vehicles and
60 customers with a search
vehicles and
61 customers with a search
vehicles and
62 customers with a search
41
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
A-n63-k9 has 1 depots, 9 vehicles and 62 customers with
space of 10^111.
A-n64-k9 has 1 depots, 9 vehicles and 63 customers with
space of 10^113.
A-n65-k9 has 1 depots, 9 vehicles and 64 customers with
space of 10^115.
A-n69-k9 has 1 depots, 9 vehicles and 68 customers with
space of 10^124.
A-n80-k10 has 1 depots, 10 vehicles and 79 customers with
space of 10^149.
F-n135-k7 has 1 depots, 7 vehicles and 134 customers with
space of 10^285.
F-n45-k4 has 1 depots, 4 vehicles and 44 customers with
space of 10^72.
F-n72-k4 has 1 depots, 4 vehicles and 71 customers with
space of 10^131.
CVRPTW ins tance s (with time windows ):
Solomon_025_C101
has 1 depots, 25 vehicles
customers with a search space of
10^34.
Solomon_025_C201
has 1 depots, 25 vehicles
customers with a search space of
10^34.
Solomon_025_R101
has 1 depots, 25 vehicles
customers with a search space of
10^34.
Solomon_025_R201
has 1 depots, 25 vehicles
customers with a search space of
10^34.
Solomon_025_RC101
has 1 depots, 25 vehicles
customers with a search space of
10^34.
Solomon_025_RC201
has 1 depots, 25 vehicles
customers with a search space of
10^34.
Solomon_100_C101
has 1 depots, 25 vehicles
customers with a search space of 10^200.
Solomon_100_C201
has 1 depots, 25 vehicles
customers with a search space of 10^200.
Solomon_100_R101
has 1 depots, 25 vehicles
customers with a search space of 10^200.
Solomon_100_R201
has 1 depots, 25 vehicles
customers with a search space of 10^200.
Solomon_100_RC101
has 1 depots, 25 vehicles
customers with a search space of 10^200.
Solomon_100_RC201
has 1 depots, 25 vehicles
customers with a search space of 10^200.
Homberger_0200_C1_2_1 has 1 depots, 50 vehicles
customers with a search space of 10^460.
Homberger_0200_C2_2_1 has 1 depots, 50 vehicles
customers with a search space of 10^460.
Homberger_0200_R1_2_1 has 1 depots, 50 vehicles
customers with a search space of 10^460.
Homberger_0200_R2_2_1 has 1 depots, 50 vehicles
customers with a search space of 10^460.
Homberger_0200_RC1_2_1 has 1 depots, 50 vehicles
customers with a search space of 10^460.
Homberger_0200_RC2_2_1 has 1 depots, 50 vehicles
customers with a search space of 10^460.
Homberger_0400_C1_4_1 has 1 depots, 100 vehicles
42
and
25
and
25
and
25
and
25
and
25
and
25
and
100
and
100
and
100
and
100
and
100
and
100
and
200
and
200
and
200
and
200
and
200
and
200
and
400
a search
a search
a search
a search
a search
a search
a search
a search
CHAPT ER 3. USE CASES AND EXAMPLES
customers with a search space of 10^1040.
Homberger_0400_C2_4_1 has 1 depots, 100 vehicles
customers with a search space of 10^1040.
Homberger_0400_R1_4_1 has 1 depots, 100 vehicles
customers with a search space of 10^1040.
Homberger_0400_R2_4_1 has 1 depots, 100 vehicles
customers with a search space of 10^1040.
Homberger_0400_RC1_4_1 has 1 depots, 100 vehicles
customers with a search space of 10^1040.
Homberger_0400_RC2_4_1 has 1 depots, 100 vehicles
customers with a search space of 10^1040.
Homberger_0600_C1_6_1 has 1 depots, 150 vehicles
customers with a search space of 10^1666.
Homberger_0600_C2_6_1 has 1 depots, 150 vehicles
customers with a search space of 10^1666.
Homberger_0600_R1_6_1 has 1 depots, 150 vehicles
customers with a search space of 10^1666.
Homberger_0600_R2_6_1 has 1 depots, 150 vehicles
customers with a search space of 10^1666.
Homberger_0600_RC1_6_1 has 1 depots, 150 vehicles
customers with a search space of 10^1666.
Homberger_0600_RC2_6_1 has 1 depots, 150 vehicles
customers with a search space of 10^1666.
Homberger_0800_C1_8_1 has 1 depots, 200 vehicles
customers with a search space of 10^2322.
Homberger_0800_C2_8_1 has 1 depots, 200 vehicles
customers with a search space of 10^2322.
Homberger_0800_R1_8_1 has 1 depots, 200 vehicles
customers with a search space of 10^2322.
Homberger_0800_R2_8_1 has 1 depots, 200 vehicles
customers with a search space of 10^2322.
Homberger_0800_RC1_8_1 has 1 depots, 200 vehicles
customers with a search space of 10^2322.
Homberger_0800_RC2_8_1 has 1 depots, 200 vehicles
customers with a search space of 10^2322.
Homberger_1000_C110_1 has 1 depots, 250 vehicles
customers with a search space of 10^3000.
Homberger_1000_C210_1 has 1 depots, 250 vehicles
customers with a search space of 10^3000.
Homberger_1000_R110_1 has 1 depots, 250 vehicles
customers with a search space of 10^3000.
Homberger_1000_R210_1 has 1 depots, 250 vehicles
customers with a search space of 10^3000.
Homberger_1000_RC110_1 has 1 depots, 250 vehicles
customers with a search space of 10^3000.
Homberger_1000_RC210_1 has 1 depots, 250 vehicles
customers with a search space of 10^3000.
and
400
and
400
and
400
and
400
and
400
and
600
and
600
and
600
and
600
and
600
and
600
and
800
and
800
and
800
and
800
and
800
and
800
and 1000
and 1000
and 1000
and 1000
and 1000
and 1000
3.3.3.3. Domain Model
43
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The ve hicle routing with time windows domain mode l make s he avily us e of s hadow
variable s . This allows it to e xpre s s its cons traints more naturally, be caus e
prope rtie s s uch as arrivalTime and departureTime, are dire ctly available on the
domain mode l.
3.3.3.4. Road Dist ances Inst ead of Air Dist ances
In the re al world, ve hicle s can’t follow a s traight line from location to location: the y
have to us e roads and highways . From a bus ine s s point of vie w, this matte rs a lot:
44
CHAPT ER 3. USE CASES AND EXAMPLES
For the optimiz ation algorithm, this doe s n’t matte r much, as long as the dis tance
be twe e n 2 points can be looke d up (and are pre fe rably pre calculate d). The road
cos t doe s n’t e ve n ne e d to be a dis tance , it can als o be trave l time , fue l cos t, or a
we ighte d function of thos e . The re are s e ve ral te chnologie s available to
pre calculate road cos ts , s uch as GraphHoppe r (e mbe ddable , offline Java e ngine ),
Ope n MapQue s t (we b s e rvice ) and Google Maps Clie nt API (we b s e rvice ).
45
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The re are als o s e ve ral te chnologie s to re nde r it, s uch as Le afle t and Google Maps
for de ve lope rs : the optaplanner-webexamples-*.war has an e xample which
de mons trate s s uch re nde ring:
46
CHAPT ER 3. USE CASES AND EXAMPLES
It’s e ve n pos s ible to re nde r the actual road route s with GraphHoppe r or Google
Map Dire ctions , but be caus e of route ove rlaps on highways , it can be come harde r
to s e e the s tands till orde r:
47
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Take s pe cial care that the road cos ts be twe e n 2 points us e the s ame optimiz ation
crite ria as the one us e d in Planne r. For e xample , GraphHoppe r e tc will by de fault
re turn the fas te s t route , not the s horte s t route . Don’t us e the km (or mile s )
dis tance s of the fas te s t GPS route s to optimiz e the s horte s t trip in Planne r: this
le ads to a s uboptimal s olution as s hown be low:
48
CHAPT ER 3. USE CASES AND EXAMPLES
Contrary to popular be lie f, mos t us e rs don’t want the s horte s t route : the y want the
fas te s t route ins te ad. The y pre fe r highways ove r normal roads . The y pre fe r
normal roads ove r dirt roads . In the re al world, the fas te s t and s horte s t route are
rare ly the s ame .
3.3.4. Project Job Scheduling
3.3.4.1. Problem Descript ion
Sche dule all jobs in time and e xe cution mode to minimiz e proje ct de lays . Each job
is part of a proje ct. A job can be e xe cute d in diffe re nt ways : e ach way is an
e xe cution mode that implie s a diffe re nt duration but als o diffe re nt re s ource
us age s . This is a form of fle xible job shop scheduling.
49
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Hard cons traints :
Job pre ce de nce : a job can only s tart whe n all its pre de ce s s or jobs are finis he d.
Re s ource capacity: do not us e more re s ource s the n available .
Re s ource s are local (s hare d be twe e n jobs of the s ame proje ct) or global
(s hare d be twe e n all jobs )
Re s ource are re ne wable (capacity available pe r day) or nonre ne wable
(capacity available for all days )
Me dium cons traints :
Total proje ct de lay: minimiz e the duration (make s pan) of e ach proje ct.
Soft cons traints :
Total make s pan: minimiz e the duration of the whole multi-proje ct s che dule .
The proble m is de fine d by the MISTA 2013 challe nge .
3.3.4.2. Problem Size
Schedule A-1 has
resources and 150
Schedule A-2 has
resources and 420
Schedule A-3 has
resources and 630
50
2 projects, 24 jobs,
64 execution modes,
resource requirements.
2 projects, 44 jobs, 124 execution modes,
resource requirements.
2 projects, 64 jobs, 184 execution modes,
resource requirements.
7
7
7
CHAPT ER 3. USE CASES AND EXAMPLES
Schedule A-4
resources and
Schedule A-5
resources and
Schedule A-6
resources and
Schedule A-7
resources and
Schedule A-8
resources and
Schedule A-9
resources and
Schedule A-10
resources and
Schedule B-1
resources and
Schedule B-2
resources and
Schedule B-3
resources and
Schedule B-4
resources and
Schedule B-5
resources and
Schedule B-6
resources and
Schedule B-7
resources and
Schedule B-8
resources and
Schedule B-9
resources and
Schedule B-10
resources and
has 5 projects, 60 jobs, 160
390 resource requirements.
has 5 projects, 110 jobs, 310
900 resource requirements.
has 5 projects, 160 jobs, 460
1440 resource requirements.
has 10 projects, 120 jobs, 320
900 resource requirements.
has 10 projects, 220 jobs, 620
1860 resource requirements.
has 10 projects, 320 jobs, 920
2880 resource requirements.
has 10 projects, 320 jobs, 920
2970 resource requirements.
has 10 projects, 120 jobs, 320
900 resource requirements.
has 10 projects, 220 jobs, 620
1740 resource requirements.
has 10 projects, 320 jobs, 920
3060 resource requirements.
has 15 projects, 180 jobs, 480
1530 resource requirements.
has 15 projects, 330 jobs, 930
2760 resource requirements.
has 15 projects, 480 jobs, 1380
4500 resource requirements.
has 20 projects, 240 jobs, 640
1710 resource requirements.
has 20 projects, 440 jobs, 1240
3180 resource requirements.
has 20 projects, 640 jobs, 1840
5940 resource requirements.
has 20 projects, 460 jobs, 1300
4260 resource requirements.
execution modes, 16
execution modes, 16
execution modes, 16
execution modes, 22
execution modes, 22
execution modes, 31
execution modes, 31
execution modes, 31
execution modes, 22
execution modes, 31
execution modes, 46
execution modes, 46
execution modes, 46
execution modes, 61
execution modes, 42
execution modes, 61
execution modes, 42
3.3.5. Hospit al Bed Planning (PAS - Pat ient Admission
Scheduling)
3.3.5.1. Problem Descript ion
As s ign e ach patie nt (that will come to the hos pital) into a be d for e ach night that
the patie nt will s tay in the hos pital. Each be d be longs to a room and e ach room
be longs to a de partme nt. The arrival and de parture date s of the patie nts is fixe d:
only a be d ne e ds to be as s igne d for e ach night.
This proble m fe ature s ove rcons traine d datas e ts .
51
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Hard cons traints :
2 patie nts mus t not be as s igne d to the s ame be d in the s ame night. We ight: 1000hard * conflictNightCount.
A room can have a ge nde r limitation: only fe male s , only male s , the s ame
ge nde r in the s ame night or no ge nde r limitation at all. We ight: -50hard *
nightCount.
A de partme nt can have a minimum or maximum age . We ight: -100hard *
nightCount.
A patie nt can re quire a room with s pe cific e quipme nt(s ). We ight: -50hard *
nightCount.
Me dium cons traints :
As s ign e ve ry patie nt to a be d, unle s s the datas e t is ove rcons traine d. We ight: 1medium * nightCount.
Soft cons traints :
A patie nt can pre fe r a maximum room s iz e , for e xample if he /s he wants a
s ingle room. We ight: -8soft * nightCount.
A patie nt is be s t as s igne d to a de partme nt that s pe cializ e s in his /he r proble m.
We ight: -10soft * nightCount.
A patie nt is be s t as s igne d to a room that s pe cializ e s in his /he r proble m. We ight:
-20soft * nightCount.
That room s pe ciality s hould be priority 1. We ight: -10soft * (priority -
52
CHAPT ER 3. USE CASES AND EXAMPLES
1) * nightCount.
A patie nt can pre fe r a room with s pe cific e quipme nt(s ). We ight: -20soft *
nightCount.
The proble m is a variant on Kaho’s Patie nt Sche duling and the datas e ts come from
re al world hos pitals .
3.3.5.2. Problem Size
testdata01 has 4 specialisms, 2 equipments, 4
rooms, 286 beds, 14 nights, 652 patients and
a search space of 10^1601.
testdata02 has 6 specialisms, 2 equipments, 6
rooms, 465 beds, 14 nights, 755 patients and
a search space of 10^2013.
testdata03 has 5 specialisms, 2 equipments, 5
rooms, 395 beds, 14 nights, 708 patients and
a search space of 10^1838.
testdata04 has 6 specialisms, 2 equipments, 6
rooms, 471 beds, 14 nights, 746 patients and
a search space of 10^1994.
testdata05 has 4 specialisms, 2 equipments, 4
rooms, 325 beds, 14 nights, 587 patients and
a search space of 10^1474.
testdata06 has 4 specialisms, 2 equipments, 4
rooms, 313 beds, 14 nights, 685 patients and
a search space of 10^1709.
testdata07 has 6 specialisms, 4 equipments, 6
rooms, 472 beds, 14 nights, 519 patients and
a search space of 10^1387.
testdata08 has 6 specialisms, 4 equipments, 6
rooms, 441 beds, 21 nights, 895 patients and
a search space of 10^2366.
testdata09 has 4 specialisms, 4 equipments, 4
rooms, 310 beds, 28 nights, 1400 patients and
a search space of 10^3487.
testdata10 has 4 specialisms, 4 equipments, 4
rooms, 308 beds, 56 nights, 1575 patients and
a search space of 10^3919.
testdata11 has 4 specialisms, 4 equipments, 4
rooms, 318 beds, 91 nights, 2514 patients and
a search space of 10^6291.
testdata12 has 4 specialisms, 4 equipments, 4
rooms, 310 beds, 84 nights, 2750 patients and
a search space of 10^6851.
testdata13 has 5 specialisms, 4 equipments, 5
rooms, 368 beds, 28 nights, 907 patients and
a search space of 10^2845.
departments, 98
652 admissions with
departments, 151
755 admissions with
departments, 131
708 admissions with
departments, 155
746 admissions with
departments, 102
587 admissions with
departments, 104
685 admissions with
departments, 162
519 admissions with
departments, 148
895 admissions with
departments, 105
1400 admissions with
departments, 104
1575 admissions with
departments, 107
2514 admissions with
departments, 105
2750 admissions with
departments, 125
1109 admissions with
3.3.5.3. Domain Model
53
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
3.4. DIFFICULT EXAMPLES
3.4.1. Exam T imet abling (IT C 2007 t rack 1 - Examinat ion)
3.4.1.1. Problem Descript ion
Sche dule e ach e xam into a pe riod and into a room. Multiple e xams can s hare the
s ame room during the s ame pe riod.
54
CHAPT ER 3. USE CASES AND EXAMPLES
Hard cons traints :
Exam conflict: 2 e xams that s hare s tude nts mus t not occur in the s ame pe riod.
Room capacity: A room’s s e ating capacity mus t s uffice at all time s .
Pe riod duration: A pe riod’s duration mus t s uffice for all of its e xams .
Pe riod re late d hard cons traints (s pe cifie d pe r datas e t):
Coincide nce : 2 s pe cifie d e xams mus t us e the s ame pe riod (but pos s ibly
anothe r room).
Exclus ion: 2 s pe cifie d e xams mus t not us e the s ame pe riod.
Afte r: A s pe cifie d e xam mus t occur in a pe riod afte r anothe r s pe cifie d
e xam’s pe riod.
Room re late d hard cons traints (s pe cifie d pe r datas e t):
Exclus ive : 1 s pe cifie d e xam s hould not have to s hare its room with any othe r
e xam.
Soft cons traints (e ach of which has a parame triz e d pe nalty):
The s ame s tude nt s hould not have 2 e xams in a row.
The s ame s tude nt s hould not have 2 e xams on the s ame day.
Pe riod s pre ad: 2 e xams that s hare s tude nts s hould be a numbe r of pe riods
apart.
55
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Mixe d durations : 2 e xams that s hare a room s hould not have diffe re nt
durations .
Front load: Large e xams s hould be s che dule d e arlie r in the s che dule .
Pe riod pe nalty (s pe cifie d pe r datas e t): Some pe riods have a pe nalty whe n
us e d.
Room pe nalty (s pe cifie d pe r datas e t): Some rooms have a pe nalty whe n us e d.
It us e s large te s t data s e ts of re al-life unive rs itie s .
The proble m is de fine d by the Inte rnational Time tabling Compe tition 2007 track 1.
Ge offre y De Sme t finis he d 4th in that compe tition with a ve ry e arly ve rs ion of
Planne r. Many improve me nts have be e n made s ince the n.
3.4.1.2. Problem Size
exam_comp_set1 has 7883 students, 607 exams, 54 periods,
rooms, 12 period constraints and 0 room constraints with
space of 10^1564.
exam_comp_set2 has 12484 students, 870 exams, 40 periods,
rooms, 12 period constraints and 2 room constraints with
space of 10^2864.
exam_comp_set3 has 16365 students, 934 exams, 36 periods,
rooms, 168 period constraints and 15 room constraints with
space of 10^3023.
exam_comp_set4 has 4421 students, 273 exams, 21 periods,
rooms, 40 period constraints and 0 room constraints with
space of 10^360.
exam_comp_set5 has 8719 students, 1018 exams, 42 periods,
rooms, 27 period constraints and 0 room constraints with
space of 10^2138.
exam_comp_set6 has 7909 students, 242 exams, 16 periods,
rooms, 22 period constraints and 0 room constraints with
space of 10^509.
exam_comp_set7 has 13795 students, 1096 exams, 80 periods,
rooms, 28 period constraints and 0 room constraints with
space of 10^3374.
exam_comp_set8 has 7718 students, 598 exams, 80 periods,
rooms, 20 period constraints and 1 room constraints with
space of 10^1678.
3.4.1.3. Domain Model
Be low you can s e e the main e xamination domain clas s e s :
Figure 3.3. Examinat io n Do main Class Diagram
56
7
a search
49
a search
48
a search
1
a search
3
a search
8
a search
15
a search
8
a search
CHAPT ER 3. USE CASES AND EXAMPLES
Notice that we ’ve s plit up the e xam conce pt into an Exam clas s and a Topic clas s .
The Exam ins tance s change during s olving (this is the planning e ntity clas s ), whe n
the ir pe riod or room prope rty change s . The Topic, Period and Room ins tance s
ne ve r change during s olving (the s e are proble m facts , jus t like s ome othe r
clas s e s ).
3.4.2. Employee Rost ering (INRC 2010 - Nurse Rost ering)
3.4.2.1. Problem Descript ion
For e ach s hift, as s ign a nurs e to work that s hift.
57
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Hard cons traints :
No unas s igne d s hifts (build-in): Eve ry s hift ne e d to be as s igne d to an e mploye e .
Shift conflict: An e mploye e can have only 1 s hift pe r day.
Soft cons traints :
Contract obligations . The bus ine s s fre que ntly violate s the s e , s o the y de cide d to
de fine the s e as s oft cons traints ins te ad of hard cons traints .
Minimum and maximum as s ignme nts : Each e mploye e ne e ds to work more
than x s hifts and le s s than y s hifts (de pe nding on the ir contract).
Minimum and maximum cons e cutive working days : Each e mploye e ne e ds to
work be twe e n x and y days in a row (de pe nding on the ir contract).
Minimum and maximum cons e cutive fre e days : Each e mploye e ne e ds to be
fre e be twe e n x and y days in a row (de pe nding on the ir contract).
Minimum and maximum cons e cutive working we e ke nds : Each e mploye e
ne e ds to work be twe e n x and y we e ke nds in a row (de pe nding on the ir
contract).
Comple te we e ke nds : Each e mploye e ne e ds to work e ve ry day in a we e ke nd
or not at all.
Ide ntical s hift type s during we e ke nd: Each we e ke nd s hift for the s ame
we e ke nd of the s ame e mploye e mus t be the s ame s hift type .
Unwante d patte rns : A combination of unwante d s hift type s in a row. For
e xample : a late s hift followe d by an e arly s hift followe d by a late s hift.
58
CHAPT ER 3. USE CASES AND EXAMPLES
Employe e wis he s :
Day on re que s t: An e mploye e wants to work on a s pe cific day.
Day off re que s t: An e mploye e doe s not want to work on a s pe cific day.
Shift on re que s t: An e mploye e wants to be as s igne d to a s pe cific s hift.
Shift off re que s t: An e mploye e doe s not want to be as s igne d to a s pe cific
s hift.
Alte rnative s kill: An e mploye e as s igne d to a s kill s hould have a proficie ncy in
e ve ry s kill re quire d by that s hift.
59
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The proble m is de fine d by the Inte rnational Nurs e Ros te ring Compe tition 2010.
3.4.2.2. Problem Size
The re are 3 datas e t type s :
s print: mus t be s olve d in s e conds .
me dium: mus t be s olve d in minute s .
long: mus t be s olve d in hours .
60
toy1
6 employees,
with a search
toy2
20 employees,
with a search
has 1 skills, 3 shiftTypes, 2 patterns, 1 contracts,
7 shiftDates, 35 shiftAssignments and
0 requests
space of
10^27.
has 1 skills, 3 shiftTypes, 3 patterns, 2 contracts,
28 shiftDates, 180 shiftAssignments and 140 requests
space of 10^234.
sprint01
10 employees,
with a search
sprint02
10 employees,
with a search
sprint03
10 employees,
with a search
sprint04
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
4 contracts,
150 requests
4 contracts,
150 requests
4 contracts,
150 requests
4 contracts,
CHAPT ER 3. USE CASES AND EXAMPLES
10 employees,
with a search
sprint05
10 employees,
with a search
sprint06
10 employees,
with a search
sprint07
10 employees,
with a search
sprint08
10 employees,
with a search
sprint09
10 employees,
with a search
sprint10
10 employees,
with a search
sprint_hint01
10 employees,
with a search
sprint_hint02
10 employees,
with a search
sprint_hint03
10 employees,
with a search
sprint_late01
10 employees,
with a search
sprint_late02
10 employees,
with a search
sprint_late03
10 employees,
with a search
sprint_late04
10 employees,
with a search
sprint_late05
10 employees,
with a search
sprint_late06
10 employees,
with a search
sprint_late07
10 employees,
with a search
sprint_late08
10 employees,
with a search
sprint_late09
10 employees,
with a search
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 3 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 8 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 8 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 8 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 3 shiftTypes, 4 patterns,
28 shiftDates, 144 shiftAssignments and
space of 10^144.
has 1 skills, 4 shiftTypes, 8 patterns,
28 shiftDates, 160 shiftAssignments and
space of 10^160.
has 1 skills, 4 shiftTypes, 8 patterns,
28 shiftDates, 160 shiftAssignments and
space of 10^160.
has 1 skills, 4 shiftTypes, 8 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 152 shiftAssignments and
space of 10^152.
150 requests
4 contracts,
150 requests
4 contracts,
150 requests
4 contracts,
150 requests
4 contracts,
150 requests
4 contracts,
150 requests
4 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
139 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
150 requests
3 contracts,
0 requests
3 contracts,
0 requests
61
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
sprint_late10 has 1 skills, 4 shiftTypes, 0 patterns, 3 contracts,
10 employees, 28 shiftDates, 152 shiftAssignments and 150 requests
with a search space of 10^152.
62
medium01
31 employees,
with a search
medium02
31 employees,
with a search
medium03
31 employees,
with a search
medium04
31 employees,
with a search
medium05
31 employees,
with a search
medium_hint01
30 employees,
with a search
medium_hint02
30 employees,
with a search
medium_hint03
30 employees,
with a search
medium_late01
30 employees,
with a search
medium_late02
30 employees,
with a search
medium_late03
30 employees,
with a search
medium_late04
30 employees,
with a search
medium_late05
30 employees,
with a search
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 608 shiftAssignments and
space of 10^906.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 608 shiftAssignments and
space of 10^906.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 608 shiftAssignments and
space of 10^906.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 608 shiftAssignments and
space of 10^906.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 608 shiftAssignments and
space of 10^906.
has 1 skills, 4 shiftTypes, 7 patterns,
28 shiftDates, 428 shiftAssignments and
space of 10^632.
has 1 skills, 4 shiftTypes, 7 patterns,
28 shiftDates, 428 shiftAssignments and
space of 10^632.
has 1 skills, 4 shiftTypes, 7 patterns,
28 shiftDates, 428 shiftAssignments and
space of 10^632.
has 1 skills, 4 shiftTypes, 7 patterns,
28 shiftDates, 424 shiftAssignments and
space of 10^626.
has 1 skills, 4 shiftTypes, 7 patterns,
28 shiftDates, 428 shiftAssignments and
space of 10^632.
has 1 skills, 4 shiftTypes, 0 patterns,
28 shiftDates, 428 shiftAssignments and
space of 10^632.
has 1 skills, 4 shiftTypes, 7 patterns,
28 shiftDates, 416 shiftAssignments and
space of 10^614.
has 2 skills, 5 shiftTypes, 7 patterns,
28 shiftDates, 452 shiftAssignments and
space of 10^667.
4 contracts,
403 requests
long01
49 employees,
with a search
long02
49 employees,
with a search
long03
49 employees,
with a search
long04
49 employees,
with a search
has 2 skills, 5 shiftTypes, 3 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1250.
has 2 skills, 5 shiftTypes, 3 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1250.
has 2 skills, 5 shiftTypes, 3 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1250.
has 2 skills, 5 shiftTypes, 3 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1250.
3 contracts,
735 requests
4 contracts,
403 requests
4 contracts,
403 requests
4 contracts,
403 requests
4 contracts,
403 requests
4 contracts,
390 requests
3 contracts,
390 requests
4 contracts,
390 requests
4 contracts,
390 requests
3 contracts,
390 requests
4 contracts,
390 requests
3 contracts,
390 requests
4 contracts,
390 requests
3 contracts,
735 requests
3 contracts,
735 requests
3 contracts,
735 requests
CHAPT ER 3. USE CASES AND EXAMPLES
long05
49 employees,
with a search
long_hint01
50 employees,
with a search
long_hint02
50 employees,
with a search
long_hint03
50 employees,
with a search
long_late01
50 employees,
with a search
long_late02
50 employees,
with a search
long_late03
50 employees,
with a search
long_late04
50 employees,
with a search
long_late05
50 employees,
with a search
has 2 skills, 5 shiftTypes, 3 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1250.
has 2 skills, 5 shiftTypes, 9 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1257.
has 2 skills, 5 shiftTypes, 7 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1257.
has 2 skills, 5 shiftTypes, 7 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1257.
has 2 skills, 5 shiftTypes, 9 patterns,
28 shiftDates, 752 shiftAssignments and
space of 10^1277.
has 2 skills, 5 shiftTypes, 9 patterns,
28 shiftDates, 752 shiftAssignments and
space of 10^1277.
has 2 skills, 5 shiftTypes, 9 patterns,
28 shiftDates, 752 shiftAssignments and
space of 10^1277.
has 2 skills, 5 shiftTypes, 9 patterns,
28 shiftDates, 752 shiftAssignments and
space of 10^1277.
has 2 skills, 5 shiftTypes, 9 patterns,
28 shiftDates, 740 shiftAssignments and
space of 10^1257.
3 contracts,
735 requests
3 contracts,
0 requests
3 contracts,
0 requests
3 contracts,
0 requests
3 contracts,
0 requests
4 contracts,
0 requests
3 contracts,
0 requests
4 contracts,
0 requests
3 contracts,
0 requests
3.4.2.3. Domain Model
63
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
3.4.3. T raveling T ournament Problem (T T P)
3.4.3.1. Problem Descript ion
Sche dule matche s be twe e n n te ams .
64
CHAPT ER 3. USE CASES AND EXAMPLES
Hard cons traints :
Each te am plays twice agains t e ve ry othe r te am: once home and once away.
Each te am has e xactly 1 match on e ach time s lot.
No te am mus t have more than 3 cons e cutive home or 3 cons e cutive away
matche s .
No re pe ate rs : no 2 cons e cutive matche s of the s ame 2 oppos ing te ams .
Soft cons traints :
Minimiz e the total dis tance trave le d by all te ams .
The proble m is de fine d on Michae l Trick’s we bs ite (which contains the world
re cords too).
3.4.3.2. Problem Size
1-nl04
space of
1-nl06
space of
1-nl08
space of
1-nl10
space of
1-nl12
space of
has 6
10^9.
has 10
10^30.
has 14
10^64.
has 18
10^112.
has 22
10^177.
days,
4 teams and
12 matches with a search
days,
6 teams and
30 matches with a search
days,
8 teams and
56 matches with a search
days, 10 teams and
90 matches with a search
days, 12 teams and
132 matches with a search
65
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
1-nl14
has 26
space of 10^257.
1-nl16
has 30
space of 10^354.
2-bra24
has 46
space of 10^917.
3-nfl16
has 30
space of 10^354.
3-nfl18
has 34
space of 10^468.
3-nfl20
has 38
space of 10^600.
3-nfl22
has 42
space of 10^749.
3-nfl24
has 46
space of 10^917.
3-nfl26
has 50
space of 10^1104.
3-nfl28
has 54
space of 10^1309.
3-nfl30
has 58
space of 10^1534.
3-nfl32
has 62
space of 10^1778.
4-super04 has 6
space of
10^9.
4-super06 has 10
space of
10^30.
4-super08 has 14
space of
10^64.
4-super10 has 18
space of 10^112.
4-super12 has 22
space of 10^177.
4-super14 has 26
space of 10^257.
5-galaxy04 has 6
space of
10^9.
5-galaxy06 has 10
space of
10^30.
5-galaxy08 has 14
space of
10^64.
5-galaxy10 has 18
space of 10^112.
5-galaxy12 has 22
space of 10^177.
5-galaxy14 has 26
space of 10^257.
5-galaxy16 has 30
space of 10^354.
5-galaxy18 has 34
space of 10^468.
5-galaxy20 has 38
space of 10^600.
5-galaxy22 has 42
space of 10^749.
66
days, 14 teams and
182 matches with a search
days, 16 teams and
240 matches with a search
days, 24 teams and
552 matches with a search
days, 16 teams and
240 matches with a search
days, 18 teams and
306 matches with a search
days, 20 teams and
380 matches with a search
days, 22 teams and
462 matches with a search
days, 24 teams and
552 matches with a search
days, 26 teams and
650 matches with a search
days, 28 teams and
756 matches with a search
days, 30 teams and
870 matches with a search
days, 32 teams and
992 matches with a search
days,
4 teams and
12 matches with a search
days,
6 teams and
30 matches with a search
days,
8 teams and
56 matches with a search
days, 10 teams and
90 matches with a search
days, 12 teams and
132 matches with a search
days, 14 teams and
182 matches with a search
days,
4 teams and
12 matches with a search
days,
6 teams and
30 matches with a search
days,
8 teams and
56 matches with a search
days, 10 teams and
90 matches with a search
days, 12 teams and
132 matches with a search
days, 14 teams and
182 matches with a search
days, 16 teams and
240 matches with a search
days, 18 teams and
306 matches with a search
days, 20 teams and
380 matches with a search
days, 22 teams and
462 matches with a search
CHAPT ER 3. USE CASES AND EXAMPLES
5-galaxy24 has 46
space of 10^917.
5-galaxy26 has 50
space of 10^1104.
5-galaxy28 has 54
space of 10^1309.
5-galaxy30 has 58
space of 10^1534.
5-galaxy32 has 62
space of 10^1778.
5-galaxy34 has 66
space of 10^2041.
5-galaxy36 has 70
space of 10^2324.
5-galaxy38 has 74
space of 10^2628.
5-galaxy40 has 78
space of 10^2951.
days, 24 teams and
552 matches with a search
days, 26 teams and
650 matches with a search
days, 28 teams and
756 matches with a search
days, 30 teams and
870 matches with a search
days, 32 teams and
992 matches with a search
days, 34 teams and 1122 matches with a search
days, 36 teams and 1260 matches with a search
days, 38 teams and 1406 matches with a search
days, 40 teams and 1560 matches with a search
3.4.4. Cheap T ime Scheduling
3.4.4.1. Problem Descript ion
Sche dule all tas ks in time and on a machine to minimiz e powe r cos t. Powe r price s
diffe rs in time . This is a form of job shop scheduling.
Hard cons traints :
Start time limits : e ach tas k mus t s tart be twe e n its e arlie s t s tart and late s t s tart
limit.
Maximum capacity: the maximum capacity for e ach re s ource for e ach machine
mus t not be e xce e de d.
Startup and s hutdown: e ach machine mus t be active in the pe riods during which
it has as s igne d tas ks . Be twe e n tas ks it is allowe d to be idle to avoid s tartup and
s hutdown cos ts .
Me dium cons traints :
Powe r cos t: minimiz e the total powe r cos t of the whole s che dule .
Machine powe r cos t: Each active or idle machine cons ume s powe r, which
infe rs a powe r cos t (de pe nding on the powe r price during that time ).
Tas k powe r cos t: Each tas k cons ume s powe r too, which infe rs a powe r cos t
(de pe nding on the powe r price during its time ).
Machine s tartup and s hutdown cos t: Eve ry time a machine s tarts up or s huts
down, an e xtra cos t is inflicte d.
Soft cons traints (adde ndum to the original proble m de finition):
Start e arly: pre fe r s tarting a tas k s oone r rathe r than late r.
The proble m is de fine d by the ICON challe nge .
3.4.4.2. Problem Size
67
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
3.4.4.2. Problem Size
sample01
tasks with
sample02
tasks with
sample03
tasks with
sample04
tasks with
sample05
tasks with
sample06
tasks with
sample07
tasks with
sample08
tasks with
sample09
tasks with
instance00
tasks with
instance01
tasks with
instance02
tasks with
instance03
tasks with
instance04
tasks with
instance05
tasks with
instance06
tasks with
instance07
tasks with
instance08
tasks with
instance09
tasks with
instance10
tasks with
instance11
tasks with
instance12
tasks with
instance13
tasks with
instance14
tasks with
instance15
tasks with
instance16
tasks with
instance17
tasks with
68
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 4 resources,
a search space of
has 1 resources,
a search space of
has 1 resources,
a search space of
has 1 resources,
a search space of
has 1 resources,
a search space of
has 1 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 2 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
has 3 resources,
a search space of
2 machines,
10^53.
2 machines,
10^114.
2 machines,
10^226.
5 machines,
10^266.
2 machines,
10^584.
5 machines,
10^673.
2 machines,
10^2388.
5 machines,
10^2748.
20 machines,
10^6668.
10 machines,
10^595.
10 machines,
10^599.
10 machines,
10^599.
10 machines,
10^591.
10 machines,
10^590.
25 machines,
10^667.
25 machines,
10^660.
25 machines,
10^662.
25 machines,
10^651.
25 machines,
10^659.
20 machines,
10^1657.
20 machines,
10^1644.
20 machines,
10^1637.
20 machines,
10^1659.
20 machines,
10^1643.
40 machines,
10^1782.
40 machines,
10^1778.
40 machines,
10^1764.
288 periods and
25
288 periods and
50
288 periods and
100
288 periods and
100
288 periods and
250
288 periods and
250
288 periods and 1000
288 periods and 1000
288 periods and 2000
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
200
288 periods and
500
288 periods and
500
288 periods and
500
288 periods and
500
288 periods and
500
288 periods and
500
288 periods and
500
288 periods and
500
CHAPT ER 3. USE CASES AND EXAMPLES
instance18
tasks with
instance19
tasks with
instance20
tasks with
instance21
tasks with
instance22
tasks with
instance23
tasks with
instance24
tasks with
instance25
tasks with
instance26
tasks with
instance27
tasks with
instance28
tasks with
instance29
tasks with
instance30
tasks with
instance31
tasks with
instance32
tasks with
instance33
tasks with
instance34
tasks with
instance35
tasks with
instance36
tasks with
instance37
tasks with
instance38
tasks with
instance39
tasks with
instance40
tasks with
instance41
tasks with
instance42
tasks with
instance43
tasks with
instance44
tasks with
instance45
tasks with
has 3 resources, 40 machines,
a search space of 10^1769.
has 3 resources, 40 machines,
a search space of 10^1778.
has 3 resources, 50 machines,
a search space of 10^3689.
has 3 resources, 50 machines,
a search space of 10^3678.
has 3 resources, 50 machines,
a search space of 10^3706.
has 3 resources, 50 machines,
a search space of 10^3676.
has 3 resources, 50 machines,
a search space of 10^3681.
has 3 resources, 60 machines,
a search space of 10^3774.
has 3 resources, 60 machines,
a search space of 10^3737.
has 3 resources, 60 machines,
a search space of 10^3744.
has 3 resources, 60 machines,
a search space of 10^3731.
has 3 resources, 60 machines,
a search space of 10^3746.
has 4 resources, 70 machines,
a search space of 10^7718.
has 4 resources, 70 machines,
a search space of 10^7740.
has 4 resources, 70 machines,
a search space of 10^7686.
has 4 resources, 70 machines,
a search space of 10^7672.
has 4 resources, 70 machines,
a search space of 10^7695.
has 4 resources, 80 machines,
a search space of 10^7807.
has 4 resources, 80 machines,
a search space of 10^7814.
has 4 resources, 80 machines,
a search space of 10^7764.
has 4 resources, 80 machines,
a search space of 10^7736.
has 4 resources, 80 machines,
a search space of 10^7783.
has 4 resources, 90 machines,
a search space of 10^15976.
has 4 resources, 90 machines,
a search space of 10^15935.
has 4 resources, 90 machines,
a search space of 10^15887.
has 4 resources, 90 machines,
a search space of 10^15896.
has 4 resources, 90 machines,
a search space of 10^15885.
has 4 resources, 100 machines,
a search space of 10^20173.
288 periods and
500
288 periods and
500
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 1000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 2000
288 periods and 4000
288 periods and 4000
288 periods and 4000
288 periods and 4000
288 periods and 4000
288 periods and 5000
69
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
instance46
tasks with
instance47
tasks with
instance48
tasks with
instance49
tasks with
has 4 resources, 100 machines,
a search space of 10^20132.
has 4 resources, 100 machines,
a search space of 10^20126.
has 4 resources, 100 machines,
a search space of 10^20110.
has 4 resources, 100 machines,
a search space of 10^20078.
288 periods and 5000
288 periods and 5000
288 periods and 5000
288 periods and 5000
3.4.5. Invest ment asset class allocat ion (port f olio opt imizat ion)
3.4.5.1. Problem Descript ion
De cide the re lative quantity to inve s t in e ach as s e t clas s .
Hard cons traints :
Ris k maximum: the total s tandard de viation mus t not be highe r than the
s tandard de viation maximum.
Total s tandard de viation calculation take s as s e t clas s corre lations into
account by applying Markowitz Portfolio The ory.
Re gion maximum: Each re gion has a quantity maximum.
Se ctor maximum: Each s e ctor has a quantity maximum.
Soft cons traints :
Maximiz e e xpe cte d re turn.
3.4.5.2. Problem Size
de_smet_1 has 1
search space of
irrinki_1 has 2
search space of
regions, 3 sectors and 11 asset classes with a
10^4.
regions, 3 sectors and 6 asset classes with a
10^3.
Large r datas e ts have not be e n cre ate d or te s te d ye t, but s hould not pos e a
proble m.
70
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
CHAPTER 4. PLANNER CONFIGURATION
4.1. OVERVIEW
Solving a planning proble m with Planne r cons is ts out of 5 s te ps :
1. Model your planning problem as a clas s that imple me nts the inte rface
Solution, for e xample the clas s NQueens.
2. Configure a Solver, for e xample a Firs t Fit and Tabu Se arch s olve r for any
NQueens ins tance .
3. Load a problem data set from your data laye r, for e xample a 4 Que e ns
ins tance . That is the planning proble m.
4. Solve it with Solver.solve(planningProblem) which re tuns the be s t
s olution found.
4.2. SOLVER CONFIGURAT ION
4.2.1. Solver Conf igurat ion by XML
Build a Solver ins tance with the SolverFactory. Configure the SolverFactory
with a s olve r configuration XML file , provide d as a clas s path re s ource (as de finie d
by ClassLoader.getResource()):
71
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
SolverFactory<NQueens> solverFactory =
SolverFactory.createFromXmlResource(
"org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml");
Solver<NQueens> solver = solverFactory.buildSolver();
In a typical proje ct (following the Mave n dire ctory s tructure ), that s olve rConfig XML
file would be locate d at
$PROJECT_DIR/src/main/resources/org/optaplanner/examples/nqueens/solv
er/nqueensSolverConfig.xml. Alte rnative ly, a SolverFactory can be cre ate d
from a File, an InputStream or a Reader with me thods s uch as
SolverFactory.createFromXmlFile(). Howe ve r, for portability re as ons , a
clas s path re s ource is re comme nde d.
No t e
On s ome e nvironme nts (OSGi, JBos s module s , …​), clas s path re s ource s
(s uch as the s olve r config, s core DRL’s and domain clas s e s ) in your jars
might not be available to the de fault ClassLoader of the optaplannercore jar. In thos e cas e s , provide the ClassLoader of your clas s e s as a
parame te r:
SolverFactory<NQueens> solverFactory =
SolverFactory.createFromXmlResource(
".../nqueensSolverConfig.xml",
getClass().getClassLoader());
No t e
Whe n us ing Workbe nch or Exe cution Se rve r or to take advantage of
Drools ’s KieContainer fe ature s , provide the KieContainer as a
parame te r:
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer =
kieServices.newKieContainer(
kieServices.newReleaseId("org.nqueens",
"nqueens", "1.0.0"));
SolverFactory<NQueens> solverFactory =
SolverFactory.createFromKieContainerXmlResource(
kieContainer, ".../nqueensSolverConfig.xml");
And us e a ks e s s ionName in the s olve r configuration.
Both a Solver and a SolverFactory have a ge ne ric type calle d Solution_, which
is the clas s re pre s e nting a planning proble m and s olution.
A s olve r configuration XML file looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<!-- Define the model -->
72
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
<solutionClass>org.optaplanner.examples.nqueens.domain.NQueens</solut
ionClass>
<entityClass>org.optaplanner.examples.nqueens.domain.Queen</entityCla
ss>
<!-- Define the score function -->
<scoreDirectorFactory>
<scoreDefinitionType>SIMPLE</scoreDefinitionType>
<scoreDrl>org/optaplanner/examples/nqueens/solver/nQueensScoreRules.d
rl</scoreDrl>
</scoreDirectorFactory>
<!-- Configure the optimization algorithms (optional) -->
<termination>
...
</termination>
<constructionHeuristic>
...
</constructionHeuristic>
<localSearch>
...
</localSearch>
</solver>
Notice the thre e parts in it:
De fine the mode l.
De fine the s core function.
Optionally configure the optimiz ation algorithm(s ).
The s e various parts of a configuration are e xplaine d furthe r in this manual.
Planne r make s it re lative ly e as y to s witch optimiz ation algorithm(s ) jus t by
changing the configuration. The re is e ve n a Be nchmarke r which allows you to play
out diffe re nt configurations agains t e ach othe r and re port the mos t appropriate
configuration for your us e cas e .
4.2.2. Solver Conf igurat ion by Java API
A s olve r configuration can als o be configure d with the SolverConfig API. This is
e s pe cially us e ful to change s ome value s dynamically at runtime . For e xample , to
change the running time bas e d on us e r input, be fore building the Solver:
SolverFactory<NQueens> solverFactory =
SolverFactory.createFromXmlResource(
"org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml");
TerminationConfig terminationConfig = new
TerminationConfig();
terminationConfig.setMinutesSpentLimit(userInput);
73
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
solverFactory.getSolverConfig().setTerminationConfig(terminationConfi
g);
Solver<NQueens> solver = solverFactory.buildSolver();
Eve ry e le me nt in the s olve r configuration XML is available as a *Config clas s or a
prope rty on a *Config clas s in the package name s pace
org.optaplanner.core.config. The s e *Config clas s e s are the Java
re pre s e ntation of the XML format. The y build the runtime compone nts (of the
package name s pace org.optaplanner.core.impl) and as s e mble the m into an
e fficie nt Solver.
Impo rt ant
The SolverFactory is only multi-thre ad s afe afte r its configure d. So the
getSolverConfig() me thod is not thre ad-s afe . To configure a
SolverFactory dynamically for e ach us e r re que s t, build a SolverFactory
as bas e during initializ ation and clone it with the cloneSolverFactory()
me thod for a us e r re que s t:
private SolverFactory<NQueens> base;
public void init() {
base = SolverFactory.createFromXmlResource(
"org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.x
ml");
base.getSolverConfig().setTerminationConfig(new
TerminationConfig());
}
// Called concurrently from different threads
public void userRequest(..., long userInput)
SolverFactory<NQueens> solverFactory =
base.cloneSolverFactory();
solverFactory.getSolverConfig().getTerminationConfig().setMinu
tesSpentLimit(userInput);
Solver<NQueens> solver = solverFactory.buildSolver();
...
}
4.2.3. Solver Conf igurat ion in Business Cent ral
To configure your s olve r, you can us e the Solve r Editor in Bus ine s s Ce ntral. To
le arn about Bus ine s s Ce ntral, s e e chapte r 1.4. Bus ine s s Ce ntral from Re d Hat
JBos s BPM Suite Us e r Guide .
74
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
No t e
You mus t have the role plannermgmt to e nable the Bus ine s s Re s ource
Planne r s e ttings in Bus ine s s Ce ntral.
Click New It em → So lver co nf igurat io n to cre ate the Solve r Editor in your
Bus ine s s Ce ntral. Note that you can als o us e othe r as s e ts , for e xample DRL rule s ,
or guide d de cis ion table s .
Figure 4.1. So lver Co nf igurat io n Edit o r
The s olve r e ditor cre ate s a bas ic s olve r configuration. You can run it, toge the r with
DRL rule s , planne r e ntitie s , and planne r s olution, in the Re altime De cis ion Se rve r
or in plain Java code afte r the kjar is de ploye d.
Once you de fine your s olve r in the e ditor, you can click So urce and vie w it in the
XML format:
<solver xStreamId="1">
<scanAnnotatedClasses xStreamId="2"/>
<scoreDirectorFactory xStreamId="3">
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
</scoreDirectorFactory>
<termination xStreamId="4">
<secondsSpentLimit>0</secondsSpentLimit>
<minutesSpentLimit>0</minutesSpentLimit>
<hoursSpentLimit>5</hoursSpentLimit>
<daysSpentLimit>0</daysSpentLimit>
</termination>
</solver>
Us e the Validat e button to validate the s olve r configuration. This will actually build
a Solve r, s o mos t is s ue s in your proje ct will pre s e nt the ms e lve s the n, without the
ne e d to de ploy and run it.
By de fault, the s olve r configuration will automatically s can for all planning e ntitie s
and a planning s olution clas s e s . If none are found (or too many), validation will fail.
Dat a Object T ab
75
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
To mode l planning e ntitie s and planning s olutions us e d in Bus ine s s Re s ource
Planne r, us e data obje cts . To le arn more about data obje cts , s e e chapte r 4.14.
Data mode ls from Re d Hat JBos s BPM Suite Us e r Guide . To de s ignate a data obje ct
as a planne r e ntity or s olution, s e e the following s te ps :
Figure 4.2. Dat a Object T ab
Click on the labe l of your data obje ct and the n on the OptaPlanne r tool
window to s e t the obje ct to be a Planning Entity or a Planning Solution.
Click a s pe cific data obje ct fie ld and the n on the OptaPlanne r tool window to
s e t the re lations be twe e n Bus ine s s Re s ource Planne r variable s and s olve r.
The OptaPlanne r tool window allows you to change the planne r s e ttings
bas e d on the conte xt, that is this window change s its conte nt bas e d on your
s e le ction.
4.2.4. Annot at ions Conf igurat ion
4.2.4.1. Aut omat ic Scanning f or Annot at ions
Ins te ad of the de claring the clas s e s that have a @PlanningSolution or
@PlanningEntity manually:
<solver>
<!-- Define the model -->
<solutionClass>org.optaplanner.examples.nqueens.domain.NQueens</solut
ionClass>
<entityClass>org.optaplanner.examples.nqueens.domain.Queen</entityCla
ss>
...
</solver>
76
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
Planne r can find s can the clas s path and find the m automatically:
<solver>
<!-- Define the model -->
<scanAnnotatedClasses/>
...
</solver>
If the re are multiple mode ls in your clas s path (or jus t to s pe e d up s canning),
s pe cify the package s to s can:
<solver>
<!-- Define the model -->
<scanAnnotatedClasses>
<packageInclude>org.optaplanner.examples.cloudbalancing</packageInclu
de>
</scanAnnotatedClasses>
...
</solver>
This will find all s olution and e ntity clas s e s in the package or s ubpackage s .
No t e
If scanAnnotatedClasses is not s pe cifie d, the org.reflections trans itive
mave n de pe nde ncy can be e xclude d.
4.2.4.2. Annot at ion Alt ernat ives
Planne r ne e ds to be told which clas s e s in your domain mode l are planning e ntitie s ,
which prope rtie s are planning variable s , e tc. The re are s e ve ral ways to de live r
this information:
Add clas s annotations and JavaBe an prope rty annotations on the domain mode l
(re comme nde d). The prope rty annotations mus t be the ge tte r me thod, not on
the s e tte r me thod. Such a ge tte r doe s not ne e d to be public.
Add clas s annotations and fie ld annotations on the domain mode l. Such a fie ld
doe s not ne e d to be public.
No annotations : e xte rnaliz e the domain configuration in an XML file . This is not
ye t s upporte d.
This manual focus e s on the firs t manne r, but e ve ry fe ature s s upports all 3
manne rs , e ve n if it’s not e xplicitly me ntione d.
4.3. MODEL A PLANNING PROBLEM
4.3.1. Is T his Class a Problem Fact or Planning Ent it y?
77
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Look at a datas e t of your planning proble m. You will re cogniz e domain clas s e s in
the re , e ach of which can be cate goriz e d as one of the following:
A unre late d clas s : not us e d by any of the s core cons traints . From a planning
s tandpoint, this data is obs ole te .
A problem fact clas s : us e d by the s core cons traints , but doe s NOT change
during planning (as long as the proble m s tays the s ame ). For e xample : Bed,
Room, Shift, Employee, Topic, Period, …​ All the prope rtie s of a proble m fact
clas s are proble m prope rtie s .
A planning entity clas s : us e d by the s core cons traints and change s during
planning. For e xample : BedDesignation, ShiftAssignment, Exam, …​ The
prope rtie s that change during planning are planning variable s . The othe r
prope rtie s are proble m prope rtie s .
As k yours e lf: What class changes during planning? Which class has variables that I
want the Solver to change for me? That clas s is a planning e ntity. Mos t us e cas e s
have only one planning e ntity clas s . Mos t us e cas e s als o have only one planning
variable pe r planning e ntity clas s .
No t e
In re al-time planning, e ve n though the proble m its e lf change s , proble m
facts do not re ally change during planning, ins te ad the y change be twe e n
planning (be caus e the Solve r te mporarily s tops to apply the proble m fact
change s ).
A good mode l can gre atly improve the s ucce s s of your planning imple me ntation.
Follow the s e guide line s to de s ign a good mode l:
In a many to one re lations hip, it is normally the many s ide that is the planning
e ntity clas s . The prope rty re fe re ncing the othe r s ide is the n the planning
variable . For e xample in e mploye e ros te ring: the planning e ntity clas s is
ShiftAssignment, not Employee, and the planning variable is
ShiftAssignment.getEmployee() be caus e one Employee has multiple
ShiftAssignmentsbut one ShiftAssignment has only one Employee.
A planning e ntity clas s s hould have at le as t one proble m prope rty. A planning
e ntity clas s with only planning variable s can normally be s implifie d by
conve rting one of thos e planning variable s into a proble m prope rty. That he avily
de cre as e s the s e arch s pace s iz e . For e xample in e mploye e ros te ring: the
ShiftAssignment's getShift() is a proble m prope rty and the getEmployee()
is a planning variable . If both we re a planning variable , s olving it would be far
le s s e fficie nt.
A s urrogate ID doe s not s uffice as the re quire d minimum of one proble m
prope rty. It ne e ds to be unde rs tandable by the bus ine s s . A bus ine s s ke y
doe s s uffice . This pre ve nts an unas s igne d e ntity from be ing name le s s
(unide ntifiable by the bus ine s s ).
This way, the re is no ne e d to add a hard cons traint to as s ure that two
planning e ntitie s are diffe re nt: the y are alre ady diffe re nt due to the ir
proble m prope rtie s .
In s ome cas e s , multiple planning e ntitie s have the s ame proble m prope rty.
78
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
In s uch cas e s , it can be us e ful to cre ate an e xtra proble m prope rty to
dis tinguis h the m. For e xample in e mploye e ros te ring: ShiftAssignment has
be s ide s the proble m prope rty Shift als o the proble m prope rty
indexInShift.
The numbe r of planning e ntitie s is re comme nde d to be fixe d during planning.
Whe n uns ure of which prope rty s hould be a planning variable and which s hould
be a proble m prope rty, choos e it s o the numbe r of planning e ntitie s is fixe d. For
e xample in e mploye e ros te ring: if the planning e ntity clas s would have be e n
EmployeeAssignment with a proble m prope rty getEmployee() and a planning
variable getShift(), than it is impos s ible to accurate ly pre dict how many
EmployeeAssignment ins tance s to make pe r Employee.
For ins piration, take a look at typical de s ign patte rns or how the e xample s mode le d
the ir domain:
No t e
Ve hicle routing is s pe cial, be caus e it us e s a chaine d planning variable .
In Planne r, all proble ms facts and planning e ntitie s are plain old JavaBe ans (POJOs ).
Load the m from a databas e , an XML file , a data re pos itory, a REST s e rvice , a
noSQL cloud, …​ (s e e inte gration): it doe s n’t matte r.
4.3.2. Problem Fact
79
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
A proble m fact is any JavaBe an (POJO) with ge tte rs that doe s not change during
planning. Imple me nting the inte rface Serializable is re comme nde d (but not
re quire d). For e xample in n que e ns , the columns and rows are proble m facts :
public class Column implements Serializable {
private int index;
// ... getters
}
public class Row implements Serializable {
private int index;
// ... getters
}
A proble m fact can re fe re nce othe r proble m facts of cours e :
public class Course implements Serializable {
private String code;
private Teacher teacher; // Other problem fact
private int lectureSize;
private int minWorkingDaySize;
private List<Curriculum> curriculumList; // Other problem facts
private int studentSize;
// ... getters
}
A proble m fact clas s doe s not re quire any Planne r s pe cific code . For e xample , you
can re us e your domain clas s e s , which might have JPA annotations .
No t e
Ge ne rally, be tte r de s igne d domain clas s e s le ad to s imple r and more
e fficie nt s core cons traints . The re fore , whe n de aling with a me s s y
(de normaliz e d) le gacy s ys te m, it can s ome time s be worthwhile to conve rt
the me s s y domain mode l into a Planne r s pe cific mode l firs t. For e xample :
if your domain mode l has two Teacher ins tance s for the s ame te ache r
that te ache s at two diffe re nt de partme nts , it is harde r to write a corre ct
s core cons traint that cons trains a te ache r’s s pare time on the original
mode l than on an adjus te d mode l.
Alte rnative ly, you can s ome time s als o introduce a cached problem fact to
e nrich the domain mode l for planning only.
4.3.3. Planning Ent it y
80
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
4.3.3.1. Planning Ent it y Annot at ion
A planning e ntity is a JavaBe an (POJO) that change s during s olving, for e xample a
Queen that change s to anothe r row. A planning proble m has multiple planning
e ntitie s , for e xample for a s ingle n que e ns proble m, e ach Queen is a planning
e ntity. But the re is us ually only one planning e ntity clas s , for e xample the Queen
clas s .
A planning e ntity clas s ne e ds to be annotate d with the @PlanningEntity
annotation.
Each planning e ntity clas s has one or more planning variables. It s hould als o have
one or more defining prope rtie s . For e xample in n que e ns , a Queen is de fine d by
its Column and has a planning variable Row. This me ans that a Que e n’s column
ne ve r change s during s olving, while its row doe s change .
@PlanningEntity
public class Queen {
private Column column;
// Planning variables: changes during planning, between score
calculations.
private Row row;
// ... getters and setters
}
A planning e ntity clas s can have multiple planning variable s . For e xample , a
Lecture is de fine d by its Course and its inde x in that cours e (be caus e one cours e
has multiple le cture s ). Each Lecture ne e ds to be s che dule d into a Period and a
Room s o it has two planning variable s (pe riod and room). For e xample : the cours e
Mathe matics has e ight le cture s pe r we e k, of which the firs t le cture is Monday
morning at 08:00 in room 212.
@PlanningEntity
public class Lecture {
private Course course;
private int lectureIndexInCourse;
// Planning variables: changes during planning, between score
calculations.
private Period period;
private Room room;
// ...
}
Without automate d s canning, the s olve r configuration als o ne e ds to de clare e ach
planning e ntity clas s :
<solver>
...
<entityClass>org.optaplanner.examples.nqueens.domain.Queen</entityCla
81
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
ss>
...
</solver>
Some us e s cas e s have multiple planning e ntity clas s e s . For e xample : route fre ight
and trains into railway ne twork arcs , whe re e ach fre ight can us e multiple trains
ove r its journe y and e ach train can carry multiple fre ights pe r arc. Having multiple
planning e ntity clas s e s dire ctly rais e s the imple me ntation comple xity of your us e
cas e .
No t e
Do not create unnecessary planning entity classes. This le ads to difficult
Move imple me ntations and s lowe r s core calculation.
For e xample , do not cre ate a planning e ntity clas s to hold the total fre e
time of a te ache r, which ne e ds to be ke pt up to date as the Lecture
planning e ntitie s change . Ins te ad, calculate the fre e time in the s core
cons traints (or as a s hadow variable ) and put the re s ult pe r te ache r into a
logically ins e rte d s core obje ct.
If his toric data ne e ds to be cons ide re d too, the n cre ate proble m fact to
hold the total of the his toric as s ignme nts up to, but not including, the
planning window (s o that it doe s not change whe n a planning e ntity
change s ) and le t the s core cons traints take it into account.
4.3.3.2. Planning Ent it y Dif f icult y
Some optimiz ation algorithms work more e fficie ntly if the y have an e s timation of
which planning e ntitie s are more difficult to plan. For e xample : in bin packing bigge r
ite ms are harde r to fit, in cours e s che duling le cture s with more s tude nts are more
difficult to s che dule , and in n que e ns the middle que e ns are more difficult to fit on
the board.
The re fore , you can s e t a difficultyComparatorClass to the @PlanningEntity
annotation:
@PlanningEntity(difficultyComparatorClass =
CloudProcessDifficultyComparator.class)
public class CloudProcess {
// ...
}
public class CloudProcessDifficultyComparator implements
Comparator<CloudProcess> {
public int compare(CloudProcess a, CloudProcess b) {
return new CompareToBuilder()
.append(a.getRequiredMultiplicand(),
b.getRequiredMultiplicand())
.append(a.getId(), b.getId())
82
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
.toComparison();
}
}
Alte rnative ly, you can als o s e t a difficultyWeightFactoryClass to the
@PlanningEntity annotation, s o that you have acce s s to the re s t of the proble m
facts from the Solution too:
@PlanningEntity(difficultyWeightFactoryClass =
QueenDifficultyWeightFactory.class)
public class Queen {
// ...
}
Se e s orte d s e le ction for more information.
Impo rt ant
Difficulty s hould be imple me nte d as ce nding: e as y e ntitie s are lowe r,
difficult e ntitie s are highe r. For e xample , in bin packing: s mall ite m <
me dium ite m < big ite m.
Although mos t algorithms s tart with the more difficult e ntitie s firs t, the y
jus t re ve rs e the orde ring.
None of the curre nt planning variable s tate s s hould be us e d to compare planning
e ntity difficulty. During Cons truction He uris tics , thos e variable s are like ly to be
null anyway. For e xample , a Queen's row variable s hould not be us e d.
4.3.4. Planning Variable
4.3.4.1. Planning Variable Annot at ion
A planning variable is a JavaBe an prope rty (s o a ge tte r and s e tte r) on a planning
e ntity. It points to a planning value , which change s during planning. For e xample , a
Queen's row prope rty is a planning variable . Note that e ve n though a Queen's row
prope rty change s to anothe r Row during planning, no Row ins tance its e lf is change d.
A planning variable ge tte r ne e ds to be annotate d with the @PlanningVariable
annotation, which ne e ds a non-e mpty valueRangeProviderRefs prope rty.
@PlanningEntity
public class Queen {
...
private Row row;
@PlanningVariable(valueRangeProviderRefs = {"rowRange"})
public Row getRow() {
return row;
}
83
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
public void setRow(Row row) {
this.row = row;
}
}
The valueRangeProviderRefs prope rty de fine s what are the pos s ible planning
value s for this planning variable . It re fe re nce s one or more @ValueRangeProvider
IDs .
No t e
A @PlanningVariable annotation ne e ds to be on a me mbe r in a clas s with
a @PlanningEntity annotation. It is ignore d on pare nt clas s e s or s ubclas s e s
without that annotation.
Annotating the fie ld ins te ad of the prope rty works too:
@PlanningEntity
public class Queen {
...
@PlanningVariable(valueRangeProviderRefs = {"rowRange"})
private Row row;
}
4.3.4.2. Nullable Planning Variable
By de fault, an initializ e d planning variable cannot be null, s o an initializ e d s olution
will ne ve r us e null for any of its planning variable s . In an ove r-cons traine d us e
cas e , this can be counte rproductive . For e xample : in tas k as s ignme nt with too
many tas ks for the workforce , we would rathe r le ave low priority tas ks unas s igne d
ins te ad of as s igning the m to an ove rloade d worke r.
To allow an initializ e d planning variable to be null, s e t nullable to true:
@PlanningVariable(..., nullable = true)
public Worker getWorker() {
return worker;
}
Impo rt ant
Planne r will automatically add the value null to the value range . The re is
no ne e d to add null in a colle ction us e d by a ValueRangeProvider.
84
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
No t e
Us ing a nullable planning variable implie s that your s core calculation is
re s pons ible for punis hing (or e ve n re warding) variable s with a null value .
Re pe ate d planning (e s pe cially re al-time planning) doe s not mix we ll with a nullable
planning variable . Eve ry time the Solve r s tarts or a proble m fact change is made ,
the Cons truction He uris tics will try to initializ e all the null variable s again, which
can be a huge was te of time . One way to de al with this , is to change whe n a
planning e ntity s hould be re initializ e d with an
reinitializeVariableEntityFilter:
@PlanningVariable(..., nullable = true,
reinitializeVariableEntityFilter = ReinitializeTaskFilter.class)
public Worker getWorker() {
return worker;
}
4.3.4.3. When is a Planning Variable Considered Init ialized?
A planning variable is cons ide re d initializ e d if its value is not null or if the variable
is nullable. So a nullable variable is always cons ide re d initializ e d, e ve n whe n a
cus tom reinitializeVariableEntityFilter trigge rs a re initializ ation during
cons truction he uris tics .
A planning e ntity is initializ e d if all of its planning variable s are initializ e d.
A Solution is initializ e d if all of its planning e ntitie s are initializ e d.
4.3.5. Planning Value and Planning Value Range
4.3.5.1. Planning Value
A planning value is a pos s ible value for a planning variable . Us ually, a planning
value is a proble m fact, but it can als o be any obje ct, for e xample a double. It can
e ve n be anothe r planning e ntity or e ve n a inte rface imple me nte d by both a
planning e ntity and a proble m fact.
A planning value range is the s e t of pos s ible planning value s for a planning
variable . This s e t can be a countable (for e xample row 1, 2, 3 or 4) or uncountable
(for e xample any double be twe e n 0.0 and 1.0).
4.3.5.2. Planning Value Range Provider
4.3.5.2.1. Overview
The value range of a planning variable is de fine d with the @ValueRangeProvider
annotation. A @ValueRangeProvider annotation always has a prope rty ID, which is
re fe re nce d by the @PlanningVariable prope rty valueRangeProviderRefs.
This annotation can be locate d on 2 type s of me thods :
85
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
On the Solution: All planning e ntitie s s hare the s ame value range .
On the planning e ntity: The value range diffe rs pe r planning e ntity. This is le s s
common.
No t e
A @Value Range Provide r annotation ne e ds to be on a me mbe r in a clas s
with a @PlanningSolution or a @PlanningEntity annotation. It is ignore d on
pare nt clas s e s or s ubclas s e s without thos e annotations .
The re turn type of that me thod can be 2 type s :
Collection: The value range is de fine d by a Collection (us ually a List) of its
pos s ible value s .
ValueRange: The value range is de fine d by its bounds . This is le s s common.
4.3.5.2.2. ValueRangePro vider o n t he So lut io n
All ins tance s of the s ame planning e ntity clas s s hare the s ame s e t of pos s ible
planning value s for that planning variable . This is the mos t common way to
configure a value range .
The Solution imple me ntation has me thod that re turns a Collection (or a
ValueRange). Any value from that Collection is a pos s ible planning value for this
planning variable .
@PlanningVariable(valueRangeProviderRefs = {"rowRange"})
public Row getRow() {
return row;
}
@PlanningSolution
public class NQueens implements Solution<SimpleScore> {
// ...
@ValueRangeProvider(id = "rowRange")
public List<Row> getRowList() {
return rowList;
}
}
Impo rt ant
That Collection (or ValueRange) mus t not contain the value null, not
e ve n for a nullable planning variable .
Annotating the fie ld ins te ad of the prope rty works too:
86
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
@PlanningSolution
public class NQueens implements Solution<SimpleScore> {
...
@ValueRangeProvider(id = "rowRange")
private List<Row> rowList;
}
4.3.5.2.3. ValueRangePro vider o n t he Planning Ent it y
Each planning e ntity has its own value range (a s e t of pos s ible planning value s ) for
the planning variable . For e xample , if a te ache r can never te ach in a room that
doe s not be long to his de partme nt, le cture s of that te ache r can limit the ir room
value range to the rooms of his de partme nt.
@PlanningVariable(valueRangeProviderRefs =
{"departmentRoomRange"})
public Room getRoom() {
return room;
}
@ValueRangeProvider(id = "departmentRoomRange")
public List<Room> getPossibleRoomList() {
return
getCourse().getTeacher().getDepartment().getRoomList();
}
Ne ve r us e this to e nforce a s oft cons traint (or e ve n a hard cons traint whe n the
proble m might not have a fe as ible s olution). For e xample : Unle s s the re is no othe r
way, a te ache r can not te ach in a room that doe s not be long to his de partme nt. In
this cas e , the te ache r s hould not be limite d in his room value range (be caus e
s ome time s the re is no othe r way).
No t e
By limiting the value range s pe cifically of one planning e ntity, you are
e ffe ctive ly cre ating a built-in hard constraint. This can have the be ne fit of
s e ve re ly lowe ring the numbe r of pos s ible s olutions ; howe ve r, it can als o
away the fre e dom of the optimiz ation algorithms to te mporarily bre ak that
cons traint in orde r to e s cape from a local optimum.
A planning e ntity s hould not us e othe r planning e ntitie s to de te rminate its value
range . That would only try to make the planning e ntity s olve the planning proble m
its e lf and inte rfe re with the optimiz ation algorithms .
Eve ry e ntity has its own List ins tance , unle s s multiple e ntitie s have the s ame
value range . For e xample , if te ache r A and B be long to the s ame de partme nt, the y
us e the s ame List<Room> ins tance . Furthe rmore , e ach List contains a s ubs e t of
the s ame s e t of planning value ins tance s . For e xample , if de partme nt A and B can
both us e room X, the n the ir List<Room> ins tance s contain the s ame Room
ins tance .
87
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
A ValueRangeProvider on the planning e ntity cons ume s more me mory
than ValueRangeProvider on the Solution and dis able s ce rtain automatic
pe rformance optimiz ations .
Warning
A ValueRangeProvider on the planning e ntity is not curre ntly compatible
with a chaine d variable .
4.3.5.2.4. ValueRangeFact o ry
Ins te ad of a Collection, you can als o re turn a ValueRange or
CountableValueRange, build by the ValueRangeFactory:
@ValueRangeProvider(id = "delayRange")
public CountableValueRange<Integer> getDelayRange() {
return ValueRangeFactory.createIntValueRange(0, 5000);
}
A ValueRange us e s far le s s me mory, be caus e it only holds the bounds . In the
e xample above , a Collection would ne e d to hold all 5000 ints , ins te ad of jus t the
two bounds .
Furthe rmore , an incrementUnit can be s pe cifie d, for e xample if you have to buy
s tocks in units of 200 pie ce s :
@ValueRangeProvider(id = "stockAmountRange")
public CountableValueRange<Integer> getStockAmountRange() {
// Range: 0, 200, 400, 600, ..., 9999600, 9999800, 10000000
return ValueRangeFactory.createIntValueRange(0, 10000000,
200);
}
No t e
Re turn CountableValueRange ins te ad of ValueRange whe ne ve r pos s ible
(s o Planne r knows that it’s countable ).
The ValueRangeFactory has cre ation me thods for s e ve ral value clas s type s :
int: A 32bit inte ge r range .
long: A 64bit inte ge r range .
double: A 64bit floating point range which only s upports random s e le ction
(be caus e it doe s not imple me nt CountableValueRange).
BigInteger: An arbitrary-pre cis ion inte ge r range .
88
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
BigDecimal: A de cimal point range . By de fault, the incre me nt unit is the lowe s t
non-z e ro value in the s cale of the bounds .
4.3.5.2.5. Co mbine ValueRangePro viders
Value range provide rs can be combine d, for e xample :
@PlanningVariable(valueRangeProviderRefs = {"companyCarRange",
"personalCarRange"})
public Car getCar() {
return car;
}
@ValueRangeProvider(id = "companyCarRange")
public List<CompanyCar> getCompanyCarList() {
return companyCarList;
}
@ValueRangeProvider(id = "personalCarRange")
public List<PersonalCar> getPersonalCarList() {
return personalCarList;
}
4.3.5.3. Planning Value St rengt h
Some optimiz ation algorithms work more e fficie ntly if the y have an e s timation of
which planning value s are s tronge r, which me ans the y are more like ly to s atis fy a
planning e ntity. For e xample : in bin packing bigge r containe rs are more like ly to fit
an ite m and in cours e s che duling bigge r rooms are le s s like ly to bre ak the s tude nt
capacity cons traint.
The re fore , you can s e t a strengthComparatorClass to the @PlanningVariable
annotation:
@PlanningVariable(..., strengthComparatorClass =
CloudComputerStrengthComparator.class)
public CloudComputer getComputer() {
// ...
}
public class CloudComputerStrengthComparator implements
Comparator<CloudComputer> {
public int compare(CloudComputer a, CloudComputer b) {
return new CompareToBuilder()
.append(a.getMultiplicand(), b.getMultiplicand())
.append(b.getCost(), a.getCost()) // Descending (but
this is debatable)
.append(a.getId(), b.getId())
.toComparison();
}
}
89
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
If you have multiple planning value clas s e s in the s ame value range , the
strengthComparatorClass ne e ds to imple me nt a Comparator of a
common s upe rclas s (for e xample Comparator<Object>) and be able to
handle comparing ins tance s of thos e diffe re nt clas s e s .
Alte rnative ly, you can als o s e t a strengthWeightFactoryClass to the
@PlanningVariable annotation, s o you have acce s s to the re s t of the proble m
facts from the s olution too:
@PlanningVariable(..., strengthWeightFactoryClass =
RowStrengthWeightFactory.class)
public Row getRow() {
// ...
}
Se e s orte d s e le ction for more information.
Impo rt ant
Stre ngth s hould be imple me nte d as ce nding: we ake r value s are lowe r,
s tronge r value s are highe r. For e xample in bin packing: s mall containe r <
me dium containe r < big containe r.
None of the curre nt planning variable s tate in any of the planning e ntitie s s hould
be us e d to compare planning value s . During cons truction he uris tics , thos e
variable s are like ly to be null. For e xample , none of the row variable s of any
Queen may be us e d to de te rmine the s tre ngth of a Row.
4.3.5.4. Chained Planning Variable (T SP, VRP, …​)
Some us e cas e s , s uch as TSP and Ve hicle Routing, re quire chaining. This me ans
the planning e ntitie s point to e ach othe r and form a chain. By mode ling the
proble m as a s e t of chains (ins te ad of a s e t of tre e s /loops ), the s e arch s pace is
he avily re duce d.
A planning variable that is chaine d e ithe r:
Dire ctly points to a proble m fact (or planning e ntity), which is calle d an anchor.
Points to anothe r planning e ntity with the s ame planning variable , which
re curs ive ly points to an anchor.
He re are s ome e xample of valid and invalid chains :
90
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
Eve ry initializ e d planning e ntity is part of an ope n-e nde d chain that be gins from an
anchor. A valid mode l me ans that:
A chain is ne ve r a loop. The tail is always ope n.
Eve ry chain always has e xactly one anchor. The anchor is a proble m fact, ne ve r
a planning e ntity.
A chain is ne ve r a tre e , it is always a line . Eve ry anchor or planning e ntity has
at mos t one trailing planning e ntity.
Eve ry initializ e d planning e ntity is part of a chain.
An anchor with no planning e ntitie s pointing to it, is als o cons ide re d a chain.
Warning
A planning proble m ins tance give n to the Solver mus t be valid.
No t e
If your cons traints dictate a clos e d chain, mode l it as an ope n-e nde d chain
(which is e as ie r to pe rs is t in a databas e ) and imple me nt a s core
cons traint for the las t e ntity back to the anchor.
91
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The optimiz ation algorithms and built-in Moves do chain corre ction to guarante e that
the mode l s tays valid:
Warning
A cus tom Move imple me ntation mus t le ave the mode l in a valid s tate .
For e xample , in TSP the anchor is a Domicile (in ve hicle routing it is Vehicle):
public class Domicile ... implements Standstill {
...
public City getCity() {...}
}
The anchor (which is a proble m fact) and the planning e ntity imple me nt a common
inte rface , for e xample TSP’s Standstill:
public interface Standstill {
City getCity();
}
92
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
That inte rface is the re turn type of the planning variable . Furthe rmore , the planning
variable is chaine d. For e xample TSP’s Visit (in ve hicle routing it is Customer):
@PlanningEntity
public class Visit ... implements Standstill {
...
public City getCity() {...}
@PlanningVariable(graphType = PlanningVariableGraphType.CHAINED,
valueRangeProviderRefs = {"domicileRange", "visitRange"})
public Standstill getPreviousStandstill() {
return previousStandstill;
}
public void setPreviousStandstill(Standstill previousStandstill)
{
this.previousStandstill = previousStandstill;
}
}
Notice how two value range provide rs are us ually combine d:
The value range provide r that holds the anchors , for e xample domicileList.
The value range provide r that holds the initializ e d planning e ntitie s , for e xample
visitList.
4.3.6. Shadow Variable
4.3.6.1. Int roduct ion
A s hadow variable is a variable whos e corre ct value can be de duce d from the
s tate of the ge nuine planning variable s . Eve n though s uch a variable violate s the
principle of normaliz ation by de finition, in s ome us e cas e s it can be ve ry practical
to us e a s hadow variable , e s pe cially to e xpre s s the cons traints more naturally. For
e xample in ve hicle routing with time windows : the arrival time at a cus tome r for a
ve hicle can be calculate d bas e d on the pre vious ly vis ite d cus tome rs of that
ve hicle (and the known trave l time s be twe e n two locations ).
93
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Whe n the cus tome rs for a ve hicle change , the arrival time for e ach cus tome r is
automatically adjus te d. For more information, s e e the ve hicle routing domain
mode l.
From a s core calculation pe rs pe ctive , a s hadow variable is like any othe r planning
variable . From an optimiz ation pe rs pe ctive , Planne r e ffe ctive ly only optimiz e s the
ge nuine variable s (and mos tly ignore s the s hadow variable s ): it jus t as s ure s that
whe n a ge nuine variable change s , any de pe nde nt s hadow variable s are change d
accordingly.
The re are s e ve ral build-in s hadow variable s :
4.3.6.2. Bi-direct ional Variable (Inverse Relat ion Shadow Variable)
Two variable s are bi-dire ctional if the ir ins tance s always point to e ach othe r
(unle s s one s ide points to null and the othe r s ide doe s not e xis t). So if A
re fe re nce s B, the n B re fe re nce s A.
94
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
For a non-chaine d planning variable , the bi-dire ctional re lations hip mus t be a many
to one re lations hip. To map a bi-dire ctional re lations hip be twe e n two planning
variable s , annotate the mas te r s ide (which is the ge nuine s ide ) as a normal
planning variable :
@PlanningEntity
public class CloudProcess {
@PlanningVariable(...)
public CloudComputer getComputer() {
return computer;
}
public void setComputer(CloudComputer computer) {...}
}
And the n annotate the othe r s ide (which is the s hadow s ide ) with a
@InverseRelationShadowVariable annotation on a Collection (us ually a Set or
List) prope rty:
@PlanningEntity
public class CloudComputer {
@InverseRelationShadowVariable(sourceVariableName = "computer")
public List<CloudProcess> getProcessList() {
return processList;
}
}
95
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The sourceVariableName prope rty is the name of the ge nuine planning variable
on the re turn type of the ge tte r (s o the name of the ge nuine planning variable on
the other s ide ).
No t e
The s hadow prope rty, which is a Collection, can ne ve r be null. If no
ge nuine variable is re fe re ncing that s hadow e ntity, the n it is an e mpty
Collection. Furthe rmore it mus t be a mutable Collection be caus e once
the Solve r s tarts initializ ing or changing ge nuine planning variable s , it will
add and re move to the Collectionsof thos e s hadow variable s
accordingly.
For a chaine d planning variable , the bi-dire ctional re lations hip mus t be a one to one
re lations hip. In that cas e , the ge nuine s ide looks like this :
@PlanningEntity
public class Customer ... {
@PlanningVariable(graphType = PlanningVariableGraphType.CHAINED,
...)
public Standstill getPreviousStandstill() {
return previousStandstill;
}
public void setPreviousStandstill(Standstill previousStandstill)
{...}
}
And the s hadow s ide looks like this :
@PlanningEntity
public class Standstill {
@InverseRelationShadowVariable(sourceVariableName =
"previousStandstill")
public Customer getNextCustomer() {
return nextCustomer;
}
public void setNextCustomer(Customer nextCustomer) {...}
}
Warning
The input planning proble m of a Solver mus t not violate bi-dire ctional
re lations hips . If A points to B, the n B mus t point to A. Planne r will not
violate that principle during planning, but the input mus t not violate it.
4.3.6.3. Anchor Shadow Variable
96
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
An anchor s hadow variable is the anchor of a chaine d variable .
Annotate the anchor prope rty as a @AnchorShadowVariable annotation:
@PlanningEntity
public class Customer {
@AnchorShadowVariable(sourceVariableName = "previousStandstill")
public Vehicle getVehicle() {...}
public void setVehicle(Vehicle vehicle) {...}
}
The sourceVariableName prope rty is the name of the chaine d variable on the
s ame e ntity clas s .
4.3.6.4. Cust om VariableList ener
To update a s hadow variable , Planne r us e s a VariableListener. To de fine a
cus tom s hadow variable , write a cus tom VariableListener: imple me nt the
inte rface and annotate it on the s hadow variable that ne e ds to change .
@PlanningVariable(...)
public Standstill getPreviousStandstill() {
return previousStandstill;
}
@CustomShadowVariable(variableListenerClass =
VehicleUpdatingVariableListener.class,
sources = {@CustomShadowVariable.Source(variableName =
"previousStandstill")})
public Vehicle getVehicle() {
return vehicle;
}
The variableName is the variable that trigge rs change s in the s hadow variable (s ).
No t e
If the clas s of the trigge r variable is diffe re nt than the s hadow variable ,
als o s pe cify the entityClass on @CustomShadowVariable.Source. In that
cas e , make s ure that that entityClass is als o prope rly configure d as a
planning e ntity clas s in the s olve r config, or the VariableListener will
s imply ne ve r trigge r.
Any clas s that has at le as t one s hadow variable , is a planning e ntity clas s ,
e ve n it has no ge nuine planning variable s .
For e xample , the VehicleUpdatingVariableListener as s ure s that e ve ry
Customer in a chain has the s ame Vehicle, name ly the chain’s anchor.
public class VehicleUpdatingVariableListener implements
VariableListener<Customer> {
97
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
public void afterEntityAdded(ScoreDirector scoreDirector,
Customer customer) {
updateVehicle(scoreDirector, customer);
}
public void afterVariableChanged(ScoreDirector scoreDirector,
Customer customer) {
updateVehicle(scoreDirector, customer);
}
...
protected void updateVehicle(ScoreDirector scoreDirector,
Customer sourceCustomer) {
Standstill previousStandstill =
sourceCustomer.getPreviousStandstill();
Vehicle vehicle = previousStandstill == null ? null :
previousStandstill.getVehicle();
Customer shadowCustomer = sourceCustomer;
while (shadowCustomer != null && shadowCustomer.getVehicle()
!= vehicle) {
scoreDirector.beforeVariableChanged(shadowCustomer,
"vehicle");
shadowCustomer.setVehicle(vehicle);
scoreDirector.afterVariableChanged(shadowCustomer,
"vehicle");
shadowCustomer = shadowCustomer.getNextCustomer();
}
}
}
Warning
A VariableListener can only change s hadow variable s . It mus t ne ve r
change a ge nuine planning variable or a proble m fact.
Warning
Any change of a s hadow variable mus t be told to the ScoreDirector.
If one VariableListener change s two s hadow variable s (be caus e having two
s e parate VariableListenerswould be ine fficie nt), the n annotate only the firs t
s hadow variable with the variableListenerClass and le t the othe r s hadow
variable (s ) re fe re nce the firs t s hadow variable :
@PlanningVariable(...)
public Standstill getPreviousStandstill() {
return previousStandstill;
}
98
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
@CustomShadowVariable(variableListenerClass =
TransportTimeAndCapacityUpdatingVariableListener.class,
sources = {@CustomShadowVariable.Source(variableName =
"previousStandstill")})
public Integer getTransportTime() {
return transportTime;
}
@CustomShadowVariable(variableListenerRef =
@PlanningVariableReference(variableName = "transportTime"))
public Integer getCapacity() {
return capacity;
}
4.3.6.5. VariableList ener t riggering order
All s hadow variable s are trigge re d by a VariableListener, re gardle s s if it’s a
build-in or a cus tom s hadow variable . The ge nuine and s hadow variable s form a
graph, that de te rmine s the orde r in which the afterEntityAdded(),
afterVariableChanged() and afterEntityRemoved() me thods are calle d:
No t e
In the e xample above , D could have als o be e n orde re d afte r E (or F)
be caus e the re is no dire ct or indire ct de pe nde ncy be twe e n D and E (or F).
99
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Planne r guarante e s that:
The firs t VariableListener after*() me thods trigge r afte r the las t ge nuine
variable has change d. The re fore the ge nuine variable s (A and B in the e xample
above ) are guarante e d to be in a cons is te nt s tate acros s all its ins tance s (with
value s A1, A2 and B1 in the e xample above ) be caus e the e ntire Move has be e n
applie d.
The s e cond VariableListener after*() me thods trigge r afte r the las t firs t
s hadow variable has change d. The re fore the firs t s hadow variable (C in the
e xample above ) are guarante e d to be in cons is te nt s tate acros s all its
ins tance s (with value s C1 and C2 in the e xample above ). And of cours e the
ge nuine variable s too.
And s o forth.
Planne r doe s not guarante e the orde r in which the after*() me thods are calle d
for the sameVariableListener with diffe re nt parame te rs (s uch as A1 and A2 in
the e xample above ), although the y are like ly to be in the orde r in which the y we re
affe cte d.
4.3.7. Planning Problem and Planning Solut ion
4.3.7.1. Planning Problem Inst ance
A datas e t for a planning proble m ne e ds to be wrappe d in a clas s for the Solver to
s olve . You mus t imple me nt this clas s . For e xample in n que e ns , this in the
NQueens clas s , which contains a Column lis t, a Row lis t, and a Queen lis t.
A planning proble m is actually a uns olve d planning s olution or - s tate d diffe re ntly an uninitializ e d Solution. The re fore , that wrapping clas s mus t imple me nt the
Solution inte rface . For e xample in n que e ns , that NQueens clas s imple me nts
Solution, ye t e ve ry Queen in a fre s h NQueens clas s is not ye t as s igne d to a Row
(the ir row prope rty is null). This is not a fe as ible s olution. It’s not e ve n a pos s ible
s olution. It’s an uninitializ e d s olution.
4.3.7.2. Solut ion Int erf ace
You ne e d to pre s e nt the proble m as a Solution ins tance to the Solver. So your
clas s ne e ds to imple me nt the Solution inte rface :
public interface Solution<S extends Score> {
S getScore();
void setScore(S score);
Collection<? extends Object> getProblemFacts();
}
For e xample , an NQueens ins tance holds a lis t of all columns , all rows and all Queen
ins tance s :
@PlanningSolution
public class NQueens implements Solution<SimpleScore> {
100
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
private int n;
// Problem facts
private List<Column> columnList;
private List<Row> rowList;
// Planning entities
private List<Queen> queenList;
// ...
}
A planning s olution clas s als o ne e ds to be annotate d with the @PlanningSolution
annotation. Without automate d s canning, the s olve r configuration als o ne e ds to
de clare the planning s olution clas s :
<solver>
...
<solutionClass>org.optaplanner.examples.nqueens.domain.NQueens</solut
ionClass>
...
</solver>
4.3.7.3. Ext ract t he ent it ies f rom t he Solut ion
Planne r ne e ds to e xtract the e ntity ins tance s from the Solution ins tance . It ge ts
thos e colle ction(s ) by calling e ve ry ge tte r (or fie ld) that is annotate d with
@PlanningEntityCollectionProperty:
@PlanningSolution
public class NQueens implements Solution<SimpleScore> {
...
private List<Queen> queenList;
@PlanningEntityCollectionProperty
public List<Queen> getQueenList() {
return queenList;
}
}
The re can be multiple @PlanningEntityCollectionProperty annotate d
me mbe rs . Thos e can e ve n re turn a Collection with the s ame e ntity clas s type .
No t e
A @PlanningEntityColle ctionPrope rty annotation ne e ds to be on a me mbe r
in a clas s with a @PlanningSolution annotation. It is ignore d on pare nt
clas s e s or s ubclas s e s without that annotation.
101
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
In rare cas e s , a planning e ntity might be a s ingle ton: us e
@PlanningEntityProperty on its ge tte r (or fie ld) ins te ad.
4.3.7.4. T he get Score() and set Score() Met hods
A Solution re quire s a s core prope rty. The s core prope rty is null if the Solution
is uninitializ e d or if the s core has not ye t be e n (re )calculate d. The score prope rty
is us ually type d to the s pe cific Score imple me ntation you us e . For e xample ,
NQueens us e s a SimpleScore:
@PlanningSolution
public class NQueens implements Solution<SimpleScore> {
private SimpleScore score;
public SimpleScore getScore() {
return score;
}
public void setScore(SimpleScore score) {
this.score = score;
}
// ...
}
Mos t us e cas e s us e a HardSoftScore ins te ad:
@PlanningSolution
public class CourseSchedule implements Solution<HardSoftScore> {
private HardSoftScore score;
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
// ...
}
Se e the Score calculation s e ction for more information on the Score
imple me ntations .
4.3.7.5. T he get ProblemFact s() Met hod
The me thod is only us e d if Drools is us e d for s core calculation. Othe r s core
dire ctors do not us e it.
All obje cts re turne d by the getProblemFacts() me thod will be as s e rte d into the
Drools working me mory, s o the s core rule s can acce s s the m. For e xample ,
NQueens jus t re turns all Column and Row ins tance s .
102
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
public Collection<? extends Object> getProblemFacts() {
List<Object> facts = new ArrayList<Object>();
facts.addAll(columnList);
facts.addAll(rowList);
// Do not add the planning entity's (queenList) because that
will be done automatically
return facts;
}
All planning e ntitie s are automatically ins e rte d into the Drools working me mory. Do
not add the m in the me thod getProblemFacts().
No t e
A common mis take is to us e facts.add(…​) ins te ad of fact.addAll(…​) for
a Collection, which le ads to s core rule s failing to match be caus e the
e le me nts of that Collection are not in the Drools working me mory.
The getProblemFacts() me thod is not calle d ofte n: at mos t only once pe r s olve r
phas e pe r s olve r thre ad.
4.3.7.5.1. Cached Pro blem Fact
A cache d proble m fact is a proble m fact that doe s not e xis t in the re al domain
mode l, but is calculate d be fore the Solver re ally s tarts s olving. The
getProblemFacts() me thod has the chance to e nrich the domain mode l with s uch
cache d proble m facts , which can le ad to s imple r and fas te r s core cons traints .
For e xample in e xamination, a cache d proble m fact TopicConflict is cre ate d for
e ve ry two Topicswhich s hare at le as t one Student.
public Collection<? extends Object> getProblemFacts() {
List<Object> facts = new ArrayList<Object>();
// ...
facts.addAll(calculateTopicConflictList());
// ...
return facts;
}
private List<TopicConflict> calculateTopicConflictList() {
List<TopicConflict> topicConflictList = new
ArrayList<TopicConflict>();
for (Topic leftTopic : topicList) {
for (Topic rightTopic : topicList) {
if (leftTopic.getId() < rightTopic.getId()) {
int studentSize = 0;
for (Student student :
leftTopic.getStudentList()) {
if
(rightTopic.getStudentList().contains(student)) {
studentSize++;
}
}
if (studentSize > 0) {
103
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
topicConflictList.add(new
TopicConflict(leftTopic, rightTopic, studentSize));
}
}
}
}
return topicConflictList;
}
Whe re a s core cons traint ne e ds to che ck that no two e xams with a topic that
s hare s a s tude nt are s che dule d clos e toge the r (de pe nding on the cons traint: at
the s ame time , in a row, or in the s ame day), the TopicConflict ins tance can be
us e d as a proble m fact, rathe r than having to combine e ve ry two Student
ins tance s .
4.3.7.6. Cloning a Solut ion
Mos t (if not all) optimiz ation algorithms clone the s olution e ach time the y e ncounte r
a ne w be s t s olution (s o the y can re call it late r) or to work with multiple s olutions in
paralle l.
No t e
The re are many ways to clone , s uch as a s hallow clone , de e p clone , …​
This conte xt focus e s on a planning clone.
A planning clone of a Solution mus t fulfill the s e re quire me nts :
The clone mus t re pre s e nt the s ame planning proble m. Us ually it re us e s the
s ame ins tance s of the proble m facts and proble m fact colle ctions as the
original.
The clone mus t us e diffe re nt, clone d ins tance s of the e ntitie s and e ntity
colle ctions . Change s to an original Solution e ntity’s variable s mus t not affe ct
its clone .
104
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
Imple me nting a planning clone me thod is hard, the re fore you do not ne e d to
imple me nt it.
4.3.7.6.1. FieldAccessingSo lut io nClo ner
This SolutionCloner is us e d by de fault. It works we ll for mos t us e cas e s .
Warning
Whe n the FieldAccessingSolutionCloner clone s your e ntity colle ction,
it may not re cogniz e the imple me ntation and re place it with ArrayList,
LinkedHashSet or TreeSet (whiche ve r is more applicable ). It re cogniz e s
mos t of the common JDK Collection imple me ntations .
The FieldAccessingSolutionCloner doe s not clone proble m facts by de fault. If
any of your proble m facts ne e ds to be de e p clone d for a planning clone , for
e xample if the proble m fact re fe re nce s a planning e ntity or the planning s olution,
mark it with a @DeepPlanningClone annotation:
@DeepPlanningClone
public class SeatDesignationDependency {
private SeatDesignation leftSeatDesignation; // planning entity
private SeatDesignation rightSeatDesignation; // planning entity
...
}
105
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
In the e xample above , be caus e SeatDesignation is a planning e ntity (which is
de e p planning clone d automatically), SeatDesignationDependency mus t als o be
de e p planning clone d.
Alte rnative ly, the @DeepPlanningClone annotation can als o be us e d on a ge tte r
me thod.
4.3.7.6.2. Cust o m Clo ning: Make So lut io n Implement PlanningClo neable
If your Solution imple me nts PlanningCloneable, Planne r will automatically
choos e to clone it by calling the planningClone() me thod.
public interface PlanningCloneable<T> {
T planningClone();
}
For e xample : If NQueens imple me nts PlanningCloneable, it would only de e p clone
all Queen ins tance s . Whe n the original s olution is change d during planning, by
changing a Queen, the clone s tays the s ame .
public class NQueens implements Solution<...>,
PlanningCloneable<NQueens> {
...
/**
* Clone will only deep copy the {@link #queenList}.
*/
public NQueens planningClone() {
NQueens clone = new NQueens();
clone.id = id;
clone.n = n;
clone.columnList = columnList;
clone.rowList = rowList;
List<Queen> clonedQueenList = new ArrayList<Queen>
(queenList.size());
for (Queen queen : queenList) {
clonedQueenList.add(queen.planningClone());
}
clone.queenList = clonedQueenList;
clone.score = score;
return clone;
}
}
The planningClone() me thod s hould only de e p clone the planning e ntitie s . Notice
that the proble m facts , s uch as Column and Row are not normally clone d: e ve n the ir
List ins tance s are not clone d. If you we re to clone the proble m facts too, the n you
would have to make s ure that the ne w planning e ntity clone s als o re fe r to the ne w
proble m facts clone s us e d by the s olution. For e xample , if you we re to clone all
Row ins tance s , the n e ach Queen clone and the NQueens clone its e lf s hould re fe r to
thos e ne w Row clone s .
106
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
Warning
Cloning an e ntity with a chaine d variable is de vious : a variable of an
e ntity A might point to anothe r e ntity B. If A is clone d, the n its variable
mus t point to the clone of B, not the original B.
4.3.7.7. Creat e an Uninit ialized Solut ion
Cre ate a Solution ins tance to re pre s e nt your planning proble m’s datas e t, s o it
can be s e t on the Solver as the planning proble m to s olve . For e xample in n
que e ns , an NQueens ins tance is cre ate d with the re quire d Column and Row
ins tance s and e ve ry Queen s e t to a diffe re nt column and e ve ry row s e t to null.
private NQueens createNQueens(int n) {
NQueens nQueens = new NQueens();
nQueens.setId(0L);
nQueens.setN(n);
nQueens.setColumnList(createColumnList(nQueens));
nQueens.setRowList(createRowList(nQueens));
nQueens.setQueenList(createQueenList(nQueens));
return nQueens;
}
private List<Queen> createQueenList(NQueens nQueens) {
int n = nQueens.getN();
List<Queen> queenList = new ArrayList<Queen>(n);
long id = 0L;
for (Column column : nQueens.getColumnList()) {
Queen queen = new Queen();
queen.setId(id);
id++;
queen.setColumn(column);
// Notice that we leave the PlanningVariable properties
on null
queenList.add(queen);
}
return queenList;
}
Figure 4.3. Uninit ialized So lut io n f o r t he 4 Queens Puzzle
107
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Us ually, mos t of this data come s from your data laye r, and your Solution
imple me ntation jus t aggre gate s that data and cre ate s the uninitializ e d planning
e ntity ins tance s to plan:
private void createLectureList(CourseSchedule schedule) {
List<Course> courseList = schedule.getCourseList();
List<Lecture> lectureList = new ArrayList<Lecture>
(courseList.size());
long id = 0L;
for (Course course : courseList) {
for (int i = 0; i < course.getLectureSize(); i++) {
Lecture lecture = new Lecture();
lecture.setId(id);
id++;
lecture.setCourse(course);
lecture.setLectureIndexInCourse(i);
// Notice that we leave the PlanningVariable
properties (period and room) on null
lectureList.add(lecture);
}
}
schedule.setLectureList(lectureList);
}
4.4. USE T HE SOLVER
4.4.1. T he Solver Int erf ace
A Solver imple me ntation will s olve your planning proble m.
public interface Solver<S extends Solution> {
S solve(S planningProblem);
...
}
A Solver can only s olve one planning proble m ins tance at a time . A Solver s hould
only be acce s s e d from a s ingle thre ad, e xce pt for the me thods that are
s pe cifically javadocce d as be ing thre ad-s afe . It is built with a SolverFactory, the re
is no ne e d to imple me nt it yours e lf.
4.4.2. Solving a Problem
Solving a proble m is quite e as y once you have :
A Solver built from a s olve r configuration
A Solution that re pre s e nts the planning proble m ins tance
Jus t provide the planning proble m as argume nt to the solve() me thod and it will
re turn the be s t s olution found:
NQueens bestSolution = solver.solve(planningProblem);
108
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
For e xample in n que e ns , the solve() me thod will re turn an NQueens ins tance with
e ve ry Queen as s igne d to a Row.
Figure 4.4. Best So lut io n f o r t he 4 Queens Puzzle in 8ms (Also an
Opt imal So lut io n)
The solve(Solution) me thod can take a long time (de pe nding on the proble m
s iz e and the s olve r configuration). The Solver inte llige ntly wade s through the
s e arch s pace of pos s ible s olutions and re me mbe rs the be s t s olution it e ncounte rs
during s olving. De pe nding on a numbe r factors (including proble m s iz e , how much
time the Solver has , the s olve r configuration, …​), that be s t s olution might or might
not be an optimal s olution.
No t e
The Solution ins tance give n to the me thod solve(Solution) is change d
by the Solver, but do not mis take it for the be s t s olution.
The Solution ins tance re turne d by the me thods solve(Solution) or
getBestSolution() is mos t like ly a planning clone of the ins tance give n
to the me thod solve(Solution), which implie s it is a diffe re nt ins tance .
No t e
The Solution ins tance give n to the solve(Solution) me thod doe s not
ne e d to be uninitializ e d. It can be partially or fully initializ e d, which is ofte n
the cas e in re pe ate d planning.
4.4.3. Environment Mode: Are T here Bugs in my Code?
The e nvironme nt mode allows you to de te ct common bugs in your imple me ntation.
It doe s not affe ct the logging le ve l.
You can s e t the e nvironme nt mode in the s olve r configuration XML file :
<solver>
<environmentMode>FAST_ASSERT</environmentMode>
...
</solver>
109
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
A s olve r has a s ingle Random ins tance . Some s olve r configurations us e the Random
ins tance a lot more than othe rs . For e xample Simulate d Anne aling de pe nds highly
on random numbe rs , while Tabu Se arch only de pe nds on it to de al with s core tie s .
The e nvironme nt mode influe nce s the s e e d of that Random ins tance .
The s e are the e nvironme nt mode s :
4.4.3.1. FULL_ASSERT
The FULL_ASSERT mode turns on all as s e rtions (s uch as as s e rt that the
incre me ntal s core calculation is uncorrupte d for e ach move ) to fail-fas t on a bug in
a Move imple me ntation, a s core rule , the rule e ngine its e lf, …​
This mode is re producible (s e e the re producible mode ). It is als o intrus ive
be caus e it calls the me thod calculateScore() more fre que ntly than a non-as s e rt
mode .
The FULL_ASSERT mode is horribly s low (be caus e it doe s not re ly on incre me ntal
s core calculation).
4.4.3.2. NON_INT RUSIVE_FULL_ASSERT
The NON_INTRUSIVE_FULL_ASSERT turns on s e ve ral as s e rtions to fail-fas t on a bug
in a Move imple me ntation, a s core rule , the rule e ngine its e lf, …​
This mode is re producible (s e e the re producible mode ). It is non-intrus ive be caus e
it doe s not call the me thod calculateScore() more fre que ntly than a non as s e rt
mode .
The NON_INTRUSIVE_FULL_ASSERT mode is horribly s low (be caus e it doe s not re ly
on incre me ntal s core calculation).
4.4.3.3. FAST _ASSERT
The FAST_ASSERT mode turns on mos t as s e rtions (s uch as as s e rt that an
undoMove ’s s core is the s ame as be fore the Move ) to fail-fas t on a bug in a Move
imple me ntation, a s core rule , the rule e ngine its e lf, …​
This mode is re producible (s e e the re producible mode ). It is als o intrus ive
be caus e it calls the me thod calculateScore() more fre que ntly than a non as s e rt
mode .
The FAST_ASSERT mode is s low.
It is re comme nde d to write a te s t cas e that doe s a s hort run of your planning
proble m with the FAST_ASSERT mode on.
4.4.3.4. REPRODUCIBLE (def ault )
The re producible mode is the de fault mode be caus e it is re comme nde d during
de ve lopme nt. In this mode , two runs in the s ame Planne r ve rs ion will e xe cute the
s ame code in the s ame orde r. Thos e two runs will have the s ame re s ult at e ve ry
s te p, e xce pt if the note be low applie s . This e nable s you to re produce bugs
cons is te ntly. It als o allows you to be nchmark ce rtain re factorings (s uch as a s core
cons traint pe rformance optimiz ation) fairly acros s runs .
110
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
No t e
De s pite the re producible mode , your application might s till not be fully
re producible be caus e of:
Us e of HashSet (or anothe r Collection which has an incons is te nt
orde r be twe e n JVM runs ) for colle ctions of planning e ntitie s or planning
value s (but not normal proble m facts ), e s pe cially in the Solution
imple me ntation. Re place it with LinkedHashSet.
Combining a time gradie nt de pe nde nt algorithms (mos t notably
Simulate d Anne aling) toge the r with time s pe nt te rmination. A
s ufficie ntly large diffe re nce in allocate d CPU time will influe nce the time
gradie nt value s . Re place Simulate d Anne aling with Late Acce ptance . Or
ins te ad, re place time s pe nt te rmination with s te p count te rmination.
The re producible mode is s lightly s lowe r than the production mode . If your
production e nvironme nt re quire s re producibility, us e this mode in production too.
In practice , this mode us e s the de fault, fixe d random s e e d if no s e e d is s pe cifie d,
and it als o dis able s ce rtain concurre ncy optimiz ations (s uch as work s te aling).
4.4.3.5. PRODUCT ION
The production mode is the fas te s t, but it is not re producible . It is re comme nde d
for a production e nvironme nt, unle s s re producibility is re quire d.
In practice , this mode us e s no fixe d random s e e d if no s e e d is s pe cifie d.
4.4.4. Logging Level: What is t he Solver Doing?
The be s t way to illuminate the black box that is a Solver, is to play with the logging
le ve l:
error: Log e rrors , e xce pt thos e that are thrown to the calling code as a
RuntimeException.
No t e
If an e rror happe ns , Planne r normally fails fas t: it throws a s ubclas s of
RuntimeException with a de taile d me s s age to the calling code . It doe s
not log it as an e rror its e lf to avoid duplicate log me s s age s . Exce pt if
the calling code e xplicitly catche s and e ats that RuntimeException, a
Thread's de fault ExceptionHandler will log it as an e rror anyway.
Me anwhile , the code is dis rupte d from doing furthe r harm or
obfus cating the e rror.
warn: Log s us picious circums tance s .
info: Log e ve ry phas e and the s olve r its e lf. Se e s cope ove rvie w.
debug: Log e ve ry s te p of e ve ry phas e . Se e s cope ove rvie w.
111
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
trace: Log e ve ry move of e ve ry s te p of e ve ry phas e . Se e s cope ove rvie w.
No t e
Turning on trace logging, will s low down pe rformance cons ide rably: it is
ofte n four time s s lowe r. Howe ve r, it is invaluable during de ve lopme nt
to dis cove r a bottle ne ck.
Eve n de bug logging can s low down pe rformance cons ide rably for fas t
s te pping algorithms (s uch as Late Acce ptance and Simulate d
Anne aling), but not for s low s te pping algorithms (s uch as Tabu Se arch).
For e xample , s e t it to debug logging, to s e e whe n the phas e s e nd and how fas t
s te ps are take n:
INFO Solving started: time spent (3), best score
(uninitialized/0), random (JDK with seed 0).
DEBUG
CH step (0), time spent (5), score (0), selected move
count (1), picked move (Queen-2 {null -> Row-0}).
DEBUG
CH step (1), time spent (7), score (0), selected move
count (3), picked move (Queen-1 {null -> Row-2}).
DEBUG
CH step (2), time spent (10), score (0), selected move
count (4), picked move (Queen-3 {null -> Row-3}).
DEBUG
CH step (3), time spent (12), score (-1), selected move
count (4), picked move (Queen-0 {null -> Row-1}).
INFO Construction Heuristic phase (0) ended: step total (4), time
spent (12), best score (-1).
DEBUG
LS step (0), time spent (19), score (-1),
best score
(-1), accepted/selected move count (12/12), picked move (Queen-1
{Row-2 -> Row-3}).
DEBUG
LS step (1), time spent (24), score (0), new best score
(0), accepted/selected move count (9/12), picked move (Queen-3
{Row-3 -> Row-2}).
INFO Local Search phase (1) ended: step total (2), time spent
(24), best score (0).
INFO Solving ended: time spent (24), best score (0), average
calculate count per second (1625).
All time s pe nt value s are in millis e conds .
Eve rything is logge d to SLF4J, which is a s imple logging facade which de le gate s
e ve ry log me s s age to Logback, Apache Commons Logging, Log4j or
java.util.logging. Add a de pe nde ncy to the logging adaptor for your logging
frame work of choice .
If you are not us ing any logging frame work ye t, us e Logback by adding this Mave n
de pe nde ncy (the re is no ne e d to add an e xtra bridge de pe nde ncy):
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.x</version>
</dependency>
Configure the logging le ve l on the org.optaplanner package in your logback.xml
112
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
file :
<configuration>
<logger name="org.optaplanner" level="debug"/>
...
<configuration>
If ins te ad, you are s till us ing Log4J 1.x (and you do not want to s witch to its fas te r
s ucce s s or, Logback), add the bridge de pe nde ncy:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.x</version>
</dependency>
And configure the logging le ve l on the package org.optaplanner in your
log4j.xml file :
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<category name="org.optaplanner">
<priority value="debug" />
</category>
...
</log4j:configuration>
113
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
In a multite nant application, multiple Solver ins tance s might be running at
the s ame time . To s e parate the ir logging into dis tinct file s , s urround the
solve() call with an MDC:
MDC.put("tenant.name",tenantName);
Solution bestSolution = solver.solve(planningProblem);
MDC.remove("tenant.name");
The n configure your logge r to us e diffe re nt file s for e ach
${tenant.name}. For e xample in Logback, us e a SiftingAppender in
logback.xml:
<appender name="fileAppender"
class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>tenant.name</key>
<defaultValue>unknown</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender.${tenant.name}"
class="...FileAppender">
<file>local/log/optaplanner-${tenant.name}.log</file>
...
</appender>
</sift>
</appender>
4.4.5. Random Number Generat or
Many he uris tics and me tahe uris tics de pe nd on a ps e udorandom numbe r ge ne rator
for move s e le ction, to re s olve s core tie s , probability bas e d move acce ptance , …​
During s olving, the s ame Random ins tance is re us e d to improve re producibility,
pe rformance and uniform dis tribution of random value s .
To change the random s e e d of that Random ins tance , s pe cify a randomSeed:
<solver>
<randomSeed>0</randomSeed>
...
</solver>
To change the ps e udorandom numbe r ge ne rator imple me ntation, s pe cify a
randomType:
<solver>
<randomType>MERSENNE_TWISTER</randomType>
...
</solver>
The following type s are s upporte d:
114
CHAPT ER 4 . PLANNER CO NFIGURAT IO N
JDK (de fault): Standard imple me ntation (java.util.Random).
MERSENNE_TWISTER: Imple me ntation by Commons Math.
WELL512A, WELL1024A, WELL19937A, WELL19937C, WELL44497A and WELL44497B:
Imple me ntation by Commons Math.
For mos t us e cas e s , the randomType has no s ignificant impact on the ave rage
quality of the be s t s olution on multiple datas e ts . If you want to confirm this on your
us e cas e , us e the be nchmarke r.
115
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 5. SCORE CALCULATION
5.1. SCORE T ERMINOLOGY
5.1.1. What is a Score?
Eve ry initializ e d Solution has a s core . The s core is an obje ctive way to compare
two s olutions . The s olution with the highe r s core is be tte r. The Solver aims to find
the Solution with the highe s t Score of all pos s ible s olutions . The best solution is
the Solution with the highe s t Score that Solver has e ncounte re d during s olving,
which might be the optimal solution.
Planne r cannot automatically know which Solution is be s t for your bus ine s s , s o
you ne e d to te ll it how to calculate the s core of a give n Solution according to your
bus ine s s ne e ds . If you forge t or are unable to imple me nt an important bus ine s s
cons traint, the s olution is probably us e le s s :
De fining cons traints in Planne r is ve ry fle xible through the following s core
te chnique s :
Score signum (positive or negative): maximiz e or minimiz e a cons traint type
Score weight: put a cos t/profit on a cons traint type
Score level (hard, soft, …​): prioritiz e a group of cons traint type s
Pareto scoring
116
CHAPT ER 5. SCO RE CALCULAT IO N
5.1.2. Score Const raint Signum (Posit ive or Negat ive)
All s core te chnique s are bas e d on cons traints . A cons traint can be a s imple
patte rn (s uch as Maximiz e the apple harve s t in the s olution) or a more comple x
patte rn. A pos itive cons traint is a cons traint you want to maximiz e . A ne gative
cons traint is a cons traint you want to minimiz e .
The image above illus trate s that the optimal s olution always has the highe s t s core ,
re gardle s s if the cons traints are pos itive or ne gative .
Mos t planning proble ms have only ne gative cons traints and the re fore have a
ne gative s core . In that cas e , the s core is the s um of the we ight of the ne gative
cons traints be ing broke n, with a pe rfe ct s core of 0. This e xplains why the s core of
a s olution of four que e ns is the ne gative of the numbe r of que e n pairs which can
attack e ach othe r.
Ne gative and pos itive cons traints can be combine d, e ve n in the s ame s core le ve l.
No t e
Do not pre s ume that your bus ine s s knows all its s core cons traints in
advance . Expe ct s core cons traints to be adde d or change d afte r the firs t
re le as e s .
Whe n a cons traint activate s (be caus e the ne gative cons traint is broke n or the
pos itive cons traint is fulfille d) on a ce rtain planning e ntity s e t, it is calle d a
constraint match.
117
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
5.1.3. Score Const raint Weight
Not all s core cons traints are e qually important. If bre aking one cons traint is e qually
bad as bre aking anothe r cons traint x time s , the n thos e two cons traints have a
diffe re nt we ight (but the y are in the s ame s core le ve l). For e xample in ve hicle
routing, you can make one "unhappy drive r" cons traint match count as much as two
"fue l tank us age " cons traint matche s :
Score we ighting is ofte n us e d in us e cas e s whe re you can put a price tag on
e ve rything. In that cas e , the pos itive cons traints maximiz e re ve nue and the
ne gative cons traints minimiz e e xpe ns e s , s o toge the r the y maximiz e profit.
Alte rnative ly, s core we ighting is als o ofte n us e d to cre ate s ocial fairne s s . For
e xample , a nurs e , who re que s ts a fre e day, pays a highe r we ight on Ne w Ye ars
e ve than on a normal day.
Putting a good we ight on a cons traint can be a difficult analytical de cis ion, be caus e
it is about making choice s and trade offs with othe r cons traints . Howe ve r, a nonaccurate we ight is le s s damaging than me diocre algorithms :
118
CHAPT ER 5. SCO RE CALCULAT IO N
The we ight of a cons traint match can be dynamically bas e d on the planning e ntitie s
involve d. For e xample in cloud balance , the we ight of the s oft cons traint match for
an active Computer is the cost of that Computer (which diffe rs pe r compute r).
No t e
Furthe rmore , it is ofte n us e ful to allow the e nd-us e r to re calibrate
cons traint we ights in the us e r inte rface , as de mons trate d in the e xam
time tabling e xample with the InstitutionParametrization clas s .
5.1.4. Score Const raint Level (hard, sof t , …​)
Some time s a s core cons traint outranks anothe r s core cons traint, no matte r how
many time s the othe r is broke n. In that cas e , thos e s core cons traints are in
diffe re nt le ve ls . For e xample , a nurs e cannot do 2 s hifts at the s ame time (due to
the cons traints of phys ical re ality), this outranks all nurs e happine s s cons traints .
Mos t us e cas e s have only two s core le ve ls , hard and s oft. Two s core s are
compare d le xicographically. The firs t s core le ve l ge ts compare d firs t. If thos e
diffe r, the othe rs s core le ve ls are ignore d. For e xample , a s core that bre aks 0
hard cons traints and 1000000 s oft cons traints is be tte r than a s core that bre aks 1
hard cons traint and 0 s oft cons traints .
119
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
If the re are two (or more ) s core le ve ls , for e xample a hard and s oft le ve l, the n a
s core is fe as ible if no hard cons traints are broke n.
No t e
By de fault, Planne r will always as s ign all planning variable s a planning
value . If the re is no fe as ible s olution, this me ans the be s t s olution will be
unfe as ible . To ins te ad le ave s ome of the planning e ntitie s unas s igne d,
apply ove rcons traine d planning.
For e ach cons traint, you ne e d to pick a s core le ve l, a s core we ight and a s core
s ignum. For e xample : -1soft which has s core le ve l of soft, a we ight of 1 and a
ne gative s ignum. Do not us e a big cons traint we ight whe n your bus ine s s actually
wants diffe re nt s core le ve ls . That hack, known as score folding, is broke n:
120
CHAPT ER 5. SCO RE CALCULAT IO N
No t e
Your bus ine s s might te ll you that your hard cons traints all have the s ame
we ight, be caus e the y cannot be broke n (s o the we ight doe s not matte r).
This is not true be caus e if no fe as ible s olution e xis ts for a s pe cific
datas e t, the le as t infe as ible s olution allows the bus ine s s to e s timate how
many bus ine s s re s ource s the y are lacking. For e xample in cloud
balancing, how many ne w compute rs to buy.
Furthe rmore , it will like ly cre ate a s core trap. For e xample in cloud balance
if a Computer has s e ve n CPU too little for its Processe s , the n it mus t be
we ighte d s e ve n time s as much as if it had only one CPU too little .
Thre e or more s core le ve ls are s upporte d. For e xample : a company might de cide
that profit outranks e mploye e s atis faction (or vis a ve rs a), while both are outranke d
by the cons traints of phys ical re ality.
No t e
To mode l fairne s s or load balancing, the re is no ne e d to us e lots of s core
le ve ls (e ve n though Planne r can handle many s core le ve ls ).
5.1.5. Paret o Scoring (AKA Mult i-object ive Opt imizat ion Scoring)
Far le s s common is the us e cas e of pare to optimiz ation, which is als o known unde r
121
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
the more confus ing te rm multi-obje ctive optimiz ation. In pare to s coring, s core
cons traints are in the s ame s core le ve l, ye t the y are not we ighte d agains t e ach
othe r. Whe n two s core s are compare d, e ach of the s core cons traints are
compare d individually and the s core with the mos t dominating s core cons traints
wins . Pare to s coring can e ve n be combine d with s core le ve ls and s core cons traint
we ighting.
Cons ide r this e xample with pos itive cons traints , whe re we want to ge t the mos t
apple s and orange s . Since it is impos s ible to compare apple s and orange s , we can
not we ight the m agains t e ach othe r. Ye t, de s pite that we can not compare the m,
we can s tate that two apple s are be tte r the n one apple . Similarly, we can s tate
that two apple s and one orange are be tte r than jus t one orange . So de s pite our
inability to compare s ome Score s conclus ive ly (at which point we de clare the m
e qual), we can find a s e t of optimal s core s . Thos e are calle d pare to optimal.
Score s are cons ide re d e qual far more ofte n. It is le ft up to a human to choos e the
be tte r out of a s e t of be s t s olutions (with e qual s core s ) found by Planne r. In the
e xample above , the us e r mus t choos e be twe e n s olution A (thre e apple s and one
orange ) and s olution B (one apple and s ix orange s ). It is guarante e d that Planne r
has not found anothe r s olution which has more apple s or more orange s or e ve n a
be tte r combination of both (s uch as two apple s and thre e orange s ).
To imple me nt pare to s coring in Planne r, imple me nt a cus tom Score De finition and
Score (and re place the BestSolutionRecaller). Future ve rs ions will provide outof-the -box s upport.
122
CHAPT ER 5. SCO RE CALCULAT IO N
No t e
A pare to Score's compareTo me thod is not trans itive be caus e it doe s a
pare to comparis on. For e xample : having two apple s is gre ate r than one
apple . One apple is e qual to One orange . Ye t, two apple s are not gre ate r
than one orange (but actually e qual). Pare to comparis on violate s the
contract of the inte rface java.lang.Comparable's compareTo me thod, but
Planne rs s ys te ms are pareto comparison safe, unle s s e xplicitly s tate d
othe rwis e in this docume ntation.
5.1.6. Combining Score T echniques
All the s core te chnique s me ntione d above , can be combine d s e amle s s ly:
5.1.7. Score int erf ace
A s core is re pre s e nte d by the Score inte rface , which naturally e xte nds
Comparable:
public interface Score<...> extends Comparable<...> {
...
}
The Score imple me ntation to us e de pe nds on your us e cas e . Your s core might not
e fficie ntly fit in a s ingle long value . Planne r has s e ve ral built-in Score
imple me ntations , but you can imple me nt a cus tom Score too. Mos t us e cas e s te nd
123
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
to us e the built-in HardSoftScore.
The Score imple me ntation (for e xample HardSoftScore) mus t be the s ame
throughout a Solver runtime . The Score imple me ntation is configure d in the s olve r
configuration as a Score De finition:
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
...
</scoreDirectorFactory>
5.1.8. Avoid Float ing Point Numbers in Score Calculat ion
Avoid the us e of float and double for s core calculation. Us e BigDecimal ins te ad.
Floating point numbe rs (float and double) cannot re pre s e nt a de cimal numbe r
corre ctly. For e xample : a double cannot hold the value 0.05 corre ctly. Ins te ad, it
holds the ne are s t re pre s e ntable value . Arithme tic (including addition and
s ubtraction) with floating point numbe rs , e s pe cially for planning proble ms , le ads to
incorre ct de cis ions :
124
CHAPT ER 5. SCO RE CALCULAT IO N
Additionally, floating point numbe r addition is not as s ociative :
System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03))
); // returns false
This le ads to score corruption.
De cimal numbe rs (BigDecimal) have none of the s e proble ms .
No t e
BigDe cimal arithme tic is cons ide rably s lowe r than int, long or double
arithme tic. In e xpe rime nts we have s e e n the ave rage calculation count
ge t divide d by 5.
The re fore , in s ome cas e s , it can be worthwhile to multiply all numbe rs for
a s ingle s core we ight by a plural of te n (for e xample 1000), s o the s core
we ight fits in an int or long.
5.2. CHOOSE A SCORE DEFINIT ION
Each Score imple me ntation als o has a ScoreDefinition imple me ntation. For
e xample : SimpleScore is de fine d by SimpleScoreDefinition.
125
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
To prope rly write a Score to databas e (with JPA/Hibe rnate ) or to XML/JSON
(with XStre am/JAXB), s e e the inte gration chapte r.
5.2.1. SimpleScore
A SimpleScore has a s ingle int value , for e xample -123. It has a s ingle s core
le ve l.
<scoreDirectorFactory>
<scoreDefinitionType>SIMPLE</scoreDefinitionType>
...
</scoreDirectorFactory>
Variants of this scoreDefinitionType:
SIMPLE_LONG: Us e s SimpleLongScore which has a long value ins te ad of an int
value .
SIMPLE_DOUBLE: Us e s SimpleDoubleScore which has a double value ins te ad of
an int value . Not re comme nde d to us e .
SIMPLE_BIG_DECIMAL: Us e s SimpleBigDecimalScore which has a BigDecimal
value ins te ad of an int value .
5.2.2. HardSof t Score (Recommended)
A HardSoftScore has a hard int value and a s oft int value , for e xample 123hard/-456soft. It has 2 s core le ve ls (hard and s oft).
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
...
</scoreDirectorFactory>
Variants of this scoreDefinitionType:
HARD_SOFT_LONG: Us e s HardSoftLongScore which has long value s ins te ad of
int value s .
HARD_SOFT_DOUBLE: Us e s HardSoftDoubleScore which has double value s
ins te ad of int value s . Not re comme nde d to us e .
HARD_SOFT_BIG_DECIMAL: Us e s HardSoftBigDecimalScore which has
BigDecimal value s ins te ad of int value s .
5.2.3. HardMediumSof t Score
A HardMediumSoftScore which has a hard int value , a me dium int value and a
s oft int value , for e xample -123hard/-456medium/-789soft. It has 3 s core
le ve ls (hard, me dium and s oft).
126
CHAPT ER 5. SCO RE CALCULAT IO N
<scoreDirectorFactory>
<scoreDefinitionType>HARD_MEDIUM_SOFT</scoreDefinitionType>
...
</scoreDirectorFactory>
Variants of this scoreDefinitionType:
HARD_MEDIUM_SOFT_LONG: Us e s HardMediumSoftLongScore which has long
value s ins te ad of int value s .
5.2.4. BendableScore
A BendableScore has a configurable numbe r of s core le ve ls . It has an array of
hard int value s and an array of s oft int value , for e xample with 2 hard le ve ls and
3 s oft le ve ls , the s core can be -123/-456/-789/-012/-345.
<scoreDirectorFactory>
<scoreDefinitionType>BENDABLE</scoreDefinitionType>
<bendableHardLevelsSize>2</bendableHardLevelsSize>
<bendableSoftLevelsSize>3</bendableSoftLevelsSize>
...
</scoreDirectorFactory>
The numbe r of hard and s oft s core le ve ls ne e ds to be s e t at configuration time . It
is not fle xible to change during s olving.
Variants of this scoreDefinitionType:
BENDABLE_Long: Us e s BendableLongScore which has long value s ins te ad of
int value s .
BENDABLE_BIG_DECIMAL: Us e s BendableBigDecimalScore which has
BigDecimal value s ins te ad of int value s .
5.2.5. Implement ing a Cust om Score
The ScoreDefinition inte rface de fine s the s core re pre s e ntation.
To imple me nt a cus tom Score, you will als o ne e d to imple me nt a cus tom
ScoreDefinition. Exte nd AbstractScoreDefinition (pre fe rably by copy pas ting
HardSoftScoreDefinition) and s tart from the re .
The n hook your cus tom ScoreDefinition in your SolverConfig.xml :
<scoreDirectorFactory>
<scoreDefinitionClass>...MyScoreDefinition</scoreDefinitionClass>
...
</scoreDirectorFactory>
To have it inte grate s e amle s s ly with JPA/Hibe rnate , XStre am, …​ you might ne e d to
write s ome glue code .
5.3. CALCULAT E T HE SCORE
5.3.1. Score Calculat ion T ypes
127
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
5.3.1. Score Calculat ion T ypes
The re are s e ve ral ways to calculate the Score of a Solution:
Easy Java score calculation: imple me nt a s ingle Java me thod
Incremental Java score calculation: imple me nt multiple Java me thods
Drools score calculation (re comme nde d): imple me nt s core rule s
Eve ry s core calculation type can us e any Score de finition. For e xample , e as y Java
s core calculation can output a HardSoftScore.
All s core calculation type s are Obje ct Orie nte d and can re us e e xis ting Java code .
Impo rt ant
The s core calculation mus t be re ad-only. It mus t not change the planning
e ntitie s or the proble m facts in any way. For e xample , it mus t not call a
s e tte r me thod on a planning e ntity in a Drools s core rule ’s RHS. This doe s
not apply to logically inserted obje cts , which can be change d by the s core
rule s that logically ins e rte d the m in the firs t place .
Planne r will not re calculate the s core of a Solution if it can pre dict it
(unle s s an e nvironme ntMode as s e rtion is e nable d). For e xample , afte r a
winning s te p is done , the re is no ne e d to calculate the s core be caus e that
move was done and undone e arlie r. As a re s ult, the re is no guarante e
that s uch change s applie d during s core calculation are actually done .
5.3.2. Easy Java Score Calculat ion
An e as y way to imple me nt your s core calculation in Java.
Advantage s :
Plain old Java: no le arning curve
Opportunity to de le gate s core calculation to an e xis ting code bas e or le gacy
s ys te m
Dis advantage s :
Slowe r and le s s s calable
Be caus e the re is no incre me ntal s core calculation
Jus t imple me nt one me thod of the inte rface EasyScoreCalculator:
public interface EasyScoreCalculator<Sol extends Solution> {
Score calculateScore(Sol solution);
}
For e xample in n que e ns :
public class NQueensEasyScoreCalculator implements
128
CHAPT ER 5. SCO RE CALCULAT IO N
EasyScoreCalculator<NQueens> {
public SimpleScore calculateScore(NQueens nQueens) {
int n = nQueens.getN();
List<Queen> queenList = nQueens.getQueenList();
int score = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Queen leftQueen = queenList.get(i);
Queen rightQueen = queenList.get(j);
if (leftQueen.getRow() != null && rightQueen.getRow()
!= null) {
if (leftQueen.getRowIndex() ==
rightQueen.getRowIndex()) {
score--;
}
if (leftQueen.getAscendingDiagonalIndex() ==
rightQueen.getAscendingDiagonalIndex()) {
score--;
}
if (leftQueen.getDescendingDiagonalIndex() ==
rightQueen.getDescendingDiagonalIndex()) {
score--;
}
}
}
}
return SimpleScore.valueOf(score);
}
}
Configure it in your s olve r configuration:
<scoreDirectorFactory>
<scoreDefinitionType>...</scoreDefinitionType>
<easyScoreCalculatorClass>org.optaplanner.examples.nqueens.solver.sco
re.NQueensEasyScoreCalculator</easyScoreCalculatorClass>
</scoreDirectorFactory>
Alte rnative ly, build an EasyScoreCalculator ins tance at runtime and s e t it with
the programmatic API:
solverFactory.getSolverConfig().getScoreDirectorFactoryConfig.setEasy
ScoreCalculator(easyScoreCalculator);
5.3.3. Increment al Java Score Calculat ion
A way to imple me nt your s core calculation incre me ntally in Java.
Advantage s :
129
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Ve ry fas t and s calable
Curre ntly the fas te s t if imple me nte d corre ctly
Dis advantage s :
Hard to write
A s calable imple me ntation he avily us e s maps , inde xe s , …​ (things the
Drools rule e ngine can do for you)
You have to le arn, de s ign, write and improve all the s e pe rformance
optimiz ations yours e lf
Hard to re ad
Re gular s core cons traint change s can le ad to a high mainte nance cos t
Imple me nt all the me thods of the inte rface IncrementalScoreCalculator and
e xte nd the clas s AbstractIncrementalScoreCalculator:
public interface IncrementalScoreCalculator<Sol extends Solution> {
void resetWorkingSolution(Sol workingSolution);
void beforeEntityAdded(Object entity);
void afterEntityAdded(Object entity);
void beforeVariableChanged(Object entity, String variableName);
void afterVariableChanged(Object entity, String variableName);
void beforeEntityRemoved(Object entity);
void afterEntityRemoved(Object entity);
Score calculateScore();
}
130
CHAPT ER 5. SCO RE CALCULAT IO N
For e xample in n que e ns :
public class NQueensAdvancedIncrementalScoreCalculator extends
AbstractIncrementalScoreCalculator<NQueens> {
private Map<Integer, List<Queen>> rowIndexMap;
private Map<Integer, List<Queen>> ascendingDiagonalIndexMap;
private Map<Integer, List<Queen>> descendingDiagonalIndexMap;
private int score;
public void resetWorkingSolution(NQueens nQueens) {
int n = nQueens.getN();
rowIndexMap = new HashMap<Integer, List<Queen>>(n);
ascendingDiagonalIndexMap = new HashMap<Integer, List<Queen>>
(n * 2);
descendingDiagonalIndexMap = new HashMap<Integer,
List<Queen>>(n * 2);
for (int i = 0; i < n; i++) {
rowIndexMap.put(i, new ArrayList<Queen>(n));
ascendingDiagonalIndexMap.put(i, new ArrayList<Queen>
(n));
descendingDiagonalIndexMap.put(i, new ArrayList<Queen>
(n));
if (i != 0) {
ascendingDiagonalIndexMap.put(n - 1 + i, new
ArrayList<Queen>(n));
descendingDiagonalIndexMap.put((-i), new
ArrayList<Queen>(n));
131
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
}
}
score = 0;
for (Queen queen : nQueens.getQueenList()) {
insert(queen);
}
}
public void beforeEntityAdded(Object entity) {
// Do nothing
}
public void afterEntityAdded(Object entity) {
insert((Queen) entity);
}
public void beforeVariableChanged(Object entity, String
variableName) {
retract((Queen) entity);
}
public void afterVariableChanged(Object entity, String
variableName) {
insert((Queen) entity);
}
public void beforeEntityRemoved(Object entity) {
retract((Queen) entity);
}
public void afterEntityRemoved(Object entity) {
// Do nothing
}
private void insert(Queen queen) {
Row row = queen.getRow();
if (row != null) {
int rowIndex = queen.getRowIndex();
List<Queen> rowIndexList = rowIndexMap.get(rowIndex);
score -= rowIndexList.size();
rowIndexList.add(queen);
List<Queen> ascendingDiagonalIndexList =
ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex());
score -= ascendingDiagonalIndexList.size();
ascendingDiagonalIndexList.add(queen);
List<Queen> descendingDiagonalIndexList =
descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex());
score -= descendingDiagonalIndexList.size();
descendingDiagonalIndexList.add(queen);
}
}
private void retract(Queen queen) {
Row row = queen.getRow();
if (row != null) {
List<Queen> rowIndexList =
132
CHAPT ER 5. SCO RE CALCULAT IO N
rowIndexMap.get(queen.getRowIndex());
rowIndexList.remove(queen);
score += rowIndexList.size();
List<Queen> ascendingDiagonalIndexList =
ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex());
ascendingDiagonalIndexList.remove(queen);
score += ascendingDiagonalIndexList.size();
List<Queen> descendingDiagonalIndexList =
descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex());
descendingDiagonalIndexList.remove(queen);
score += descendingDiagonalIndexList.size();
}
}
public SimpleScore calculateScore() {
return SimpleScore.valueOf(score);
}
}
Configure it in your s olve r configuration:
<scoreDirectorFactory>
<scoreDefinitionType>...</scoreDefinitionType>
<incrementalScoreCalculatorClass>org.optaplanner.examples.nqueens.sol
ver.score.NQueensAdvancedIncrementalScoreCalculator</incrementalScore
CalculatorClass>
</scoreDirectorFactory>
Optionally, to e xplain a s core with ScoreDirector.getConstraintMatchTotals()
or to ge t be tte r output whe n the IncrementalScoreCalculator is corrupte d in
FAST_ASSERT or FULL_ASSERT environmentMode, imple me nt als o the
ConstraintMatchAwareIncrementalScoreCalculator inte rface :
public interface ConstraintMatchAwareIncrementalScoreCalculator<Sol
extends Solution> {
void resetWorkingSolution(Sol workingSolution, boolean
constraintMatchEnabled);
Collection<ConstraintMatchTotal> getConstraintMatchTotals();
}
5.3.4. Drools Score Calculat ion
5.3.4.1. Overview
Imple me nt your s core calculation us ing the Drools rule e ngine . Eve ry s core
cons traint is writte n as one or more s core rule s .
Advantage s :
Incre me ntal s core calculation for fre e
133
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Be caus e mos t DRL s yntax us e s forward chaining, it doe s incre me ntal
calculation without any e xtra code
Score cons traints are is olate d as s e parate rule s
Eas y to add or e dit e xis ting s core rule s
Fle xibility to augme nt your s core cons traints by
De fining the m in de cis ion table s
Exce l (XLS) s pre ads he e t
KIE Workbe nch We bUI
Trans late the m into natural language with DSL
Store and re le as e in the KIE Workbe nch re pos itory
Pe rformance optimiz ations in future ve rs ions for fre e
In e ve ry re le as e , the Drools rule e ngine te nds to be come fas te r
Dis advantage s :
DRL le arning curve
Us age of DRL
Polyglot fe ar can prohibit the us e of a ne w language s uch as DRL in s ome
organiz ations
5.3.4.2. Drools Score Rules Conf igurat ion
The re are s e ve ral ways to de fine whe re your s core rule s live .
5.3.4.2.1. A sco reDrl Reso urce o n t he Classpat h
This is the e as y way. The s core rule s live in a DRL file which is provide d as a
clas s path re s ource . Jus t add the s core rule s DRL file in the s olve r configuration as
a <scoreDrl> e le me nt:
<scoreDirectorFactory>
<scoreDefinitionType>...</scoreDefinitionType>
<scoreDrl>org/optaplanner/examples/nqueens/solver/nQueensScoreRules.d
rl</scoreDrl>
</scoreDirectorFactory>
In a typical proje ct (following the Mave n dire ctory s tructure ), that DRL file would be
locate d at
$PROJECT_DIR/src/main/resources/org/optaplanner/examples/nqueens/solv
er/nQueensScoreRules.drl (e ve n for a war proje ct).
134
CHAPT ER 5. SCO RE CALCULAT IO N
No t e
The <scoreDrl> e le me nt e xpe cts a clas s path re s ource , as de fine d by
ClassLoader.getResource(String), it doe s not acce pt a File, nor an
URL, nor a we bapp re s ource . Se e be low to us e a File ins te ad.
Add multiple <scoreDrl> e le me nts if the s core rule s are s plit acros s multiple DRL
file s .
Optionally, you can als o s e t drools configuration prope rtie s (but be care ful of
backwards compatibility is s ue s ):
<scoreDirectorFactory>
...
<scoreDrl>org/optaplanner/examples/nqueens/solver/nQueensScoreRules.d
rl</scoreDrl>
<kieBaseConfigurationProperties>
<drools.equalityBehavior>...</drools.equalityBehavior>
</kieBaseConfigurationProperties>
</scoreDirectorFactory>
5.3.4.2.2. A sco reDrlFile
To us e File on the local file s ys te m, ins te ad of a clas s path re s ource , add the
s core rule s DRL file in the s olve r configuration as a <scoreDrlFile> e le me nt:
<scoreDirectorFactory>
<scoreDefinitionType>...</scoreDefinitionType>
<scoreDrlFile>/home/ge0ffrey/tmp/nQueensScoreRules.drl</scoreDrlFile>
</scoreDirectorFactory>
Warning
For portability re as ons , a clas s path re s ource is re comme nde d ove r a
File . An application build on one compute r, but us e d on anothe r compute r,
might not find the file on the s ame location. Wors e , if the y us e a
diffe re nt Ope rating Sys te m, it is hard to choos e a portable file path.
Add multiple <scoreDrlFile> e le me nts if the s core rule s are s plit acros s multiple
DRL file s .
5.3.4.2.3. A ksessio nName in a Kjar f ro m a Maven repo sit o ry
This way allows you to us e s core rule s de fine d by the Workbe nch or build a kjar
and de ploy it to the Exe cution Se rve r. Both the s core rule s and the s olve r
configuration are re s ource s in a kjar. Clie nts can obtain that kjar e ithe r from the
local clas s path, from a local Mave n re pos itory or e ve n from a re mote Mave n
re pos itory.
135
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The s core rule s s till live in a DRL file , but the KieContainer finds it through the
META-INF/kmodule.xml file :
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<kbase name="nQueensKbase"
packages="org.optaplanner.examples.nqueens.solver">
<ksession name="nQueensKsession"/>
</kbase>
</kmodule>
The kmodule above will pick up all the DRL file s in the package
org.optaplanner.examples.nqueens.solver. A kbas e can e ve n e xte nd anothe r
kbas e .
Add the ks e s s ion name in the s olve r configuration as a <ksessionName> e le me nt:
<scoreDirectorFactory>
<scoreDefinitionType>...</scoreDefinitionType>
<ksessionName>nQueensKsession</ksessionName>
</scoreDirectorFactory>
Whe n us ing this approach, it’s re quire d to us e a
SolverFactory.createFromKieContainerXmlResource(…​) me thod to build the
SolverFactory.
5.3.4.3. Implement ing a Score Rule
He re is an e xample of a s core cons traint imple me nte d as a s core rule in a DRL
file :
rule "multipleQueensHorizontal"
when
Queen($id : id, row != null, $i : rowIndex)
Queen(id > $id, rowIndex == $i)
then
scoreHolder.addConstraintMatch(kcontext, -1);
end
This s core rule will fire once for e ve ry 2 que e ns with the s ame rowIndex. The (id
> $id) condition is ne e de d to as s ure that for 2 que e ns A and B, it can only fire for
(A, B) and not for (B, A), (A, A) or (B, B). Le t us take a clos e r look at this s core rule
on this s olution of 4 que e ns :
136
CHAPT ER 5. SCO RE CALCULAT IO N
In this s olution the multiple Que e ns Horiz ontal s core rule will fire for 6 que e n
couple s : (A, B), (A, C), (A, D), (B, C), (B, D) and (C, D). Be caus e none of the que e ns
are on the s ame ve rtical or diagonal line , this s olution will have a s core of -6. An
optimal s olution of 4 que e ns has a s core of 0.
No t e
Notice that e ve ry s core rule will re late to at le as t one planning e ntity clas s
(dire ctly or indire ctly through a logically ins e rte d fact).
This is a normal cas e . It would be a was te of time to write a s core rule
that only re late s to proble m facts , as the cons e que nce will ne ve r change
during planning, no matte r what the pos s ible s olution.
No t e
The kcontext variable is a magic variable in Drools Expe rt. The
scoreHolder's me thod us e s it to do incre me ntal s core calculation
corre ctly and to cre ate a ConstraintMatch ins tance .
5.3.4.4. Weighing Score Rules
A ScoreHolder ins tance is as s e rte d into the KieSession as a global calle d
scoreHolder. The s core rule s ne e d to (dire ctly or indire ctly) update that ins tance .
global SimpleScoreHolder scoreHolder;
rule "multipleQueensHorizontal"
when
Queen($id : id, row != null, $i : rowIndex)
Queen(id > $id, rowIndex == $i)
then
scoreHolder.addConstraintMatch(kcontext, -1);
end
// multipleQueensVertical is obsolete because it is always 0
rule "multipleQueensAscendingDiagonal"
when
Queen($id : id, row != null, $i : ascendingDiagonalIndex)
Queen(id > $id, ascendingDiagonalIndex == $i)
then
scoreHolder.addConstraintMatch(kcontext, -1);
end
rule "multipleQueensDescendingDiagonal"
when
Queen($id : id, row != null, $i : descendingDiagonalIndex)
Queen(id > $id, descendingDiagonalIndex == $i)
then
scoreHolder.addConstraintMatch(kcontext, -1);
end
137
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
To le arn more about the Drools rule language (DRL), cons ult the Drools
docume ntation.
Mos t us e cas e s als o we igh the ir cons traint type s or e ve n the ir matche s
diffe re ntly, by us ing a s pe cific we ight for e ach cons traint match. For e xample in
cours e s che duling, as s igning a Lecture to a Room that is lacking two s e ats is
we ighte d e qually bad as having one is olate d Lecture in a Curriculum:
global HardSoftScoreHolder scoreHolder;
// RoomCapacity: For each lecture, the number of students that
attend the course must be less or equal
// than the number of seats of all the rooms that host its
lectures.
rule "roomCapacity"
when
$room : Room($capacity : capacity)
$lecture : Lecture(room == $room, studentSize > $capacity,
$studentSize : studentSize)
then
// Each student above the capacity counts as 1 point of
penalty.
scoreHolder.addSoftConstraintMatch(kcontext, ($capacity $studentSize));
end
// CurriculumCompactness: Lectures belonging to a curriculum should
be adjacent
// to each other (i.e., in consecutive periods).
// For a given curriculum we account for a violation every time
there is one lecture not adjacent
// to any other lecture within the same day.
rule "curriculumCompactness"
when
...
then
// Each isolated lecture in a curriculum counts as 2 points
of penalty.
scoreHolder.addSoftConstraintMatch(kcontext, -2);
end
5.3.5. Init ializingScoreT rend
The InitializingScoreTrend s pe cifie s how the Score will change as more and
more variable s are initializ e d (while the alre ady initializ e d variable s do not
change ). Some optimiz ation algorithms (s uch Cons truction He uris tics and
Exhaus tive Se arch) run fas te r if the y have s uch information.
For for the Score (or e ach s core le ve l s e parate ly), s pe cify a tre nd:
ANY (de fault): Initializ ing an e xtra variable can change the s core pos itive ly or
ne gative ly. Give s no pe rformance gain.
138
CHAPT ER 5. SCO RE CALCULAT IO N
ONLY_UP (rare ): Initializ ing an e xtra variable can only change the s core
pos itive ly. Implie s that:
The re are only pos itive cons traints
And initializ ing the ne xt variable can not unmatch a pos itive cons traint that
was matche d by a pre vious initializ e d variable .
ONLY_DOWN: Initializ ing an e xtra variable can only change the s core ne gative ly.
Implie s that:
The re are only ne gative cons traints
And initializ ing the ne xt variable can not unmatch a ne gative cons traint that
was matche d by a pre vious initializ e d variable .
Mos t us e cas e s only have ne gative cons traints . Many of thos e have an
InitializingScoreTrend that only goe s down:
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<scoreDrl>.../cloudBalancingScoreRules.drl</scoreDrl>
<initializingScoreTrend>ONLY_DOWN</initializingScoreTrend>
</scoreDirectorFactory>
Alte rnative ly, you can als o s pe cify the tre nd for e ach s core le ve l s e parate ly:
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<scoreDrl>.../cloudBalancingScoreRules.drl</scoreDrl>
<initializingScoreTrend>ONLY_DOWN/ONLY_DOWN</initializingScoreTrend>
</scoreDirectorFactory>
5.3.6. Invalid Score Det ect ion
Put the environmentMode in FULL_ASSERT (or FAST_ASSERT) to de te ct corruption in
the incre me ntal s core calculation. For more information, s e e the s e ction about
environmentMode. Howe ve r, that will not ve rify that your s core calculator
imple me nts your s core cons traints as your bus ine s s actually de s ire s .
A pie ce of incre me ntal s core calculator code can be difficult to write and to re vie w.
As s e rt its corre ctne s s by us ing a diffe re nt imple me ntation (for e xample a
EasyScoreCalculator) to do the as s e rtions trigge re d by the environmentMode.
Jus t configure the diffe re nt imple me ntation as a
assertionScoreDirectorFactory:
<environmentMode>FAST_ASSERT</environmentMode>
...
<scoreDirectorFactory>
<scoreDefinitionType>...</scoreDefinitionType>
<scoreDrl>org/optaplanner/examples/nqueens/solver/nQueensScoreRules.d
rl</scoreDrl>
<assertionScoreDirectorFactory>
139
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<easyScoreCalculatorClass>org.optaplanner.examples.nqueens.solver.sco
re.NQueensEasyScoreCalculator</easyScoreCalculatorClass>
</assertionScoreDirectorFactory>
</scoreDirectorFactory>
This way, the scoreDrl will be validate d by the EasyScoreCalculator.
5.4. SCORE CALCULAT ION PERFORMANCE T RICKS
5.4.1. Overview
The Solver will normally s pe nd mos t of its e xe cution time running the s core
calculation (which is calle d in its de e pe s t loops ). Fas te r s core calculation will re turn
the s ame s olution in le s s time with the s ame algorithm, which normally me ans a
be tte r s olution in e qual time .
5.4.2. Average Calculat ion Count Per Second
Afte r s olving a proble m, the Solver will log the average calculation count per
second. This is a good me as ure me nt of Score calculation pe rformance , de s pite
that it is affe cte d by non s core calculation e xe cution time . It de pe nds on the
proble m s cale of the proble m datas e t. Normally, e ve n for high s cale proble ms , it is
highe r than 1000, e xce pt whe n you are us ing EasyScoreCalculator.
Impo rt ant
Whe n improving your s core calculation, focus on maximiz ing the ave rage
calculation count pe r s e cond, ins te ad of maximiz ing the be s t s core . A big
improve me nt in s core calculation can s ome time s yie ld little or no be s t
s core improve me nt, for e xample whe n the algorithm is s tuck in a local or
global optima. If you are watching the calculation count ins te ad, s core
calculation improve me nts are far more vis ible .
Furthe rmore , watching the calculation count, allows you to re move or add
s core cons traints , and s till compare it with the original calculation count.
Comparing the be s t s core with the original would be wrong, be caus e it is
comparing apple s and orange s .
5.4.3. Increment al Score Calculat ion (wit h Delt as)
Whe n a Solution change s , incre me ntal s core calculation (AKA de lta bas e d s core
calculation), will calculate the de lta with the pre vious s tate to find the ne w Score,
ins te ad of re calculating the e ntire s core on e ve ry s olution e valuation.
For e xample , if a s ingle que e n A move s from row 1 to 2, it will not bothe r to che ck
if que e n B and C can attack e ach othe r, s ince ne ithe r of the m change d.
Figure 5.1. Increment al Sco re Calculat io n f o r t he 4 Queens Puzzle
140
CHAPT ER 5. SCO RE CALCULAT IO N
This is a huge pe rformance and s calability gain. Drools s core calculation give s you
this huge s calability gain without forcing you to write a complicate d incre me ntal
s core calculation algorithm. Jus t le t the Drools rule e ngine do the hard work.
Notice that the s pe e dup is re lative to the s iz e of your planning proble m (your n),
making incre me ntal s core calculation far more s calable .
5.4.4. Avoid Calling Remot e Services During Score Calculat ion
Do not call re mote s e rvice s in your s core calculation (e xce pt if you are bridging
EasyScoreCalculator to a le gacy s ys te m). The ne twork late ncy will kill your s core
calculation pe rformance . Cache the re s ults of thos e re mote s e rvice s if pos s ible .
If s ome parts of a cons traint can be calculate d once , whe n the Solver s tarts , and
ne ve r change during s olving, the n turn the m into cache d proble m facts .
5.4.5. Point less Const raint s
If you know a ce rtain cons traint can ne ve r be broke n (or it is always broke n), you
ne e d not write a s core cons traint for it. For e xample in n que e ns , the s core
calculation doe s not che ck if multiple que e ns occupy the s ame column, be caus e a
Queen's column ne ve r change s and e ve ry Solution s tarts with e ach Queen on a
diffe re nt column.
141
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
Do not go ove rboard with this . If s ome datas e ts do not us e a s pe cific
cons traint but othe rs do, jus t re turn out of the cons traint as s oon as you
can. The re is no ne e d to dynamically change your s core calculation bas e d
on the datas e t.
5.4.6. Built -in Hard Const raint
Ins te ad of imple me nting a hard cons traint, it can s ome time s be built in. For
e xample , If Lecture A s hould ne ve r be as s igne d to Room X, but it us e s
ValueRangeProvider on Solution, s o the Solver will ofte n try to as s ign it to Room X
too (only to find out that it bre aks a hard cons traint). Us e a Value Range Provide r on
the planning e ntity or filte re d s e le ction to de fine that Cours e A s hould only be
as s igne d a Room diffe re nt than X.
This can give a good pe rformance gain in s ome us e cas e s , not jus t be caus e the
s core calculation is fas te r, but mainly be caus e mos t optimiz ation algorithms will
s pe nd le s s time e valuating unfe as ible s olutions . Howe ve r, us ually this not a good
ide a be caus e the re is a re al ris k of trading s hort te rm be ne fits for long te rm harm:
Many optimiz ation algorithms re ly on the fre e dom to bre ak hard cons traints
whe n changing planning e ntitie s , to ge t out of local optima.
Both imple me ntation approache s have limitations (fe ature compatibility,
dis abling automatic pe rformance optimiz ations ), as e xplaine d in the ir
docume ntation.
5.4.7. Ot her Score Calculat ion Perf ormance T ricks
Ve rify that your s core calculation happe ns in the corre ct Number type . If you are
making the s um of int value s , do not le t Drools s um it in a double which take s
longe r.
For optimal pe rformance , always us e s e rve r mode (java -server). We have
s e e n pe rformance incre as e s of 50% by turning on s e rve r mode .
For optimal pe rformance , us e the late s t Java ve rs ion. For e xample , in the pas t
we have s e e n pe rformance incre as e s of 30% by s witching from java 1.5 to 1.6.
Always re me mbe r that pre mature optimiz ation is the root of all e vil. Make s ure
your de s ign is fle xible e nough to allow configuration bas e d twe aking.
5.4.8. Score T rap
Make s ure that none of your s core cons traints caus e a s core trap. A trappe d s core
cons traint us e s the s ame we ight for diffe re nt cons traint matche s , whe n it could
jus t as e as ily us e a diffe re nt we ight. It e ffe ctive ly lumps its cons traint matche s
toge the r, which cre ate s a flatline d s core function for that cons traint. This can caus e
a s olution s tate in which s e ve ral move s ne e d to be done to re s olve or lowe r the
we ight of that s ingle cons traint. Some e xample s of s core traps :
You ne e d two doctors at e ach table , but you are only moving one doctor at a
time . So the s olve r has no ince ntive to move a doctor to a table with no doctors .
Punis h a table with no doctors more the n a table with only one doctor in that
142
CHAPT ER 5. SCO RE CALCULAT IO N
s core cons traint in the s core function.
Two e xams ne e d to be conducte d at the s ame time , but you are only moving
one e xam at a time . So the s olve r has to move one of thos e e xams to anothe r
time s lot without moving the othe r in the s ame move . Add a coars e -graine d
move that move s both e xams at the s ame time .
For e xample , cons ide r this s core trap. If the blue ite m move s from an ove rloade d
compute r to an e mpty compute r, the hard s core s hould improve . The trappe d
s core imple me ntation fails to do that:
The Solve r s hould e ve ntually ge t out of this trap, but it will take a lot of e ffort
(e s pe cially if the re are e ve n more proce s s e s on the ove rloade d compute r).
Be fore the y do that, the y might actually s tart moving more proce s s e s into that
ove rloade d compute r, as the re is no pe nalty for doing s o.
No t e
Avoiding s core traps doe s not me an that your s core function s hould be
s mart e nough to avoid local optima. Le ave it to the optimiz ation algorithms
to de al with the local optima.
Avoiding s core traps me ans to avoid, for e ach s core cons traint individually,
a flatline d s core function.
143
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Impo rt ant
Always s pe cify the de gre e of infe as ibility. The bus ine s s will ofte n s ay "if
the s olution is infe as ible , it doe s not matte r how infe as ible it is ." While that
is true for the bus ine s s , it is not true for s core calculation as it be ne fits
from knowing how infe as ible it is . In practice , s oft cons traints us ually do
this naturally and it is jus t a matte r of doing it for the hard cons traints too.
The re are s e ve ral ways to de al with a s core trap:
Improve the s core cons traint to make a dis tinction in the s core we ight. For
e xample , pe naliz e -1hard for e ve ry mis s ing CPU, ins te ad of jus t -1hard if any
CPU is mis s ing.
If changing the s core cons traint is not allowe d from the bus ine s s pe rs pe ctive ,
add a lowe r s core le ve l with a s core cons traint that make s s uch a dis tinction.
For e xample , pe naliz e -1subsoft for e ve ry mis s ing CPU, on top of -1hard if
any CPU is mis s ing. The bus ine s s ignore s the s ubs oft s core le ve l.
Add coars e -graine d move s and union s e le ct the m with the e xis ting fine -graine d
move s . A coars e -graine d move e ffe ctive ly doe s multiple move s to dire ctly ge t
out of a s core trap with a s ingle move . For e xample , move multiple ite ms from
the s ame containe r to anothe r containe r.
5.4.9. st epLimit Benchmark
Not all s core cons traints have the s ame pe rformance cos t. Some time s one s core
cons traint can kill the s core calculation pe rformance outright. Us e the Be nchmarke r
to do a one minute run and che ck what happe ns to the ave rage calculation count
pe r s e cond if you comme nt out all but one of the s core cons traints .
5.4.10. Fairness Score Const raint s
Some us e cas e s have a bus ine s s re quire me nt to provide a fair s che dule (us ually
as a s oft s core cons traint), for e xample :
Fairly dis tribute the workload amongs t the e mploye e s , to avoid e nvy.
Eve nly dis tribute the workload amongs t as s e ts , to improve re liability.
Imple me nting s uch a cons traint can s e e m difficult (e s pe cially be caus e the re are
diffe re nt ways to formaliz e fairne s s ), but us ually the squared workload
imple me ntation be have s mos t de s irable . For e ach e mploye e /as s e t, count the
workload w and s ubtract w² from the s core .
144
CHAPT ER 5. SCO RE CALCULAT IO N
As s hown above , the squared workload imple me ntation guarante e s that if you
s e le ct two e mploye e s from a give n s olution and make the ir dis tribution be twe e n
thos e two e mploye e s faire r, the n the re s ulting ne w s olution will have a be tte r
ove rall s core . Don not jus t us e the diffe re nce from the ave rage workload, as that
can le ad to unfairne s s , as de mons trate d be low.
145
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
Ins te ad of the squared workload, it is als o pos s ible to us e the variance
(s quare d diffe re nce to the ave rage ) or the s tandard de viation (s quare root
of the variance ). This has no e ffe ct on the s core comparis on, be caus e the
ave rage will not change during planning. It is jus t more work to imple me nt
(be caus e the ave rage ne e ds to be known) and trivially s lowe r (be caus e
the calculation is a bit longe r).
Whe n the workload is pe rfe ct balance d, the us e r ofte n like s to s e e a 0 s core ,
ins te ad of the dis tracting -34soft in the image above (for the las t s olution which is
almos t pe rfe ctly balance d). To nullify this , e ithe r add the ave rage multiplie d by the
numbe r of e ntitie s to the s core or ins te ad s how the variance or s tandard de viation
in the UI.
5.5. EXPLAINING T HE SCORE: USING SCORE
CALCULAT ION OUT SIDE T HE SOLVER
Othe r parts of your application, for e xample your we bUI, might ne e d to calculate
the s core too. Do that by re us ing the ScoreDirectorFactory of the Solver to
build a s e parate ScoreDirector for that we bUI:
ScoreDirectorFactory scoreDirectorFactory =
solver.getScoreDirectorFactory();
ScoreDirector guiScoreDirector =
scoreDirectorFactory.buildScoreDirector();
146
CHAPT ER 5. SCO RE CALCULAT IO N
The n us e it whe n you ne e d to calculate the Score of a Solution:
guiScoreDirector.setWorkingSolution(solution);
Score score = guiScoreDirector.calculateScore();
To e xplain in the GUI what e ntitie s are caus ing which part of the Score, ge t the
ConstraintMatch obje cts from the ScoreDirector:
for (ConstraintMatchTotal constraintMatchTotal :
guiScoreDirector.getConstraintMatchTotals()) {
String constraintName = constraintMatchTotal.getConstraintName();
Number weightTotal =
constraintMatchTotal.getWeightTotalAsNumber();
for (ConstraintMatch constraintMatch :
constraintMatchTotal.getConstraintMatchSet()) {
List<Object> justificationList =
constraintMatch.getJustificationList();
Number weight = constraintMatch.getWeightAsNumber();
...
}
}
No t e
Drools s core calculation s upports cons traint matche s automatically, but
incre me ntal Java s core calculation re quire s re quire s imple me nting an
e xtra inte rface (s e e that s e ction).
147
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 6. OPTIMIZATION ALGORITHMS
6.1. SEARCH SPACE SIZE IN T HE REAL WORLD
The numbe r of pos s ible s olutions for a planning proble m can be mind blowing. For
e xample :
4 que e ns has 256 pos s ible s olutions (4^4) and 2 optimal s olutions .
5 que e ns has 3125 pos s ible s olutions (5^5) and 1 optimal s olution.
8 que e ns has 16777216 pos s ible s olutions (8^8) and 92 optimal s olutions .
64 que e ns has more than 10^115 pos s ible s olutions (64^64).
Mos t re al-life planning proble ms have an incre dible numbe r of pos s ible
s olutions and only 1 or a fe w optimal s olutions .
For comparis on: the minimal numbe r of atoms in the known unive rs e (10^80). As a
planning proble m ge ts bigge r, the s e arch s pace te nds to blow up re ally fas t.
Adding only 1 e xtra planning e ntity or planning value can he avily multiply the
running time of s ome algorithms .
Calculating the numbe r of pos s ible s olutions de pe nds on the de s ign of the domain
mode l:
148
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
No t e
This s e arch s pace s iz e calculation include s infe as ible s olutions (if the y can
be re pre s e nte d by the mode l), be caus e :
The optimal s olution might be infe as ible .
The re are many type s of hard cons traints which cannot be incorporate d
in the formula practically. For e xample in Cloud Balancing, try
incorporating the CPU capacity cons traint in the formula.
Eve n in cas e s we re adding s ome of the hard cons traints in the formula is
practical, for e xample Cours e Sche duling, the re s ulting s e arch s pace is
s till huge .
An algorithm that che cks e ve ry pos s ible s olution (e ve n with pruning s uch as in
Branch And Bound) can e as ily run for billions of ye ars on a s ingle re al-life planning
proble m. What we re ally want is to find the be s t s olution in the limite d time at our
dis pos al. Planning compe titions (s uch as the Inte rnational Time tabling Compe tition)
s how that Local Se arch variations (Tabu Se arch, Simulate d Anne aling, Late
Acce ptance , …​) us ually pe rform be s t for re al-world proble ms give n re al-world time
limitations .
6.2. DOES PLANNER FIND T HE OPT IMAL SOLUT ION?
The bus ine s s wants the optimal s olution, but the y als o have othe r re quire me nts :
149
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Scale out: Large production datas e ts mus t not cras h and have good re s ults too.
Optimiz e the right proble m: The cons traints mus t match the actual bus ine s s
ne e ds .
Available time : The s olution mus t be found in time , be fore it be come s us e le s s
to e xe cute .
Re liability: Eve ry datas e t mus t have at le as t a de ce nt re s ult (be tte r than a
human planne r).
Give n the s e re quire me nts , and de s pite the promis e s of s ome s ale s me n, it’s
us ually impos s ible for anyone or anything to find the optimal s olution. The re fore ,
Planne r focus e s on finding the be s t s olution in available time . In re alis tic,
inde pe nde nt compe titions , it ofte n come s out as the be s t reusable s oftware .
The nature of NP-comple te proble ms make s caling a prime conce rn. The re s ult
quality of a s mall datas e t guarante e s nothing about the re s ult quality of a large
datas e t. Scaling is s ue s cannot be mitigate d by hardware purchas e s late r on. Start
te s ting with a production s iz e d datas e t as s oon as pos s ible . Don’t as s e s s quality
on s mall datas e ts (unle s s production e ncounte rs only s uch datas e ts ). Ins te ad,
s olve a production s iz e d datas e t and compare the re s ults of longe r e xe cutions ,
diffe re nt algorithms and - if available - the human planne r.
6.3. ARCHIT ECT URE OVERVIEW
Planne r is the firs t frame work to combine optimiz ation algorithms (me tahe uris tics ,
…​) with s core calculation by a rule e ngine (s uch as Drools Expe rt). This
combination turns out to be a ve ry e fficie nt, be caus e :
A rule e ngine s uch as Drools Expe rt is gre at for calculating the s core of a
s olution of a planning proble m. It make s it e as y and s calable to add additional
s oft or hard cons traints s uch as "a te ache r s houldn’t te ach more the n 7 hours a
day". It doe s de lta bas e d s core calculation without any e xtra code . Howe ve r it
te nds to be not s uitable to actually find ne w s olutions .
An optimiz ation algorithm is gre at at finding ne w improving s olutions for a
planning proble m, without ne ce s s arily brute -forcing e ve ry pos s ibility. Howe ve r it
ne e ds to know the s core of a s olution and offe rs no s upport in calculating that
s core e fficie ntly.
150
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
6.4. OPT IMIZAT ION ALGORIT HMS OVERVIEW
Planne r s upports 3 familie s of optimiz ation algorithms : Exhaus tive Se arch,
Cons truction He uris tics and Me tahe uris tics . In practice , Me tahe uris tics (in
combination with Cons truction He uris tics to initializ e ) are the re comme nde d choice :
151
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Each of the s e familie s of algorithms has multiple optimiz ation algorithms :
T able 6.1. Opt imizat io n Algo rit hms Overview
Algo r it hm
Sc alable ?
O pt imal?
Eas y t o
us e ?
T we akabl
e?
Re quir e s
CH?
Brute Force
0/5
5/5
5/5
0/5
No
Branch And
Bound
0/5
5/5
4/5
2/5
No
1/5
5/5
1/5
No
Exhaustive
Search (ES)
C onstruction heuristics (C H)
First Fit
152
5/5
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
Algo r it hm
Sc alable ?
O pt imal?
Eas y t o
us e ?
T we akabl
e?
Re quir e s
CH?
First Fit
Decreasing
5/5
2/5
4/5
2/5
No
Weakest Fit
5/5
2/5
4/5
2/5
No
Weakest Fit
Decreasing
5/5
2/5
4/5
2/5
No
Strongest
Fit
5/5
2/5
4/5
2/5
No
Strongest
Fit
Decreasing
5/5
2/5
4/5
2/5
No
C heapest
Insertion
3/5
2/5
5/5
2/5
No
Regret
Insertion
3/5
2/5
5/5
2/5
No
Metaheuristics (MH)
Local Search
Hill
C lim bing
5/5
2/5
4/5
3/5
Yes
Tabu
Search
5/5
4/5
3/5
5/5
Yes
Sim ulated
Annealing
5/5
4/5
2/5
5/5
Yes
153
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Algo r it hm
Sc alable ?
O pt imal?
Eas y t o
us e ?
T we akabl
e?
Re quir e s
CH?
Late
Acceptance
5/5
4/5
3/5
5/5
Yes
Step
C ounting
Hill
C lim bing
5/5
4/5
3/5
5/5
Yes
Evolutionary Algorithm s
Evolutionar
y
Strategies
4/5
3/5
2/5
5/5
Yes
Genetic
Algorithm s
4/5
3/5
2/5
5/5
Yes
If you want to le arn more about me tahe uris tics , re ad the fre e books Es s e ntials of
Me tahe uris tics or Cle ve r Algorithms .
6.5. WHICH OPT IMIZAT ION ALGORIT HMS SHOULD I USE?
The best optimiz ation algorithms configuration for your us e cas e de pe nds he avily
on your us e cas e . Ne ve rthe le s s , this vanilla re cipe will ge t you into the game with
a pre tty good configuration, probably much be tte r than what you’re us e d to.
Start with a quick configuration that involve s little or no configuration and
optimiz ation code :
1. Firs t Fit
Ne xt, imple me nt planning e ntity difficulty comparis on and turn it into:
1. Firs t Fit De cre as ing
Ne xt, add Late Acce ptance be hind it:
1. Firs t Fit De cre as ing
2. Late Acce ptance . A Late Acce ptance s iz e of 400 us ually works we ll.
154
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
At this point the fre e lunch is ove r. The re turn on inve s te d time lowe rs . The re s ult
is probably alre ady more than good e nough.
But you can do e ve n be tte r, at a lowe r re turn on inve s te d time . Us e the
Be nchmarke r and try a couple of diffe re nt Tabu Se arch, Simulate d Anne aling and
Late Acce ptance configurations , for e xample :
1. Firs t Fit De cre as ing
2. Tabu Se arch. An e ntity tabu s iz e of 7 us ually works we ll.
Us e the Be nchmarke r to improve the value s for thos e s iz e parame te rs .
If it’s worth your time , continue e xpe rime nting furthe r. For e xample , try combining
multiple algorithms toge the r:
1. Firs t Fit De cre as ing
2. Late Acce ptance (re lative ly long time )
3. Tabu Se arch (re lative ly s hort time )
6.6. POWER T WEAKING OR DEFAULT PARAMET ER
VALUES
Many optimiz ation algorithms have parame te rs which affe ct re s ults and s calability.
Planne r applie s configuration by exception, s o all optimiz ation algorithms have
de fault parame te r value s . This is ve ry s imilar to the Garbage Colle ction
parame te rs in a JVM: mos t us e rs have no ne e d to twe ak the m, but powe r us e rs do
twe ak the m.
The de fault parame te r value s are good e nough for many cas e s (and e s pe cially for
prototype s ), but if de ve lopme nt time allows , it can be we ll worth to powe r twe ak
the m with the be nchmarke r for be tte r re s ults and s calability on a s pe cific us e
cas e . The docume ntation for e ach optimiz ation algorithm als o de clare s its
advance d configuration for powe r twe aking.
Warning
The de fault value of parame te rs will change be twe e n minor ve rs ions , to
improve the m for mos t us e rs (but not ne ce s s ary for you). To s hie ld
yours e lf from the s e change s , for be tte r or wors e , always us e the
advance d configuration. This is not re comme nde d.
6.7. SOLVER PHASE
A Solver can us e multiple optimiz ation algorithms in s e que nce . Each optimiz ation
algorithm is re pre s e nte d by a s olve r Phase. The re is ne ve r more than 1 Phase
s olving at the s ame time .
155
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
Some Phase imple me ntations can combine te chnique s from multiple
optimiz ation algorithms , but it is s till jus t 1 Phase. For e xample : a Local
Se arch Phase can do Simulate d Anne aling with e ntity Tabu.
He re ’s a configuration that runs 3 phas e s in s e que nce :
<solver>
...
<constructionHeuristic>
... <!-- First phase: First Fit Decreasing -->
</constructionHeuristic>
<localSearch>
... <!-- Second phase: Late Acceptance -->
</localSearch>
<localSearch>
... <!-- Third phase: Tabu Search -->
</localSearch>
</solver>
The s olve r phas e s are run in the orde r de fine d by s olve r configuration. Whe n the
firs t Phase te rminate s , the s e cond Phase s tarts , and s o on. Whe n the las t Phase
te rminate s , the Solver te rminate s . Us ually, a Solver will firs t run a cons truction
he uris tic and the n run 1 or multiple me tahe uris tics :
156
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
If no phas e s are configure d, Planne r will de fault to a Cons truction He uris tic phas e
followe d by a Local Se arch phas e .
Some phas e s (e s pe cially cons truction he uris tics ) will te rminate automatically.
Othe r phas e s (e s pe cially me tahe uris tics ) will only te rminate if the Phase is
configure d to te rminate :
<solver>
...
<termination><!-- Solver termination -->
<secondsSpentLimit>90</secondsSpentLimit>
</termination>
<localSearch>
<termination><!-- Phase termination -->
<secondsSpentLimit>60</secondsSpentLimit><!-- Give the next
phase a chance to run too, before the Solver terminates -->
</termination>
...
</localSearch>
<localSearch>
...
</localSearch>
</solver>
If the Solver te rminate s (be fore the las t Phase te rminate s its e lf), the curre nt
phas e is te rminate d and all s ubs e que nt phas e s won’t run.
6.8. SCOPE OVERVIEW
A s olve r will ite rative ly run phas e s . Each phas e will us ually ite rative ly run s te ps .
Each s te p, in turn, us ually ite rative ly runs move s . The s e form 4 ne s te d s cope s :
s olve r, phas e , s te p and move .
157
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Configure logging to dis play the log me s s age s of e ach s cope .
6.9. T ERMINAT ION
Not all phas e s te rminate automatically and s ome time s you don’t want to wait that
long anyway. A Solver can be te rminate d s ynchronous ly by up-front configuration
or as ynchronous ly from anothe r thre ad.
Es pe cially me tahe uris tic phas e s will ne e d to be told whe n to s top s olving. This can
be be caus e of a numbe r of re as ons : the time is up, the pe rfe ct s core has be e n
re ache d, jus t be fore its s olution is us e d, …​ The only thing you can’t de pe nd on, is
on finding the optimal s olution (unle s s you know the optimal s core ), be caus e a
me tahe uris tic algorithm ge ne rally doe s n’t know it whe n it finds the optimal s olution.
For re al-life proble ms this doe s n’t turn out to be much of a proble m, be caus e
finding the optimal s olution could take ye ars , s o you’ll want to te rminate s oone r
anyway. The only thing that matte rs is finding the be s t s olution in the available
time .
Impo rt ant
If no te rmination is configure d (and a me tahe uris tic algorithm is us e d), the
Solver will run fore ve r, until te rminate Early() is calle d from anothe r
thre ad. This is e s pe cially common during re al-time planning.
For s ynchronous te rmination, configure a Termination on a Solver or a Phase
whe n it ne e ds to s top. You can imple me nt your own Termination, but the built-in
imple me ntations s hould s uffice for mos t ne e ds . Eve ry Termination can calculate
158
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
a time gradient (ne e de d for s ome optimiz ation algorithms ), which is a ratio
be twe e n the time alre ady s pe nt s olving and the e s timate d e ntire s olving time of
the Solver or Phase.
6.9.1. T imeMillisSpent T erminat ion
Te rminate s whe n an amount of time has be e n us e d.
<termination>
<millisecondsSpentLimit>500</millisecondsSpentLimit>
</termination>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
<termination>
<minutesSpentLimit>5</minutesSpentLimit>
</termination>
<termination>
<hoursSpentLimit>1</hoursSpentLimit>
</termination>
<termination>
<daysSpentLimit>2</daysSpentLimit>
</termination>
Multiple time type s can be us e d toge the r, for e xample to configure 150 minute s ,
e ithe r configure it dire ctly:
<termination>
<minutesSpentLimit>150</minutesSpentLimit>
</termination>
Or us e a combination that s ums up to 150 minute s :
<termination>
<hoursSpentLimit>2</hoursSpentLimit>
<minutesSpentLimit>30</minutesSpentLimit>
</termination>
159
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
This Termination will mos t like ly s acrifice pe rfe ct re producibility (e ve n
with environmentMode REPRODUCIBLE) be caus e the available CPU time
diffe rs fre que ntly be twe e n runs :
The available CPU time influe nce s the numbe r of s te ps that can be
take n, which might be a fe w more or le s s .
The Termination might produce s lightly diffe re nt time gradie nt value s ,
which will s e nd time gradie nt bas e d algorithms (s uch as Simulate d
Anne aling) on a radically diffe re nt path.
6.9.2. UnimprovedT imeMillisSpent T erminat ion
Te rminate s whe n the be s t s core has n’t improve d in an amount of time .
<localSearch>
<termination>
<unimprovedMillisecondsSpentLimit>500</unimprovedMillisecondsSpentLim
it>
</termination>
</localSearch>
<localSearch>
<termination>
<unimprovedSecondsSpentLimit>10</unimprovedSecondsSpentLimit>
</termination>
</localSearch>
<localSearch>
<termination>
<unimprovedMinutesSpentLimit>5</unimprovedMinutesSpentLimit>
</termination>
</localSearch>
<localSearch>
<termination>
<unimprovedHoursSpentLimit>1</unimprovedHoursSpentLimit>
</termination>
</localSearch>
<localSearch>
<termination>
<unimprovedDaysSpentLimit>1</unimprovedDaysSpentLimit>
</termination>
</localSearch>
This te rmination s hould not be applie d to Cons truction He uris tics , be caus e the y
only update the be s t s olution at the e nd. The re fore it might be be tte r to configure
it on a s pe cific Phase (s uch as <localSearch>), ins te ad of on the Solver its e lf.
160
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
No t e
This Termination will mos t like ly s acrifice pe rfe ct re producibility (e ve n
with environmentMode REPRODUCIBLE) be caus e the available CPU time
diffe rs fre que ntly be twe e n runs :
The available CPU time influe nce s the numbe r of s te ps that can be
take n, which might be a fe w more or le s s .
The Termination might produce s lightly diffe re nt time gradie nt value s ,
which will s e nd time gradie nt bas e d algorithms (s uch as Simulate d
Anne aling) on a radically diffe re nt path.
6.9.3. Best ScoreT erminat ion
Te rminate s whe n a ce rtain s core has be e n re ache d. Us e this Termination if you
know the pe rfe ct s core , for e xample for 4 que e ns (which us e s a Simple Score ):
<termination>
<bestScoreLimit>0</bestScoreLimit>
</termination>
For a planning proble m with a HardSoftScore , it could look like this :
<termination>
<bestScoreLimit>0hard/-5000soft</bestScoreLimit>
</termination>
For a planning proble m with a Be ndable Score with 3 hard le ve ls and 1 s oft le ve l, it
could look like this :
<termination>
<bestScoreLimit>0/0/0/-5000</bestScoreLimit>
</termination>
To te rminate once a fe as ible s olution has be e n re ache d, this Termination is n’t
practical be caus e it re quire s a bestScoreLimit s uch as 0hard/-2147483648soft.
Ins te ad, us e the ne xt te rmination.
6.9.4. Best ScoreFeasibleT erminat ion
Te rminate s whe n a ce rtain s core is fe as ible . Re quire s that the Score
imple me ntation imple me nts FeasibilityScore.
<termination>
<bestScoreFeasible>true</bestScoreFeasible>
</termination>
This Termination is us ually combine d with othe r te rminations .
6.9.5. St epCount T erminat ion
161
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Te rminate s whe n a numbe r of s te ps has be e n re ache d. This is us e ful for
hardware pe rformance inde pe nde nt runs .
<localSearch>
<termination>
<stepCountLimit>100</stepCountLimit>
</termination>
</localSearch>
This Termination can only be us e d for a Phase (s uch as <localSearch>), not for
the Solver its e lf.
6.9.6. UnimprovedSt epCount T erminat ion
Te rminate s whe n the be s t s core has n’t improve d in a numbe r of s te ps . This is
us e ful for hardware pe rformance inde pe nde nt runs .
<localSearch>
<termination>
<unimprovedStepCountLimit>100</unimprovedStepCountLimit>
</termination>
</localSearch>
If the s core has n’t improve d re ce ntly, it’s probably not going to improve s oon
anyway and it’s not worth the e ffort to continue . We have obs e rve d that once a
ne w be s t s olution is found (e ve n afte r a long time of no improve me nt on the be s t
s olution), the ne xt fe w s te ps te nd to improve the be s t s olution too.
This Termination can only be us e d for a Phase (s uch as <localSearch>), not for
the Solver its e lf.
6.9.7. Calculat eCount T erminat ion
Te rminate s whe n a numbe r of s core calculations (which is us ually the s um of the
numbe r of move s and the numbe r of s te ps ) have be e n re ache d. This is us e ful for
be nchmarking.
<termination>
<calculateCountLimit>100000</calculateCountLimit>
</termination>
Switching Environme ntMode can he avily impact whe n this te rmination e nds .
6.9.8. Combining Mult iple T erminat ions
Te rminations can be combine d, for e xample : te rminate afte r 100 s te ps or if a
s core of 0 has be e n re ache d:
<termination>
<terminationCompositionStyle>OR</terminationCompositionStyle>
<stepCountLimit>100</stepCountLimit>
<bestScoreLimit>0</bestScoreLimit>
</termination>
162
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
Alte rnative ly you can us e AND, for e xample : te rminate afte r re aching a fe as ible
s core of at le as t -100 and no improve me nts in 5 s te ps :
<termination>
<terminationCompositionStyle>AND</terminationCompositionStyle>
<unimprovedStepCountLimit>5</unimprovedStepCountLimit>
<bestScoreLimit>-100</bestScoreLimit>
</termination>
This e xample e ns ure s it doe s n’t jus t te rminate afte r finding a fe as ible s olution, but
als o comple te s any obvious improve me nts on that s olution be fore te rminating.
6.9.9. Asynchronous T erminat ion f rom Anot her T hread
Some time s you’ll want to te rminate a Solve r e arly from anothe r thre ad, for
e xample be caus e a us e r action or a s e rve r re s tart. This cannot be configure d by a
Termination as it’s impos s ible to pre dict whe n and if it will occur. The re fore the
Solver inte rface has the s e 2 thre ad-s afe me thods :
public interface Solver<S extends Solution> {
// ...
boolean terminateEarly();
boolean isTerminateEarly();
}
If you call the terminateEarly() me thod from anothe r thre ad, the Solver will
te rminate at its e arlie s t conve nie nce and the solve(Solution) me thod will re turn
(in the original Solver thre ad).
No t e
Inte rrupting the Solve r thre ad (which is the thre ad that calle d
Solver.solve(Solution)) has the s ame affe ct as calling
terminateEarly() e xce pt that it le ave s that thre ad in the inte rrupte d
s tate . This guarante e s a grace ful s hutdown whe n an ExecutorService
(s uch as a thre ad pool) is s hutdown be caus e that only inte rrupts all active
thre ads in the pool.
6.10. SOLVEREVENT LIST ENER
Each time a ne w be s t s olution is found, the Solver fire s a
BestSolutionChangedEvent, in the s olve r’s thre ad.
To lis te n to s uch e ve nts , add a SolverEventListener to the Solver:
public interface Solver<S extends Solution> {
// ...
163
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
void addEventListener(SolverEventListener<S> eventListener);
void removeEventListener(SolverEventListener<S> eventListener);
}
The BestSolutionChangedEvent's newBestSolution might not be initializ e d or
fe as ible . Us e the me thods on BestSolutionChangedEvent to de te ct s uch cas e s :
solver.addEventListener(new SolverEventListener<CloudBalance>() {
public void
bestSolutionChanged(BestSolutionChangedEvent<CloudBalance> event) {
// Ignore invalid solutions
if (event.isNewBestSolutionInitialized()
&&
event.getNewBestSolution().getScore().isFeasible()) {
...
}
}
});
Warning
The bestSolutionChanged() me thod is calle d in the s olve r’s thre ad, as
part of Solver.solve(). So it s hould re turn quickly to avoid s lowing down
the s olving.
6.11. CUST OM SOLVER PHASE
Be twe e n phas e s or be fore the firs t phas e , you might want to run a cus tom
optmiz ation algorithm to initializ e the Solution or to take s ome low hanging fruit to
ge t a be tte r s core quickly. Ye t you’ll s till want to re us e the s core calculation. For
e xample , to imple me nt a cus tom Cons truction He uris tic without imple me nting an
e ntire Phase.
No t e
Mos t of the time , a cus tom s olve r phas e is not worth the has s le . The
s upporte d Cons tructions He uris tics are configurable (us e the Be nchmarke r
to twe ak the m), Termination aware and s upport partially initializ e d
s olutions too.
The CustomPhaseCommand inte rface looks like this :
public interface CustomPhaseCommand {
void applyCustomProperties(Map<String, String>
customPropertyMap);
164
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
void changeWorkingSolution(ScoreDirector scoreDirector);
}
For e xample , e xte nd AbstractCustomPhaseCommand and imple me nt the
changeWorkingSolution() me thod:
public class ToOriginalMachineSolutionInitializer extends
AbstractCustomPhaseCommand {
public void changeWorkingSolution(ScoreDirector scoreDirector) {
MachineReassignment machineReassignment =
(MachineReassignment) scoreDirector.getWorkingSolution();
for (MrProcessAssignment processAssignment :
machineReassignment.getProcessAssignmentList()) {
scoreDirector.beforeVariableChanged(processAssignment,
"machine");
processAssignment.setMachine(processAssignment.getOriginalMachine());
scoreDirector.afterVariableChanged(processAssignment,
"machine");
scoreDirector.triggerVariableListeners();
}
}
}
Warning
Any change on the planning e ntitie s in a CustomPhaseCommand mus t be
notifie d to the ScoreDirector.
Warning
Do not change any of the proble m facts in a CustomPhaseCommand. That
will corrupt the Solver be caus e any pre vious s core or s olution was for a
diffe re nt proble m. To do that, re ad about re pe ate d planning and do it with
a Proble mFactChange ins te ad.
Configure your CustomPhaseCommand like this :
<solver>
...
<customPhase>
<customPhaseCommandClass>org.optaplanner.examples.machinereassignment
.solver.solution.initializer.ToOriginalMachineSolutionInitializer</cu
165
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
stomPhaseCommandClass>
</customPhase>
... <!-- Other phases -->
</solver>
Configure multiple customPhaseCommandClass ins tance s to run the m in s e que nce .
Impo rt ant
If the change s of a CustomPhaseCommand don’t re s ult in a be tte r s core , the
be s t s olution won’t be change d (s o e ffe ctive ly nothing will have change d
for the ne xt Phase or CustomPhaseCommand). To force s uch change s
anyway, us e forceUpdateBestSolution:
<customPhase>
<customPhaseCommandClass>...MyUninitializer</customPhaseComman
dClass>
<forceUpdateBestSolution>true</forceUpdateBestSolution>
</customPhase>
No t e
If the Solver or a Phase wants to te rminate while a CustomPhaseCommand
is s till running, it will wait to te rminate until the CustomPhaseCommand is
done , howe ve r long that take s . The build-in s olve r phas e s don’t s uffe r
from this proble m.
To configure value s of your CustomPhaseCommand dynamically in the s olve r
configuration (s o you can twe ak thos e parame te rs with the Be nchmarke r), us e the
customProperties e le me nt:
<customPhase>
<customProperties>
<mySelectionSize>5</mySelectionSize>
</customProperties>
</customPhase>
The n ove rride the applyCustomProperties() me thod to pars e and apply the m
whe n a Solver is build.
public class MySolutionInitializer extends AbstractCustomPhaseCommand
{
private int mySelectionSize;
public void applyCustomProperties(Map<String, String>
customPropertyMap) {
String mySelectionSizeString =
customPropertyMap.get("mySelectionSize");
if (mySelectionSizeString == null) {
throw new IllegalArgumentException("A customProperty
166
CHAPT ER 6 . O PT IMIZAT IO N ALGO RIT HMS
(mySelectionSize) is missing from the solver configuration.");
}
solverFactory =
SolverFactory.createFromXmlResource(partitionSolverConfigResource);
if (customPropertyMap.size() != 1) {
throw new IllegalArgumentException("The
customPropertyMap's size (" + customPropertyMap.size() + ") is not
1.");
}
mySelectionSize = Integer.parseInt(mySelectionSizeString);
}
...
}
167
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 7. MOVE AND NEIGHBORHOOD
SELECTION
7.1. MOVE AND NEIGHBORHOOD INT RODUCT ION
7.1.1. What is a Move?
A Move is a change (or s e t of change s ) from a s olution A to a s olution B. For
e xample , the move be low change s que e n C from row 0 to row 2:
The ne w s olution is calle d a neighbor of the original s olution, be caus e it can be
re ache d in a s ingle Move. Although a s ingle move can change multiple que e ns , the
ne ighbors of a s olution s hould always be a ve ry s mall s ubs e t of all pos s ible
s olutions . For e xample , on that original s olution, the s e are all pos s ible
changeMove's :
If we ignore the 4 changeMove's that have not impact and are the re fore not doable ,
we can s e e that numbe r of move s is n * (n - 1) = 12. This is far le s s than the
numbe r of pos s ible s olutions , which is n ^ n = 256. As the proble m s cale s out,
the numbe r of pos s ible move s incre as e s far le s s than the numbe r of pos s ible
s olutions .
Ye t, in 4 changeMove's or le s s we can re ach any s olution. For e xample we can
re ach a ve ry diffe re nt s olution in 3 changeMove's :
168
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
No t e
The re are many othe r type s of move s be s ide s changeMove's . Many move
type s are include d out-of-the -box, but you can als o imple me nt cus tom
move s .
A Move can affe ct multiple e ntitie s or e ve n cre ate /de le te e ntitie s . But it
mus t not change the proble m facts .
All optimiz ation algorithms us e Move's to trans ition from one s olution to a ne ighbor
s olution. The re fore , all the optimiz ation algorithms are confronte d with Move
s e le ction: the craft of cre ating and ite rating move s e fficie ntly and the art of finding
the mos t promis ing s ubs e t of random move s to e valuate firs t.
7.1.2. What is a MoveSelect or?
A MoveSelector's main function is to cre ate Iterator<Move> whe n ne e de d. An
optimiz ation algorithm will ite rate through a s ubs e t of thos e move s .
He re ’s an e xample how to configure a changeMoveSelector for the optimiz ation
algorithm Local Se arch:
<localSearch>
<changeMoveSelector/>
...
</localSearch>
Out of the box, this works and all prope rtie s of the changeMoveSelector are
de faulte d s e ns ibly (unle s s that fails fas t due to ambiguity). On the othe r hand, the
configuration can be cus tomiz e d s ignificantly for s pe cific us e cas e s . For e xample :
you might want to configure a filte r to dis card pointle s s move s .
7.1.3. Subselect ing of Ent it ies, Values and Ot her Moves
To cre ate a Move, a MoveSelector ne e ds to s e le ct 1 or more planning e ntitie s
and/or planning value s to move . Jus t like MoveSelectors, EntitySelectorsand
ValueSelectorsne e d to s upport a s imilar fe ature s e t (s uch as s calable jus t-intime s e le ction). The re fore , the y all imple me nt a common inte rface Selector and
the y are configure d s imilarly.
A Move Se le ctor is ofte n compos e d out of EntitySelectors, ValueSelectorsor
e ve n othe r MoveSelectors, which can be configure d individually if de s ire d:
<unionMoveSelector>
169
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<changeMoveSelector>
<entitySelector>
...
</entitySelector>
<valueSelector>
...
</valueSelector>
...
</changeMoveSelector>
<swapMoveSelector>
...
</swapMoveSelector>
</unionMoveSelector>
Toge the r, this s tructure forms a Selector tre e :
The root of this tre e is a MoveSelector which is inje cte d into the optimiz ation
algorithm imple me ntation to be (partially) ite rate d in e ve ry s te p.
7.2. GENERIC MOVESELECT ORS
7.2.1. changeMoveSelect or
For 1 planning variable , the ChangeMove s e le cts 1 planning e ntity and 1 planning
value and as s igns the e ntity’s variable to that value .
170
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
Simple s t configuration:
<changeMoveSelector/>
If the re are multiple e ntity clas s e s or multiple planning variable s for 1 e ntity clas s ,
a s imple configuration will automatically unfold into a union of ChangeMove
s e le ctors for e ve ry planning variable .
Advance d configuration:
<changeMoveSelector>
... <!-- Normal selector properties -->
<entitySelector>
<entityClass>...Lecture</entityClass>
...
</entitySelector>
<valueSelector>
<variableName>room</variableName>
...
<nearbySelection>...</nearbySelection>
</valueSelector>
</changeMoveSelector>
A ChangeMove is the fine s t graine d move .
171
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Impo rt ant
Almos t e ve ry moveSelector configuration inje cte d into a me tahe uris tic
algorithm s hould include a change Move Se le ctor or a cus tom
imple me ntation. This guarante e s that e ve ry pos s ible Solution can be
re ache d through applying a numbe r of move s in s e que nce (not taking
s core traps into account). Of cours e , normally it is unione d with othe r,
more coars e graine d move s e le ctors .
7.2.2. swapMoveSelect or
The SwapMove s e le cts 2 diffe re nt planning e ntitie s and s waps the planning value s
of all the ir planning variable s .
Although a SwapMove on a s ingle variable is e s s e ntially jus t 2 ChangeMoves, it’s
ofte n the winning s te p whe re the firs t of the 2 ChangeMoveswould not be the
winning s te p be caus e it le ave s the s olution in a s tate with broke n hard cons traints .
For e xample : s wapping the room of 2 le cture s doe s n’t bring the s olution in a
inte rme diate s tate whe re both le cture s are in the s ame room which bre aks a hard
cons traint.
Simple s t configuration:
<swapMoveSelector/>
If the re are multiple e ntity clas s e s , a s imple configuration will automatically unfold
into a union of SwapMove s e le ctors for e ve ry e ntity clas s .
172
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
Advance d configuration:
<swapMoveSelector>
... <!-- Normal selector properties -->
<entitySelector>
<entityClass>...Lecture</entityClass>
...
</entitySelector>
<secondaryEntitySelector>
<entityClass>...Lecture</entityClass>
...
<nearbySelection>...</nearbySelection>
</secondaryEntitySelector>
<variableNameInclude>room</variableNameInclude>
<variableNameInclude>...</variableNameInclude>
</swapMoveSelector>
The secondaryEntitySelector is rare ly ne e de d: if it is not s pe cifie d, e ntitie s
from the s ame entitySelector are s wappe d.
If one or more variableNameInclude prope rtie s are s pe cifie d, not all planning
variable s will be s wappe d, but only thos e s pe cifie d. For e xample for cours e
s che duling, s pe cifying only variableNameInclude room will make it only s wap
room, not pe riod.
7.2.3. pillarChangeMoveSelect or
A pillar is a s e t of planning e ntitie s which have the s ame planning value (s ) for the ir
planning variable (s ). The PillarChangeMove s e le cts 1 e ntity pillar (or s ubs e t of
thos e ) and change s the value of 1 variable (which is the s ame for all e ntitie s ) to
anothe r value .
173
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
In the e xample above , que e n A and C have the s ame value (row 0) and are
move d to row 2. Als o the ye llow and blue proce s s have the s ame value (compute r
Y) and are move d to compute r X.
Simple s t configuration:
<pillarChangeMoveSelector/>
Advance d configuration:
<pillarSwapMoveSelector>
... <!-- Normal selector properties -->
<pillarSelector>
<entitySelector>
<entityClass>...Lecture</entityClass>
...
</entitySelector>
<subPillarEnabled>true</subPillarEnabled>
<minimumSubPillarSize>1</minimumSubPillarSize>
<maximumSubPillarSize>1000</maximumSubPillarSize>
</pillarSelector>
<valueSelector>
<variableName>room</variableName>
...
</valueSelector>
</pillarSwapMoveSelector>
A s ub pillar is a s ubs e t of e ntitie s that s hare the s ame value (s ) for the ir
variable (s ). For e xample if que e n A, B, C and D are all locate d on row 0, the y are a
174
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
pillar and [A, D] is one of the many s ub pillars . If subPillarEnabled (de faults to
true) is fals e , no s ub pillars are s e le cte d. If s ub pillars are e nable d, the pillar its e lf
is als o include d and the prope rtie s minimumSubPillarSize (de faults to 1) and
maximumSubPillarSize (de faults to infinity) limit the s iz e of the s e le cte d (s ub)
pillar.
No t e
The numbe r of s ub pillars of a pillar is e xpone ntial to the s iz e of the pillar.
For e xample a pillar of s iz e 32 has (2^32 - 1) s ubpillars . The re fore a
pillarSelector only s upports JIT random s e le ction (which is the de fault).
The othe r prope rtie s are e xplaine d in change Move Se le ctor.
7.2.4. pillarSwapMoveSelect or
A pillar is a s e t of planning e ntitie s which have the s ame planning value (s ) for the ir
planning variable (s ). The PillarSwapMove s e le cts 2 diffe re nt e ntity pillars and
s waps the value s of all the ir variable s for all the ir e ntitie s .
Simple s t configuration:
<pillarSwapMoveSelector/>
Advance d configuration:
175
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<pillarSwapMoveSelector>
... <!-- Normal selector properties -->
<pillarSelector>
<entitySelector>
<entityClass>...Lecture</entityClass>
...
</entitySelector>
<subPillarEnabled>true</subPillarEnabled>
<minimumSubPillarSize>1</minimumSubPillarSize>
<maximumSubPillarSize>1000</maximumSubPillarSize>
</pillarSelector>
<secondaryPillarSelector>
<entitySelector>
...
</entitySelector>
...
</secondaryPillarSelector>
<variableNameInclude>room</variableNameInclude>
<variableNameInclude>...</variableNameInclude>
</pillarSwapMoveSelector>
The secondaryPillarSelector is rare ly ne e de d: if it is not s pe cifie d, e ntitie s
from the s ame pillarSelector are s wappe d.
The othe r prope rtie s are e xplaine d in s wapMove Se le ctor and
pillarChange Move Se le ctor.
7.2.5. t ailChainSwapMoveSelect or or 2-opt (chained variables
only)
A tailChain is a s e t of planning e ntitie s with a chaine d planning variable which form
a las t part of a chain. The tailChainSwapMove s e le cts a tail chain and s waps it
with the tail chain of anothe r planning value (in a diffe re nt or the s ame anchor
chain). If the targe te d planning value , doe s n’t have a tail chain, it s waps with
nothing (re s ulting in a change like move ). If it occurs within the s ame anchor chain,
a partial chain re ve rs e occurs . In acade mic pape rs , this is ofte n calle d a 2-opt
move .
Simple s t configuration:
<tailChainSwapMoveSelector/>
Advance d configuration:
<subChainChangeMoveSelector>
... <!-- Normal selector properties -->
<entitySelector>
<entityClass>...Customer</entityClass>
...
</entitySelector>
<valueSelector>
<variableName>previousStandstill</variableName>
176
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
...
<nearbySelection>...</nearbySelection>
</valueSelector>
</subChainChangeMoveSelector>
The entitySelector s e le cts the s tart of the tail chain that is be ing move d. The
value Se le ctor s e le cts to whe re that tail chain is move d. If it has a tail chain its e lf,
that is move d to the location of the original tail chain. It us e s a valueSelector
ins te ad of a secondaryEntitySelector to be able to include all pos s ible 2opt
move s (s uch as moving to the e nd of a tail) and to work corre ctly with ne arby
s e le ction (be caus e of as ymme tric dis tance s and als o s wappe d e ntity dis tance
give s an incorre ct s e le ction probability).
No t e
Although subChainChangeMoveSelector and subChainSwapMoveSelector
include almos t e ve ry pos s ible tailChainSwapMove, e xpe rime nts have
s hown that focus ing on tailChainSwapMovesincre as e s e fficie ncy.
7.2.6. subChainChangeMoveSelect or (chained variables only)
A subChain is a s e t of planning e ntitie s with a chaine d planning variable which form
part of a chain. The subChainChangeMoveSelector s e le cts a s ubChain and move s
it to anothe r place (in a diffe re nt or the s ame anchor chain).
Simple s t configuration:
<subChainChangeMoveSelector/>
Advance d configuration:
<subChainChangeMoveSelector>
... <!-- Normal selector properties -->
<entityClass>...Customer</entityClass>
<subChainSelector>
<valueSelector>
<variableName>previousStandstill</variableName>
...
</valueSelector>
<minimumSubChainSize>2</minimumSubChainSize>
<maximumSubChainSize>40</maximumSubChainSize>
</subChainSelector>
<valueSelector>
<variableName>previousStandstill</variableName>
...
</valueSelector>
<selectReversingMoveToo>true</selectReversingMoveToo>
</subChainChangeMoveSelector>
The subChainSelector s e le cts a numbe r of e ntitie s , no le s s than
minimumSubChainSize (de faults to 1) and no more than maximumSubChainSize
(de faults to infinity).
177
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
If minimumSubChainSize is 1 (which is the de fault), this s e le ctor might
s e le ct the s ame move as a ChangeMoveSelector, at a far lowe r s e le ction
probability (be caus e e ach move type has the s ame s e le ction chance by
de fault (not e ve ry move ins tance ) and the re are far more
SubChainChangeMove ins tance s than ChangeMove ins tance s ). Howe ve r,
don’t jus t re move the ChangeMoveSelector, be caus e e xpe rime nts s how
that it’s good to focus on ChangeMoves.
Furthe rmore , in a SubChainSwapMoveSelector, s e tting
minimumSubChainSize pre ve nts s wapping a s ubchain of s iz e 1 with a
s ubchain of at le as t s iz e 2.
The selectReversingMoveToo prope rty (de faults to true ) e nable s s e le cting the
re ve rs e of e ve ry s ubchain too.
7.2.7. subChainSwapMoveSelect or (chained variables only)
The subChainSwapMoveSelector s e le cts 2 diffe re nt s ubChains and move s the m
to anothe r place in a diffe re nt or the s ame anchor chain.
Simple s t configuration:
<subChainSwapMoveSelector/>
Advance d configuration:
<subChainSwapMoveSelector>
... <!-- Normal selector properties -->
<entityClass>...Customer</entityClass>
<subChainSelector>
<valueSelector>
<variableName>previousStandstill</variableName>
...
</valueSelector>
<minimumSubChainSize>2</minimumSubChainSize>
<maximumSubChainSize>40</maximumSubChainSize>
</subChainSelector>
<secondarySubChainSelector>
<valueSelector>
<variableName>previousStandstill</variableName>
...
</valueSelector>
<minimumSubChainSize>2</minimumSubChainSize>
<maximumSubChainSize>40</maximumSubChainSize>
</secondarySubChainSelector>
<selectReversingMoveToo>true</selectReversingMoveToo>
</subChainSwapMoveSelector>
The secondarySubChainSelector is rare ly ne e de d: if it is not s pe cifie d, e ntitie s
from the s ame subChainSelector are s wappe d.
The othe r prope rtie s are e xplaine d in s ubChainChange Move Se le ctor.
178
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
7.3. COMBINING MULT IPLE MOVESELECT ORS
7.3.1. unionMoveSelect or
A unionMoveSelector s e le cts a Move by s e le cting 1 of its MoveSelector childre n
to s upply the ne xt Move.
Simple s t configuration:
<unionMoveSelector>
<...MoveSelector/>
<...MoveSelector/>
<...MoveSelector/>
...
</unionMoveSelector>
Advance d configuration:
<unionMoveSelector>
... <!-- Normal selector properties -->
<selectorProbabilityWeightFactoryClass>...ProbabilityWeightFactory</s
electorProbabilityWeightFactoryClass>
<changeMoveSelector>
<fixedProbabilityWeight>...</fixedProbabilityWeight>
...
</changeMoveSelector>
<swapMoveSelector>
<fixedProbabilityWeight>...</fixedProbabilityWeight>
...
</swapMoveSelector>
<...MoveSelector>
<fixedProbabilityWeight>...</fixedProbabilityWeight>
...
</...MoveSelector>
...
</unionMoveSelector>
The selectorProbabilityWeightFactory de te rmine s in selectionOrder RANDOM
how ofte n a MoveSelector child is s e le cte d to s upply the ne xt Move . By de fault,
e ach MoveSelector child has the s ame chance of be ing s e le cte d.
179
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Change the fixedProbabilityWeight of s uch a child to s e le ct it more ofte n. For
e xample , the unionMoveSelector can re turn a SwapMove twice as ofte n as a
ChangeMove:
<unionMoveSelector>
<changeMoveSelector>
<fixedProbabilityWeight>1.0</fixedProbabilityWeight>
...
</changeMoveSelector>
<swapMoveSelector>
<fixedProbabilityWeight>2.0</fixedProbabilityWeight>
...
</swapMoveSelector>
</unionMoveSelector>
The numbe r of pos s ible ChangeMovesis ve ry diffe re nt from the numbe r of pos s ible
SwapMovesand furthe rmore it’s proble m de pe nde nt. To give e ach individual Move
the s ame s e le ction chance (as oppos e d to e ach MoveSelector), us e the
FairSelectorProbabilityWeightFactory:
<unionMoveSelector>
<selectorProbabilityWeightFactoryClass>org.optaplanner.core.impl.heur
istic.selector.common.decorator.FairSelectorProbabilityWeightFactory<
/selectorProbabilityWeightFactoryClass>
<changeMoveSelector/>
<swapMoveSelector/>
</unionMoveSelector>
180
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
7.3.2. cart esianProduct MoveSelect or
A cartesianProductMoveSelector s e le cts a ne w CompositeMove. It builds that
CompositeMove by s e le cting 1 Move pe r MoveSelector child and adding it to the
CompositeMove.
Simple s t configuration:
<cartesianProductMoveSelector>
<...MoveSelector/>
<...MoveSelector/>
<...MoveSelector/>
...
</cartesianProductMoveSelector>
Advance d configuration:
<cartesianProductMoveSelector>
... <!-- Normal selector properties -->
<ignoreEmptyChildIterators>true</ignoreEmptyChildIterators>
<changeMoveSelector>
...
</changeMoveSelector>
<swapMoveSelector>
...
</swapMoveSelector>
<...MoveSelector>
...
</...MoveSelector>
...
</cartesianProductMoveSelector>
The ignoreEmptyChildIterators prope rty (true by de fault) will ignore e ve ry
e mpty childMoveSelector to avoid re turning no move s . For e xample : a carte s ian
product of changeMoveSelector A and B, for which B is e mpty (be caus e all it’s
e ntitie s are immovable ) re turns no move if ignoreEmptyChildIterators is false
and the move s of A if ignoreEmptyChildIterators is true.
To e nforce that 2 child s e le ctors us e the s ame e ntity or value e fficie ntly, us e
mimic s e le ction, not move filte ring.
7.4. ENT IT YSELECT OR
Simple s t configuration:
<entitySelector/>
Advance d configuration:
<entitySelector>
... <!-- Normal selector properties -->
<entityClass>org.optaplanner.examples.curriculumcourse.domain.Lecture
</entityClass>
</entitySelector>
181
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The entityClass prope rty is only re quire d if it cannot be de duce d automatically
be caus e the re are multiple e ntity clas s e s .
7.5. VALUESELECT OR
Simple s t configuration:
<valueSelector/>
Advance d configuration:
<valueSelector>
... <!-- Normal selector properties -->
<variableName>room</variableName>
</valueSelector>
The variableName prope rty is only re quire d if it cannot be de duce d automatically
be caus e the re are multiple variable s (for the re late d e ntity clas s ).
In e xotic Cons truction He uris tic configurations , the entityClass from the
EntitySelector s ome time s ne e ds to be downcas te d, which can be done with the
prope rty downcastEntityClass:
<valueSelector>
<downcastEntityClass>...LeadingExam</downcastEntityClass>
<variableName>period</variableName>
</valueSelector>
If a s e le cte d e ntity cannot be downcas te d, the ValueSelector is e mpty for that
e ntity.
7.6. GENERAL SELECT OR FEAT URES
7.6.1. CacheT ype: Creat e Moves Ahead of T ime or Just In T ime
A Selector's cacheType de te rmine s whe n a s e le ction (s uch as a Move, an e ntity,
a value , …​) is cre ate d and how long it live s .
Almos t e ve ry Selector s upports s e tting a cacheType:
<changeMoveSelector>
<cacheType>PHASE</cacheType>
...
</changeMoveSelector>
The following cacheTypesare s upporte d:
JUST_IN_TIME (de fault): Not cache d. Cons truct e ach s e le ction (Move, …​) jus t
be fore it’s us e d. This s cale s up we ll in me mory footprint.
182
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
STEP: Cache d. Cre ate e ach s e le ction (Move, …​) at the be ginning of a s te p and
cache the m in a lis t for the re mainde r of the s te p. This s cale s up badly in
me mory footprint.
PHASE: Cache d. Cre ate e ach s e le ction (Move, …​) at the be ginning of a s olve r
phas e and cache the m in a lis t for the re mainde r of the phas e . Some s e le ctions
cannot be phas e cache d be caus e the lis t change s e ve ry s te p. This s cale s up
badly in me mory footprint, but has a s light pe rformance gain.
SOLVER: Cache d. Cre ate e ach s e le ction (Move, …​) at the be ginning of a Solver
and cache the m in a lis t for the re mainde r of the Solver. Some s e le ctions
cannot be s olve r cache d be caus e the lis t change s e ve ry s te p. This s cale s up
badly in me mory footprint, but has a s light pe rformance gain.
A cacheType can be s e t on compos ite s e le ctors too:
<unionMoveSelector>
<cacheType>PHASE</cacheType>
<changeMoveSelector/>
<swapMoveSelector/>
...
</unionMoveSelector>
Ne s te d s e le ctors of a cache d s e le ctor cannot be configure d to be cache d
the ms e lve s , unle s s it’s a highe r cacheType. For e xample : a STEP cache d
unionMoveSelector can hold a PHASE cache d changeMoveSelector, but not a STEP
cache d changeMoveSelector.
7.6.2. Select ionOrder: Original, Sort ed, Random, Shuf f led or
Probabilist ic
A Selector's selectionOrder de te rmine s the orde r in which the s e le ctions (s uch
as Moves, e ntitie s , value s , …​) are ite rate d. An optimiz ation algorithm will us ually
only ite rate through a s ubs e t of its MoveSelector's s e le ctions , s tarting from the
s tart, s o the selectionOrder is critical to de cide which Moves are actually
e valuate d.
Almos t e ve ry Selector s upports s e tting a selectionOrder:
<changeMoveSelector>
...
<selectionOrder>RANDOM</selectionOrder>
...
</changeMoveSelector>
The following selectionOrdersare s upporte d:
ORIGINAL: Se le ct the s e le ctions (Moves, e ntitie s , value s , …​) in de fault orde r.
Each s e le ction will be s e le cte d only once .
For e xample : A0, A1, A2, A3, …​, B0, B1, B2, B3, …​, C0, C1, C2, C3, …​
SORTED: Se le ct the s e le ctions (Moves, e ntitie s , value s , …​) in s orte d orde r. Each
s e le ction will be s e le cte d only once . Re quire s cacheType >= STEP. Mos tly us e d
on an entitySelector or valueSelector for cons truction he uris tics . Se e
s orte d s e le ction.
183
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
For e xample : A0, B0, C0, …​, A2, B2, C2, …​, A1, B1, C1, …​
RANDOM (de fault): Se le ct the s e le ctions (Moves, e ntitie s , value s , …​) in nons huffle d random orde r. A s e le ction might be s e le cte d multiple time s . This
s cale s up we ll in pe rformance be caus e it doe s not re quire caching.
For e xample : C2, A3, B1, C2, A0, C0, …​
SHUFFLED: Se le ct the s e le ctions (Moves, e ntitie s , value s , …​) in s huffle d random
orde r. Each s e le ction will be s e le cte d only once . Re quire s cacheType >= STEP.
This s cale s up badly in pe rformance , not jus t be caus e it re quire s caching, but
als o be caus e a random numbe r is ge ne rate d for e ach e le me nt, e ve n if it’s not
s e le cte d (which is the grand majority whe n s caling up).
For e xample : C2, A3, B1, A0, C0, …​
PROBABILISTIC: Se le ct the s e le ctions (Moves, e ntitie s , value s , …​) in random
orde r, bas e d on the s e le ction probability of e ach e le me nt. A s e le ction with a
highe r probability has a highe r chance to be s e le cte d than e le me nts with a
lowe r probability. A s e le ction might be s e le cte d multiple time s . Re quire s
cacheType >= STEP. Mos tly us e d on an entitySelector or valueSelector.
Se e probabilis tic s e le ction.
For e xample : B1, B1, A1, B2, B1, C2, B1, B1, …​
A selectionOrder can be s e t on compos ite s e le ctors too.
No t e
Whe n a Selector is cache d, all of its ne s te d Selectors will naturally
de fault to selectionOrder ORIGINAL. Avoid ove rwriting the
selectionOrder of thos e ne s te d Selectors.
7.6.3. Recommended Combinat ions of CacheT ype and
Select ionOrder
7.6.3.1. Just in T ime Random Select ion (def ault )
This combination is gre at for big us e cas e s (10 000 e ntitie s or more ), as it s cale s
up we ll in me mory footprint and pe rformance . Othe r combinations are ofte n not
e ve n viable on s uch s iz e s . It works for s malle r us e cas e s too, s o it’s a good way
to s tart out. It’s the de fault, s o this e xplicit configuration of cacheType and
selectionOrder is actually obs ole te :
<unionMoveSelector>
<cacheType>JUST_IN_TIME</cacheType>
<selectionOrder>RANDOM</selectionOrder>
<changeMoveSelector/>
<swapMoveSelector/>
</unionMoveSelector>
He re ’s how it works . Whe n Iterator<Move>.next() is calle d, a child
MoveSelector is randomly s e le cte d (1), which cre ate s a random Move (2, 3, 4) and
is the n re turne d (5):
184
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
Notice that it ne ve r cre ate s a lis t of Moves and it ge ne rate s random numbe rs only
for Moves that are actually s e le cte d.
7.6.3.2. Cached Shuf f led Select ion
This combination ofte n wins for s mall and me dium us e cas e s (5000 e ntitie s or
le s s ). Be yond that s iz e , it s cale s up badly in me mory footprint and pe rformance .
<unionMoveSelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SHUFFLED</selectionOrder>
<changeMoveSelector/>
<swapMoveSelector/>
</unionMoveSelector>
He re ’s how it works : At the s tart of the phas e (or s te p de pe nding on the
cacheType), all move s are cre ate d (1) and cache d (2). Whe n
MoveSelector.iterator() is calle d, the move s are s huffle d (3). Whe n
Iterator<Move>.next() is calle d, the ne xt e le me nt in the s huffle d lis t is re turne d
(4):
185
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Notice that e ach Move will only be s e le cte d once , e ve n though the y are s e le cte d in
random orde r.
Us e cache Type PHASE if none of the (pos s ibly ne s te d) Se le ctors re quire STEP.
Othe rwis e , do s ome thing like this :
<unionMoveSelector>
<cacheType>STEP</cacheType>
<selectionOrder>SHUFFLED</selectionOrder>
<changeMoveSelector>
<cacheType>PHASE</cacheType>
</changeMoveSelector>
<swapMoveSelector/>
<cacheType>PHASE</cacheType>
</swapMoveSelector>
<pillarSwapMoveSelector/><!-- Does not support cacheType PHASE
-->
</unionMoveSelector>
7.6.3.3. Cached Random Select ion
This combination is ofte n a worthy compe titor for me dium us e cas e s , e s pe cially
with fas t s te pping optimiz ation algorithms (s uch as Simulate d Anne aling). Unlike
cache d s huffle d s e le ction, it doe s n’t was te time s huffling the move s lis t at the
be ginning of e ve ry s te p.
<unionMoveSelector>
186
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
<cacheType>PHASE</cacheType>
<selectionOrder>RANDOM</selectionOrder>
<changeMoveSelector/>
<swapMoveSelector/>
</unionMoveSelector>
7.6.4. Filt ered Select ion
The re can be ce rtain move s that you don’t want to s e le ct, be caus e :
The move is pointle s s and would only was te CPU time . For e xample , s wapping 2
le cture s of the s ame cours e will re s ult in the s ame s core and the s ame
s che dule be caus e all le cture s of 1 cours e are inte rchange able (s ame te ache r,
s ame s tude nts , s ame topic).
Doing the move would bre ak a built-in hard cons traint, s o the s olution would be
infe as ible but the s core function doe s n’t che ck built-in hard cons traints (for
pe rformance gain). For e xample , don’t change a gym le cture to a room which is
not a gym room.
No t e
Any built-in hard cons traint mus t probably be filte re d on e ve ry move
type of e ve ry s olve r phas e . For e xample if it’s filte rs the change move
of Local Se arch, it mus t als o filte r the s wap move that s waps the room
of a gym le cture with anothe r le cture for which the othe r le cture ’s
original room is n’t a gym room. Furthe rmore , it mus t als o filte r the
change move s of the Cons truction He uris tics (which re quire s an
advance d configuration).
Filte re d s e le ction can happe n on any Se le ctor in the s e le ctor tre e , including any
MoveSelector, EntitySelector or ValueSelector. It works with any cacheType
and selectionOrder.
187
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Filte ring us e s the inte rface SelectionFilter:
public interface SelectionFilter<T> {
boolean accept(ScoreDirector scoreDirector, T selection);
}
Imple me nt the accept me thod to re turn false on a dis carde d selection.
Unacce pte d move s will not be s e le cte d and will the re fore ne ve r have the ir doMove
me thod calle d.
public class DifferentCourseSwapMoveFilter implements
SelectionFilter<SwapMove> {
public boolean accept(ScoreDirector scoreDirector, SwapMove move)
{
Lecture leftLecture = (Lecture) move.getLeftEntity();
Lecture rightLecture = (Lecture) move.getRightEntity();
return
!leftLecture.getCourse().equals(rightLecture.getCourse());
}
}
Apply the filte r on the lowe s t le ve l pos s ible . In mos t cas e s , you’ll ne e d to know
both the e ntity and the value involve d and you’ll have to apply a filterClass on
the moveSelector:
188
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
<swapMoveSelector>
<filterClass>org.optaplanner.examples.curriculumcourse.solver.move.Di
fferentCourseSwapMoveFilter</filterClass>
</swapMoveSelector>
But if pos s ible , apply it on a lowe r le ve ls , s uch as a filterClass on the
entitySelector or valueSelector:
<changeMoveSelector>
<entitySelector>
<filterClass>...EntityFilter</filterClass>
</entitySelector>
</changeMoveSelector>
You can configure multiple filterClass e le me nts on a s ingle s e le ctor.
7.6.5. Sort ed Select ion
Sorte d s e le ction can happe n on any Se le ctor in the s e le ctor tre e , including any
MoveSelector, EntitySelector or ValueSelector. It doe s not work with
cacheType JUST_IN_TIME and it only works with selectionOrder SORTED.
It’s mos tly us e d in cons truction he uris tics .
No t e
If the chos e n cons truction he uris tic implie s s orting, for e xample
FIRST_FIT_DECREASING implie s that the EntitySelector is s orte d, the re
is no ne e d to e xplicitly configure a Selector with s orting. If you do
e xplicitly configure the Selector, it ove rwrite s the de fault s e ttings of that
cons truction he uris tic.
7.6.5.1. Sort ed Select ion by Sort erManner
Some Selector type s imple me nt a SorterManner out of the box:
EntitySelector s upports :
DECREASING_DIFFICULTY: Sorts the planning e ntitie s according to de cre as ing
planning e ntity difficulty. Re quire s that planning e ntity difficulty is annotate d
on the domain mode l.
<entitySelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>DECREASING_DIFFICULTY</sorterManner>
</entitySelector>
ValueSelector s upports :
INCREASING_STRENGTH: Sorts the planning value s according to incre as ing
planning value s tre ngth. Re quire s that planning value s tre ngth is annotate d
on the domain mode l.
189
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<valueSelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>INCREASING_STRENGTH</sorterManner>
</valueSelector>
7.6.5.2. Sort ed Select ion by Comparat or
An e as y way to s ort a Selector is with a plain old Comparator:
public class CloudProcessDifficultyComparator implements
Comparator<CloudProcess> {
public int compare(CloudProcess a, CloudProcess b) {
return new CompareToBuilder()
.append(a.getRequiredMultiplicand(),
b.getRequiredMultiplicand())
.append(a.getId(), b.getId())
.toComparison();
}
}
You 'll als o ne e d to configure it (unle s s it’s annotate d on the domain mode l and
automatically applie d by the optimiz ation algorithm):
<entitySelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterComparatorClass>...CloudProcessDifficultyComparator</sorterCom
paratorClass>
<sorterOrder>DESCENDING</sorterOrder>
</entitySelector>
7.6.5.3. Sort ed Select ion by Select ionSort erWeight Fact ory
If you ne e d the e ntire Solution to s ort a Selector, us e a
SelectionSorterWeightFactory ins te ad:
public interface SelectionSorterWeightFactory<Sol extends Solution,
T> {
Comparable createSorterWeight(Sol solution, T selection);
}
public class QueenDifficultyWeightFactory implements
SelectionSorterWeightFactory<NQueens, Queen> {
public Comparable createSorterWeight(NQueens nQueens, Queen
queen) {
int distanceFromMiddle =
190
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
calculateDistanceFromMiddle(nQueens.getN(), queen.getColumnIndex());
return new QueenDifficultyWeight(queen, distanceFromMiddle);
}
// ...
public static class QueenDifficultyWeight implements
Comparable<QueenDifficultyWeight> {
private final Queen queen;
private final int distanceFromMiddle;
public QueenDifficultyWeight(Queen queen, int
distanceFromMiddle) {
this.queen = queen;
this.distanceFromMiddle = distanceFromMiddle;
}
public int compareTo(QueenDifficultyWeight other) {
return new CompareToBuilder()
// The more difficult queens have a lower
distance to the middle
.append(other.distanceFromMiddle,
distanceFromMiddle) // Decreasing
// Tie breaker
.append(queen.getColumnIndex(),
other.queen.getColumnIndex())
.toComparison();
}
}
}
You 'll als o ne e d to configure it (unle s s it’s annotate d on the domain mode l and
automatically applie d by the optimiz ation algorithm):
<entitySelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterWeightFactoryClass>...QueenDifficultyWeightFactory</sorterWeig
htFactoryClass>
<sorterOrder>DESCENDING</sorterOrder>
</entitySelector>
7.6.5.4. Sort ed Select ion by Select ionSort er
Alte rnative ly, you can als o us e the inte rface SelectionSorter dire ctly:
public interface SelectionSorter<T> {
void sort(ScoreDirector scoreDirector, List<T> selectionList);
}
191
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<entitySelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterClass>...MyEntitySorter</sorterClass>
</entitySelector>
7.6.6. Probabilist ic Select ion
Probabilis tic s e le ction can happe n on any Se le ctor in the s e le ctor tre e , including
any MoveSelector, EntitySelector or ValueSelector. It doe s not work with
cacheType JUST_IN_TIME and it only works with selectionOrder PROBABILISTIC.
Each s e le ction has a probabilityWeight, which de te rmine s the chance that
s e le ction will be s e le cte d:
public interface SelectionProbabilityWeightFactory<T> {
double createProbabilityWeight(ScoreDirector scoreDirector, T
selection);
}
<entitySelector>
<cacheType>PHASE</cacheType>
<selectionOrder>PROBABILISTIC</selectionOrder>
192
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
<probabilityWeightFactoryClass>...MyEntityProbabilityWeightFactoryCla
ss</probabilityWeightFactoryClass>
</entitySelector>
For e xample , if the re are 3 e ntitie s : proce s s A (probabilityWe ight 2.0), proce s s B
(probabilityWe ight 0.5) and proce s s C (probabilityWe ight 0.5), the n proce s s A will
be s e le cte d 4 time s more than B and C.
7.6.7. Limit ed Select ion
Se le cting all pos s ible move s s ome time s doe s not s cale we ll e nough, e s pe cially
for cons truction he uris tics (which don’t s upport acce pte dCountLimit).
To limit the numbe r of s e le cte d s e le ction pe r s te p, apply a selectedCountLimit
on the s e le ctor:
<changeMoveSelector>
<selectedCountLimit>100</selectedCountLimit>
</changeMoveSelector>
No t e
To s cale Local Se arch, s e tting acce pte dCountLimit is us ually be tte r than
us ing selectedCountLimit.
7.6.8. Mimic Select ion (Record/Replay)
During mimic s e le ction, 1 normal s e le ctor re cords its s e le ction and 1 or multiple
othe r s pe cial s e le ctors re play that s e le ction. The re cording s e le ctor acts as a
normal s e le ctor and s upports all othe r configuration prope rtie s . A re playing
s e le ctor mimics the re cording s e le ction and s upport no othe r configuration
prope rtie s .
The re cording s e le ctor ne e ds an ID. A re playing s e le ctor mus t re fe re nce a
re corde r’s ID with a mimicSelectorRef:
<cartesianProductMoveSelector>
<changeMoveSelector>
<entitySelector id="entitySelector"/>
<valueSelector>
<variableName>period</variableName>
</valueSelector>
</changeMoveSelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="entitySelector"/>
<valueSelector>
<variableName>room</variableName>
</valueSelector>
</changeMoveSelector>
</cartesianProductMoveSelector>
Mimic s e le ction is us e ful to cre ate a compos ite move from 2 move s that affe ct the
s ame e ntity.
193
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
7.6.9. Nearby Select ion
In s ome us e cas e s (s uch as TSP and VRP, but als o in non-chaine d variable cas e s ),
changing e ntitie s to ne arby value s or s wapping ne arby e ntitie s can he avily
incre as e s calability and improve s olution quality.
Ne arby s e le ction incre as e s the probability of s e le cting an e ntity or value which is
ne arby to the firs t e ntity be ing move d in that move .
194
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
The dis tance be twe e n 2 e ntitie s or value s is domain s pe cific. The re fore ,
imple me nt the NearbyDistanceMeter inte rface :
public interface NearbyDistanceMeter<O, D> {
double getNearbyDistance(O origin, D destination);
}
It re turns a double which re pre s e nts the dis tance :
public class CustomerNearbyDistanceMeter implements
NearbyDistanceMeter<Customer, Standstill> {
public double getNearbyDistance(Customer origin, Standstill
destination) {
return origin.getDistanceTo(destination);
}
}
To configure ne arby s e le ction, add a nearbySelection e le me nt in the
entitySelector or valueSelector and us e mimic s e le ction to s pe cify which
e ntity s hould be ne ar by the s e le ction.
<unionMoveSelector>
<changeMoveSelector>
<entitySelector id="entitySelector1"/>
195
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<valueSelector>
<nearbySelection>
<originEntitySelector
mimicSelectorRef="entitySelector1"/>
<nearbyDistanceMeterClass>...CustomerNearbyDistanceMeter</nearbyDista
nceMeterClass>
<parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximu
m>
</nearbySelection>
</valueSelector>
</changeMoveSelector>
<swapMoveSelector>
<entitySelector id="entitySelector2"/>
<secondaryEntitySelector>
<nearbySelection>
<originEntitySelector
mimicSelectorRef="entitySelector2"/>
<nearbyDistanceMeterClass>...CustomerNearbyDistanceMeter</nearbyDista
nceMeterClass>
<parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximu
m>
</nearbySelection>
</secondaryEntitySelector>
</swapMoveSelector>
<tailChainSwapMoveSelector>
<entitySelector id="entitySelector3"/>
<valueSelector>
<nearbySelection>
<originEntitySelector
mimicSelectorRef="entitySelector3"/>
<nearbyDistanceMeterClass>...CustomerNearbyDistanceMeter</nearbyDista
nceMeterClass>
<parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximu
m>
</nearbySelection>
</valueSelector>
</tailChainSwapMoveSelector>
</unionMoveSelector>
A distributionSizeMaximum parame te r s hould not be 1 be caus e if the ne are s t is
alre ady the planning value of the curre nt e ntity, the n the only move that is
s e le ctable is not doable .
To allow e ve ry e le me nt to be s e le cte d, re gardle s s of the numbe r of e ntitie s , only
s e t the dis tribution type (s o without a distributionSizeMaximum parame te r):
<nearbySelection>
<nearbySelectionDistributionType>PARABOLIC_DISTRIBUTION</nearbySelect
ionDistributionType>
196
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
</nearbySelection>
The following NearbySelectionDistributionTypesare s upporte d:
BLOCK_DISTRIBUTION: Only the n ne are s t are s e le cte d, with an e qual
probability. For e xample , s e le ct the 20 ne are s t:
<nearbySelection>
<blockDistributionSizeMaximum>20</blockDistributionSizeMaximum>
</nearbySelection>
LINEAR_DISTRIBUTION: Ne are s t e le me nts are s e le cte d with a highe r
probability. The probability de cre as e s line arly.
<nearbySelection>
<linearDistributionSizeMaximum>40</linearDistributionSizeMaximum>
</nearbySelection>
PARABOLIC_DISTRIBUTION (re comme nde d): Ne are s t e le me nts are s e le cte d
with a highe r probability.
<nearbySelection>
<parabolicDistributionSizeMaximum>80</parabolicDistributionSizeMaxi
mum>
</nearbySelection>
BETA_DISTRIBUTION: Se le ction according to a be ta dis tribution. Slows down the
s olve r s ignificantly.
<nearbySelection>
<betaDistributionAlpha>1</betaDistributionAlpha>
<betaDistributionBeta>5</betaDistributionBeta>
</nearbySelection>
As always , us e the Be nchmarke r to twe ak value s if de s ire d.
7.7. CUST OM MOVES
7.7.1. Which Move T ypes Might be Missing in my
Implement at ion?
To de te rmine which move type s might be mis s ing in your imple me ntation, run a
Be nchmarke rfor a short amount of time and configure it to write the be s t s olutions
to dis k. Take a look at s uch a be s t s olution: it will like ly be a local optima. Try to
figure out if the re ’s a move that could ge t out of that local optima fas te r.
If you find one , imple me nt that coars e -graine d move , mix it with the e xis ting
move s and be nchmark it agains t the pre vious configurations to s e e if you want to
ke e p it.
7.7.2. Cust om Moves Int roduct ion
197
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Ins te ad of re us ing the ge ne ric Moves (s uch as ChangeMove) you can als o
imple me nt your own Moves. Ge ne ric and cus tom MoveSelectorscan be combine d
as de s ire d.
A cus tom Move can be tailore d to work to the advantage of your cons traints . For
e xample , in e xamination s che duling, changing the pe riod of an e xam A als o
change s the pe riod of all the e xams that ne e d to coincide with e xam A.
A cus tom Move is als o s lightly fas te r than a ge ne ric Move. Howe ve r, it’s far more
work to imple me nt and much harde r to avoid bugs . Afte r imple me nting a cus tom
Move, make s ure to turn on environmentMode FULL_ASSERT to che ck for s core
corruptions .
7.7.3. T he Int erf ace Move
Your cus tom move s mus t imple me nt the Move inte rface :
public interface Move {
boolean isMoveDoable(ScoreDirector scoreDirector);
Move createUndoMove(ScoreDirector scoreDirector);
void doMove(ScoreDirector scoreDirector);
Collection<? extends Object> getPlanningEntities();
Collection<? extends Object> getPlanningValues();
}
Le t’s take a look at the Move imple me ntation for 4 que e ns which move s a que e n to
a diffe re nt row:
public class RowChangeMove extends AbstractMove {
private Queen queen;
private Row toRow;
public RowChangeMove(Queen queen, Row toRow) {
this.queen = queen;
this.toRow = toRow;
}
// ... see below
}
An ins tance of RowChangeMove move s a que e n from its curre nt row to a diffe re nt
row.
Planne r calls the doMove(ScoreDirector) me thod to do a move , which calls
doMoveOnGenuineVariables(ScoreDirector). The Move imple me ntation mus t
notify the ScoreDirector of any change s it make s to planning e ntity’s variable s :
public void doMoveOnGenuineVariables(ScoreDirector scoreDirector)
{
scoreDirector.beforeVariableChanged(queen, "row"); // before
198
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
changes are made to the queen.row
queen.setRow(toRow);
scoreDirector.afterVariableChanged(queen, "row"); // after
changes are made to the queen.row
}
You ne e d to call the scoreDirector.beforeVariableChanged(Object, String)
and scoreDirector.afterVariableChanged(Object, String) me thods dire ctly
be fore and afte r modifying the e ntity.
No t e
You can alte r multiple e ntitie s in a s ingle move and e ffe ctive ly cre ate a
big move (als o known as a coars e -graine d move ).
Warning
A Move can only change /add/re move planning e ntitie s , it mus t not change
any of the proble m facts .
Planne r automatically filte rs out non doable move s by calling the
isMoveDoable(ScoreDirector) me thod on a move . A non doable move is :
A move that change s nothing on the curre nt s olution. For e xample , moving
que e n B0 to row 0 is not doable , be caus e it is alre ady the re .
A move that is impos s ible to do on the curre nt s olution. For e xample , moving
que e n B0 to row 10 is not doable be caus e it would move it outs ide the board
limits .
In the n que e ns e xample , a move which move s the que e n from its curre nt row to
the s ame row is n’t doable :
public boolean isMoveDoable(ScoreDirector scoreDirector) {
return !ObjectUtils.equals(queen.getRow(), toRow);
}
Be caus e we won’t ge ne rate a move which can move a que e n outs ide the board
limits , we don’t ne e d to che ck it. A move that is curre ntly not doable could be come
doable on the working Solution of a late r s te p.
Each move has an undo move: a move (normally of the s ame type ) which doe s the
e xact oppos ite . In the e xample above the undo move of C0 to C2 would be the
move C2 to C0. An undo move is cre ate d from a Move, be fore the Move has be e n
done on the curre nt s olution.
public Move createUndoMove(ScoreDirector scoreDirector) {
return new RowChangeMove(queen, queen.getRow());
}
Notice that if C0 would have alre ady be e n move d to C2, the undo move would
cre ate the move C2 to C2, ins te ad of the move C2 to C0.
199
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
A s olve r phas e might do and undo the s ame Move more than once . In fact, many
s olve r phas e s will ite rative ly do and undo a numbe r of move s to e valuate the m,
be fore s e le cting one of thos e and doing that move again (without undoing it this
time ).
A Move mus t imple me nt the getPlanningEntities() and getPlanningValues()
me thods . The y are us e d by e ntity tabu and value tabu re s pe ctive ly. Whe n the y
are calle d, the Move has alre ady be e n done .
public List<? extends Object> getPlanningEntities() {
return Collections.singletonList(queen);
}
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toRow);
}
If your Move change s multiple planning e ntitie s , re turn all of the m in
getPlanningEntities() and re turn all the ir value s (to which the y are changing) in
getPlanningValues().
public Collection<? extends Object> getPlanningEntities() {
return Arrays.asList(leftCloudProcess, rightCloudProcess);
}
public Collection<? extends Object> getPlanningValues() {
return Arrays.asList(leftCloudProcess.getComputer(),
rightCloudProcess.getComputer());
}
A Move mus t imple me nt the equals() and hashCode() me thods . 2 move s which
make the s ame change on a s olution, s hould be e qual.
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof RowChangeMove) {
RowChangeMove other = (RowChangeMove) o;
return new EqualsBuilder()
.append(queen, other.queen)
.append(toRow, other.toRow)
.isEquals();
} else {
return false;
}
}
public int hashCode() {
return new HashCodeBuilder()
.append(queen)
.append(toRow)
.toHashCode();
}
200
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
Notice that it che cks if the othe r move is an ins tance of the s ame move type . This
instanceof che ck is important be caus e a move will be compare d to a move with
anothe r move type if you’re us ing more than 1 move type .
Imple me nt the toString() me thod to ke e p Planne r’s logs re adable :
public String toString() {
return queen + " {" + queen.getRow() + " -> " + toRow + "}";
}
Now that we can imple me nt a s ingle cus tom Move, le t’s take a look at ge ne rating
s uch cus tom move s .
7.7.4. MoveList Fact ory: t he Easy Way t o Generat e Cust om
Moves
The e as ie s t way to ge ne rate cus tom move s is by imple me nting the inte rface
MoveListFactory:
public interface MoveListFactory<S extends Solution> {
List<Move> createMoveList(S solution);
}
For e xample :
public class RowChangeMoveFactory implements MoveListFactory<NQueens>
{
public List<Move> createMoveList(NQueens nQueens) {
List<Move> moveList = new ArrayList<Move>();
for (Queen queen : nQueens.getQueenList()) {
for (Row toRow : nQueens.getRowList()) {
moveList.add(new RowChangeMove(queen, toRow));
}
}
return moveList;
}
}
Simple configuration (which can be ne s te d in a unionMoveSelector jus t like any
othe r MoveSelector):
<moveListFactory>
<moveListFactoryClass>org.optaplanner.examples.nqueens.solver.move.fa
ctory.RowChangeMoveFactory</moveListFactoryClass>
</moveListFactory>
Advance d configuration:
<moveListFactory>
201
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
... <!-- Normal moveSelector properties -->
<moveListFactoryClass>org.optaplanner.examples.nqueens.solver.move.fa
ctory.RowChangeMoveFactory</moveListFactoryClass>
</moveListFactory>
Be caus e the MoveListFactory ge ne rate s all move s at once in a List<Move>, it
doe s not s upport cacheType JUST_IN_TIME. The re fore , moveListFactory us e s
cacheType STEP by de fault and it s cale s badly in me mory footprint.
7.7.5. MoveIt erat orFact ory: Generat e Cust om Moves Just in
T ime
Us e this advance d form to ge ne rate cus tom move s by imple me nting the
MoveIteratorFactory inte rface :
public interface MoveIteratorFactory {
long getSize(ScoreDirector scoreDirector);
Iterator<Move> createOriginalMoveIterator(ScoreDirector
scoreDirector);
Iterator<Move> createRandomMoveIterator(ScoreDirector
scoreDirector, Random workingRandom);
}
The getSize() me thod mus t give an e s timation of the s iz e . It doe s n’t ne e d to be
corre ct. The createOriginalMoveIterator me thod is calle d if the
selectionOrder is ORIGINAL or if it is cache d. The createRandomMoveIterator
me thod is calle d for selectionOrder RANDOM combine d with cache Type
JUST_IN_TIME.
Impo rt ant
Don’t cre ate a colle ction (lis t, array, map, s e t) of Moves whe n cre ating the
Iterator<Move>: the whole purpos e of MoveIteratorFactory ove r
MoveListFactory is giving you the ability to cre ate a Move jus t in time in
the Iterator's me thod next().
Simple configuration (which can be ne s te d in a unionMoveSelector jus t like any
othe r MoveSelector):
<moveIteratorFactory>
<moveIteratorFactoryClass>...</moveIteratorFactoryClass>
</moveIteratorFactory>
Advance d configuration:
202
CHAPT ER 7. MO VE AND NEIGHBO RHO O D SELECT IO N
<moveIteratorFactory>
... <!-- Normal moveSelector properties -->
<moveIteratorFactoryClass>...</moveIteratorFactoryClass>
</moveIteratorFactory>
203
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 8. EXHAUSTIVE SEARCH
8.1. OVERVIEW
Exhaus tive Se arch will always find the global optimum and re cogniz e it too. That
be ing s aid, it doe s n’t s cale (not e ve n be yond toy data s e ts ) and is the re fore
mos tly us e le s s .
8.2. BRUT E FORCE
8.2.1. Algorit hm Descript ion
The Brute Force algorithm cre ate s and e valuate s e ve ry pos s ible s olution.
Notice that it cre ate s a s e arch tre e that e xplode s e xpone ntially as the proble m
s iz e incre as e s , s o it hits a s calability wall.
Impo rt ant
Brute Force is mos tly unus able for a re al-world proble m due to time
limitations , as s hown in s calability of Exhaus tive FSe arch.
8.2.2. Conf igurat ion
204
CHAPT ER 8 . EXHAUST IVE SEARCH
Simple s t configuration of Brute Force :
<solver>
...
<exhaustiveSearch>
<exhaustiveSearchType>BRUTE_FORCE</exhaustiveSearchType>
</exhaustiveSearch>
</solver>
8.3. BRANCH AND BOUND
8.3.1. Algorit hm Descript ion
Branch And Bound als o e xplore s node s in an e xpone ntial s e arch tre e , but it
inve s tigate s more promis ing node s firs t and prune s away worthle s s node s .
For e ach node , Branch And Bound calculate s the optimis tic bound: the be s t
pos s ible s core to which that node can le ad to. If the optimis tic bound of a node is
lowe r or e qual to the global pe s s imis tic bound, the n it prune s away that node
(including the e ntire branch of all its s ubnode s ).
No t e
Acade mic pape rs us e the te rm lowe r bound ins te ad of optimis tic bound
(and the te rm uppe r bound ins te ad of pe s s imis tic bound), be caus e the y
minimiz e the s core .
Planne r maximiz e s the s core (be caus e it s upports combining ne gative and
pos itive cons traints ). The re fore , for clarity, it us e s diffe re nt te rms , as it
would be confus ing to us e the te rm lowe r bound for a bound which is
always highe r.
For e xample : at inde x 15, it can prune away all unvis ite d s olutions with que e n A on
row 0, be caus e none will be be tte r than the s olution of inde x 14 with a s core of -1.
205
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Notice that Branch And Bound (much like Brute Force ) cre ate s a s e arch tre e that
e xplode s e xpone ntially as the proble m s iz e incre as e s . So it hits the s ame
s calability wall, only a little bit late r.
Impo rt ant
Branch And Bound is mos tly unus able for a re al-world proble m due to time
limitations , as s hown in s calability of Exhaus tive Se arch.
8.3.2. Conf igurat ion
Simple s t configuration of Branch And Bound:
<solver>
...
<exhaustiveSearch>
<exhaustiveSearchType>BRANCH_AND_BOUND</exhaustiveSearchType>
</exhaustiveSearch>
</solver>
206
CHAPT ER 8 . EXHAUST IVE SEARCH
Impo rt ant
For the pruning to work with the de fault ScoreBounder, the
Initializ ingScore Tre nd s hould be s e t. Es pe cially an Initializ ingScore Tre nd of
ONLY_DOWN (or at le as t has ONLY_DOWN in the le ading s core le ve ls ) prune s
a lot.
Advance d configuration:
<exhaustiveSearch>
<exhaustiveSearchType>BRANCH_AND_BOUND</exhaustiveSearchType>
<nodeExplorationType>DEPTH_FIRST</nodeExplorationType>
<entitySorterManner>DECREASING_DIFFICULTY_IF_AVAILABLE</entitySorterM
anner>
<valueSorterManner>INCREASING_STRENGTH_IF_AVAILABLE</valueSorterManne
r>
</exhaustiveSearch>
The nodeExplorationType options are :
DEPTH_FIRST (de fault): Explore de e pe r node s firs t (and the n a be tte r s core and
the n a be tte r optimis tic bound). De e pe r node s (e s pe cially le af node s ) ofte n
improve the pe s s imis tic bound. A be tte r pe s s imis tic bound allows pruning more
node s to re duce the s e arch s pace .
<exhaustiveSearch>
<exhaustiveSearchType>BRANCH_AND_BOUND</exhaustiveSearchType>
<nodeExplorationType>DEPTH_FIRST</nodeExplorationType>
</exhaustiveSearch>
BREADTH_FIRST (not re comme nde d): Explore node s laye r by laye r (and the n a
be tte r s core and the n a be tte r optimis tic bound). Scale s te rribly in me mory (and
us ually in pe rformance too).
<exhaustiveSearch>
<exhaustiveSearchType>BRANCH_AND_BOUND</exhaustiveSearchType>
<nodeExplorationType>BREADTH_FIRST</nodeExplorationType>
</exhaustiveSearch>
SCORE_FIRST: Explore node s with a be tte r s core firs t (and the n a be tte r
optimis tic bound and the n de e pe r node s firs t). Might s cale as te rribly as
BREADTH_FIRST in s ome cas e s .
<exhaustiveSearch>
<exhaustiveSearchType>BRANCH_AND_BOUND</exhaustiveSearchType>
<nodeExplorationType>SCORE_FIRST</nodeExplorationType>
</exhaustiveSearch>
OPTIMISTIC_BOUND_FIRST: Explore node s with a be tte r optimis tic bound firs t
(and the n a be tte r s core and the n de e pe r node s firs t). Might s cale as te rribly as
BREADTH_FIRST in s ome cas e s .
207
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<exhaustiveSearch>
<exhaustiveSearchType>BRANCH_AND_BOUND</exhaustiveSearchType>
<nodeExplorationType>OPTIMISTIC_BOUND_FIRST</nodeExplorationType>
</exhaustiveSearch>
The entitySorterManner options are :
DECREASING_DIFFICULTY: Initializ e the more difficult planning e ntitie s firs t. This
us ually incre as e s pruning (and the re fore improve s s calability). Re quire s the
mode l to s upport planning e ntity difficulty comparis on.
DECREASING_DIFFICULTY_IF_AVAILABLE (de fault): If the mode l s upports
planning e ntity difficulty comparis on, be have like DECREASING_DIFFICULTY, e ls e
like NONE.
NONE: Initializ e the planning e ntitie s in original orde r.
The valueSorterManner options are :
INCREASING_STRENGTH: Evaluate the planning value s in incre as ing s tre ngth.
Re quire s the mode l to s upport planning value s tre ngth comparis on.
INCREASING_STRENGTH_IF_AVAILABLE (de fault): If the mode l s upports planning
value s tre ngth comparis on, be have like INCREASING_STRENGTH, e ls e like NONE.
DECREASING_STRENGTH: Evaluate the planning value s in de cre as ing s tre ngth.
Re quire s the mode l to s upport planning value s tre ngth comparis on.
DECREASING_STRENGTH_IF_AVAILABLE: If the mode l s upports planning value
s tre ngth comparis on, be have like DECREASING_STRENGTH, e ls e like NONE.
NONE: Try the planning value s in original orde r.
8.4. SCALABILIT Y OF EXHAUST IVE SEARCH
Exhaus tive Se arch variants s uffe r from 2 big s calability is s ue s :
The y s cale te rribly me mory wis e .
The y s cale horribly pe rformance wis e .
As s hown in the s e time s pe nt graphs from the Be nchmarke r, Brute Force and
Branch And Bound both hit a pe rformance s calability wall. For e xample , on N
que e ns it hits wall at a fe w doz e n que e ns :
208
CHAPT ER 8 . EXHAUST IVE SEARCH
In mos t us e cas e s , s uch as Cloud Balancing, the wall appe ars out of thin air:
209
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Exhaus tive Se arch hits this wall on s mall datas e ts alre ady, s o in production the s e
optimiz ations algorithms are mos tly us e le s s . Us e Cons truction He uris tics with
Local Se arch ins te ad: thos e can handle thous ands of que e ns /compute rs e as ily.
No t e
Throwing hardware at the s e s calability is s ue s has no notice able impact.
Ne we r and more hardware are jus t a drop in the oce an. Moore ’s law
cannot win agains t the ons laught of a fe w more planning e ntitie s in the
datas e t.
210
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
CHAPTER 9. CONSTRUCTION HEURISTICS
9.1. OVERVIEW
A cons truction he uris tic builds a pre tty good initial s olution in a finite le ngth of time .
Its s olution is n’t always fe as ible , but it finds it fas t s o me tahe uris tics can finis h the
job.
Cons truction he uris tics te rminate automatically, s o the re ’s us ually no ne e d to
configure a Termination on the cons truction he uris tic phas e s pe cifically.
9.2. FIRST FIT
9.2.1. Algorit hm Descript ion
The Firs t Fit algorithm cycle s through all the planning e ntitie s (in de fault orde r),
initializ ing 1 planning e ntity at a time . It as s igns the planning e ntity to the be s t
available planning value , taking the alre ady initializ e d planning e ntitie s into account.
It te rminate s whe n all planning e ntitie s have be e n initializ e d. It ne ve r change s a
planning e ntity afte r it has be e n as s igne d.
Notice that it s tarts with putting Queen A into row 0 (and ne ve r moving it late r),
which make s it impos s ible to re ach the optimal s olution. Suffixing this cons truction
he uris tic with me tahe uris tics can re me dy that.
211
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
9.2.2. Conf igurat ion
Configure this s olve r phas e :
<constructionHeuristic>
<constructionHeuristicType>FIRST_FIT</constructionHeuristicType>
</constructionHeuristic>
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate Entity From Que ue .
9.3. FIRST FIT DECREASING
9.3.1. Algorit hm Descript ion
Like Firs t Fit, but as s igns the more difficult planning e ntitie s firs t, be caus e the y are
le s s like ly to fit in the le ftove rs . So it s orts the planning e ntitie s on de cre as ing
difficulty.
Re quire s the mode l to s upport planning e ntity difficulty comparis on.
212
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
No t e
One would e xpe ct that this algorithm has be tte r re s ults than Firs t Fit.
That’s us ually the cas e , but not always .
9.3.2. Conf igurat ion
Configure this s olve r phas e :
<constructionHeuristic>
<constructionHeuristicType>FIRST_FIT_DECREASING</constructionHeuristi
cType>
</constructionHeuristic>
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate Entity From Que ue .
9.4. WEAKEST FIT
9.4.1. Algorit hm Descript ion
Like Firs t Fit, but us e s the we ake r planning value s firs t, be caus e the s trong
planning value s are more like ly to be able to accommodate late r planning e ntitie s .
So it s orts the planning value s on incre as ing s tre ngth.
Re quire s the mode l to s upport planning value s tre ngth comparis on.
No t e
Do not pre s ume that this algorithm has be tte r re s ults than Firs t Fit. That’s
ofte n not the cas e .
9.4.2. Conf igurat ion
Configure this s olve r phas e :
<constructionHeuristic>
<constructionHeuristicType>WEAKEST_FIT</constructionHeuristicType>
</constructionHeuristic>
213
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate Entity From Que ue .
9.5. WEAKEST FIT DECREASING
9.5.1. Algorit hm Descript ion
Combine s Firs t Fit De cre as ing and We ake s t Fit. So it s orts the planning e ntitie s on
de cre as ing difficulty and the planning value s on incre as ing s tre ngth.
Re quire s the mode l to s upport planning e ntity difficulty comparis on and planning
value s tre ngth comparis on.
No t e
Do not pre s ume that this algorithm has be tte r re s ults than Firs t Fit
De cre as ing. That’s ofte n not the cas e . Howe ve r, it is us ually be tte r than
We ake s t Fit.
9.5.2. Conf igurat ion
Configure this s olve r phas e :
<constructionHeuristic>
<constructionHeuristicType>WEAKEST_FIT_DECREASING</constructionHeuris
ticType>
</constructionHeuristic>
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate Entity From Que ue .
9.6. ST RONGEST FIT
9.6.1. Algorit hm Descript ion
214
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
Like Firs t Fit, but us e s the s trong planning value s firs t, be caus e the s trong planning
value s are more like ly to have a lowe r s oft cos t to us e . So it s orts the planning
value s on de cre as ing s tre ngth.
Re quire s the mode l to s upport planning value s tre ngth comparis on.
No t e
Do not pre s ume that this algorithm has be tte r re s ults than Firs t Fit or
We ake s t Fit. That’s ofte n not the cas e .
9.6.2. Conf igurat ion
Configure this s olve r phas e :
<constructionHeuristic>
<constructionHeuristicType>STRONGEST_FIT</constructionHeuristicType>
</constructionHeuristic>
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate Entity From Que ue .
9.7. ST RONGEST FIT DECREASING
9.7.1. Algorit hm Descript ion
Combine s Firs t Fit De cre as ing and Stronge s t Fit. So it s orts the planning e ntitie s on
de cre as ing difficulty and the planning value s on de cre as ing s tre ngth.
Re quire s the mode l to s upport planning e ntity difficulty comparis on and planning
value s tre ngth comparis on.
No t e
Do not pre s ume that this algorithm has be tte r re s ults than Firs t Fit
De cre as ing or We ake s t Fit De cre as ing. That’s ofte n not the cas e .
Howe ve r, it is us ually be tte r than Stronge s t Fit.
9.7.2. Conf igurat ion
Configure this s olve r phas e :
<constructionHeuristic>
215
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<constructionHeuristicType>STRONGEST_FIT_DECREASING</constructionHeur
isticType>
</constructionHeuristic>
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate Entity From Que ue .
9.8. ALLOCAT E ENT IT Y FROM QUEUE
9.8.1. Algorit hm Descript ion
Allocate Entity From Que ue is a ve rs atile , ge ne ric form of Firs t Fit, Firs t Fit
De cre as ing, We ake s t Fit and We ake s t Fit De cre as ing. It works like this :
1. Put all e ntitie s in a que ue .
2. As s ign the firs t e ntity (from that que ue ) to the be s t value .
3. Re pe at until all e ntitie s are as s igne d.
9.8.2. Conf igurat ion
Simple configuration:
<constructionHeuristic>
<constructionHeuristicType>ALLOCATE_ENTITY_FROM_QUEUE</constructionHe
uristicType>
</constructionHeuristic>
Ve rbos e s imple configuration:
<constructionHeuristic>
<constructionHeuristicType>ALLOCATE_ENTITY_FROM_QUEUE</constructionHe
uristicType>
<entitySorterManner>DECREASING_DIFFICULTY_IF_AVAILABLE</entitySorterM
anner>
<valueSorterManner>INCREASING_STRENGTH_IF_AVAILABLE</valueSorterManne
r>
</constructionHeuristic>
The entitySorterManner options are :
216
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
DECREASING_DIFFICULTY: Initializ e the more difficult planning e ntitie s firs t. This
us ually incre as e s pruning (and the re fore improve s s calability). Re quire s the
mode l to s upport planning e ntity difficulty comparis on.
DECREASING_DIFFICULTY_IF_AVAILABLE (de fault): If the mode l s upports
planning e ntity difficulty comparis on, be have like DECREASING_DIFFICULTY, e ls e
like NONE.
NONE: Initializ e the planning e ntitie s in original orde r.
The valueSorterManner options are :
INCREASING_STRENGTH: Evaluate the planning value s in incre as ing s tre ngth.
Re quire s the mode l to s upport planning value s tre ngth comparis on.
INCREASING_STRENGTH_IF_AVAILABLE (de fault): If the mode l s upports planning
value s tre ngth comparis on, be have like INCREASING_STRENGTH, e ls e like NONE.
DECREASING_STRENGTH: Evaluate the planning value s in de cre as ing s tre ngth.
Re quire s the mode l to s upport planning value s tre ngth comparis on.
DECREASING_STRENGTH_IF_AVAILABLE: If the mode l s upports planning value
s tre ngth comparis on, be have like DECREASING_STRENGTH, e ls e like NONE.
NONE: Try the planning value s in original orde r.
Advance d de taile d configuration. For e xample , a We ake s t Fit De cre as ing
configuration for a s ingle e ntity clas s with a s ingle variable :
<constructionHeuristic>
<queuedEntityPlacer>
<entitySelector id="placerEntitySelector">
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>DECREASING_DIFFICULTY</sorterManner>
</entitySelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
<valueSelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>INCREASING_STRENGTH</sorterManner>
</valueSelector>
</changeMoveSelector>
</queuedEntityPlacer>
</constructionHeuristic>
Pe r s te p, the QueuedEntityPlacer s e le cts 1 uninitializ e d e ntity from the
EntitySelector and applie s the winning Move (out of all the move s for that e ntity
ge ne rate d by the MoveSelector). The mimic s e le ction e ns ure s that the winning
Move change s (only) the s e le cte d e ntity.
To cus tomiz e the e ntity or value s orting, s e e s orte d s e le ction. Othe r Selector
cus tomiz ation (s uch as filte ring and limiting) is s upporte d too.
9.8.3. Mult iple Variables
217
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The re are 2 ways to de al with multiple variable s , de pe nding on how the ir
ChangeMovesare combine d:
Carte s ian product of the ChangeMoves(de fault): All variable s of the s e le cte d
e ntity are as s igne d toge the r. Has far be tte r re s ults (e s pe cially for time tabling
us e cas e s ).
Se que ntial ChangeMoves: One variable is as s igne d at a time . Scale s much
be tte r, e s pe cially for 3 or more variable s .
For e xample , pre s ume a cours e s che duling e xample with 200 rooms and 40
pe riods .
This Firs t Fit configuration for a s ingle e ntity clas s with 2 variable s , us ing a
carte s ian product of the ir ChangeMoves, will s e le ct 8000 move s pe r e ntity:
<constructionHeuristic>
<queuedEntityPlacer>
<entitySelector id="placerEntitySelector">
<cacheType>PHASE</cacheType>
</entitySelector>
<cartesianProductMoveSelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
<valueSelector>
<variableName>room</variableName>
</valueSelector>
</changeMoveSelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
<valueSelector>
<variableName>period</variableName>
</valueSelector>
</changeMoveSelector>
</cartesianProductMoveSelector>
</queuedEntityPlacer>
...
</constructionHeuristic>
Warning
With 3 variable s of 1000 value s e ach, a carte s ian product s e le cts
1000000000 value s pe r e ntity, which will take far too long.
This Firs t Fit configuration for a s ingle e ntity clas s with 2 variable s , us ing
s e que ntial ChangeMoves, will s e le ct 240 move s pe r e ntity:
<constructionHeuristic>
<queuedEntityPlacer>
<entitySelector id="placerEntitySelector">
<cacheType>PHASE</cacheType>
</entitySelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
218
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
<valueSelector>
<variableName>period</variableName>
</valueSelector>
</changeMoveSelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
<valueSelector>
<variableName>room</variableName>
</valueSelector>
</changeMoveSelector>
</queuedEntityPlacer>
...
</constructionHeuristic>
Impo rt ant
Es pe cially for s e que ntial ChangeMoves, the orde r of the variable s is
important. In the e xample above , it’s be tte r to s e le ct the pe riod firs t
(ins te ad of the othe r way around), be caus e the re are more hard
cons traints that do not involve the room (for e xample : no te ache r s hould
te ach 2 le cture s at the s ame time ). Le t the Be nchmarke r guide you.
With 3 or more variable s , it’s pos s ible to combine the carte s ian product and
s e que ntial te chnique s :
<constructionHeuristic>
<queuedEntityPlacer>
...
<cartesianProductMoveSelector>
<changeMoveSelector>...</changeMoveSelector>
<changeMoveSelector>...</changeMoveSelector>
</cartesianProductMoveSelector>
<changeMoveSelector>...</changeMoveSelector>
</queuedEntityPlacer>
...
</constructionHeuristic>
9.8.4. Mult iple Ent it y Classes
The e as ie s t way to de al with multiple e ntity clas s e s is to run a s e parate
cons truction he uris tic for e ach e ntity clas s :
<constructionHeuristic>
<queuedEntityPlacer>
<entitySelector id="placerEntitySelector">
<cacheType>PHASE</cacheType>
<entityClass>...DogEntity</entityClass>
</entitySelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
</changeMoveSelector>
</queuedEntityPlacer>
...
219
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
</constructionHeuristic>
<constructionHeuristic>
<queuedEntityPlacer>
<entitySelector id="placerEntitySelector">
<cacheType>PHASE</cacheType>
<entityClass>...CatEntity</entityClass>
</entitySelector>
<changeMoveSelector>
<entitySelector mimicSelectorRef="placerEntitySelector"/>
</changeMoveSelector>
</queuedEntityPlacer>
...
</constructionHeuristic>
9.8.5. Pick Early T ype
The re are s e ve ral pick e arly type s for Cons truction He uris tics :
NEVER: Evaluate all the s e le cte d move s to initializ e the variable (s ). This is the
de fault if the Initializ ingScore Tre nd is not ONLY_DOWN.
<constructionHeuristic>
...
<forager>
<pickEarlyType>NEVER</pickEarlyType>
</forager>
</constructionHeuristic>
FIRST_NON_DETERIORATING_SCORE: Initializ e the variable (s ) with the firs t move
that doe s n’t de te riorate the s core , ignore the re maining s e le cte d move s . This
is the de fault if the Initializ ingScore Tre nd is ONLY_DOWN.
<constructionHeuristic>
...
<forager>
<pickEarlyType>FIRST_NON_DETERIORATING_SCORE</pickEarlyType>
</forager>
</constructionHeuristic>
No t e
If the re are only ne gative cons traints , but the Initializ ingScore Tre nd is
s trictly not ONLY_DOWN, it can s ome time s make s e ns e to apply
FIRST_NON_DETERIORATING_SCORE. Us e the Be nchmarke r to de cide if
the s core quality los s is worth the time gain.
FIRST_FEASIBLE_SCORE: Initializ e the variable (s ) with the firs t move that has a
fe as ible s core .
<constructionHeuristic>
...
<forager>
<pickEarlyType>FIRST_FEASIBLE_SCORE</pickEarlyType>
220
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
</forager>
</constructionHeuristic>
If the Initializ ingScore Tre nd is ONLY_DOWN, us e
FIRST_FEASIBLE_SCORE_OR_NON_DETERIORATING_HARD ins te ad, be caus e that’s
fas te r without any dis advantage s .
FIRST_FEASIBLE_SCORE_OR_NON_DETERIORATING_HARD: Initializ e the variable (s )
with the firs t move that doe s n’t de te riorate the fe as ibility of the s core any
furthe r.
<constructionHeuristic>
...
<forager>
<pickEarlyType>FIRST_FEASIBLE_SCORE_OR_NON_DETERIORATING_HARD</pick
EarlyType>
</forager>
</constructionHeuristic>
9.9. ALLOCAT E T O VALUE FROM QUEUE
9.9.1. Algorit hm Descript ion
Allocate To Value From Que ue works like this :
1. Put all value s in a round-robin que ue .
2. As s ign the be s t e ntity to the firs t value (from that que ue ).
3. Re pe at until all e ntitie s are as s igne d.
9.9.2. Conf igurat ion
Simple configuration:
<constructionHeuristic>
<constructionHeuristicType>ALLOCATE_TO_VALUE_FROM_QUEUE</construction
HeuristicType>
</constructionHeuristic>
Ve rbos e s imple configuration:
<constructionHeuristic>
<constructionHeuristicType>ALLOCATE_TO_VALUE_FROM_QUEUE</construction
HeuristicType>
<entitySorterManner>DECREASING_DIFFICULTY_IF_AVAILABLE</entitySorterM
anner>
221
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<valueSorterManner>INCREASING_STRENGTH_IF_AVAILABLE</valueSorterManne
r>
</constructionHeuristic>
Advance d de taile d configuration. For e xample , a configuration for a s ingle e ntity
clas s with a s ingle variable :
<constructionHeuristic>
<queuedValuePlacer>
<valueSelector id="placerValueSelector">
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>INCREASING_STRENGTH</sorterManner>
</valueSelector>
<changeMoveSelector>
<entitySelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>DECREASING_DIFFICULTY</sorterManner>
</entitySelector>
<valueSelector mimicSelectorRef="placerValueSelector"/>
</changeMoveSelector>
</queuedValuePlacer>
</constructionHeuristic>
9.10. CHEAPEST INSERT ION
9.10.1. Algorit hm Descript ion
The Che ape s t Ins e rtion algorithm cycle s through all the planning value s for all the
planning e ntitie s , initializ ing 1 planning e ntity at a time . It as s igns a planning e ntity
to the be s t available planning value (out of all the planning e ntitie s and value s ),
taking the alre ady initializ e d planning e ntitie s into account. It te rminate s whe n all
planning e ntitie s have be e n initializ e d. It ne ve r change s a planning e ntity afte r it
has be e n as s igne d.
222
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
No t e
Che ape s t Ins e rtion s cale s cons ide rably wors e than Firs t Fit, e tc.
9.10.2. Conf igurat ion
Simple s t configuration of Che ape s t Ins e rtion:
<constructionHeuristic>
<constructionHeuristicType>CHEAPEST_INSERTION</constructionHeuristicT
ype>
</constructionHeuristic>
No t e
If the Initializ ingScore Tre nd is ONLY_DOWN, this algorithm is fas te r: for an
e ntity, it picks the firs t move for which the s core doe s not de te riorate the
las t s te p s core , ignoring all s ubs e que nt move s .
For advance d configuration, s e e Allocate from pool.
9.11. REGRET INSERT ION
223
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
9.11.1. Algorit hm Descript ion
The Re gre t Ins e rtion algorithm be have s like the Che ape s t Ins e rtion algorithm. It
als o cycle s through all the planning value s for all the planning e ntitie s , initializ ing 1
planning e ntity at a time . But ins te ad of picking the e ntity-value combination with
the be s t s core , it picks the e ntity which has the large s t s core los s be twe e n its
be s t and s e cond be s t value as s ignme nt. It the n as s igns that e ntity to its be s t
value , to avoid re gre tting not having done that.
9.11.2. Conf igurat ion
This algorithm has not be e n imple me nte d ye t.
9.12. ALLOCAT E FROM POOL
9.12.1. Algorit hm Descript ion
Allocate From Pool is a ve rs atile , ge ne ric form of Che ape s t Ins e rtion and Re gre t
Ins e rtion. It works like this :
1. Put all e ntity-value combinations in a pool.
2. As s ign the be s t e ntity to be s t value .
3. Re pe at until all e ntitie s are as s igne d.
9.12.2. Conf igurat ion
Simple configuration:
<constructionHeuristic>
<constructionHeuristicType>ALLOCATE_FROM_POOL</constructionHeuristicT
ype>
</constructionHeuristic>
Ve rbos e s imple configuration:
<constructionHeuristic>
<constructionHeuristicType>ALLOCATE_FROM_POOL</constructionHeuristicT
ype>
<entitySorterManner>DECREASING_DIFFICULTY_IF_AVAILABLE</entitySorterM
anner>
<valueSorterManner>INCREASING_STRENGTH_IF_AVAILABLE</valueSorterManne
r>
</constructionHeuristic>
The entitySorterManner and valueSorterManner options are de s cribe d in
Allocate Entity From Que ue .
224
CHAPT ER 9 . CO NST RUCT IO N HEURIST ICS
Advance d de taile d configuration. For e xample , a Che ape s t Ins e rtion configuration
for a s ingle e ntity clas s with a s ingle variable :
<constructionHeuristic>
<pooledEntityPlacer>
<changeMoveSelector>
<entitySelector id="placerEntitySelector">
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>DECREASING_DIFFICULTY</sorterManner>
</entitySelector>
<valueSelector>
<cacheType>PHASE</cacheType>
<selectionOrder>SORTED</selectionOrder>
<sorterManner>INCREASING_STRENGTH</sorterManner>
</valueSelector>
</changeMoveSelector>
</pooledEntityPlacer>
</constructionHeuristic>
Pe r s te p, the PooledEntityPlacer applie s the winning Move (out of all the move s
for that e ntity ge ne rate d by the MoveSelector).
To cus tomiz e the e ntity or value s orting, s e e s orte d s e le ction. Othe r Selector
cus tomiz ation (s uch as filte ring and limiting) is s upporte d too.
225
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 10. LOCAL SEARCH
10.1. OVERVIEW
Local Se arch s tarts from an initial s olution and e volve s that s ingle s olution into a
mos tly be tte r and be tte r s olution. It us e s a s ingle s e arch path of s olutions , not a
s e arch tre e . At e ach s olution in this path it e valuate s a numbe r of move s on the
s olution and applie s the mos t s uitable move to take the s te p to the ne xt s olution. It
doe s that for a high numbe r of ite rations until it’s te rminate d (us ually be caus e its
time has run out).
Local Se arch acts a lot like a human planne r: it us e s a s ingle s e arch path and
move s facts around to find a good fe as ible s olution. The re fore it’s pre tty natural to
imple me nt.
Local Se arch us ually ne e ds to s tart from an initializ e d s olution, the re fore it’s
us ually re quire d to configure a cons truction he uris tic s olve r phas e be fore it.
10.2. LOCAL SEARCH CONCEPT S
10.2.1. St ep by St ep
A s te p is the winning Move. Local Se arch trie s a numbe r of move s on the curre nt
s olution and picks the be s t acce pte d move as the s te p:
Figure 10 .1. Decide t he next st ep at st ep 0 (4 queens example)
Be caus e the move B0 to B3 has the highe s t s core (-3), it is picke d as the ne xt
s te p. If multiple move s have the s ame highe s t s core , one is picke d randomly, in
this cas e B0 to B3. Note that C0 to C3 (not s hown) could als o have be e n picke d
be caus e it als o has the s core -3.
226
CHAPT ER 10 . LO CAL SEARCH
The s te p is applie d on the s olution. From that ne w s olution, Local Se arch trie s
e ve ry move again, to de cide the ne xt s te p afte r that. It continually doe s this in a
loop, and we ge t s ome thing like this :
Figure 10 .2. All st eps (4 queens example)
Notice that Local Se arch doe s n’t us e a s e arch tre e , but a s e arch path. The s e arch
path is highlighte d by the gre e n arrows . At e ach s te p it trie s all s e le cte d move s ,
but unle s s it’s the s te p, it doe s n’t inve s tigate that s olution furthe r. This is one of
the re as ons why Local Se arch is ve ry s calable .
As s hown above , Local Se arch s olve s the 4 que e ns proble m by s tarting with the
s tarting s olution and make the following s te ps s e que ntially:
1. B0 to B3
2. D0 to B2
227
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
3. A0 to B1
Turn on debug logging for the cate gory org.optaplanner to s how thos e s te ps in
the log:
INFO Solving started: time spent (0), best score (-6), random (JDK
with seed 0).
DEBUG
LS step (0), time spent (20), score (-3), new best score
(-3), accepted/selected move count (12/12), picked move (Queen-1
{Row-0 -> Row-3}).
DEBUG
LS step (1), time spent (31), score (-1), new best score
(-1), accepted/selected move count (12/12), picked move (Queen-3
{Row-0 -> Row-2}).
DEBUG
LS step (2), time spent (40), score (0), new best score
(0), accepted/selected move count (12/12), picked move (Queen-0
{Row-0 -> Row-1}).
INFO Local Search phase (0) ended: step total (3), time spent
(41), best score (0).
INFO Solving ended: time spent (41), best score (0), average
calculate count per second (1780).
Notice that a log me s s age include s the toString() me thod of the Move
imple me ntation which re turns for e xample Queen-1 {Row-0 → Row-3}.
A naive Local Se arch configuration s olve s the 4 que e ns proble m in 3 s te ps , by
e valuating only 37 pos s ible s olutions (3 s te ps with 12 move s e ach + 1 s tarting
s olution), which is only fraction of all 256 pos s ible s olutions . It s olve s 16 que e ns in
31 s te ps , by e valuating only 7441 out of 18446744073709551616 pos s ible
s olutions . By us ing a Cons truction He uris tics phas e firs t, it’s e ve n a lot more
e fficie nt.
10.2.2. Decide t he Next St ep
Local Se arch de cide s the ne xt s te p with the aid of 3 configurable compone nts :
A MoveSelector which s e le cts the pos s ible move s of the curre nt s olution. Se e
the chapte r move and ne ighborhood s e le ction.
An Acceptor which filte rs out unacce ptable move s .
A Forager which gathe rs acce pte d move s and picks the ne xt s te p from the m.
The s olve r phas e configuration looks like this :
<localSearch>
<unionMoveSelector>
...
</unionMoveSelector>
<acceptor>
...
</acceptor>
<forager>
...
</forager>
</localSearch>
228
CHAPT ER 10 . LO CAL SEARCH
In the e xample be low, the MoveSelector ge ne rate d the move s s hown with the
blue line s , the Acceptor acce pte d all of the m and the Forager picke d the move B0
to B3.
Turn on trace logging to s how the de cis ion making in the log:
INFO Solver started: time spent (0), score (-6), new best score (6), random (JDK with seed 0).
TRACE
Move index (0) not doable, ignoring move (Queen-0
{Row-0 -> Row-0}).
TRACE
Move index (1), score (-4), accepted (true), move
(Queen-0 {Row-0 -> Row-1}).
TRACE
Move index (2), score (-4), accepted (true), move
(Queen-0 {Row-0 -> Row-2}).
TRACE
Move index (3), score (-4), accepted (true), move
(Queen-0 {Row-0 -> Row-3}).
...
TRACE
Move index (6), score (-3), accepted (true), move
(Queen-1 {Row-0 -> Row-3}).
...
TRACE
Move index (9), score (-3), accepted (true), move
(Queen-2 {Row-0 -> Row-3}).
...
TRACE
Move index (12), score (-4), accepted (true), move
(Queen-3 {Row-0 -> Row-3}).
DEBUG
LS step (0), time spent (6), score (-3), new best score
(-3), accepted/selected move count (12/12), picked move (Queen-1
{Row-0 -> Row-3}).
...
Be caus e the las t s olution can de grade (for e xample in Tabu Se arch), the Solver
re me mbe rs the be s t s olution it has e ncounte re d through the e ntire s e arch path.
Each time the curre nt s olution is be tte r than the las t be s t s olution, the curre nt
s olution is clone d and re fe re nce d as the ne w be s t s olution.
229
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
10.2.3. Accept or
An Acceptor is us e d (toge the r with a Forager) to active Tabu Se arch, Simulate d
Anne aling, Late Acce ptance , …​ For e ach move it che cks whe the r it is acce pte d or
not.
By changing a fe w line s of configuration, you can e as ily s witch from Tabu Se arch to
Simulate d Anne aling or Late Acce ptance and back.
You can imple me nt your own Acceptor, but the build-in acce ptors s hould s uffice for
mos t ne e ds . You can als o combine multiple acce ptors .
10.2.4. Forager
A Forager gathe rs all acce pte d move s and picks the move which is the ne xt s te p.
Normally it picks the acce pte d move with the highe s t s core . If s e ve ral acce pte d
move s have the highe s t s core , one is picke d randomly to bre ak the tie . Bre aking
tie s randomly le ads to be tte r re s ults .
230
CHAPT ER 10 . LO CAL SEARCH
No t e
It is pos s ible to dis able bre aking tie s randomly by e xplicitly s e tting
breakTieRandomly to false, but that’s almos t ne ve r a good ide a:
If an e arlie r move is be tte r than a late r move with the s ame s core , the
s core calculator s hould add an e xtra s ofte r s core le ve l to s core the
firs t move as s lightly be tte r. Don’t re ly on move s e le ction orde r to
e nforce that.
Random tie bre aking doe s not affe ct re producibility.
10.2.4.1. Accept ed Count Limit
Whe n the re are many pos s ible move s , it be come s ine fficie nt to e valuate all of
the m at e ve ry s te p. To e valuate only a random s ubs e t of all the move s , us e :
An acceptedCountLimit inte ge r, which s pe cifie s how many acce pte d move s
s hould be e valuate d during e ach s te p. By de fault, all acce pte d move s are
e valuate d at e ve ry s te p.
<forager>
<acceptedCountLimit>1000</acceptedCountLimit>
</forager>
Unlike the n que e ns proble m, re al world proble ms re quire the us e of
acceptedCountLimit. Start from an acceptedCountLimit that take s a s te p in le s s
the n 2 s e conds . Turn on INFO logging to s e e the s te p time s . Us e the Be nchmarke r
to twe ak the value .
Impo rt ant
With a low acceptedCountLimit (s o a fas t s te pping algorithm), it is
re comme nde d to avoid us ing selectionOrder SHUFFLED be caus e the
s huffling ge ne rate s a random numbe r for e ve ry e le me nt in the s e le ctor,
taking up a lot of time , but only a fe w e le me nts are actually s e le cte d.
10.2.4.2. Pick Early T ype
A forage r can pick a move e arly during a s te p, ignoring s ubs e que nt s e le cte d
move s . The re are 3 pick e arly type s for Local Se arch:
NEVER: A move is ne ve r picke d e arly: all acce pte d move s are e valuate d that
the s e le ction allows . This is the de fault.
<forager>
<pickEarlyType>NEVER</pickEarlyType>
</forager>
FIRST_BEST_SCORE_IMPROVING: Pick the firs t acce pte d move that improve s the
be s t s core . If none improve the be s t s core , it be have s e xactly like the
pickEarlyType NEVER.
231
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<forager>
<pickEarlyType>FIRST_BEST_SCORE_IMPROVING</pickEarlyType>
</forager>
FIRST_LAST_STEP_SCORE_IMPROVING: Pick the firs t acce pte d move that
improve s the las t s te p s core . If none improve the las t s te p s core , it be have s
e xactly like the pickEarlyType NEVER.
<forager>
<pickEarlyType>FIRST_LAST_STEP_SCORE_IMPROVING</pickEarlyType>
</forager>
10.3. HILL CLIMBING (SIMPLE LOCAL SEARCH)
10.3.1. Algorit hm Descript ion
Hill Climbing trie s all s e le cte d move s and the n take s the be s t move , which is the
move which le ads to the s olution with the highe s t s core . That be s t move is calle d
the s te p move . From that ne w s olution, it again trie s all s e le cte d move s and take s
the be s t move and continue s like that ite rative ly. If multiple s e le cte d move s tie for
the be s t move , one of the m is randomly chos e n as the be s t move .
Notice that once a que e n has move d, it can be move d again late r. This is a good
thing, be caus e in an NP-comple te proble m it’s impos s ible to pre dict what will be
the optimal final value for a planning variable .
232
CHAPT ER 10 . LO CAL SEARCH
10.3.2. St uck in Local Opt ima
Hill Climbing always take s improving move s . This may s e e m like a good thing, but
it’s not: Hill Climbing can e as ily ge t s tuck in a local optimum. This happe ns whe n it
re ache s a s olution for which all the move s de te riorate the s core . Eve n if it picks
one of thos e move s , the ne xt s te p might go back to the original s olution and which
cas e chas ing its own tail:
Improve me nts upon Hill Climbing (s uch as Tabu Se arch, Simulate d Anne aling and
Late Acce ptance ) addre s s the proble m of be ing s tuck in local optima. The re fore ,
it’s re comme nd to ne ve r us e Hill Climbing, unle s s you’re abs olute ly s ure the re are
no local optima in your planning proble m.
10.3.3. Conf igurat ion
Simple s t configuration:
<localSearch>
<localSearchType>HILL_CLIMBING</localSearchType>
</localSearch>
Advance d configuration:
<localSearch>
...
<acceptor>
<acceptorType>HILL_CLIMBING</acceptorType>
233
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
</acceptor>
<forager>
<acceptedCountLimit>1</acceptedCountLimit>
</forager>
</localSearch>
10.4. T ABU SEARCH
10.4.1. Algorit hm Descript ion
Tabu Se arch works like Hill Climbing, but it maintains a tabu lis t to avoid ge tting
s tuck in local optima. The tabu lis t holds re ce ntly us e d obje cts that are taboo to
us e for now. Move s that involve an obje ct in the tabu lis t, are not acce pte d. The
tabu lis t obje cts can be anything re late d to the move , s uch as the planning e ntity,
planning value , move , s olution, …​ He re ’s an e xample with e ntity tabu for 4 que e ns ,
s o the que e ns are put in the tabu lis t:
No t e
It’s calle d Tabu Se arch, not Taboo Se arch. The re is no s pe lling e rror.
Scie ntific pape r: Tabu Search - Part 1 and Part 2 by Fre d Glove r (1989 - 1990)
10.4.2. Conf igurat ion
234
CHAPT ER 10 . LO CAL SEARCH
Simple s t configuration:
<localSearch>
<localSearchType>TABU_SEARCH</localSearchType>
</localSearch>
Whe n Tabu Se arch take s s te ps it cre ate s one or more tabu’s . For a numbe r of
s te ps , it doe s not acce pt a move if that move bre aks tabu. That numbe r of s te ps is
the tabu s iz e . Advance d configuration:
<localSearch>
...
<acceptor>
<entityTabuSize>7</entityTabuSize>
</acceptor>
<forager>
<acceptedCountLimit>1000</acceptedCountLimit>
</forager>
</localSearch>
Impo rt ant
A Tabu Se arch acce ptor s hould be combine d with a high
acceptedCountLimit, s uch as 1000.
Planne r imple me nts s e ve ral tabu type s :
Planning entity tabu (re comme nde d) make s the planning e ntitie s of re ce nt s te ps
tabu. For e xample , for N que e ns it make s the re ce ntly move d que e ns tabu. It’s
re comme nde d to s tart with this tabu type .
<acceptor>
<entityTabuSize>7</entityTabuSize>
</acceptor>
To avoid hard coding the tabu s iz e , configure a tabu ratio, re lative to the
numbe r of e ntitie s , for e xample 2%:
<acceptor>
<entityTabuRatio>0.02</entityTabuRatio>
</acceptor>
Planning value tabu make s the planning value s of re ce nt s te ps tabu. For
e xample , for N que e ns it make s the re ce ntly move d to rows tabu.
<acceptor>
<valueTabuSize>7</valueTabuSize>
</acceptor>
To avoid hard coding the tabu s iz e , configure a tabu ratio, re lative to the
numbe r of value s , for e xample 2%:
235
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<acceptor>
<valueTabuRatio>0.02</valueTabuRatio>
</acceptor>
Move tabu make s re ce nt s te ps tabu. It doe s not acce pt a move e qual to one of
thos e s te ps .
<acceptor>
<moveTabuSize>7</moveTabuSize>
</acceptor>
Undo move tabu make s the undo move of re ce nt s te ps tabu.
<acceptor>
<undoMoveTabuSize>7</undoMoveTabuSize>
</acceptor>
Solution tabu make s re ce ntly vis ite d s olutions tabu. It doe s not acce pt a move
that le ads to one of thos e s olutions . It re quire s that the Solution imple me nts
equals() and hashCode() prope rly. If you can s pare the me mory, don’t be
che ap on the tabu s iz e .
<acceptor>
<solutionTabuSize>1000</solutionTabuSize>
</acceptor>
For non-trivial cas e s , s olution tabu is us ually us e le s s be caus e the s e arch s pace
s iz e make s it s tatis tically highly unlike ly to re ach the s ame s olution twice .
The re fore its us e is not re comme nde d, e xce pt for s mall datas e ts .
Some time s it’s us e ful to combine tabu type s :
<acceptor>
<entityTabuSize>7</entityTabuSize>
<valueTabuSize>3</valueTabuSize>
</acceptor>
If the tabu s iz e is too s mall, the s olve r can s till ge t s tuck in a local optimum. On the
othe r hand, if the tabu s iz e is too large , the s olve r can be ine fficie nt by bouncing of
the walls . Us e the Be nchmarke r to fine twe ak your configuration.
10.5. SIMULAT ED ANNEALING
10.5.1. Algorit hm Descript ion
Simulate d Anne aling e valuate s only a fe w move s pe r s te p, s o it s te ps quickly. In
the clas s ic imple me ntation, the firs t acce pte d move is the winning s te p. A move is
acce pte d if it doe s n’t de cre as e the s core or - in cas e it doe s de cre as e the s core it pas s e s a random che ck. The chance that a de cre as ing move pas s e s the random
che ck de cre as e s re lative to the s iz e of the s core de cre me nt and the time the
phas e has be e n running (which is re pre s e nte d as the te mpe rature ).
236
CHAPT ER 10 . LO CAL SEARCH
Simulate d Anne aling doe s not always pick the move with the highe s t s core , ne ithe r
doe s it e valuate many move s pe r s te p. At le as t at firs t. Ins te ad, it give s non
improving move s als o a chance to be picke d, de pe nding on its s core and the time
gradie nt of the Termination. In the e nd, it gradually turns into Hill Climbing, only
acce pting improving move s .
10.5.2. Conf igurat ion
Start with a simulatedAnnealingStartingTemperature s e t to the maximum
s core de lta a s ingle move can caus e . Us e the Be nchmarke r to twe ak the value .
Advance d configuration:
<localSearch>
...
<acceptor>
<simulatedAnnealingStartingTemperature>2hard/100soft</simulatedAnneal
ingStartingTemperature>
</acceptor>
<forager>
<acceptedCountLimit>1</acceptedCountLimit>
</forager>
</localSearch>
Simulate d Anne aling s hould us e a low acceptedCountLimit. The clas s ic algorithm
us e s an acceptedCountLimit of 1, but ofte n 4 pe rforms be tte r.
237
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Simulate d Anne aling can be combine d with a tabu acce ptor at the s ame time . That
give s Simulate d Anne aling s alte d with a bit of Tabu. Us e a lowe r tabu s iz e than in a
pure Tabu Se arch configuration.
<localSearch>
...
<acceptor>
<simulatedAnnealingStartingTemperature>2hard/100soft</simulatedAnneal
ingStartingTemperature>
<entityTabuSize>5</entityTabuSize>
</acceptor>
<forager>
<acceptedCountLimit>1</acceptedCountLimit>
</forager>
</localSearch>
10.6. LAT E ACCEPT ANCE
10.6.1. Algorit hm Descript ion
Late Acce ptance (als o known as Late Acce ptance Hill Climbing) als o e valuate s only
a fe w move s pe r s te p. A move is acce pte d if it doe s not de cre as e the s core , or if
it le ads to a s core that is at le as t the late s core (which is the winning s core of a
fixe d numbe r of s te ps ago).
Scie ntific pape r: The Late Acce ptance Hill-Climbing He uris tic by Edmund K. Burke ,
238
CHAPT ER 10 . LO CAL SEARCH
Yuri Bykov (2012)
10.6.2. Conf igurat ion
Simple s t configuration:
<localSearch>
<localSearchType>LATE_ACCEPTANCE</localSearchType>
</localSearch>
Late Acce ptance acce pts any move that has a s core which is highe r than the be s t
s core of a numbe r of s te ps ago. That numbe r of s te ps is the
lateAcceptanceSize. Advance d configuration:
<localSearch>
...
<acceptor>
<lateAcceptanceSize>400</lateAcceptanceSize>
</acceptor>
<forager>
<acceptedCountLimit>1</acceptedCountLimit>
</forager>
</localSearch>
Late Acce ptance s hould us e a low acceptedCountLimit.
Late Acce ptance can be combine d with a tabu acce ptor at the s ame time . That
give s Late Acce ptance s alte d with a bit of Tabu. Us e a lowe r tabu s iz e than in a
pure Tabu Se arch configuration.
<localSearch>
...
<acceptor>
<lateAcceptanceSize>400</lateAcceptanceSize>
<entityTabuSize>5</entityTabuSize>
</acceptor>
<forager>
<acceptedCountLimit>1</acceptedCountLimit>
</forager>
</localSearch>
10.7. ST EP COUNT ING HILL CLIMBING
10.7.1. Algorit hm Descript ion
Ste p Counting Hill Climbing als o e valuate s only a fe w move s pe r s te p. For a
numbe r of s te ps , it ke e ps the s te p s core as a thre s hold. A move is acce pte d if it
doe s not de cre as e the s core , or if it le ads to a s core that is at le as t the thre s hold
s core .
Scie ntific pape r: An initial s tudy of a nove l Ste p Counting Hill Climbing he uris tic
applie d to time tabling proble ms by Yuri Bykov, Sanja Pe trovic (2013)
10.7.2. Conf igurat ion
239
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
10.7.2. Conf igurat ion
Ste p Counting Hill Climbing acce pts any move that has a s core which is highe r than
a thre s hold s core . Eve ry numbe r of s te ps (s pe cifie d by
stepCountingHillClimbingSize), the thre s hold s core is s e t to the s te p s core .
<localSearch>
...
<acceptor>
<stepCountingHillClimbingSize>400</stepCountingHillClimbingSize>
</acceptor>
<forager>
<acceptedCountLimit>1</acceptedCountLimit>
</forager>
</localSearch>
Ste p Counting Hill Climbing s hould us e a low acceptedCountLimit.
Ste p Counting Hill Climbing can be combine d with a tabu acce ptor at the s ame time ,
s imilar as s hown in the Late Acce ptance s e ction.
10.8. ST RAT EGIC OSCILLAT ION
10.8.1. Algorit hm Descript ion
Strate gic Os cillation is an add-on, which works e s pe cially we ll with Tabu Se arch.
Ins te ad of picking the acce pte d move with the highe s t s core , it e mploys a diffe re nt
me chanis m: If the re ’s an improving move , it picks it. If the re ’s no improving move
howe ve r, it pre fe rs move s which improve a s ofte r s core le ve l, ove r move s which
bre ak a harde r s core le ve l le s s .
10.8.2. Conf igurat ion
Configure a finalistPodiumType, for e xample in a Tabu Se arch configuration:
<localSearch>
...
<acceptor>
<entityTabuSize>7</entityTabuSize>
</acceptor>
<forager>
<acceptedCountLimit>1000</acceptedCountLimit>
<finalistPodiumType>STRATEGIC_OSCILLATION</finalistPodiumType>
</forager>
</localSearch>
The following finalistPodiumTypesare s upporte d:
HIGHEST_SCORE (de fault): Pick the acce pte d move with the highe s t s core .
STRATEGIC_OSCILLATION: Alias for the de fault s trate gic os cillation variant.
STRATEGIC_OSCILLATION_BY_LEVEL: If the re is an acce pte d improving move ,
pick it. If no s uch move e xis ts , pre fe r an acce pte d move which improve s a
240
CHAPT ER 10 . LO CAL SEARCH
s ofte r s core le ve l ove r one that doe s n’t (e ve n if it has a be tte r harde r s core
le ve l). A move is improving if it’s be tte r than the las t comple te d s te p s core .
STRATEGIC_OSCILLATION_BY_LEVEL_ON_BEST_SCORE: Like
STRATEGIC_OSCILLATION_BY_LEVEL, but de fine improving as be tte r than the
be s t s core (ins te ad of the las t comple te d s te p s core ).
10.9. USING A CUST OM T ERMINAT ION, MOVESELECT OR,
ENT IT YSELECT OR, VALUESELECT OR OR ACCEPT OR
You can plug in a cus tom Termination, MoveSelector, EntitySelector,
ValueSelector or Acceptor by e xte nding the abs tract clas s and als o the re late d
*Config clas s .
For e xample , to us e a cus tom MoveSelector, e xte nd the AbstractMoveSelector
clas s , e xte nd the MoveSelectorConfig clas s and configure it in the s olve r
configuration.
No t e
It’s not pos s ible to inje ct a Termination, …​ ins tance dire ctly (to avoid
e xte nding a Config clas s too) be caus e :
A SolverFactory can build multiple Solver ins tance s , which e ach
re quire a dis tinct Termination, …​ ins tance .
A s olve r configuration ne e ds to be s e rializ able to and from XML. This
make s be nchmarking with PlannerBenchmark particularly e as y
be caus e you can configure diffe re nt Solver variants in XML.
A Config clas s is ofte n e as ie r and cle are r to configure . For e xample :
TerminationConfig trans late s minutesSpentLimit and
secondsSpentLimit into timeMillisSpentLimit.
If you build a be tte r imple me ntation that’s not domain s pe cific, cons ide r
contributing it back as a pull re que s t on github: we ’ll optimiz e it and take it along in
future re factorings .
241
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 11. EVOLUTIONARY ALGORITHMS
11.1. OVERVIEW
Evolutionary Algorithms work on a population of s olutions and e volve that
population.
11.2. EVOLUT IONARY ST RAT EGIES
This algorithm has not be e n imple me nte d ye t.
11.3. GENET IC ALGORIT HMS
This algorithm has not be e n imple me nte d ye t.
No t e
A good Ge ne tic Algorithms prototype in Planne r was writte n s ome time
ago, but it was n’t practical to me rge and s upport it at the time . The re s ults
of Ge ne tic Algorithms we re cons is te ntly and s e rious ly infe rior to all the
Local Se arch variants (e xce pt Hill Climbing) on all us e cas e s trie d.
Ne ve rthe le s s , a future ve rs ion of Planne r will add s upport for Ge ne tic
Algorithms , s o you can e as ily be nchmark Ge ne tic Algorithms on your us e
cas e too.
242
CHAPT ER 12. HYPERHEURIST ICS
CHAPTER 12. HYPERHEURISTICS
12.1. OVERVIEW
A hype rhe uris tic automate s the de cis ion which he uris tic(s ) to us e on a s pe cific
data s e t.
A future ve rs ion of Planne r will have native s upport for hype rhe uris tics . Me anwhile ,
it’s pre tty e as y to imple me nt it yours e lf: Bas e d on the s iz e or difficulty of a data
s e t (which is a crite rion), us e a diffe re nt Solve r configuration (or adjus t the de fault
configuration us ing the Solve r configuration API). The Be nchmarke r can he lp to
ide ntify s uch crite ria.
243
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 13. PARTITIONED SEARCH
13.1. OVERVIEW
For ve ry big datas e ts , it is s ome time s worthwhile to partition the datas e ts into
s malle r pie ce s .
Howe ve r, partitioning le ads to s uboptimal re s ults , e ve n if the pie ce s are s olve d
optimally:
A future ve rs ion of Planne r will have native s upport for s e ve ral forms of
partitioning. Me anwhile , you can imple me nt it yours e lf as s hown in the image
above . Us e an Solver to s olve e ach pie ce .
No t e
Not all us e cas e s can be partitione d. It only works on us e cas e s for which
the planning e ntitie s and value range s can be divide d into n pie ce s , s uch
that none of the cons traints cros s pie ce boundarie s .
244
CHAPT ER 14 . BENCHMARKING AND T WEAKING
CHAPTER 14. BENCHMARKING AND TWEAKING
14.1. FIND T HE BEST SOLVER CONFIGURAT ION
Planne r s upports s e ve ral optimiz ation algorithms , s o you’re probably wonde ring
which is the be s t one ? Although s ome optimiz ation algorithms ge ne rally pe rform
be tte r than othe rs , it re ally de pe nds on your proble m domain. Mos t s olve r phas e s
have parame te rs which can be twe ake d. Thos e parame te rs can influe nce the
re s ults a lot, e ve n though mos t s olve r phas e s work pre tty we ll out-of-the -box.
Luckily, Planne r include s a be nchmarke r, which allows you to play out diffe re nt
s olve r phas e s with diffe re nt s e ttings agains t e ach othe r in de ve lopme nt, s o you
can us e the be s t configuration for your planning proble m in production.
14.2. BENCHMARK CONFIGURAT ION
14.2.1. Add Dependency On opt aplanner-benchmark
The be nchmarke r is in a s e parate artifact calle d optaplanner-benchmark.
If you us e Mave n, add a de pe nde ncy in your pom.xml file :
<dependency>
<groupId>org.optaplanner</groupId>
<artifactId>optaplanner-benchmark</artifactId>
</dependency>
245
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
This is s imilar for Gradle , Ivy and Buildr. The ve rs ion mus t be e xactly the s ame as
the optaplanner-core ve rs ion us e d (which is automatically the cas e if you import
optaplanner-bom).
If you us e ANT, you’ve probably alre ady copie d the re quire d jars from the
download z ip’s binaries dire ctory.
14.2.2. Build And Run A PlannerBenchmark
Build a PlannerBenchmark ins tance with a PlannerBenchmarkFactory. Configure it
with a be nchmark configuration XML file , provide d as a clas s path re s ource :
PlannerBenchmarkFactory plannerBenchmarkFactory =
PlannerBenchmarkFactory.createFromXmlResource(
"org/optaplanner/examples/nqueens/benchmark/nqueensBenchmarkConfig.xm
l");
PlannerBenchmark plannerBenchmark =
plannerBenchmarkFactory.buildPlannerBenchmark();
plannerBenchmark.benchmark();
A be nchmark configuration file looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<plannerBenchmark>
<benchmarkDirectory>local/data/nqueens</benchmarkDirectory>
<inheritedSolverBenchmark>
<problemBenchmarks>
...
<inputSolutionFile>data/nqueens/unsolved/32queens.xml</inputSolutionF
ile>
<inputSolutionFile>data/nqueens/unsolved/64queens.xml</inputSolutionF
ile>
</problemBenchmarks>
<solver>
...<!-- Common solver configuration -->
</solver>
</inheritedSolverBenchmark>
<solverBenchmark>
<name>Tabu Search</name>
<solver>
...<!-- Tabu Search specific solver configuration -->
</solver>
</solverBenchmark>
<solverBenchmark>
<name>Simulated Annealing</name>
<solver>
...<!-- Simulated Annealing specific solver configuration -->
</solver>
</solverBenchmark>
246
CHAPT ER 14 . BENCHMARKING AND T WEAKING
<solverBenchmark>
<name>Late Acceptance</name>
<solver>
...<!-- Late Acceptance specific solver configuration -->
</solver>
</solverBenchmark>
</plannerBenchmark>
This PlannerBenchmark will try 3 configurations (Tabu Se arch, Simulate d Anne aling
and Late Acce ptance ) on 2 data s e ts (32que e ns and 64que e ns ), s o it will run 6
s olve rs .
Eve ry <solverBenchmark> e le me nt contains a s olve r configuration and one or
more <inputSolutionFile> e le me nts . It will run the s olve r configuration on e ach
of thos e uns olve d s olution file s . The e le me nt name is optional, be caus e it is
ge ne rate d if abs e nt. The inputSolutionFile is re ad by a SolutionFile IO (re lative
to the working dire ctory).
No t e
Us e a forward s las h (/) as the file s e parator (for e xample in the e le me nt
<inputSolutionFile>). That will work on any platform (including Windows ).
Do not us e backs las h (\) as the file s e parator: that bre aks portability
be caus e it doe s not work on Linux and Mac.
The be nchmark re port will be writte n in the dire ctory s pe cifie d the
<benchmarkDirectory> e le me nt (re lative to the working dire ctory).
No t e
It’s re comme nde d that the benchmarkDirectory is a dire ctory ignore d for
s ource control and not cle ane d by your build s ys te m. This way the
ge ne rate d file s are not bloating your s ource control and the y are n’t los t
whe n doing a build. Us ually that dire ctory is calle d local.
If an Exception or Error occurs in a s ingle be nchmark, the e ntire Be nchmarke r
will not fail-fas t (unlike e ve rything e ls e in Planne r). Ins te ad, the Be nchmarke r will
continue to run all othe r be nchmarks , write the be nchmark re port and the n fail (if
the re is at le as t 1 failing s ingle be nchmark). The failing be nchmarks will be cle arly
marke d as s uch in the be nchmark re port.
14.2.2.1. Inherit ed solver benchmark
To lowe r ve rbos ity, the common parts of multiple <solverBenchmark> e le me nts
are e xtracte d to the <inheritedSolverBenchmark> e le me nt. Eve ry prope rty can
s till be ove rwritte n pe r <solverBenchmark> e le me nt. Note that inhe rite d s olve r
phas e s s uch as <constructionHeuristic> or <localSearch> are not ove rwritte n
but ins te ad are adde d to the tail of the s olve r phas e s lis t.
14.2.3. Solut ionFileIO: Input And Out put Of Solut ion Files
247
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
14.2.3.1. Solut ionFileIO Int erf ace
The be nchmarke r ne e ds to be able to re ad the input file s to load a Solution. Als o,
it might ne e d to write the be s t Solution of e ach be nchmark to an output file . For
that it us e s a clas s that imple me nts the SolutionFileIO inte rface :
public interface SolutionFileIO {
String getInputFileExtension();
String getOutputFileExtension();
Solution read(File inputSolutionFile);
void write(Solution solution, File outputSolutionFile);
}
The SolutionFileIO inte rface is in the optaplanner-persistence-common jar
(which is a de pe nde ncy of the optaplanner-benchmark jar).
14.2.3.2. XSt reamSolut ionFileIO: T he Def ault Solut ionFileIO
By de fault, a be nchmarke r us e s a XStreamSolutionFileIO ins tance to re ad and
write s olutions .
It’s re quire d to te ll the be nchmarke r about your Solution clas s which is annotate d
with XStre am annotations :
<problemBenchmarks>
<xStreamAnnotatedClass>org.optaplanner.examples.nqueens.domain.NQueen
s</xStreamAnnotatedClass>
<inputSolutionFile>data/nqueens/unsolved/32queens.xml</inputSolutionF
ile>
...
</problemBenchmarks>
Thos e input file s ne e d to have be e n writte n with a XStreamSolutionFileIO
ins tance , not jus t any XStream ins tance , be caus e the XStreamSolutionFileIO
us e s a cus tomiz e d XStream ins tance .
Warning
XStre am (and XML in ge ne ral) is a ve ry ve rbos e format. Re ading or
writing ve ry large datas e ts in this format can caus e an
OutOfMemoryError and pe rformance de gradation.
14.2.3.3. Cust om Solut ionFileIO
248
CHAPT ER 14 . BENCHMARKING AND T WEAKING
Alte rnative ly, imple me nt your own SolutionFileIO imple me ntation and configure
it with the solutionFileIOClass e le me nt:
<problemBenchmarks>
<solutionFileIOClass>org.optaplanner.examples.machinereassignment.per
sistence.MachineReassignmentFileIO</solutionFileIOClass>
<inputSolutionFile>data/machinereassignment/import/model_a1_1.txt</in
putSolutionFile>
...
</problemBenchmarks>
It’s re comme nde d that output file s can be re ad as input file s , which als o implie s
that getInputFileExtension() and getOutputFileExtension() re turn the s ame
value .
Warning
A SolutionFileIO imple me ntation mus t be thre ad-s afe .
14.2.3.4. Reading An Input Solut ion From A Dat abase (Or Ot her
Reposit ory)
The be nchmark configuration curre ntly e xpe cts an <inputSolutionFile> e le me nt
for e ach datas e t. The re are 2 ways to de al with this if your datas e t is in a
databas e or anothe r type of re pos itory:
Extract the datas e ts from the databas e and s e rializ e the m to a local file (for
e xample as XML with XStreamSolutionFileIO). The n us e thos e file s an
<inputSolutionFile> e le me nts .
For e ach datas e t, cre ate a txt file that holds the unique ID of the datas e t. Write
a cus tom SolutionFile IO that re ads that ide ntifie r, conne cts to the databas e and
e xtract the proble m ide ntifie d by that id. Configure thos e txt file s as
<inputSolutionFile> e le me nts .
No t e
Local file s are always fas te r and don’t re quire a ne twork conne ction.
14.2.4. Warming Up T he Hot Spot Compiler
Without a warm up, the re s ults of the firs t (or firs t fe w) be nchmarks are not
re liable , be caus e the y will have los t CPU time on HotSpot JIT compilation (and
pos s ibly DRL compilation too).
To avoid that dis tortion, the be nchmarke r can run s ome of the be nchmarks for a
s pe cifie d amount of time , be fore running the re al be nchmarks . Ge ne rally, a warm
up of 30 s e conds s uffice s :
249
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<plannerBenchmark>
...
<warmUpSecondsSpentLimit>30</warmUpSecondsSpentLimit>
...
</plannerBenchmark>
No t e
The warm up time budge t doe s not include the time it take s to load the
datas e ts . With large datas e ts , this can caus e the warm up to run
cons ide rably longe r than s pe cifie d in the configuration.
14.2.5. Benchmark Blueprint : A Predef ined Conf igurat ion
To quickly configure and run a be nchmark for typical s olve r configs , us e a
solverBenchmarkBluePrint ins te ad of solverBenchmarks:
<?xml version="1.0" encoding="UTF-8"?>
<plannerBenchmark>
<benchmarkDirectory>local/data/nqueens</benchmarkDirectory>
<warmUpSecondsSpentLimit>30</warmUpSecondsSpentLimit>
<inheritedSolverBenchmark>
<problemBenchmarks>
<xStreamAnnotatedClass>org.optaplanner.examples.nqueens.domain.NQueen
s</xStreamAnnotatedClass>
<inputSolutionFile>data/nqueens/unsolved/32queens.xml</inputSolutionF
ile>
<inputSolutionFile>data/nqueens/unsolved/64queens.xml</inputSolutionF
ile>
<problemStatisticType>BEST_SCORE</problemStatisticType>
</problemBenchmarks>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<scoreDefinitionType>SIMPLE</scoreDefinitionType>
<scoreDrl>org/optaplanner/examples/nqueens/solver/nQueensScoreRules.d
rl</scoreDrl>
<initializingScoreTrend>ONLY_DOWN</initializingScoreTrend>
</scoreDirectorFactory>
<termination>
<minutesSpentLimit>1</minutesSpentLimit>
</termination>
</solver>
</inheritedSolverBenchmark>
<solverBenchmarkBluePrint>
250
CHAPT ER 14 . BENCHMARKING AND T WEAKING
<solverBenchmarkBluePrintType>EVERY_CONSTRUCTION_HEURISTIC_TYPE_WITH_
EVERY_LOCAL_SEARCH_TYPE</solverBenchmarkBluePrintType>
</solverBenchmarkBluePrint>
</plannerBenchmark>
The following SolverBenchmarkBluePrintTypesare s upporte d:
EVERY_CONSTRUCTION_HEURISTIC_TYPE: Run e ve ry Cons truction He uris tic type
(Firs t Fit, Firs t Fit De cre as ing, Che ape s t Ins e rtion, …​).
EVERY_LOCAL_SEARCH_TYPE: Run e ve ry Local Se arch type (Tabu Se arch, Late
Acce ptance , …​) with the de fault Cons truction He uris tic.
EVERY_CONSTRUCTION_HEURISTIC_TYPE_WITH_EVERY_LOCAL_SEARCH_TYPE: Run
e ve ry Cons truction He uris tic type with e ve ry Local Se arch type .
14.2.6. Writ e T he Out put Solut ion Of Benchmark Runs
The be s t s olution of e ach be nchmark run can be writte n in the
benchmarkDirectory. By de fault, this is dis able d, be caus e the file s are rare ly
us e d and cons ide re d bloat. Als o, on large datas e ts , writing the be s t s olution of
e ach s ingle be nchmark can take quite s ome time and me mory (caus ing an
OutOfMemoryError), e s pe cially in a ve rbos e format like XStre am XML.
To write thos e s olutions in the benchmarkDirectory, e nable
writeOutputSolutionEnabled:
<problemBenchmarks>
...
<writeOutputSolutionEnabled>true</writeOutputSolutionEnabled>
...
</problemBenchmarks>
14.2.7. Benchmark Logging
Be nchmark logging is configure d like the Solve r logging.
To s e parate the log me s s age s of e ach s ingle be nchmark run into a s e parate file ,
us e the MDC with ke y singleBenchmark.name in a s ifting appe nde r. For e xample
with Logback in logback.xml:
<appender name="fileAppender"
class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>singleBenchmark.name</key>
<defaultValue>app</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender.${singleBenchmark.name}"
class="...FileAppender">
<file>local/log/optaplannerBenchmark${singleBenchmark.name}.log</file>
251
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
...
</appender>
</sift>
</appender>
14.3. BENCHMARK REPORT
14.3.1. HT ML Report
Afte r running a be nchmark, an HTML re port will be writte n in the
benchmarkDirectory with the index.html file name . Ope n it in your brows e r. It
has a nice ove rvie w of your be nchmark including:
Summary s tatis tics : graphs and table s
Proble m s tatis tics pe r inputSolutionFile: graphs and CSV
Each s olve r configuration (ranke d): Handy to copy and pas te
Be nchmark information: s e ttings , hardware , …​
No t e
Graphs are ge ne rate d by the e xce lle nt JFre e Chart library.
The HTML re port will us e your de fault locale to format numbe rs . If you s hare the
be nchmark re port with pe ople from anothe r country, cons ide r ove rwriting the
locale accordingly:
<plannerBenchmark>
...
<benchmarkReport>
<locale>en_US</locale>
</benchmarkReport>
...
</plannerBenchmark>
14.3.2. Ranking T he Solvers
The be nchmark re port automatically ranks the s olve rs . The Solver with rank 0 is
calle d the favorite Solver: it pe rforms be s t ove rall, but it might not be the be s t on
e ve ry proble m. It’s re comme nde d to us e that favorite Solver in production.
Howe ve r, the re are diffe re nt ways of ranking the s olve rs . Configure it like this :
<plannerBenchmark>
...
<benchmarkReport>
<solverRankingType>TOTAL_SCORE</solverRankingType>
</benchmarkReport>
...
</plannerBenchmark>
252
CHAPT ER 14 . BENCHMARKING AND T WEAKING
The following solverRankingTypesare s upporte d:
TOTAL_SCORE (de fault): Maximiz e the ove rall s core , s o minimiz e the ove rall cos t
if all s olutions would be e xe cute d.
WORST_SCORE: Minimiz e the wors t cas e s ce nario.
TOTAL_RANKING: Maximiz e the ove rall ranking. Us e this if your datas e ts diffe r
gre atly in s iz e or difficulty, producing a diffe re nce in Score magnitude .
Solverswith at le as t one faile d s ingle be nchmark do not ge t a ranking.
Solverswith not fully initializ e d s olutions are ranke d wors e .
You can als o us e a cus tom ranking, by imple me nting a Comparator:
<benchmarkReport>
<solverRankingComparatorClass>...TotalScoreSolverRankingComparator</s
olverRankingComparatorClass>
</benchmarkReport>
Or by imple me nting a we ight factory:
<benchmarkReport>
<solverRankingWeightFactoryClass>...TotalRankSolverRankingWeightFacto
ry</solverRankingWeightFactoryClass>
</benchmarkReport>
14.4. SUMMARY ST AT IST ICS
14.4.1. Best Score Summary (Graph And T able)
Shows the be s t s core pe r inputSolutionFile for e ach s olve r configuration.
Us e ful for vis ualiz ing the be s t s olve r configuration.
Figure 14.1. Best Sco re Summary St at ist ic
253
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
14.4.2. Best Score Scalabilit y Summary (Graph)
Shows the be s t s core pe r proble m s cale for e ach s olve r configuration.
Us e ful for vis ualiz ing the s calability of e ach s olve r configuration.
No t e
The proble m s cale will re port 0 if any @ValueRangeProvider me thod
s ignature re turns Value Range (ins te ad of CountableValueRange or
Collection).
14.4.3. Best Score Dist ribut ion Summary (Graph)
Shows the be s t s core dis tribution pe r inputSolutionFile for e ach s olve r
configuration.
Us e ful for vis ualiz ing the re liability of e ach s olve r configuration.
Figure 14.2. Best Sco re Dist ribut io n Summary St at ist ic
254
CHAPT ER 14 . BENCHMARKING AND T WEAKING
Enable s tatis tical be nchmarking to us e this s ummary.
14.4.4. Winning Score Dif f erence Summary (Graph And T able)
Shows the winning s core diffe re nce pe r inputSolutionFile for e ach s olve r
configuration. The winning s core diffe re nce is the s core diffe re nce with the s core
of the winning s olve r configuration for that particular inputSolutionFile.
Us e ful for z ooming in on the re s ults of the be s t s core s ummary.
14.4.5. Worst Score Dif f erence Percent age (ROI) Summary
(Graph and T able)
Shows the re turn on inve s tme nt (ROI) pe r inputSolutionFile for e ach s olve r
configuration if you’d upgrade from the wors t s olve r configuration for that particular
inputSolutionFile.
Us e ful for vis ualiz ing the re turn on inve s tme nt (ROI) to de cis ion make rs .
14.4.6. Average Calculat ion Count Summary (Graph and T able)
Shows the s core calculation s pe e d: the ave rage calculation count pe r s e cond pe r
proble m s cale for e ach s olve r configuration.
Us e ful for comparing diffe re nt s core calculators and/or s core rule imple me ntations
(pre s uming that the s olve r configurations do not diffe r othe rwis e ). Als o us e ful to
me as ure the s calability cos t of an e xtra cons traint.
255
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
14.4.7. T ime Spent Summary (Graph And T able)
Shows the time s pe nt pe r inputSolutionFile for e ach s olve r configuration. This
is pointle s s if it’s be nchmarking agains t a fixe d time limit.
Us e ful for vis ualiz ing the pe rformance of cons truction he uris tics (pre s uming that
no othe r s olve r phas e s are configure d).
14.4.8. T ime Spent Scalabilit y Summary (Graph)
Shows the time s pe nt pe r proble m s cale for e ach s olve r configuration. This is
pointle s s if it’s be nchmarking agains t a fixe d time limit.
Us e ful for e xtrapolating the s calability of cons truction he uris tics (pre s uming that no
othe r s olve r phas e s are configure d).
14.4.9. Best Score Per T ime Spent Summary (Graph)
Shows the be s t s core pe r time s pe nt for e ach s olve r configuration. This is
pointle s s if it’s be nchmarking agains t a fixe d time limit.
Us e ful for vis ualiz ing trade -off be twe e n the be s t s core ve rs us the time s pe nt for
cons truction he uris tics (pre s uming that no othe r s olve r phas e s are configure d).
14.5. ST AT IST IC PER DAT ASET (GRAPH AND CSV)
14.5.1. Enable A Problem St at ist ic
The be nchmarke r s upports outputting proble m s tatis tics as graphs and CSV
(comma s e parate d value s ) file s to the benchmarkDirectory. To configure one , add
a problemStatisticType line :
<plannerBenchmark>
<benchmarkDirectory>local/data/nqueens/solved</benchmarkDirectory>
<inheritedSolverBenchmark>
<problemBenchmarks>
...
<problemStatisticType>BEST_SCORE</problemStatisticType>
<problemStatisticType>CALCULATE_COUNT_PER_SECOND</problemStatisticTyp
e>
</problemBenchmarks>
...
</inheritedSolverBenchmark>
...
</plannerBenchmark>
Multiple problemStatisticType e le me nts are allowe d.
256
CHAPT ER 14 . BENCHMARKING AND T WEAKING
No t e
The s e s tatis tic pe r datas e t can s low down the s olve r notice ably, which
affe cts the be nchmark re s ults . That’s why the y are optional and not
e nable d by de fault.
The non-optional s ummary s tatis tics cannot s low down the s olve r
notice ably.
The following type s are s upporte d:
14.5.2. Best Score Over T ime St at ist ic (Graph And CSV)
To s e e how the be s t s core e volve s ove r time , add:
<problemBenchmarks>
...
<problemStatisticType>BEST_SCORE</problemStatisticType>
</problemBenchmarks>
Figure 14.3. Best Sco re Over T ime St at ist ic
257
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
A time gradie nt bas e d algorithm (s uch as Simulate d Anne aling) will have a
diffe re nt s tatis tic if it’s run with a diffe re nt time limit configuration. That’s
be caus e this Simulate d Anne aling imple me ntation automatically
de te rmine s its ve locity bas e d on the amount of time that can be s pe nt. On
the othe r hand, for the Tabu Se arch and Late Anne aling, what you s e e is
what you’d ge t.
The be s t s core ove r time s tatis tic is ve ry us e ful to de te ct abnormalitie s , s uch as a
pote ntial s core trap which ge ts the s olve r te mporarily s tuck in a local optima.
14.5.3. St ep Score Over T ime St at ist ic (Graph And CSV)
To s e e how the s te p s core e volve s ove r time , add:
<problemBenchmarks>
...
<problemStatisticType>STEP_SCORE</problemStatisticType>
</problemBenchmarks>
Figure 14.4. St ep Sco re Over T ime St at ist ic
258
CHAPT ER 14 . BENCHMARKING AND T WEAKING
Compare the s te p s core s tatis tic with the be s t s core s tatis tic (e s pe cially on parts
for which the be s t s core flatline s ). If it hits a local optima, the s olve r s hould take
de te riorating s te ps to e s cape it. But it s houldn’t de te riorate too much e ithe r.
Warning
The s te p s core s tatis tic has be e n s e e n to s low down the s olve r
notice ably due to GC s tre s s , e s pe cially for fas t s te pping algorithms (s uch
as Simulate d Anne aling and Late Acce ptance ).
14.5.4. Calculat e Count Per Second St at ist ic (Graph And CSV)
To s e e how fas t the s core s are calculate d, add:
<problemBenchmarks>
...
<problemStatisticType>CALCULATE_COUNT_PER_SECOND</problemStatisticTyp
e>
</problemBenchmarks>
Figure 14.5. Calculat e Co unt Per Seco nd St at ist ic
259
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
The initial high calculate count is typical during s olution initializ ation: it’s far
e as ie r to calculate the s core of a s olution if only a handful planning
e ntitie s have be e n initializ e d, than whe n all the planning e ntitie s are
initializ e d.
Afte r thos e fe w s e conds of initializ ation, the calculate count is re lative ly
s table , apart from an occas ional s top-the -world garbage colle ctor
dis ruption.
14.5.5. Best Solut ion Mut at ion Over T ime St at ist ic (Graph And
CSV)
To s e e how much e ach ne w be s t s olution diffe rs from the previous best solution,
by counting the numbe r of planning variable s which have a diffe re nt value (not
including the variable s that have change d multiple time s but s till e nd up with the
s ame value ), add:
<problemBenchmarks>
...
<problemStatisticType>BEST_SOLUTION_MUTATION</problemStatisticType>
</problemBenchmarks>
Figure 14.6. Best So lut io n Mut at io n Over T ime St at ist ic
260
CHAPT ER 14 . BENCHMARKING AND T WEAKING
Us e Tabu Se arch - an algorithm that be have s like a human - to ge t an e s timation
on how difficult it would be for a human to improve the pre vious be s t s olution to
that ne w be s t s olution.
14.5.6. Move Count Per St ep St at ist ic (Graph And CSV)
To s e e how the s e le cte d and acce pte d move count pe r s te p e volve s ove r time ,
add:
<problemBenchmarks>
...
<problemStatisticType>MOVE_COUNT_PER_STEP</problemStatisticType>
</problemBenchmarks>
Figure 14.7. Mo ve Co unt Per St ep St at ist ic
261
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Warning
This s tatis tic has be e n s e e n to s low down the s olve r notice ably due to
GC s tre s s , e s pe cially for fas t s te pping algorithms (s uch as Simulate d
Anne aling and Late Acce ptance ).
14.5.7. Memory Use St at ist ic (Graph And CSV)
To s e e how much me mory is us e d, add:
<problemBenchmarks>
...
<problemStatisticType>MEMORY_USE</problemStatisticType>
</problemBenchmarks>
Figure 14.8. Memo ry Use St at ist ic
262
CHAPT ER 14 . BENCHMARKING AND T WEAKING
Warning
The me mory us e s tatis tic has be e n s e e n to affe ct the s olve r notice ably.
14.6. ST AT IST IC PER SINGLE BENCHMARK (GRAPH AND
CSV)
14.6.1. Enable A Single St at ist ic
A s ingle s tatis tic is a s tatics for 1 datas e t for 1 s olve r configuration. Unlike a
proble m s tatis tic, it doe s not aggre gate ove r s olve r configurations .
The be nchmarke r s upports outputting s ingle s tatis tics as graphs and CSV (comma
s e parate d value s ) file s to the benchmarkDirectory. To configure one , add a
singleStatisticType line :
<plannerBenchmark>
<benchmarkDirectory>local/data/nqueens/solved</benchmarkDirectory>
<inheritedSolverBenchmark>
<problemBenchmarks>
...
<problemStatisticType>...</problemStatisticType>
<singleStatisticType>PICKED_MOVE_TYPE_BEST_SCORE_DIFF</singleStatisti
cType>
263
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
</problemBenchmarks>
...
</inheritedSolverBenchmark>
...
</plannerBenchmark>
Multiple singleStatisticType e le me nts are allowe d.
No t e
The s e s tatis tic pe r s ingle be nchmark can s low down the s olve r notice ably,
which affe cts the be nchmark re s ults . That’s why the y are optional and not
e nable d by de fault.
The following type s are s upporte d:
14.6.2. Const raint Mat ch T ot al Best Score Over T ime St at ist ic
(Graph And CSV)
To s e e which cons traints are matche d in the be s t s core (and how much) ove r time ,
add:
<problemBenchmarks>
...
<singleStatisticType>CONSTRAINT_MATCH_TOTAL_BEST_SCORE</singleStatist
icType>
</problemBenchmarks>
Figure 14.9. Co nst raint Mat ch T o t al Best Sco re Dif f Over T ime St at ist ic
264
CHAPT ER 14 . BENCHMARKING AND T WEAKING
Re quire s the s core calculation to s upport cons traint matche s . Drools s core
calculation s upports cons traint matche s automatically, but incre me ntal Java s core
calculation re quire s more work.
Warning
The cons traint match total s tatis tics has be e n s e e n to affe ct the s olve r
notice ably.
14.6.3. Const raint Mat ch T ot al St ep Score Over T ime St at ist ic
(Graph And CSV)
To s e e which cons traints are matche d in the s te p s core (and how much) ove r time ,
add:
<problemBenchmarks>
...
<singleStatisticType>CONSTRAINT_MATCH_TOTAL_STEP_SCORE</singleStatist
icType>
</problemBenchmarks>
Figure 14.10 . Co nst raint Mat ch T o t al St ep Sco re Dif f Over T ime
St at ist ic
265
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Re quire s the s core calculation to s upport cons traint matche s . Drools s core
calculation s upports cons traint matche s automatically, but incre me ntal Java s core
calculation re quire s more work.
Warning
The cons traint match total s tatis tics has be e n s e e n to affe ct the s olve r
notice ably.
14.6.4. Picked Move T ype Best Score Dif f Over T ime St at ist ic
(Graph And CSV)
To s e e which move type s improve the be s t s core (and how much) ove r time , add:
<problemBenchmarks>
...
<singleStatisticType>PICKED_MOVE_TYPE_BEST_SCORE_DIFF</singleStatisti
cType>
</problemBenchmarks>
Figure 14.11. Picked Mo ve T ype Best Sco re Dif f Over T ime St at ist ic
266
CHAPT ER 14 . BENCHMARKING AND T WEAKING
14.6.5. Picked Move T ype St ep Score Dif f Over T ime St at ist ic
(Graph And CSV)
To s e e how much e ach winning s te p affe cts the s te p s core ove r time , add:
<problemBenchmarks>
...
<singleStatisticType>PICKED_MOVE_TYPE_STEP_SCORE_DIFF</singleStatisti
cType>
</problemBenchmarks>
Figure 14.12. Picked Mo ve T ype St ep Sco re Dif f Over T ime St at ist ic
267
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
14.7. ADVANCED BENCHMARKING
14.7.1. Benchmarking Perf ormance T ricks
14.7.1.1. Parallel Benchmarking On Mult iple T hreads
If you have multiple proce s s ors available on your compute r, you can run multiple
be nchmarks in paralle l on multiple thre ads to ge t your be nchmarks re s ults fas te r:
<plannerBenchmark>
...
<parallelBenchmarkCount>AUTO</parallelBenchmarkCount>
...
</plannerBenchmark>
Warning
Running too many be nchmarks in paralle l will affe ct the re s ults of
be nchmarks ne gative ly. Le ave s ome proce s s ors unus e d for garbage
colle ction and othe r proce s s e s .
We twe ak parallelBenchmarkCount AUTO to maximiz e the re liability and
e fficie ncy of the be nchmark re s ults .
268
CHAPT ER 14 . BENCHMARKING AND T WEAKING
The following parallelBenchmarkCountsare s upporte d:
1 (de fault): Run all be nchmarks s e que ntially.
AUTO: Le t Planne r de cide how many be nchmarks to run in paralle l. This formula
is bas e d on e xpe rie nce . It’s re comme nde d to pre fe r this ove r the othe r paralle l
e nabling options .
Static numbe r: The numbe r of be nchmarks to run in paralle l.
<parallelBenchmarkCount>2</parallelBenchmarkCount>
JavaScript formula: Formula for the numbe r of be nchmarks to run in paralle l. It
can us e the variable availableProcessorCount. For e xample :
<parallelBenchmarkCount>(availableProcessorCount / 2) +
1</parallelBenchmarkCount>
No t e
The parallelBenchmarkCount is always limite d to the numbe r of
available proce s s ors . If it’s highe r, it will be automatically de cre as e d.
No t e
If you have a compute r with s low or unre liable cooling, incre as ing the
parallelBenchmarkCount above 1 (e ve n on AUTO) may ove rhe at your
CPU.
The sensors command can he lp you de te ct if this is the cas e . It is
available in the package lm_sensors or lm-sensors in mos t Linux
dis tributions . The re are s e ve ral fre e ware tools available for Windows too.
No t e
In the future , we will als o s upport multi-JVM be nchmarking. This fe ature is
inde pe nde nt of multi-thre ade d s olving or multi-JVM s olving.
14.7.2. St at ist ical Benchmarking
To minimiz e the influe nce of your e nvironme nt and the Random Numbe r Ge ne rator
on the be nchmark re s ults , configure the numbe r of time s e ach s ingle be nchmark
run is re pe ate d. The re s ults of thos e runs are s tatis tically aggre gate d. Each
individual re s ult is als o vis ible in the re port, as we ll as plotte d in the be s t s core
dis tribution s ummary.
Jus t add a <subSingleCount> e le me nt to an <inheritedSolverBenchmark>
e le me nt or in a <solverBenchmark> e le me nt:
<?xml version="1.0" encoding="UTF-8"?>
<plannerBenchmark>
269
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
...
<inheritedSolverBenchmark>
...
<solver>
...
</solver>
<subSingleCount>10<subSingleCount>
</inheritedSolverBenchmark>
...
</plannerBenchmark>
The subSingleCount de faults to 1 (s o no s tatis tical be nchmarking).
No t e
If subSingleCount is highe r than 1, the be nchmarke r will automatically
us e a diffe re nt Random s e e d for e ve ry s ub s ingle run, without los ing
re producibility (for e ach s ub s ingle inde x) in
Environme ntMode REPRODUCIBLE and lowe r.
14.7.3. T emplat e Based Benchmarking And Mat rix Benchmarking
Matrix be nchmarking is be nchmarking a combination of value s e ts . For e xample :
be nchmark 4 entityTabuSize value s (5, 7, 11 and 13) combine d with 3
acceptedCountLimit value s (500, 1000 and 2000), re s ulting in 12 s olve r
configurations .
To re duce the ve rbos ity of s uch a be nchmark configuration, you can us e a
Fre e marke r te mplate for the be nchmark configuration ins te ad:
<plannerBenchmark>
...
<inheritedSolverBenchmark>
...
</inheritedSolverBenchmark>
<#list [5, 7, 11, 13] as entityTabuSize>
<#list [500, 1000, 2000] as acceptedCountLimit>
<solverBenchmark>
<name>entityTabuSize ${entityTabuSize} acceptedCountLimit
${acceptedCountLimit}</name>
<solver>
<localSearch>
<unionMoveSelector>
<changeMoveSelector/>
<swapMoveSelector/>
</unionMoveSelector>
<acceptor>
<entityTabuSize>${entityTabuSize}</entityTabuSize>
</acceptor>
<forager>
<acceptedCountLimit>${acceptedCountLimit}</acceptedCountLimit>
270
CHAPT ER 14 . BENCHMARKING AND T WEAKING
</forager>
</localSearch>
</solver>
</solverBenchmark>
</#list>
</#list>
</plannerBenchmark>
And build it with the clas s PlannerBenchmarkFactory:
PlannerBenchmarkFactory plannerBenchmarkFactory =
PlannerBenchmarkFactory.createFromFreemarkerXmlResource(
"org/optaplanner/examples/cloudbalancing/benchmark/cloudBalancingBenc
hmarkConfigTemplate.xml.ftl");
PlannerBenchmark plannerBenchmark =
plannerBenchmarkFactory.buildPlannerBenchmark();
14.7.4. Benchmark Report Aggregat ion
The BenchmarkAggregator take s 1 or more e xis ting be nchmarks and me rge s
the m into ne w be nchmark re port, without actually running the be nchmarks again.
This is us e ful to:
Re port on the impact of code change s : Run the s ame be nchmark configuration
be fore and afte r the code change s , the n aggre gate a re port.
271
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Re port on the impact of de pe nde ncy upgrade s : Run the s ame be nchmark
configuration be fore and afte r upgrading the de pe nde ncy, the n aggre gate a
re port.
Conde ns e a too ve rbos e re port: Se le ct only the inte re s ting s olve r be nchmarks
from the e xis ting re port. This e s pe cially us e ful on te mplate re ports to make the
graphs re adable .
Partially re run a be nchmark: Re run part of an e xis ting re port (for e xample only
the faile d or invalid s olve rs ), the n re cre ate the original inte nde d re port with the
ne w value s .
To us e it, provide a PlannerBenchmarkFactory to the
BenchmarkAggregatorFrame to dis play the GUI:
public static void main(String[] args) {
PlannerBenchmarkFactory plannerBenchmarkFactory =
PlannerBenchmarkFactory.createFromXmlResource(
"org/optaplanner/examples/nqueens/benchmark/nqueensBenchmarkConfig.xm
l");
BenchmarkAggregatorFrame.createAndDisplay(plannerBenchmarkFactory);
}
Warning
De s pite that it us e s a be nchmark configuration as input, it ignore s all
e le me nts of that configuration, e xce pt for the e le me nts
<benchmarkDirectory> and <benchmarkReport>.
In the GUI, s e le ct the inte re s ting be nchmarks and click the button to ge ne rate the
re port.
No t e
All the input re ports which are be ing me rge d s hould have be e n ge ne rate d
with the s ame Planne r ve rs ion (e xcluding hotfix diffe re nce s ) as the
BenchmarkAggregator. Us ing re ports from diffe re nt Planne r major or
minor ve rs ions are not guarante e d to s ucce e d and de live r corre ct
information, be caus e the be nchmark re port data s tructure ofte n change s .
272
CHAPT ER 15. REPEAT ED PLANNING
CHAPTER 15. REPEATED PLANNING
15.1. INT RODUCT ION T O REPEAT ED PLANNING
The world cons tantly change s . The proble m facts us e d to cre ate a s olution, might
change be fore or during the e xe cution of that s olution. The re are diffe re nt
s ituations (which can be combine d):
Unfore s e e n fact change s : For e xample : an e mploye e as s igne d to a s hift calls in
s ick, an airplane s che dule d to take off has a te chnical de lay, one of the
machine s or ve hicle s bre ak down, …​ Us e backup planning.
Impos s ible to as s ign all e ntitie s now: Le ave s ome unas s igne d. For e xample :
the re are 10 s hifts at the s ame time to as s ign but only 9 e mploye e s to handle
s hifts . Us e overconstrained planning.
Unknown long te rm future facts : For e xample : The hos pital admis s ions for the
ne xt 2 we e ks are re liable , but thos e for we e k 3 and 4 are le s s re liable and for
we e k 5 and be yond are not worth planning ye t. Us e continuous planning.
Cons tantly changing proble m facts : Us e real-time planning.
Waiting to s tart planning - to lowe r the ris k of proble m facts changing - us ually is n’t
a good way to de al with that. More CPU time me ans a be tte r planning s olution. An
incomple te plan is be tte r than no plan.
Luckily, the optimiz ation algorithms s upport planning a s olution that’s alre ady
(partially) planne d, known as re pe ate d planning.
15.2. BACKUP PLANNING
Backup planning is the te chnique of adding e xtra s core cons traints to cre ate s pace
in the planning for whe n things go wrong. That cre ate s a backup plan in the plan.
For e xample : try to as s ign an e mploye e as the s pare e mploye e (1 for e ve ry 10
s hifts at the s ame time ), ke e p 1 hos pital be d ope n in e ach de partme nt, …​
The n, whe n things go wrong (one of the e mploye e s calls in s ick), change the
proble m facts on the original s olution (de le te the s ick e mploye e le ave his /he r
s hifts unas s igne d) and jus t re s tart the planning, s tarting from that s olution, which
has a diffe re nt s core now. The cons truction he uris tics will fill in the ne wly cre ate d
gaps (probably with the s pare e mploye e ) and the me tahe uris tics will e ve n
improve it furthe r.
15.3. OVERCONST RAINED PLANNING
Whe n the re is no fe as ible s olution to as s ign all planning e ntitie s , it’s ofte n de s ire d
to as s ign as many e ntitie s as pos s ible without bre aking hard cons traints . This is
calle d ove rcons traine d planning.
273
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
To imple me nt this :
1. Add a additional s core le ve l (us ually a me dium le ve l be twe e n the hard and
s oft le ve l) by s witching Score De finition.
2. Make the planning variable nullable .
3. Add a s core cons traint on the ne w le ve l (s o us ually a me dium cons traint) to
pe naliz e the numbe r of unas s igne d e ntitie s (or a we ighte d s um of the m).
15.4. CONT INUOUS PLANNING (WINDOWED PLANNING)
Continuous planning is the te chnique of planning one or more upcoming planning
windows at the s ame time and re pe ating that proce s s monthly, we e kly, daily or
hourly. Be caus e time is infinite , the re are infinite future windows , s o planning all
future windows is impos s ible . Ins te ad, plan only a fixe d numbe r of upcoming
planning windows .
Pas t planning windows are immutable . The firs t upcoming planning window is
cons ide re d s table (unlike ly to change ), while late r upcoming planning windows are
cons ide re d draft (like ly to change during the ne xt planning e ffort). Dis tant future
planning windows are not planne d at all.
Pas t planning windows have only immovable planning e ntitie s : the planning e ntitie s
can no longe r be change d (the y are unable to move ), but s ome of the m are s till
ne e de d in the s core calculation, as the y might affe ct s ome of the s core cons traints
that apply on the upcoming planning e ntitie s . For e xample : whe n an e mploye e
274
CHAPT ER 15. REPEAT ED PLANNING
s hould not work more than 5 days in a row, he s houldn’t work today and tomorrow
if he worke d the pas t 4 days alre ady.
Some time s s ome planning e ntitie s are s e mi-immovable : the y can be change d, but
occur a ce rtain s core pe nalty if the y diffe r from the ir original place . For e xample :
avoid re s che duling hos pital be ds le s s than 2 days be fore the patie nt arrive s
(unle s s it’s re ally worth it), avoid changing the airplane gate during the 2 hours
be fore boarding (unle s s the re is no alte rnative ), …​
Notice the diffe re nce be twe e n the original planning of Nove mbe r 1th and the ne w
planning of Nove mbe r 5th: s ome proble m facts (F, H, I, J, K) change d, which re s ults
in unre late d planning e ntitie s (G) changing too.
15.4.1. Immovable Planning Ent it ies
To make s ome planning e ntitie s immovable , s imply add an e ntity
SelectionFilter that re turns true if an e ntity is movable and false if it is
immovable .
public class MovableShiftAssignmentSelectionFilter implements
SelectionFilter<ShiftAssignment> {
public boolean accept(ScoreDirector scoreDirector,
ShiftAssignment shiftAssignment) {
ShiftDate shiftDate =
shiftAssignment.getShift().getShiftDate();
NurseRoster nurseRoster = (NurseRoster)
scoreDirector.getWorkingSolution();
275
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
return
nurseRoster.getNurseRosterInfo().isInPlanningWindow(shiftDate);
}
}
And configure it like this :
@PlanningEntity(movableEntitySelectionFilter =
MovableShiftAssignmentSelectionFilter.class)
public class ShiftAssignment {
...
}
Warning
Cus tom MoveListFactory and MoveIteratorFactory imple me ntations
mus t make s ure that the y don’t move immovable e ntitie s .
15.4.2. Nonvolat ile Replanning t o minimize disrupt ion (Semimovable Planning Ent it ies)
Re planning an e xis ting plan can be ve ry dis ruptive on the plan. If the plan affe cts
humans (s uch as e mploye e s , drive rs , …​), ve ry dis ruptive change s are ofte n
unde s irable . In s uch cas e s , nonvolatile re planning he lps : the gain of changing a
plan mus t be highe r than the dis ruption it caus e s .
276
CHAPT ER 15. REPEAT ED PLANNING
For e xample , in the Machine Re as s ignme nt e xample , the e ntity has both the
planning variable machine and its original value originalMachine:
@PlanningEntity(...)
public class ProcessAssignment {
private MrProcess process;
private Machine originalMachine;
private Machine machine;
public Machine getOriginalMachine() {...}
@PlanningVariable(...)
public Machine getMachine() {...}
public boolean isMoved() {
return originalMachine != null && originalMachine != machine;
}
...
}
During planning, the planning variable machine change s . By comparing it with the
originalMachine , a change in plan can be pe naliz e d:
rule "processMoved"
when
ProcessAssignment(moved == true)
then
277
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
scoreHolder.addSoftConstraintMatch(kcontext, -1000);
end
The s oft pe nalty of -1000 me ans that a be tte r s olution is only acce pte d if it
improve s the s oft s core for at le as t 1000 points pe r variable change d (or if it
improve s the hard s core ).
15.5. REAL-T IME PLANNING
To do re al-time planning, firs t combine backup planning and continuous planning
with s hort planning windows to lowe r the burde n of re al-time planning. As time
pas s e s , the proble m its e lf change s :
In the e xample above , 3 cus tome rs are adde d at diffe re nt time s (07:56, 08:02
and 08:45), afte r the original cus tome r s e t finis he d s olving at 07:55 and in s ome
cas e s afte r the ve hicle s alre ady le ft. Planne r can handle s uch s ce nario’s with
ProblemFactChange (in combination with immovable planning e ntitie s ).
15.5.1. ProblemFact Change
While the Solver is s olving, an outs ide e ve nt might want to change one of the
proble m facts , for e xample an airplane is de laye d and ne e ds the runway at a late r
time . Do not change the proble m fact ins tance s us e d by the Solver while it is
s olving (from anothe r thre ad or e ve n in the s ame thre ad), as that will corrupt it.
Ins te ad, add a ProblemFactChange to the Solver which it will e xe cute in the
s olve r thre ad as s oon as pos s ible .
278
CHAPT ER 15. REPEAT ED PLANNING
public interface Solver {
...
boolean addProblemFactChange(ProblemFactChange
problemFactChange);
boolean isEveryProblemFactChangeProcessed();
...
}
public interface ProblemFactChange {
void doChange(ScoreDirector scoreDirector);
}
He re ’s an e xample :
public void deleteComputer(final CloudComputer computer) {
solver.addProblemFactChange(new ProblemFactChange() {
public void doChange(ScoreDirector scoreDirector) {
CloudBalance cloudBalance = (CloudBalance)
scoreDirector.getWorkingSolution();
// First remove the problem fact from all planning
entities that use it
for (CloudProcess process :
cloudBalance.getProcessList()) {
if (ObjectUtils.equals(process.getComputer(),
computer)) {
scoreDirector.beforeVariableChanged(process,
"computer");
process.setComputer(null);
scoreDirector.afterVariableChanged(process,
"computer");
}
}
// A SolutionCloner does not clone problem fact lists
(such as computerList)
// Shallow clone the computerList so only
workingSolution is affected, not bestSolution or guiSolution
cloudBalance.setComputerList(new
ArrayList<CloudComputer>(cloudBalance.getComputerList()));
// Next remove it the problem fact itself
for (Iterator<CloudComputer> it =
cloudBalance.getComputerList().iterator(); it.hasNext(); ) {
CloudComputer workingComputer = it.next();
if (ObjectUtils.equals(workingComputer,
computer)) {
scoreDirector.beforeProblemFactRemoved(workingComputer);
it.remove(); // remove from list
279
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
scoreDirector.afterProblemFactRemoved(workingComputer);
break;
}
}
}
});
}
Warning
Any change on the proble m facts or planning e ntitie s in a
ProblemFactChange mus t be told to the ScoreDirector.
Impo rt ant
To write a ProblemFactChange corre ctly, it’s important to unde rs tand the
be haviour of a planning clone :
Any change in a ProblemFactChange mus t be done on the Solution
ins tance of scoreDirector.getWorkingSolution(). The
workingSolution is a planning clone of the
BestSolutionChangedEvent's bestSolution. So the workingSolution
in the Solver is ne ve r the s ame ins tance as the Solution in the re s t
of your application.
A planning clone als o clone s the planning e ntitie s and planning e ntity
colle ctions . So any change on the planning e ntitie s mus t happe n on the
ins tance s hold by scoreDirector.getWorkingSolution().
A planning clone doe s not clone the proble m facts , nor the proble m fact
colle ctions . The re fore the workingSolution and the bestSolution
s hare the s ame proble m fact ins tance s and the s ame proble m fact lis t
ins tance s .
Any proble m fact or proble m fact lis t change d by a ProblemFactChange
mus t be proble m clone d firs t (which can imply re routing re fe re nce s in
othe r proble m facts and planning e ntitie s ). Othe rwis e , if the
workingSolution and bestSolution are us e d in diffe re nt thre ads (for
e xample a s olve r thre ad and a GUI e ve nt thre ad), a race condition can
occur.
No t e
Many type s of change s can le ave a planning e ntity uninitializ e d, re s ulting
in a partially initializ e d s olution. That’s fine , as long as the firs t s olve r
phas e can handle it. All cons truction he uris tics s olve r phas e s can handle
that, s o it’s re comme nde d to configure s uch a s olve r phas e as the firs t
phas e .
In e s s e nce , the Solver s tops , runs the ProblemFactChange and re s tarts . This is a
280
CHAPT ER 15. REPEAT ED PLANNING
warm start be caus e its initial s olution is the adjus te d be s t s olution of the pre vious
run. Each s olve r phas e runs again. This implie s the cons truction he uris tic runs
again, but be caus e little or no planning variable s are uninitializ e d (unle s s you have
a nullable planning variable ), it finis he s much quicke r than in a cold s tart.
Each configure d Termination re s e ts (both in s olve r and phas e configuration), but a
pre vious call to terminateEarly() is not undone . Normally howe ve r, you won’t
configure any Termination (e xce pt in dae mon mode ), jus t call
Solver.terminateEarly() whe n the re s ults are ne e de d. Alte rnative ly, do
configure a Termination and us e the dae mon mode in combination with
BestSolutionChangedEvent as de s cribe d be low.
15.5.2. Daemon: solve() Does Not Ret urn
In re al-time planning, it’s ofte n us e ful to have a s olve r thre ad wait whe n it runs out
of work, and imme diate ly re s ume s olving a proble m once ne w proble m fact
change s are adde d. Putting the Solver in dae mon mode has the s e e ffe cts :
If the Solver's Termination te rminate s , it doe s not re turn from solve() but
blocks its thre ad ins te ad (which fre e s up CPU powe r).
Exce pt for terminateEarly(), which doe s make it re turn from solve(),
fre e ing up s ys te m re s ource s and allowing an application to s hutdown
grace fully.
If a Solver s tarts with an e mpty planning e ntity colle ction, it waits in the
blocke d s tate imme diate ly.
If a ProblemFactChange is adde d, it goe s into the running s tate , applie s the
ProblemFactChange and runs the Solver again.
To configure the dae mon mode :
<solver>
<daemon>true</daemon>
...
</solver>
Warning
Don’t forge t to call Solver.terminateEarly() whe n your application
ne e ds to s hutdown to avoid killing the s olve r thre ad unnaturally.
Subs cribe to the BestSolutionChangedEvent to proce s s ne w be s t s olutions found
by the s olve r thre ad. A BestSolutionChangedEvent doe s n’t guarante e that e ve ry
ProblemFactChange has be e n proce s s e d alre ady, nor that the s olution is
initializ e d and fe as ible . To ignore BestSolutionChangedEventswith s uch invalid
s olutions , do this :
public void
bestSolutionChanged(BestSolutionChangedEvent<CloudBalance> event) {
// Ignore invalid solutions
if (event.isEveryProblemFactChangeProcessed()
281
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
&& event.isNewBestSolutionInitialized()
&&
event.getNewBestSolution().getScore().isFeasible()) {
...
}
}
282
CHAPT ER 16 . INT EGRAT IO N
CHAPTER 16. INTEGRATION
16.1. OVERVIEW
Planne r’s input and output data (the planning proble m and the be s t s olution) are
plain old JavaBe ans (POJO’s ), s o inte gration with othe r Java te chnologie s is
s traightforward. For e xample :
To re ad a planning proble m from the databas e (and s tore the be s t s olution in it),
annotate the domain POJO’s with JPA annotations .
To re ad a planning proble m from an XML file (and s tore the be s t s olution in it),
annotate the domain POJO’s with XStre am or JAXB annotations .
To e xpos e the Solve r as a REST Se rvice that re ads the planning proble m and
re s ponds with the be s t s olution, annotate the domain POJO’s with XStre am or
JAXB annotations and hook the Solver in Came l or RESTEas y.
16.2. PERSIST ENT ST ORAGE
16.2.1. Dat abase: JPA and Hibernat e
Enrich the domain POJO’s (s olution, e ntitie s and proble m facts ) with JPA annotations
to s tore the m in a databas e .
283
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
No t e
Do not confus e JPA’s @Entity annotation with Planne r’s @PlanningEntity
annotation. The y can appe ar both on the s ame clas s :
@PlanningEntity // OptaPlanner annotation
@Entity // JPA annotation
public class Talk {...}
Add a de pe nde ncy to the optaplanner-persistence-jpa jar to take advantage of
the s e e xtra inte gration fe ature s :
16.2.1.1. JPA and Hibernat e: Persist ing a Score
Whe n a Score is pe rs is te d into a re lational databas e , JPA and Hibe rnate will de fault
to Java s e rializ ing it to a BLOB column. This has s e ve ral dis advantage s :
The Java s e rializ ation format of Score clas s e s is curre ntly not backwards
compatible . Upgrading to a ne we r Planne r ve rs ion can bre ak re ading an e xis ting
databas e .
The s core is not e as ily re adable for a que ry e xe cute d in the databas e cons ole .
This is annoying during de ve lopme nt.
The s core cannot be us e d in a SQL or JPA-QL que ry to filte r the re s ults : for
e xample to que ry all infe as ible s che dule s .
To avoid the s e is s ue s , configure it to us e 2 INTEGER columns ins te ad by us ing the
appropriate *ScoreHibernateType for your Score type , for e xample for a
HardSoftScore:
@PlanningSolution
@Entity
@TypeDef(defaultForType = HardSoftScore.class, typeClass =
HardSoftScoreHibernateType.class)
public class CloudBalance implements Solution<HardSoftScore> {
@Columns(columns = {@Column(name = "hardScore"), @Column(name =
"softScore")})
protected HardSoftScore score;
...
}
No t e
Configure the s ame numbe r of @Column annotations as the numbe r of
s core le ve ls in the s core , othe rwis e Hibe rnate will fail fas t be caus e a
prope rty mapping has the wrong numbe r of columns .
In this cas e , the DDL will look like this :
284
CHAPT ER 16 . INT EGRAT IO N
CREATE TABLE CloudBalance(
...
hardScore INTEGER,
softScore INTEGER
);
Whe n us ing a BigDecimal bas e d Score, s pe cify the pre cis ion and s cale of the
columns to avoid s ile nt rounding:
@PlanningSolution
@Entity
@TypeDef(defaultForType = HardSoftBigDecimalScore.class, typeClass =
HardSoftBigDecimalScoreHibernateType.class)
public class CloudBalance implements
Solution<HardSoftBigDecimalScore> {
@Columns(columns = {
@Column(name = "hardScore", precision = 10, scale = 5),
@Column(name = "softScore", precision = 10, scale = 5)})
protected HardSoftBigDecimalScore score;
...
}
Whe n us ing any type of be ndable Score, s pe cify the hard and s oft le ve l s iz e s as
parame te rs :
@PlanningSolution
@Entity
@TypeDef(defaultForType = BendableScore.class, typeClass =
BendableScoreHibernateType.class, parameters = {
@Parameter(name = "hardLevelsSize", value = "3"),
@Parameter(name = "softLevelsSize", value = "2")})
public class Schedule implements Solution<BendableScore> {
@Columns(columns = {
@Column(name = "hard0Score"),
@Column(name = "hard1Score"),
@Column(name = "hard2Score"),
@Column(name = "soft0Score"),
@Column(name = "soft1Score")})
protected BendableScore score;
...
}
All this s upport is Hibe rnate s pe cific be caus e curre ntly JPA 2.1’s conve rte rs do not
s upport conve rting to multiple columns .
16.2.1.2. JPA and Hibernat e: Planning Cloning
In JPA and Hibe rnate , the re is us ually a @ManyToOne re lations hip from mos t
proble m fact clas s e s to the planning s olution clas s . The re fore , the proble m fact
clas s e s re fe re nce the planning s olution clas s , which implie s that whe n the s olution
is planning clone d, the y ne e d to be clone d too. Us e an @DeepPlanningClone on
285
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
e ach s uch proble m fact clas s to e nforce that:
@PlanningSolution // OptaPlanner annotation
@Entity // JPA annotation
public class Conference {
@OneToMany(mappedBy="conference")
private List<Room> roomList;
...
}
@DeepPlanningClone // OptaPlanner annotation: Force the default
planning cloner to planning clone this class too
@Entity // JPA annotation
public class Room {
@ManyToOne
private Conference conference; // Because of this reference, this
problem fact needs to be planning cloned too
}
Ne gle cting to do this can le ad to pe rs is ting duplicate s olutions , JPA e xce ptions or
othe r s ide e ffe cts .
16.2.2. XML or JSON: XSt ream
Enrich the domain POJO’s (s olution, e ntitie s and proble m facts ) with XStre am
annotations to s e rializ e the m to/from XML or JSON.
Add a de pe nde ncy to the optaplanner-persistence-xstream jar to take
advantage of the s e e xtra inte gration fe ature s :
16.2.2.1. XSt ream: Marshalling a Score
Whe n a Score is mars halle d to XML or JSON by the de fault XStre am configuration,
it’s ve rbos e and ugly. To fix that, configure the XStreamScoreConverter and
provide the ScoreDefinition as a parame te r:
@PlanningSolution
@XStreamAlias("CloudBalance")
public class CloudBalance implements Solution<HardSoftScore> {
@XStreamConverter(value = XStreamScoreConverter.class, types =
{HardSoftScoreDefinition.class})
private HardSoftScore score;
...
}
For e xample , this will ge ne rate pre tty XML:
286
CHAPT ER 16 . INT EGRAT IO N
<CloudBalance>
...
<score>0hard/-200soft</score>
</CloudBalance>
To us e this for any type of be ndable s core , als o provide 2 int parame te rs to
de fine hardLevelsSize and softLevelsSize:
@PlanningSolution
@XStreamAlias("Schedule")
public class Schedule implements Solution<BendableScore> {
@XStreamConverter(value = XStreamScoreConverter.class, types =
{BendableScoreDefinition.class}, ints = {2, 3})
private BendableScore score;
...
}
For e xample , this will ge ne rate :
<Schedule>
...
<score>0/0/-100/-20/-3</score>
</Schedule>
16.2.3. XML or JSON: JAXB
Enrich the domain POJO’s (s olution, e ntitie s and proble m facts ) with JAXB
annotations to s e rializ e the m to/from XML or JSON.
16.3. SOA AND ESB
16.3.1. Camel and Karaf
Came l is an e nte rpris e inte gration frame work which include s s upport for Planne r
(s tarting from Came l 2.13). It can e xpos e a us e cas e as a REST s e rvice , a SOAP
s e rvice , a JMS s e rvice , …​
Re ad the docume ntation for the came l-optaplanne r compone nt. That compone nt
works in Karaf too.
16.4. OT HER ENVIRONMENT S
16.4.1. JBoss Modules, WildFly and JBoss EAP
To de ploy an Planne r we b application on WildFly, s imply include the optaplanne r
de pe nde ncy jars in the war file ’s WEB-INF/lib dire ctory (jus t like any othe r
de pe nde ncy) as s hown in the optaplanner-webexamples-*.war. Howe ve r, in this
approach the war file can e as ily grow to s e ve ral MB in s iz e , which is fine for a one -
287
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
time de ployme nt, but too he avywe ight for fre que nt re de ployme nts (e s pe cially
ove r a s low ne twork conne ction).
The re me dy is to us e de live r the optaplanne r jars in a JBos s module to WildFly and
cre ate a s kinny war. Le t’s cre ate an module calle d org.optaplanner:
1. Navigate to the dire ctory
${WILDFLY_HOME}/modules/system/layers/base/. This dire ctory contains
the JBos s module s of WildFly. Cre ate dire ctory s tructure
org/optaplanner/main for our ne w module .
a. Copy optaplanner-core-${version}.jar and all its dire ct and
trans itive de pe nde ncy jars into that ne w dire ctory. Us e "mvn
de pe nde ncy:tre e " on e ach optaplanne r artifact to dis cove r all
de pe nde ncie s .
b. Cre ate the file module.xml in that ne w dire ctory. Give it this conte nt:
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3"
name="org.optaplanner">
<resources>
...
<resource-root path="kie-api-${version}.jar"/>
...
<resource-root path="optaplanner-core${version}.jar"/>
...
<resource-root path="."/>
</resources>
<dependencies>
<module name="javaee.api"/>
</dependencies>
</module>
2. Navigate to the de ploye d war file .
a. Re move optaplanner-core-${version}.jar and all its dire ct and
trans itive de pe nde ncy jars from the WEB-INF/lib dire ctory in the
war file .
b. Cre ate the file jboss-deployment-structure.xml in the WEBINF/lib dire ctory. Give it this conte nt:
<?xml version="1.0" encoding="UTF-8" ?>
<jboss-deployment-structure>
<deployment>
<dependencies>
<module name="org.optaplanner" export="true"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
288
CHAPT ER 16 . INT EGRAT IO N
Be caus e of JBos s Module s ' ClassLoader magic, you’ll like ly ne e d to provide the
ClassLoader of your clas s e s during the Solve rFactory cre ation, s o it can find the
clas s path re s ource s (s uch as the s olve r config, s core DRL’s and domain clas s e s )
in your jars .
16.4.2. OSGi
The optaplanner-core jar include s OSGi me tadata in its MANIFEST.MF file to
function prope rly in an OSGi e nvironme nt too. Furthe rmore , the mave n artifact
drools-karaf-features (which will be re name d to kie-karaf-features) contains
a features.xml file that s upports the OSGi-fe ature optaplanner-engine.
Be caus e of the OSGi’s ClassLoader magic, you’ll like ly ne e d to provide the
ClassLoader of your clas s e s during the Solve rFactory cre ation, s o it can find the
clas s path re s ource s (s uch as the s olve r config, s core DRL’s and domain clas s e s )
in your jars .
No t e
Planne r doe s not re quire OSGi. It works pe rfe ctly fine in a normal Java
e nvironme nt too.
16.4.3. Android
Android is not a comple te JVM (be caus e s ome JDK librarie s are mis s ing), but
Planne r works on Android with e as y Java or incre me ntal Java s core calculation. The
Drools rule e ngine doe s not work on Android ye t, s o Drools s core calculation
doe s n’t work on Android and its de pe nde ncie s ne e d to be e xclude d.
Wo rkaro und t o use Planner o n Andro id:
1. Add a de pe nde ncy to the build.gradle file in your Android proje ct to
e xclude org.drools and xmlpull de pe nde ncie s :
dependencies {
...
compile('org.optaplanner:optaplanner-core:...') {
exclude group: 'xmlpull'
exclude group: 'org.drools'
}
...
}
16.5. INT EGRAT ION WIT H HUMAN PLANNERS (POLIT ICS)
A good Planne r imple me ntation be ats any good human planne r for non-trivial
datas e ts . Many human planne rs fail to acce pt this , ofte n be caus e the y fe e l
thre ate ne d by an automate d s ys te m.
But de s pite that, both can be ne fit if the human planne r acts as s upe rvis or to
Planne r:
289
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
The human planne r de fine s and validate s the s core function.
Some e xample s e xpos e a Parametrization obje ct, which de fine s the
we ight for e ach s core cons traint. The human planne r can the n twe ak thos e
we ights at runtime .
Whe n the bus ine s s change s , the s core function ofte n ne e ds to change too.
The human planne r can notify the de ve lope rs to add, change or re move
s core cons traints .
The human planne r is always in control of Planne r.
As s hown in the cours e s che duling e xample , the human planne r can lock 1 or
more planning variable s to a s pe cific planning value and make thos e
immovable . Be caus e the y are immovable , Planne r doe s not change the m: it
optimiz e s the planning around the e nforce me nts made by the human. If the
human planne r locks all planning variable s , he /s he s ide line s Planne r
comple te ly.
In a prototype imple me ntation, the human planne r might us e this
occas ionally. But as the imple me ntation mature s , it mus t be come obs ole te .
But do ke e p the fe ature alive : as a re as s urance for the humans . Or in cas e
that one day the bus ine s s change s dramatically be fore the s core cons traints
can be adjus te d.
The re fore , it’s ofte n a good ide a to involve the human planne r in your proje ct.
290
CHAPT ER 17. DESIGN PAT T ERNS
CHAPTER 17. DESIGN PATTERNS
17.1. DESIGN PAT T ERNS INT RODUCT ION
The s e de s ign patte rns lis t and s olve common de s ign challe nge s .
17.2. ASSIGNING T IME T O PLANNING ENT IT IES
De aling with time and date s in planning proble ms may be proble matic be caus e it is
de pe nde nt on the ne e ds of your us e cas e .
The re are s e ve ral re pre s e ntations of time s tamps , date s , durations and pe riods in
Java. Choos e the right re pre s e ntation type for your us e cas e :
java.util.Date (de pre cate d): a s low, e rror-prone way to re pre s e nt
time s tamps . Do not us e .
javax.time.LocalDateTime, LocalDate, DayOfWeek, Duration, Period, …​: an
accurate way to re pre s e nt and calculate with time s tamps , date s , …​
Supports time z one s and DST (Daylight Saving Time ).
Re quire s Java 8 or highe r.
On Java 7 us e its backport calle d ThreeTen Backport ins te ad.
On Java 6 or lowe r, us e its pre de ce s s or calle d Joda Time ins te ad.
int or long: Cache s a time s tamp as a s implifie d numbe r of coars e -graine d
time units (s uch as minute s ) from the s tart of the global planning time window
or the e poch.
For e xample : a LocalDateTime of 1-JAN 08:00:00 be come s an int of 400
minute s . Similarly 1-JAN 09:00:00 be come s 460 minute s .
It ofte n re pre s e nts an e xtra fie ld in a clas s , alongs ide the LocalDateTime
fie ld from which it was calculate d. The LocalDateTime is us e d for us e r
vis ualiz ation, but the int is us e d in the s core cons traints .
It is fas te r in calculations , which is e s pe cially us e ful in the Time Grain patte rn.
Do not us e if time z one s or DST affe ct the s core cons traints .
The re are als o s e ve ral de s igns for as s igning a planning e ntity to a s tarting time
(or date ):
The s tarting time is fixe d be fore hand. It is not a planning variable (in s uch
s olve r).
For e xample , in the hos pital be d planning e xample , the arrival day of e ach
patie nt is fixe d be fore hand.
This is common in multi s tage planning, whe n the s tarting time has be e n
de cide d alre ady in an e arlie r planning s tage .
The s tarting time is not fixe d, it is a planning variable (ge nuine or s hadow).
If all planning e ntitie s have the s ame duration, us e the Time s lot patte rn.
291
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
For e xample in cours e s che duling, all le cture s take 1 hour. The re fore ,
e ach time s lot is 1 hour.
If the duration diffe rs and time is rounde d to a s pe cifc time granularity (for
e xample 5 minute s ) us e the Time Grain patte rn.
For e xample in me e ting s che duling, all me e tings s tart at 15 minute
inte rvals . All me e tings take 15, 30, 45, 60, 90 or 120 minute s .
If the duration diffe rs and one tas k s tarts imme diate ly afte r the pre vious
tas k (as s igne d to the s ame e xe cutor) finis he s , us e the Chaine d Through
Time patte rn.
For e xample in time windowe d ve hicle routing, e ach ve hicle de parts
imme diate ly to the ne xt cus tome r whe n the de live ry for the pre vious
cus tome r finis he s .
Choos e the right patte rn de pe nding on the us e cas e :
17.2.1. T imeslot Pat t ern: Assign t o a Fixed-Lengt h T imeslot
If all planning e ntitie s have the s ame duration (or can be inflate d to the s ame
duration), the Time s lot patte rn is us e ful. The planning e ntitie s are as s igne d to a
time s lot rathe r than time . For e xample in cours e time tabling, all le cture s take 1
hour.
The time s lots can s tart at any time . For e xample , the time s lots s tart at 8:00, 9:00,
10:15 (afte r a 15-minute bre ak), 11:15, …​ The y can e ve n ove rlap, but that is
unus ual.
292
CHAPT ER 17. DESIGN PAT T ERNS
It is als o us able if all planning e ntitie s can be inflate d to the s ame duration. For
e xample in e xam time tabling, s ome e xams take 90 minute s and othe rs 120
minute s , but all time s lots are 120 minute s . Whe n an e xam of 90 minute s is
as s igne d to a time s lot, for the re maining 30 minute s , its s e ats are occupie d too
and cannot be us e d by anothe r e xam.
Us ually the re is a s e cond planning variable , for e xample the room. In cours e
time tabling, two le cture s are in conflict if the y s hare the s ame room at the s ame
time s lot. Howe ve r, in e xam time tabling, that is allowe d, if the re is e nough s e ating
capacity in the room (although mixe d e xam durations in the s ame room do inflict a
s oft s core pe nalty).
17.2.2. T imeGrain Pat t ern: Assign t o a St art ing T imeGrain
As s igning humans to s tart a me e ting at 4 s e conds afte r 9 o’clock is pointle s s
be caus e mos t human activitie s have a time granularity of 5 minute s or 15 minute s .
The re fore it is not ne ce s s ary to allow a planning e ntity to be as s igne d s ubs e cond,
s e cond or e ve n 1 minute accuracy. The 5 minute or 15 minute s accuracy s uffice s .
The Time Grain patte rn mode ls s uch time accuracy by partitioning time as time
grains . For e xample in me e ting s che duling, all me e tings s tart/e nd in hour, half
hour, or 15-minute inte rvals be fore or afte r e ach hour, the re fore the optimal
s e ttings for time grains is 15 minute s .
Each planning e ntity is as s igne d to a s tart time grain. The e nd time grain is
calculate d by adding the duration in grains to the s tarting time grain. Ove rlap of two
e ntitie s is de te rmine d by comparing the ir s tart and e nd time grains .
This patte rn als o works we ll with a coars e r time granularity (s uch as days , half
days , hours , …​). With a fine r time granularity (s uch as s e conds , millis e conds , …​)
and a long time window, the value range (and the re fore the s e arch s pace ) can
be come too high, which re duce s e fficie ncy and s calability. Howe ve r, s uch s olution
is not impos s ible , as s hown in che ap time s che duling.
17.2.3. Chained T hrough T ime Pat t ern: Assign in a Chain t hat
Det ermines St art ing T ime
If a pe rs on or a machine continuous ly works on 1 tas k at a time in s e que nce , which
me ans s tarting a tas k whe n the pre vious is finis he d (or with a de te rminis tic de lay),
the Chaine d Through Time patte rn is us e ful. For e xample , in the ve hicle routing
with time windows e xample , a ve hicle drive s from cus tome r to cus tome r (thus it
handle s one cus tome r at a time ).
In this patte rn, the planning e ntitie s are chaine d. The anchor de te rmine s the
s tarting time of its firs t planning e ntity. The s e cond e ntity’s s tarting time is
calculate d bas e d on the s tarting time and duration of the firs t e ntity. For e xample ,
in tas k as s ignme nt, Be th (the anchor) s tarts working at 8:00, thus he r firs t tas k
s tarts at 8:00. It las ts 52 mins , the re fore he r s e cond tas k s tarts at 8:52. The
s tarting time of an e ntity is us ually a s hadow variable .
An anchor has only one chain. Although it is pos s ible to s plit up the anchor into two
s e parate anchors , for e xample s plit up Be th into Be th’s le ft hand and Be th’s right
hand (be caus e s he can do two tas ks at the s ame time ), this mode l make s pooling
re s ource s difficult. Cons e que ntly, us ing this mode l in the e xam s che duling
e xample to allow two or more e xams to us e the s ame room at the s ame time is
proble matic.
293
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Be twe e n planning e ntitie s , the re are thre e ways to cre ate gaps :
No gaps : This is common whe n the anchor is a machine . For e xample , a build
s e rve r always s tarts the ne xt job whe n the pre vious finis he s , without a bre ak.
Only de te rminis tic gaps : This is common for humans . For e xample , any tas k that
cros s e s the 10:00 barrie r ge ts an e xtra 15 minute s duration s o the human can
take a bre ak.
A de te rminis tic gap can be s ubje cte d to comple x bus ine s s logic. For e xample
in ve hicle routing, a cros s -contine nt truck drive r ne e ds to re s t 15 minute s
afte r 2 hours of driving (which may als o occur during loading or unloading
time at a cus tome r location) and als o ne e ds to re s t 10 hours afte r 14 hours
of work.
Planning variable gaps : This is uncommon, be caus e an e xtra planning variable
(which impacts the s e arch s pace ) re duce s e fficie ncy and s calability.
17.3. MULT I-ST AGE PLANNING
For practical or organiz ational re as ons (s uch as Conway’s law), comple x planning
proble ms are ofte n broke n down in multiple s tage s . A typical e xample is train
s che duling, whe re one de partme nt de cide s whe re and whe n a train will arrive or
de part, and anothe r de partme nts as s igns the ope rators to the actual train
cars /locomotive s .
Each s tage has its own s olve r configuration (and the re fore its own
SolverFactory). Do not confus e it with multi-phas e s olving which us e s a one s olve r configuration.
Similarly to Partitione d Se arch, multi-s tage planning le ads to s uboptimal re s ults .
Ne ve rthe le s s , it may be be ne ficial in orde r to s implify the mainte nance ,
owne rs hip, and he lp to s tart a proje ct.
294
CHAPT ER 18 . DEVELO PMENT
CHAPTER 18. DEVELOPMENT
18.1. MET HODOLOGY OVERVIEW
The diagram be low e xplains the ove rall s tructure of the OptaPlanne r s ource code :
In the diagram above , it’s important to unde rs tand the cle ar s e paration be twe e n
the configuration and runtime clas s e s .
The de ve lopme nt philos ophy include s :
Reuse: The e xample s are re us e d as inte gration te s ts , s tre s s te s ts and de mo’s .
The docume ntation image s are re us e d as s lide s .
Consistent terminology: Each e xample has a clas s App (e xe cutable clas s ), Dao
(Data Acce s s Obje ct) and Panel (s wing UI).
Consistent structure: Each e xample has the s ame package s : domain,
persistence, app, solver and swingui.
Real world usefulness: Eve ry fe ature is us e d in an e xample . Mos t e xample s are
re al world us e cas e s with re al world cons traints , ofte n with re al world data.
Automated testing: The re are unit te s ts , inte gration te s ts , pe rformance
re gre s s ions te s ts and s tre s s te s ts . The te s t cove rage is high.
Fail fast with an understandable error message: Invalid s tate s are che cke d as
e arly as pos s ible .
295
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
18.2. DEVELOPMENT GUIDELINES
1. Fail fas t. The re are s e ve ral le ve ls of fail fas t, from be tte r to wors e :
a. Fail Fast at compile time. For e xample : Don’t acce pt an Object as
parame te r if it ne e ds to be a String or an Integer.
b. Fail Fast at startup time. For e xample : if the configuration parame te r
ne e ds to be a pos itive int and it’s ne gative , fail fas t
c. Fail Fast at runtime. For e xample : if the re que s t ne e ds to contain a
double be twe e n 0.0 and 1.0 and it’s bigge r than 1.0, fail fas t.
d. Fail Fast at runtime in assertion mode if the de te ction pe rformance
cos t is high. For e xample : If, afte r e ve ry low le ve l ite ration, the
variable A ne e ds to be e qual to the s quare root of B, che ck it if and
only if an as s e rt flag is s e t to true (us ually controlle d by the
Environme ntMode ).
2. Exception me s s age s
a. The Exception me s s age mus t include the name and s tate of e ach
re le vant variable . For e xample :
if (fooSize < 0) {
throw new IllegalArgumentException("The fooSize (" +
fooSize + ") of bar (" + this + ") must be positive.");
}
Notice that the output cle arly e xplains what’s wrong:
Exception in thread "main"
java.lang.IllegalArgumentException: The fooSize (-5) of
bar (myBar) must be positive.
at ...
b. Whe ne ve r pos s ible , the Exception me s s age mus t include conte xt.
c. Whe ne ve r the fix is not obvious , the Exception me s s age s hould
include advice . Advice normally s tarts with the word maybe on a ne w
line :
Exception in thread "main"
java.lang.IllegalStateException: The valueRangeDescriptor
(fooRange) is nullable, but not countable (false).
Maybe the member (getFooRange) should return
CountableValueRange.
at ...
The word maybe is to indicate that the advice is not guarante e d to be
right in all cas e s .
3. Ge ne rics . The Solution clas s is ofte n pas s e d as a ge ne ric type parame te r
to s ubs ys te ms . The PlanningEntity clas s (e s ) are rare ly pas s e d as a
ge ne ric type parame te r.
296
CHAPT ER 19 . MIGRAT IO N GUIDE
CHAPTER 19. MIGRATION GUIDE
19.1. ABOUT T HE BUSINESS RESOURCE PLANNER
MIGRAT ION
From Re d Hat JBos s BRMS and Re d Hat JBos s BPM Suite 6.1 onwards , Bus ine s s
Re s ource Planne r is fully s upporte d. Bus ine s s Re s ource Planne r is a lightwe ight,
e mbe ddable cons traint s atis faction e ngine that is able to s olve planning proble ms .
Bus ine s s Re s ource Planne r include s a public API, which will be backwards
compatible in late r ve rs ions s uch as 6.2 and 6. For more information, s e e the
Bus ine s s Re s ource Planne r docume ntation.
The following change s s hould be note d for imple me ntation in JBos s BPM
Suite /JBos s BRMS 6.1 onwards :
Simulate d Anne aling now us e s the time gradie nt of the curre nt s te p ins te ad of
the time gradie nt of the las t s te p. The impact of this change is ne gligible .
On Abs tractScore , the me thods parseLevelStrings(…​) and
buildScorePattern(…​) have be e n change d from public to prote cte d. It is highly
unlike ly that this affe cts your code .
The Descriptor clas s e s have be e n move d into a de s criptor package .
SolutionDescriptor.isInitialized(Solution) now re quire s a
ScoreDirector parame te r.
The re is now a be tte r alte rnative to Brute Force : Branch And Bound, s e e docs
for more information.
InverseRelationShadowVariableListener has be e n re name d to
SingletonInverseVariableListener. It, and
InverseRelationShadowVariableDescriptor have move d to the package
...impl.domain.variable.inverserelation.
The ConstraintOccurrence clas s e s (which we re de pre cate d) have be e n
re move , and s hould be s witche d to the ConstraintMatch s ys te m.
The inte rface Solution has be e n promote d to the public API. It has als o move d
package from impl.solution to api.domain.solution.
Pre vious ly in *.java :
import org.optaplanner.core.impl.solution.Solution;
Now in *.java :
import org.optaplanner.core.api.domain.solution.Solution;
All clas s e s in the package impl.move have be e n move d to
impl.heuristic.move. None of the m are future -proof e nough at this time to be
adde d the public API. Pre fe r ge ne ric move s whe ne ve r pos s ible .
Pre vious ly in *.java :
297
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
import org.optaplanner.core.impl.move.Move;
import org.optaplanner.core.impl.move.CompositeMove;
import org.optaplanner.core.impl.move.NoChangeMove;
Now in *.java :
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.heuristic.move.CompositeMove;
import org.optaplanner.core.impl.heuristic.move.NoChangeMove;
All clas s path re s ource s mus t los e the ir le ading s las h, be caus e Bus ine s s
Re s ource Planne r now e xpe cts the m to adhe re to
ClassLoader.getResource(String) ins te ad of Class.getResource(String).
The SolverFactory.createFromXmlResource(String) parame te r mus t
los e its le ading s las h.
Pre vious ly in *.java :
... = SolverFactory.createFromXmlResource(
"/org/optaplanner/examples/cloudbalancing/solver/cloudBalancin
gSolverConfig.xml");
Now in *.java :
... = SolverFactory.createFromXmlResource(
"org/optaplanner/examples/cloudbalancing/solver/cloudBalancing
SolverConfig.xml");
All e le me nts <scoreDrl> mus t los e the ir le ading s las h.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml:
<scoreDrl>/org/optaplanner/examples/cloudbalancing/solver/clou
dBalancingScoreRules.drl</scoreDrl>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<scoreDrl>org/optaplanner/examples/cloudbalancing/solver/cloud
BalancingScoreRules.drl</scoreDrl>
The PlannerBenchmarkFactory.createFromXmlResource(String)
parame te r mus t los e its le ading s las h.
Pre vious ly in *.java :
... = PlannerBenchmarkFactory.createFromXmlResource(
"/org/optaplanner/examples/cloudbalancing/benchmark/cloudBalan
cingBenchmarkConfig.xml");
Now in *.java :
298
CHAPT ER 19 . MIGRAT IO N GUIDE
... = PlannerBenchmarkFactory.createFromXmlResource(
"org/optaplanner/examples/cloudbalancing/benchmark/cloudBalanc
ingBenchmarkConfig.xml");
The
PlannerBenchmarkFactory.createFromFreemarkerXmlResource(String)
parame te r mus t los e its le ading s las h.
Pre vious ly in *.java :
... = PlannerBenchmarkFactory.createFromFreemarkerXmlResource(
"/org/optaplanner/examples/cloudbalancing/benchmark/cloudBalan
cingBenchmarkConfigTemplate.xml.ftl");
Now in *.java :
... = PlannerBenchmarkFactory.createFromFreemarkerXmlResource(
"org/optaplanner/examples/cloudbalancing/benchmark/cloudBalanc
ingBenchmarkConfigTemplate.xml.ftl");
The @PlanningVariable prope rty chaine d has be e n re factore d to graphType.
This is to allow s upport for othe r graph type s (s uch as TREE) in the future .
Pre vious ly in *.java :
@PlanningVariable(chained = true, ...)
public Standstill getPreviousStandstill() {
return previousStandstill;
}
Now in *.java :
@PlanningVariable(graphType = PlanningVariableGraphType.CHAINED,
...)
public Standstill getPreviousStandstill() {
return previousStandstill;
}
The constructionHeuristicType BEST_FIT has be e n re name d into
WEAKEST_FIT. The te rminology "Be s t Fit" was not corre ct and did not allow for
STRONGEST_FIT.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<constructionHeuristic>
<constructionHeuristicType>BEST_FIT</constructionHeuristicType>
</constructionHeuristic>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<constructionHeuristic>
<constructionHeuristicType>WEAKEST_FIT</constructionHeuristicTyp
299
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
e>
</constructionHeuristic>
The constructionHeuristicType BEST_FIT_DECREASING has be e n re name d
into WEAKEST_FIT_DECREASING. The te rminology "Be s t Fit" was not corre ct and
did not allow for STRONGEST_FIT_DECREASING.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<constructionHeuristic>
<constructionHeuristicType>BEST_FIT_DECREASING</constructionHeur
isticType>
</constructionHeuristic>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<constructionHeuristic>
<constructionHeuristicType>WEAKEST_FIT_DECREASING</constructionH
euristicType>
</constructionHeuristic>
For the s hadow variable of a bi-dire ctional re lations hip, the de claration has
change d from @PlanningVariable(mappedBy) to
@InverseRelationShadowVariable(sourceVariableName).
Pre vious ly in *.java :
@PlanningVariable(mappedBy = "previousStandstill")
Customer getNextCustomer();
void setNextCustomer(Customer nextCustomer);
Now in *.java :
@InverseRelationShadowVariable(sourceVariableName =
"previousStandstill")
Customer getNextCustomer();
void setNextCustomer(Customer nextCustomer);
Multiple <planningEntityClass> e le me nts now ne e d to be orde re d by
s upe rclas s e s (and s upe rinte rface s ) firs t, ins te ad of s upe rclas s e s (and
s upe rinte rface s ) las t.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<planningEntityClass>...TimeWindowedCustomer</planningEntityClas
s>
<planningEntityClass>...Customer</planningEntityClass>
<planningEntityClass>...Standstill</planningEntityClass>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<planningEntityClass>...Standstill</planningEntityClass>
<planningEntityClass>...Customer</planningEntityClass>
<planningEntityClass>...TimeWindowedCustomer</planningEntityClas
s>
300
CHAPT ER 19 . MIGRAT IO N GUIDE
The e le me nt <planningEntityClass> has be e n re name d to <entityClass>.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<planningEntityClass>org.optaplanner.examples.cloudbalancing.dom
ain.CloudProcess</planningEntityClass>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<entityClass>org.optaplanner.examples.cloudbalancing.domain.Clou
dProcess</entityClass>
XStreamScoreConverter and XStreamBendableScoreConverter have move d
package .
Pre vious ly in *.java :
import
org.optaplanner.persistence.xstream.XStreamScoreConverter;
Now in *.java :
import
org.optaplanner.persistence.xstream.impl.score.XStreamScoreConve
rter;
Pre vious ly in *.java :
import
org.optaplanner.persistence.xstream.XStreamBendableScoreConverte
r;
Now in *.java :
import
org.optaplanner.persistence.xstream.impl.score.XStreamBendableSc
oreConverter;
If you have a cus tom Move imple me ntation, now e xtract AbstractMove.
Pre vious ly in *.java :
public class CloudComputerChangeMove implements Move {...}
Now in *.java :
public class CloudComputerChangeMove extends AbstractMove {...}
19.2. PLANNING VALUES AND VALUE RANGES
19.2.1. ValueRangeProvider
301
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
If you have a @ValueRangeProvider that re turns a colle ction of numbe rs (for
e xample List<Integer> or List<BigDecimal>), the n you s hould s witch to a
ValueRange, which us e s le s s me mory and offe rs additional opportunitie s .
For e xample :
@ValueRangeProvider(id = "delayRange")
public List<Integer> getDelayRange() {
List<Integer> = new ArrayList<Integer>(5000);
for (int i = 0; i < 5000; i++) {
delayRange.add(i);
}
return delayRange;
}
Is change d to:
@ValueRangeProvider(id = "delayRange")
public CountableValueRange<Integer> getDelayRange() {
return ValueRangeFactory.createIntValueRange(0, 5000);
}
No t e
The annotation @ValueRangeProvider has be e n move d into anothe r
package , from:
import
org.optaplanner.core.api.domain.value.ValueRangeProvider;
to
import
org.optaplanner.core.api.domain.valuerange.ValueRangeProvide
r;
19.2.2. Planning Variables
The inte rface PlanningVariableListener has be e n re name d to
VariableListener.
Pre vious ly in *.java :
public class VehicleUpdatingVariableListener implements
PlanningVariableListener<Customer> {
Now in *.java :
public class VehicleUpdatingVariableListener implements
VariableListener<Customer> {
The clas s Abs tractPlanningVariable Lis te ne r has be e n re move d.
302
CHAPT ER 19 . MIGRAT IO N GUIDE
Pre vious ly in *.java :
public class VehicleUpdatingVariableListener extends
AbstractPlanningVariableListener<Customer> {
Now in *.java :
public class VehicleUpdatingVariableListener implements
VariableListener<Customer> {
The Variable Lis te ne r is now de clare d on the s hadow s ide , ins te ad of the
@PlanningVariable s ide . This way, Bus ine s s Rule s Planne r re cogniz e s the
s hadow variable s , and all s hadow variable s are de clare d in a cons is te nt matte r.
Furthe rmore , it allows a s hadow variable to bas e d on othe r s hadow variable .
Pre vious ly in *.java :
@PlanningVariable(valueRangeProviderRefs = {"vehicleRange",
"customerRange"},
graphType = PlanningVariableGraphType.CHAINED,
variableListenerClasses = {VehicleUpdatingVariableListener.class,
ArrivalTimeUpdatingVariableListener.class})
public Standstill getPreviousStandstill() {
return previousStandstill;
}
public Vehicle getVehicle() {
return vehicle;
}
public Integer getArrivalTime() {
return arrivalTime;
}
Now in *.java :
@PlanningVariable(...)
public Standstill getPreviousStandstill() {
return previousStandstill;
}
@CustomShadowVariable(variableListenerClass =
VehicleUpdatingVariableListener.class,
sources = {@CustomShadowVariable.Source(variableName =
"previousStandstill")})
public Vehicle getVehicle() {
return vehicle;
}
@CustomShadowVariable(variableListenerClass =
ArrivalTimeUpdatingVariableListener.class,
sources = {@CustomShadowVariable.Source(variableName =
303
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
"previousStandstill")})
public Integer getArrivalTime() {
return arrivalTime;
}
The re is now out-of-the -box s upport for a s hadow variable re pre s e nting the anchor
of a chaine d variable . For e xample , in a VRP e ach Cus tome r (= e ntity) ne e ds to
know to which Ve hicle (= anchor) it be longs . This de clarative s upport allows build-in
s e le ctors to re us e that knowle dge without duplicating the calculation.
Pre vious ly in *.java :
@PlanningEntity
public class Customer implements Standstill {
@PlanningVariable(...)
public Standstill getPreviousStandstill() {...}
@CustomShadowVariable(variableListenerClass =
VehicleUpdatingVariableListener.class,
sources = {@CustomShadowVariable.Source(variableName =
"previousStandstill")})
public Vehicle getVehicle() {...}
}
public class VehicleUpdatingVariableListener implements
VariableListener<Customer> {
...
}
Now in *.java :
@PlanningEntity
public class Customer implements Standstill {
@PlanningVariable(...)
public Standstill getPreviousStandstill() {...}
@AnchorShadowVariable(sourceVariableName = "previousStandstill")
public Vehicle getVehicle() {...}
}
To s cale VRP cas e s , Ne arby Se le ction is critical. It is now finally comple te ly
s upporte d and docume nte d.
19.3. BENCHMARK
The inte rnals of Be nchmark have be e n de e ply re factore d to s upport the ne w
aggre gator functionality.
The phras e "time s pe nd" has be e n re name d to "time s pe nt". This include s the
log output and the be nchmark re port.
The <warmUp*> e le me nts have be e n re name d:
304
CHAPT ER 19 . MIGRAT IO N GUIDE
The e le me nt <warmUpTime Millis Spe nd> has be e n re name d to
<warmUpMillis e conds Spe ntLimit>
The e le me nt <warmUpSe conds Spe nd> has be e n re name d to
<warmUpSe conds Spe ntLimit>
The e le me nt <warmUpMinute s Spe nd> has be e n re name d to
<warmUpMinute s Spe ntLimit>
The e le me nt <warmUpHours Spe nd> has be e n re name d to
<warmUpHours Spe ntLimit>
Pre vious ly in *BenchmarkConfig.xml
<plannerBenchmark>
<warmUpTimeMillisSpend>...</warmUpTimeMillisSpend>
<warmUpSecondsSpend>...</warmUpSecondsSpend>
<warmUpMinutesSpend>...</warmUpMinutesSpend>
<warmUpHoursSpend>...</warmUpHoursSpend>
...
<//plannerBenchmark>
Now in *BenchmarkConfig.xml :
<plannerBenchmark>
<warmUpMillisecondsSpentLimit>...
</warmUpMillisecondsSpentLimit>
<warmUpSecondsSpentLimit>...</warmUpSecondsSpentLimit>
<warmUpMinutesSpentLimit>...</warmUpMinutesSpentLimit>
<warmUpHoursSpentLimit>...</warmUpHoursSpentLimit>
...
<//plannerBenchmark>
The clas s XmlPlannerBenchmarkFactory has be e n re move d and re place d by
s tatic me thods on PlannerBenchmarkFactory.
Pre vious ly in *.java :
PlannerBenchmarkFactory plannerBenchmarkFactory = new
XmlPlannerBenchmarkFactory(...);
Now in *.java :
PlannerBenchmarkFactory plannerBenchmarkFactory =
PlannerBenchmarkFactory.createFromXmlResource(...);
No t e
If you us e d the me thod addXstreamAnnotations(), take a look at the nonpublic API clas s XStreamXmlPlannerBenchmarkFactory.
The e le me nt <xstreamAnnotatedClass> has be e n re name d to
<xStreamAnnotatedClass>.
305
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
Pre vious ly in *BenchmarkConfig.xml
<problemBenchmarks>
<xstreamAnnotatedClass>org.optaplanner.examples.nqueens.domain.NQue
ens</xstreamAnnotatedClass>
...
</problemBenchmarks>
</plannerBenchmark>
Now in *BenchmarkConfig.xml :
<problemBenchmarks>
<xStreamAnnotatedClass>org.optaplanner.examples.nqueens.domain.NQu
eens</xStreamAnnotatedClass>
...
</problemBenchmarks>
19.3.1. Solut ionFileIO
Proble mIO has be e n re name d to SolutionFile IO and move d package (into the public
API).
Be fore in *.java :
import org.optaplanner.core.impl.solution.ProblemIO;
public class MachineReassignmentFileIO implements ProblemIO {
...
}
After in *.java:
import
org.optaplanner.persistence.common.api.domain.solution.SolutionFile
IO;
public class MachineReassignmentFileIO implements SolutionFileIO {
...
}
Now in *.java :
Pre vious ly in *SolverConfig.xml and *BenchmarckConfig.xml :
<problemBenchmarks>
<problemIOClass>...MachineReassignmentProblemIO</problemIOClass>
...
</problemBenchmarks>
Now in *SolverConfig.xml and *BenchmarckConfig.xml :
<problemBenchmarks>
<solutionFileIOClass>...MachineReassignmentFileIO</solutionFileIOCl
ass>
...
</problemBenchmarks>
306
CHAPT ER 19 . MIGRAT IO N GUIDE
The me thod SolutionFileIO.getFileExtension() has be e n s plit up in
getInputFileExtension() and getOutputFileExtension();. It is s till highly
re comme nde d to us e the s ame input and output file e xte ns ion.
Be fore in *.java :
public String getFileExtension() {
return FILE_EXTENSION;
}
Now in *.java :
public String getInputFileExtension() {
return FILE_EXTENSION;
}
public String getOutputFileExtension() {
return FILE_EXTENSION;
}
19.4. SOLVER CONFIGURAT ION
In Solve r and Be s tSolutionChange dEve nt, the me thod getTimeMillisSpend() has
be e n re name d to getTimeMillisSpent().
Pre vious ly in *.java:
... = solver.getTimeMillisSpend();
Now in *.java:
... = solver.getTimeMillisSpent();
Pre vious ly in *.java:
public void bestSolutionChanged(BestSolutionChangedEvent event) {
... = event.getTimeMillisSpend();
}
Now in *.java:
public void bestSolutionChanged(BestSolutionChangedEvent event) {
... = event.getTimeMillisSpent();
}
The s olve r phas e <bruteForce> has be e n re place d by <exhaustiveSearch>'s
BRUTE_FORCE type .
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<bruteForce/>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<exhaustiveSearch>
307
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
<exhaustiveSearchType>BRUTE_FORCE</exhaustiveSearchType>
</exhaustiveSearch>
The me thods setPlanningProblem(Solution) and solve() have be e n me rge d
as the me thod solve(Solution).
Pre vious ly in *.java:
solver.setPlanningProblem(planningProblem);
solver.solve();
Now in *.java:
solver.solve(planningProblem);
No t e
You s till ne e d to us e solver.getBestSolution() to re trie ve the be s t
s olution. That is inte ntional due to re al-time planning and to s upport pare
to optimiz ation in the future .
The clas s XmlSolverFactory (which was not part of the public API) has be e n
re move d and re place d by s tatic me thods on SolverFactory (which are part of the
public API).
Pre vious ly in *.java:
SolverFactory solverFactory = new
XmlSolverFactory("...solverConfig.xml");
Now in *.java:
SolverFactory solverFactory =
SolverFactory.createFromXmlResource("...solverConfig.xml");
Pre vious ly in *.java:
SolverFactory solverFactory = new
XmlSolverFactory().configure(inputStream);
Now in *.java:
SolverFactory solverFactory =
SolverFactory.createFromXmlInputStream(inputStream);
Pre vious ly in *.java:
SolverFactory solverFactory = new
XmlSolverFactory().configure(reader);
Now in *.java:
308
CHAPT ER 19 . MIGRAT IO N GUIDE
SolverFactory solverFactory =
SolverFactory.createFromXmlReader(reader);
No t e
If you us e d the me thod addXstreamAnnotations(), take a look at the nonpublic API clas s XStreamXmlSolverFactory.
The following change s have be e n made to the Cus tom Solve rPhas e :
The inte rface CustomSolverPhaseCommand has be e n re name d to
CustomPhaseCommand.
The e le me nt <customSolverPhase> has be e n re name d to
<customPhase>.
The e le me nt <customSolverPhaseCommandClass> has be e n re name d to
>customPhaseCommandClass>.
Pre vious ly in *.java:
public class ToOriginalMachineSolutionInitializer implements
CustomSolverPhaseCommand {
...
}
Now in *.java:
public class ToOriginalMachineSolutionInitializer implements
CustomPhaseCommand {
...
}
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<customSolverPhase>
<customSolverPhaseCommandClass>...ToOriginalMachineSolutionInitial
izer</customSolverPhaseCommandClass>
</customSolverPhase>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<customPhase>
<customPhaseCommandClass>....ToOriginalMachineSolutionInitializer<
/customPhaseCommandClass>
</customPhase>
The me thod ScoreDefinition.getLevelCount() has be e n re name d to
ScoreDefinition.getLevelsSize().
19.5. OPT IMIZAT ION
19.5.1. T erminat ion
309
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
All child e le me nts of <termination> have be e n re name d:
The e le me nt <maximumTimeMillisSpend> has be e n re name d to
<millisecondsSpentLimit>
The e le me nt <maximumSecondsSpend> has be e n re name d to
<secondsSpentLimit>
The e le me nt <maximumMinutesSpend> has be e n re name d to
<minutesSpentLimit>
The e le me nt <maximumHoursSpend> has be e n re name d to <hoursSpentLimit>
The e le me nt <scoreAttained> has be e n re name d to <bestScoreLimit>
The e le me nt <maximumStepCount> has be e n re name d to <stepCountLimit>
The e le me nt <maximumUnimprovedStepCount> has be e n re name d to
<unimprovedStepCountLimit>
Configuration in *SolverConfig.xml and *BenchmarkConfig.xml has change d
from:
<termination>
<maximumTimeMillisSpend>...</maximumTimeMillisSpend>
<maximumSecondsSpend>...</maximumSecondsSpend>
<maximumMinutesSpend>...</maximumMinutesSpend>
<maximumHoursSpend>...</maximumHoursSpend>
<scoreAttained>...</scoreAttained>
<maximumStepCount>...</maximumStepCount>
<maximumUnimprovedStepCount>...</maximumUnimprovedStepCount>
</termination>
to:
<termination>
<millisecondsSpentLimit>...</millisecondsSpentLimit>
<secondsSpentLimit>...</secondsSpentLimit>
<minutesSpentLimit>...</minutesSpentLimit>
<hoursSpentLimit>...</hoursSpentLimit>
<bestScoreLimit>...</bestScoreLimit>
<stepCountLimit>...</stepCountLimit>
<unimprovedStepCountLimit>...</unimprovedStepCountLimit>
</termination>
19.5.2. Event s
Clas s e s BestSolutionChangedEvent and SolverEventListener move d from
package impl.event to api.solver.event. The y are now part of the public api.
Pre vious ly in *.java :
import org.optaplanner.core.impl.event.BestSolutionChangedEvent;
import org.optaplanner.core.impl.event.SolverEventListener;
Now in *.java :
310
CHAPT ER 19 . MIGRAT IO N GUIDE
import
org.optaplanner.core.api.solver.event.BestSolutionChangedEvent;
import org.optaplanner.core.api.solver.event.SolverEventListener;
19.5.3. Score T rends
Spe cify an <initializingScoreTrend> in the <scoreDirectorFactory> to
incre as e pe rformance of s ome algorithms (Cons truction He uris tics and Exhaus tive
Se arch).
Se e the docume ntation s e ction on InitializingScoreTrend whe n to us e ANY,
ONLY_UP, or ONLY_DOWN.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<scoreDrl>.../cloudBalancingScoreRules.drl</scoreDrl>
</scoreDirectorFactory>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<scoreDirectorFactory>
<scoreDefinitionType>HARD_SOFT</scoreDefinitionType>
<scoreDrl>.../cloudBalancingScoreRules.drl</scoreDrl>
<initializingScoreTrend>ONLY_DOWN</initializingScoreTrend>
</scoreDirectorFactory>
Re place <pickEarlyType> FIRST_NON_DETERIORATING_SCORE with
<initializingScoreTrend> ONLY_DOWN. If the <initializingScoreTrend> is
s pe cifie d, the <constructionHeuristic> will automatically us e the mos t
appropriate <pickEarlyType>.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml:
<scoreDirectorFactory>
...
</scoreDirectorFactory>
...
<constructionHeuristic>
<constructionHeuristicType>FIRST_FIT_DECREASING</constructionHeuris
ticType>
<forager>
<pickEarlyType>FIRST_NON_DETERIORATING_SCORE</pickEarlyType>
</forager>
</constructionHeuristic>
Now in *SolverConfig.xml and *BenchmarkConfig.xml :
<scoreDirectorFactory>
...
<initializingScoreTrend>ONLY_DOWN</initializingScoreTrend>
</scoreDirectorFactory>
311
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
...
<constructionHeuristic>
<constructionHeuristicType>FIRST_FIT_DECREASING</constructionHeuris
ticType>
</constructionHeuristic>
19.5.4. Score Calculat or
The inte rface SimpleScoreCalculator has be e n re name d to
EasyScoreCalculator to avoid confus ion with SimpleScore and SimpleScore: it
can re turn othe r Score type s . The package name has als o change d.
Pre vious ly in *.java :
import
org.optaplanner.core.impl.score.director.simple.SimpleScoreCalculat
or;
public class CloudBalancingEasyScoreCalculator implements
SimpleScoreCalculator<CloudBalance> {
...
}
Now in *.java :
import
org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
public class CloudBalancingEasyScoreCalculator implements
EasyScoreCalculator<CloudBalance> {
...
}
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<simpleScoreCalculatorClass>org.optaplanner.examples.cloudbalancing
.solver.score.CloudBalancingEasyScoreCalculator<simpleScoreCalculat
orClass>
Afte r in *SolverConfig.xml and *BenchmarkConfig.xml :
<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.s
olver.score.CloudBalancingEasyScoreCalculator
The BendableScore configuration has change d: …​L evelCount has be e n re name d
to …​L evelsSize.
Pre vious ly in *SolverConfig.xml and *BenchmarkConfig.xml :
<scoreDirectorFactory>
<scoreDefinitionType>BENDABLE</scoreDefinitionType>
<bendableHardLevelCount>2</bendableHardLevelCount>
<bendableSoftLevelCount>3</bendableSoftLevelCount>
312
CHAPT ER 19 . MIGRAT IO N GUIDE
...
</scoreDirectorFactory>
Afte r in *SolverConfig.xml and *BenchmarkConfig.xml :
<scoreDirectorFactory>
<scoreDefinitionType>BENDABLE</scoreDefinitionType>
<bendableHardLevelsSize>2</bendableHardLevelsSize>
<bendableSoftLevelsSize>3</bendableSoftLevelsSize>
...
</scoreDirectorFactory>
313
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
CHAPTER 20. REALTIME DECISION SERVER
FUNCTIONALITY
20.1. INT RODUCT ION
The Realtime Decision Server is a modular, s tandalone s e rve r compone nt that can
be us e d to ins tantiate and e xe cute rule s and proce s s e s . It e xpos e s this
functionality through REST, JMS and Java inte rface s to clie nt application.
At its core , the Realtime Decision Server is a configurable we b application package d
as a WAR file . Dis tributions are available s for pure we b containe rs (like Tomcat)
and for JEE 6 and JEE 7 containe rs .
Mos t capabilitie s on the Re altime De cis ion Se rve r are configurable , and bas e d on
the conce pts of e xte ns ions . Each e xte ns ion can be e nable d/dis able d
inde pe nde ntly, allowing the us e r to configure the s e rve r to its ne e d.
20.2. BUSINESS RESOURCE PLANNER REST API
Whe n the Planne r capability is e nable d, the Re altime De cis ion Se rve r s upports the
following additional REST APIs . All the s e APIs are als o available through JMS and the
Java clie nt API. Ple as e als o note :
To de ploy the Re altime De cis ion Se rve r, s e e chapte r The Realtime Decision
Server from Red Hat JBoss BRMS User Guide.
The bas e URL for the s e will re main as the e ndpoint de fine d e arlie r (for e xample
http://SERVER:PORT/kie-server/services/rest/server/).
All re que s ts re quire bas ic HTTP Authe ntication for the role kie -s e rve r as
indicate d e arlie r.
To ge t a s pe cific mars halling format, add the HTTP he ade rs Content-Type and
optional X-KIE-ContentType in the HTTP re que s t. For e xample :
Content-Type: application/xml
X-KIE-ContentType: xstream
The e xample re que s ts and re s pons e s us e d be low pre s ume that a kie containe r is
built us ing the optacloud e xample of OptaPlanne r Workbe nch, by calling a PUT on
/services/rest/server/containers/optacloud-kiecontainer-1 with this
conte nt:
<kie-container container-id="optacloud-kiecontainer-1">
<release-id>
<group-id>opta</group-id>
<artifact-id>optacloud</artifact-id>
<version>1.0.0</version>
</release-id>
</kie-container>
20.2.1. [GET ] /cont ainers/{cont ainerId}/solvers
314
CHAPT ER 20 . REALT IME DECISIO N SERVER FUNCT IO NALIT Y
Re turns the lis t of s olve rs cre ate d in the containe r.
Example 20 .1. Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Solvers list successfully retrieved from container 'optacloudkiecontainer-1'</msg>
<result
class="org.kie.server.api.model.instance.SolverInstanceList">
<solvers>
<solver-instance>
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver1</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>NOT_SOLVING</status>
</solver-instance>
<solver-instance>
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver2</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>NOT_SOLVING</status>
</solver-instance>
</solvers>
</result>
</org.kie.server.api.model.ServiceResponse>
Example 20 .2. Example Server Respo nse (JSON)
{
"type" : "SUCCESS",
"msg" : "Solvers list successfully retrieved from container
'optacloud-kiecontainer-1'",
"result" : {
"solver-instance-list" : {
"solver" : [ {
"status" : "NOT_SOLVING",
"container-id" : "optacloud-kiecontainer-1",
"solver-id" : "solver1",
"solver-config-file" :
"opta/optacloud/cloudSolverConfig.solver.xml"
}, {
"status" : "NOT_SOLVING",
"container-id" : "optacloud-kiecontainer-1",
"solver-id" : "solver2",
"solver-config-file" :
"opta/optacloud/cloudSolverConfig.solver.xml"
315
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
} ]
}
}
}
20.2.2. [PUT ] /cont ainers/{cont ainerId}/solvers/{solverId}
Cre ate s a ne w s olve r with the give n {solverId} in the containe r {containerId}.
The re que s t’s body is a mars halle d Solve rIns tance e ntity that mus t s pe cify the
s olve r configuration file .
The following is an e xample of the re que s t and the corre s ponding re s pons e .
Example 20 .3. Example Server Request (XSt ream)
<solver-instance>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
</solver-instance>
Example 20 .4. Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Solver 'solver1' successfully created in container
'optacloud-kiecontainer-1'</msg>
<result class="solver-instance">
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver1</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>NOT_SOLVING</status>
</result>
</org.kie.server.api.model.ServiceResponse>
Example 20 .5. Example Server Request (JSON)
{
"solver-config-file" :
"opta/optacloud/cloudSolverConfig.solver.xml"
}
316
CHAPT ER 20 . REALT IME DECISIO N SERVER FUNCT IO NALIT Y
Example 20 .6. Example Server Respo nse (JSON)
{
"type" : "SUCCESS",
"msg" : "Solver 'solver1' successfully created in container
'optacloud-kiecontainer-1'",
"result" : {
"solver-instance" : {
"container-id" : "optacloud-kiecontainer-1",
"solver-id" : "solver1",
"solver-config-file" :
"opta/optacloud/cloudSolverConfig.solver.xml",
"status" : "NOT_SOLVING"
}
}
}
20.2.3. [GET ] /cont ainers/{cont ainerId}/solvers/{solverId}
Re turns the curre nt s tate of the s olve r {solverId} in containe r {containerId}.
Example 20 .7. Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Solver 'solver1' state successfully retrieved from container
'optacloud-kiecontainer-1'</msg>
<result class="solver-instance">
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver1</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>NOT_SOLVING</status>
</result>
</org.kie.server.api.model.ServiceResponse>
Example 20 .8. Example Server Respo nse (JSON)
{
"type" : "SUCCESS",
"msg" : "Solver 'solver1' state successfully retrieved from
container 'optacloud-kiecontainer-1'",
"result" : {
"solver-instance" : {
"container-id" : "optacloud-kiecontainer-1",
"solver-id" : "solver1",
"solver-config-file" :
317
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
"opta/optacloud/cloudSolverConfig.solver.xml",
"status" : "NOT_SOLVING"
}
}
}
20.2.4. St art solving
He re is an e xample to s olve an optacloud proble m with 2 compute rs and 1
proce s s :
Example 20 .9. Example Server Request (XSt ream)
<solver-instance>
<status>SOLVING</status>
<planning-problem class="opta.optacloud.CloudSolution">
<computerList>
<opta.optacloud.Computer>
<cpuPower>10</cpuPower>
<memory>4</memory>
<networkBandwidth>100</networkBandwidth>
<cost>1000</cost>
</opta.optacloud.Computer>
<opta.optacloud.Computer>
<cpuPower>20</cpuPower>
<memory>8</memory>
<networkBandwidth>100</networkBandwidth>
<cost>3000</cost>
</opta.optacloud.Computer>
</computerList>
<processList>
<opta.optacloud.Process>
<requiredCpuPower>1</requiredCpuPower>
<requiredMemory>7</requiredMemory>
<requiredNetworkBandwidth>1</requiredNetworkBandwidth>
</opta.optacloud.Process>
</processList>
</planning-problem>
</solver-instance>
Notice that the re s pons e doe s not contain the be s t s olution ye t, be caus e s olving
can take s e conds , minute s , days or hours and this would time out the HTTP
re que s t:
Example 20 .10 . Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Solver 'solver1' from container 'optacloud-kiecontainer-1'
318
CHAPT ER 20 . REALT IME DECISIO N SERVER FUNCT IO NALIT Y
successfully updated.</msg>
<result class="solver-instance">
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver1</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>SOLVING</status>
</result>
</org.kie.server.api.model.ServiceResponse>
Ins te ad, it’s s olving as ynchronous ly and you ne e d to call the be s ts olution URL to
ge t the be s t s olution.
20.2.5. T erminat e solving
For e xample , to te rminate s olving:
Example 20 .11. Example Server Request (XSt ream)
<solver-instance>
<status>NOT_SOLVING</status>
</solver-instance>
Example 20 .12. Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Solver 'solver1' from container 'optacloud-kiecontainer-1'
successfully updated.</msg>
<result class="solver-instance">
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver1</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>TERMINATING_EARLY</status>
<score
class="org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScor
e">
<hardScore>0</hardScore>
<softScore>-3000</softScore>
</score>
</result>
</org.kie.server.api.model.ServiceResponse>
This doe s n’t de le te the s olve r, the be s t s olution can s till be re trie ve d.
319
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
20.2.6. [GET ]
/cont ainers/{cont ainerId}/solvers/{solverId}/best solut ion
Re turns the be s t s olution found at the time the re que s t is made . If the s olve r
has n’t te rminate d ye t (s o the status fie ld is s till SOLVING), it will re turn the be s t
s olution found up to the n, but late r calls can re turn a be tte r s olution.⁠
For e xample , the proble m s ubmitte d above would re turn this s olution, with the
proce s s as s igne d to the s e cond compute r (be caus e the firs t one doe s n’t have
e nough me mory).
Example 20 .13. Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Best computed solution for 'solver1' successfully retrieved
from container 'optacloud-kiecontainer-1'</msg>
<result class="solver-instance">
<container-id>optacloud-kiecontainer-1</container-id>
<solver-id>solver1</solver-id>
<solver-configfile>opta/optacloud/cloudSolverConfig.solver.xml</solver-configfile>
<status>SOLVING</status>
<score
class="org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScor
e">
<hardScore>0</hardScore>
<softScore>-3000</softScore>
</score>
<best-solution class="opta.optacloud.CloudSolution">
<score
class="org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScor
e" reference="../../score" />
<computerList>
<opta.optacloud.Computer>
<cpuPower>10</cpuPower>
<memory>4</memory>
<networkBandwidth>100</networkBandwidth>
<cost>1000</cost>
</opta.optacloud.Computer>
<opta.optacloud.Computer>
<cpuPower>20</cpuPower>
<memory>8</memory>
<networkBandwidth>100</networkBandwidth>
<cost>3000</cost>
</opta.optacloud.Computer>
</computerList>
<processList>
<opta.optacloud.Process>
<requiredCpuPower>1</requiredCpuPower>
<requiredMemory>7</requiredMemory>
<requiredNetworkBandwidth>1</requiredNetworkBandwidth>
<computer
320
CHAPT ER 20 . REALT IME DECISIO N SERVER FUNCT IO NALIT Y
reference="../../../computerList/opta.optacloud.Computer[2]" />
</opta.optacloud.Process>
</processList>
</best-solution>
</result>
</org.kie.server.api.model.ServiceResponse>
20.2.7. [DELET E] /cont ainers/{cont ainerId}/solvers/{solverId}
⁠D is pos e s the s olve r {solverId} in containe r {containerId}. If it has n’t
te rminate d ye t, it te rminate s it firs t.
Example 20 .14. Example Server Respo nse (XSt ream)
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Solver 'solver1' successfully disposed from container
'optacloud-kiecontainer-1'</msg>
</org.kie.server.api.model.ServiceResponse>
Example 20 .15. Example Server Respo nse (JSON)
{
"type" : "SUCCESS",
"msg" : "Solver 'solver1' successfully disposed from container
'optacloud-kiecontainer-1'"
}
321
Re d Hat JBo s s BRMS 6 .3 Bus ine s s Re s o ur c e Planne r Guide
APPENDIX A. REVISION HISTORY
Note that re vis ion numbe rs re late to the e dition of this manual, not to ve rs ion
numbe rs of Re d Hat JBos s BRMSBPM Suite .
Re vis io n 6 .3.0 -11
T hu Se p 15 20 16
T o mas Rade j
T hu Se p 15 20 16
T o mas Rade j
Re built.
Re vis io n 6 .3.0 -10
Publis he d the As c iiD o c ve rs io n o f the do c s .
Re vis io n 6 .3.0 -5
T hu Jun 2 20 16
Mar e k Cz e r ne k
Re le as ing the ne we s t do c ume ntatio n.
Re vis io n 6 .3.0 -4
T hu Apr 28 20 16
T o mas Rade j
T hu Apr 28 20 16
T o mas Rade j
T hu Apr 28 20 16
T o mas Rade j
Re built all bo o ks .
Re vis io n 6 .3.0 -3
Re built all bo o ks .
Re vis io n 6 .3.0 -2
Re build due to PD F build failure .
Re vis io n 6 .3.0 -1
T hu Apr 28 20 16
Initial build fo r re le as e 6 .3.0 o f JBo s s BPM S uite JBo s s BRMS .
322
T o mas Rade j
Download