/
AbstractScoreDirector.java
486 lines (421 loc) · 22.8 KB
/
AbstractScoreDirector.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.score.director;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.core.api.domain.solution.cloner.SolutionCloner;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.constraint.ConstraintMatch;
import org.optaplanner.core.api.score.constraint.ConstraintMatchTotal;
import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor;
import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import org.optaplanner.core.impl.domain.variable.descriptor.VariableDescriptor;
import org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import org.optaplanner.core.impl.domain.variable.listener.VariableListener;
import org.optaplanner.core.impl.domain.variable.listener.support.VariableListenerSupport;
import org.optaplanner.core.impl.domain.variable.supply.SupplyManager;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract superclass for {@link ScoreDirector}.
* <p>
* Implementation note: Extending classes should follow these guidelines:
* <ul>
* <li>before* method: last statement should be a call to the super method</li>
* <li>after* method: first statement should be a call to the super method</li>
* </ul>
* @see ScoreDirector
*/
public abstract class AbstractScoreDirector<F extends AbstractScoreDirectorFactory>
implements InnerScoreDirector, Cloneable {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final F scoreDirectorFactory;
protected final boolean constraintMatchEnabledPreference;
protected final VariableListenerSupport variableListenerSupport;
protected Solution workingSolution;
protected long workingEntityListRevision = 0L;
protected boolean allChangesWillBeUndoneBeforeStepEnds = false;
protected long calculateCount = 0L;
protected AbstractScoreDirector(F scoreDirectorFactory, boolean constraintMatchEnabledPreference) {
this.scoreDirectorFactory = scoreDirectorFactory;
this.constraintMatchEnabledPreference = constraintMatchEnabledPreference;
variableListenerSupport = new VariableListenerSupport(this);
variableListenerSupport.linkVariableListeners();
}
public F getScoreDirectorFactory() {
return scoreDirectorFactory;
}
public SolutionDescriptor getSolutionDescriptor() {
return scoreDirectorFactory.getSolutionDescriptor();
}
public ScoreDefinition getScoreDefinition() {
return scoreDirectorFactory.getScoreDefinition();
}
public Solution getWorkingSolution() {
return workingSolution;
}
public long getWorkingEntityListRevision() {
return workingEntityListRevision;
}
public boolean isAllChangesWillBeUndoneBeforeStepEnds() {
return allChangesWillBeUndoneBeforeStepEnds;
}
public void setAllChangesWillBeUndoneBeforeStepEnds(boolean allChangesWillBeUndoneBeforeStepEnds) {
this.allChangesWillBeUndoneBeforeStepEnds = allChangesWillBeUndoneBeforeStepEnds;
}
public long getCalculateCount() {
return calculateCount;
}
public void resetCalculateCount() {
this.calculateCount = 0L;
}
public SupplyManager getSupplyManager() {
return variableListenerSupport;
}
// ************************************************************************
// Complex methods
// ************************************************************************
public void setWorkingSolution(Solution workingSolution) {
this.workingSolution = workingSolution;
variableListenerSupport.resetWorkingSolution();
setWorkingEntityListDirty();
}
public boolean isWorkingEntityListDirty(long expectedWorkingEntityListRevision) {
return workingEntityListRevision != expectedWorkingEntityListRevision;
}
protected void setWorkingEntityListDirty() {
workingEntityListRevision++;
}
public Solution cloneWorkingSolution() {
return cloneSolution(workingSolution);
}
public Solution cloneSolution(Solution originalSolution) {
SolutionDescriptor solutionDescriptor = getSolutionDescriptor();
Solution cloneSolution = solutionDescriptor.getSolutionCloner().cloneSolution(originalSolution);
if (scoreDirectorFactory.isAssertClonedSolution()) {
if (!ObjectUtils.equals(originalSolution.getScore(), cloneSolution.getScore())) {
throw new IllegalStateException("Cloning corruption: "
+ "the original's score (" + originalSolution.getScore()
+ ") is different from the clone's score (" + cloneSolution.getScore() + ").\n"
+ "Check the " + SolutionCloner.class.getSimpleName() + ".");
}
List<Object> originalEntityList = solutionDescriptor.getEntityList(originalSolution);
Map<Object, Object> originalEntityMap = new IdentityHashMap<Object, Object>(originalEntityList.size());
for (Object originalEntity : originalEntityList) {
originalEntityMap.put(originalEntity, null);
}
for (Object cloneEntity : solutionDescriptor.getEntityList(cloneSolution)) {
if (originalEntityMap.containsKey(cloneEntity)) {
throw new IllegalStateException("Cloning corruption: "
+ "the same entity (" + cloneEntity
+ ") is present in both the original and the clone.\n"
+ "So when a planning variable in the original solution changes, "
+ "the cloned solution will change too.\n"
+ "Check the " + SolutionCloner.class.getSimpleName() + ".");
}
}
}
return cloneSolution;
}
public int getWorkingEntityCount() {
return getSolutionDescriptor().getEntityCount(workingSolution);
}
public List<Object> getWorkingEntityList() {
return getSolutionDescriptor().getEntityList(workingSolution);
}
public int getWorkingValueCount() {
return getSolutionDescriptor().getValueCount(workingSolution);
}
public int countWorkingSolutionUninitializedVariables() {
return getSolutionDescriptor().countUninitializedVariables(workingSolution);
}
@Override
public void triggerVariableListeners() {
variableListenerSupport.triggerVariableListenersInNotificationQueues();
}
protected void setCalculatedScore(Score score) {
workingSolution.setScore(score);
calculateCount++;
}
public AbstractScoreDirector clone() {
// Breaks incremental score calculation.
// Subclasses should overwrite this method to avoid breaking it if possible.
AbstractScoreDirector clone = (AbstractScoreDirector) scoreDirectorFactory.buildScoreDirector(
constraintMatchEnabledPreference);
clone.setWorkingSolution(cloneWorkingSolution());
return clone;
}
public void dispose() {
variableListenerSupport.clearWorkingSolution();
}
// ************************************************************************
// Entity/variable add/change/remove methods
// ************************************************************************
public final void beforeEntityAdded(Object entity) {
beforeEntityAdded(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
public final void afterEntityAdded(Object entity) {
afterEntityAdded(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
public final void beforeVariableChanged(Object entity, String variableName) {
VariableDescriptor variableDescriptor = getSolutionDescriptor()
.findVariableDescriptorOrFail(entity, variableName);
beforeVariableChanged(variableDescriptor, entity);
}
public final void afterVariableChanged(Object entity, String variableName) {
VariableDescriptor variableDescriptor = getSolutionDescriptor()
.findVariableDescriptorOrFail(entity, variableName);
afterVariableChanged(variableDescriptor, entity);
}
public final void beforeEntityRemoved(Object entity) {
beforeEntityRemoved(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
public final void afterEntityRemoved(Object entity) {
afterEntityRemoved(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
public void beforeEntityAdded(EntityDescriptor entityDescriptor, Object entity) {
variableListenerSupport.beforeEntityAdded(entityDescriptor, entity);
}
public void afterEntityAdded(EntityDescriptor entityDescriptor, Object entity) {
variableListenerSupport.afterEntityAdded(entityDescriptor, entity);
if (!allChangesWillBeUndoneBeforeStepEnds) {
setWorkingEntityListDirty();
}
}
public void beforeVariableChanged(VariableDescriptor variableDescriptor, Object entity) {
variableListenerSupport.beforeVariableChanged(variableDescriptor, entity);
}
public void afterVariableChanged(VariableDescriptor variableDescriptor, Object entity) {
variableListenerSupport.afterVariableChanged(variableDescriptor, entity);
}
public void changeVariableFacade(VariableDescriptor variableDescriptor, Object entity, Object newValue) {
beforeVariableChanged(variableDescriptor, entity);
variableDescriptor.setValue(entity, newValue);
afterVariableChanged(variableDescriptor, entity);
}
public void beforeEntityRemoved(EntityDescriptor entityDescriptor, Object entity) {
variableListenerSupport.beforeEntityRemoved(entityDescriptor, entity);
}
public void afterEntityRemoved(EntityDescriptor entityDescriptor, Object entity) {
variableListenerSupport.afterEntityRemoved(entityDescriptor, entity);
if (!allChangesWillBeUndoneBeforeStepEnds) {
setWorkingEntityListDirty();
}
}
// ************************************************************************
// Problem fact add/change/remove methods
// ************************************************************************
public void beforeProblemFactAdded(Object problemFact) {
// Do nothing
}
public void afterProblemFactAdded(Object problemFact) {
variableListenerSupport.resetWorkingSolution(); // TODO do not nuke it
}
public void beforeProblemFactChanged(Object problemFact) {
// Do nothing
}
public void afterProblemFactChanged(Object problemFact) {
variableListenerSupport.resetWorkingSolution(); // TODO do not nuke it
}
public void beforeProblemFactRemoved(Object problemFact) {
// Do nothing
}
public void afterProblemFactRemoved(Object problemFact) {
variableListenerSupport.resetWorkingSolution(); // TODO do not nuke it
}
// ************************************************************************
// Assert methods
// ************************************************************************
public void assertExpectedWorkingScore(Score expectedWorkingScore, Object completedAction) {
Score workingScore = calculateScore();
if (!expectedWorkingScore.equals(workingScore)) {
throw new IllegalStateException(
"Score corruption: the expectedWorkingScore (" + expectedWorkingScore
+ ") is not the workingScore (" + workingScore
+ ") after completedAction (" + completedAction + ").");
}
}
public void assertShadowVariablesAreNotStale(Score expectedWorkingScore, Object completedAction) {
SolutionDescriptor solutionDescriptor = getSolutionDescriptor();
Map<Object, Map<ShadowVariableDescriptor, Object>> entityToShadowVariableValuesMap
= new IdentityHashMap<Object, Map<ShadowVariableDescriptor, Object>>();
for (Iterator<Object> it = solutionDescriptor.extractAllEntitiesIterator(workingSolution); it.hasNext();) {
Object entity = it.next();
EntityDescriptor entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
Collection<ShadowVariableDescriptor> shadowVariableDescriptors = entityDescriptor.getShadowVariableDescriptors();
Map<ShadowVariableDescriptor, Object> shadowVariableValuesMap
= new HashMap<ShadowVariableDescriptor, Object>(shadowVariableDescriptors.size());
for (ShadowVariableDescriptor shadowVariableDescriptor : shadowVariableDescriptors) {
Object value = shadowVariableDescriptor.getValue(entity);
shadowVariableValuesMap.put(shadowVariableDescriptor, value);
}
entityToShadowVariableValuesMap.put(entity, shadowVariableValuesMap);
}
variableListenerSupport.triggerAllVariableListeners();
for (Iterator<Object> it = solutionDescriptor.extractAllEntitiesIterator(workingSolution); it.hasNext();) {
Object entity = it.next();
EntityDescriptor entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
Collection<ShadowVariableDescriptor> shadowVariableDescriptors = entityDescriptor.getShadowVariableDescriptors();
Map<ShadowVariableDescriptor, Object> shadowVariableValuesMap = entityToShadowVariableValuesMap.get(entity);
for (ShadowVariableDescriptor shadowVariableDescriptor : shadowVariableDescriptors) {
Object newValue = shadowVariableDescriptor.getValue(entity);
Object originalValue = shadowVariableValuesMap.get(shadowVariableDescriptor);
if (!ObjectUtils.equals(originalValue, newValue)) {
throw new IllegalStateException(VariableListener.class.getSimpleName() + " corruption:"
+ " the entity (" + entity
+ ")'s shadow variable (" + shadowVariableDescriptor.getSimpleEntityAndVariableName()
+ ")'s originalValue (" + originalValue + ") changed to newValue (" + newValue
+ ") after all " + VariableListener.class.getSimpleName() + "s were triggered without changes to the genuine variables.\n"
+ "Probably the " + VariableListener.class.getSimpleName()
+ " class for that shadow variable (" + shadowVariableDescriptor.getSimpleEntityAndVariableName()
+ ") forgot to update it when one of its sources changed"
+ " after completedAction (" + completedAction + ").");
}
}
}
Score workingScore = calculateScore();
if (!expectedWorkingScore.equals(workingScore)) {
throw new IllegalStateException("Impossible " + VariableListener.class.getSimpleName() + " corruption:"
+ " the expectedWorkingScore (" + expectedWorkingScore
+ ") is not the workingScore (" + workingScore
+ ") after all " + VariableListener.class.getSimpleName() + "s were triggered without changes to the genuine variables.\n"
+ "But all the shadow variable values are still the same, so this is impossible.");
}
}
public void assertWorkingScoreFromScratch(Score workingScore, Object completedAction) {
InnerScoreDirectorFactory assertionScoreDirectorFactory
= scoreDirectorFactory.getAssertionScoreDirectorFactory();
if (assertionScoreDirectorFactory == null) {
assertionScoreDirectorFactory = scoreDirectorFactory;
}
InnerScoreDirector uncorruptedScoreDirector = assertionScoreDirectorFactory.buildScoreDirector(true);
uncorruptedScoreDirector.setWorkingSolution(workingSolution);
Score uncorruptedScore = uncorruptedScoreDirector.calculateScore();
if (!workingScore.equals(uncorruptedScore)) {
String scoreCorruptionAnalysis = buildScoreCorruptionAnalysis(uncorruptedScoreDirector);
uncorruptedScoreDirector.dispose();
throw new IllegalStateException(
"Score corruption: the workingScore (" + workingScore + ") is not the uncorruptedScore ("
+ uncorruptedScore + ") after completedAction (" + completedAction
+ "):\n" + scoreCorruptionAnalysis);
} else {
uncorruptedScoreDirector.dispose();
}
}
/**
* @param uncorruptedScoreDirector never null
* @return never null
*/
protected String buildScoreCorruptionAnalysis(ScoreDirector uncorruptedScoreDirector) {
if (!isConstraintMatchEnabled() || !uncorruptedScoreDirector.isConstraintMatchEnabled()) {
return " Score corruption analysis could not be generated because"
+ " either corrupted constraintMatchEnabled (" + isConstraintMatchEnabled()
+ ") or uncorrupted constraintMatchEnabled (" + uncorruptedScoreDirector.isConstraintMatchEnabled()
+ ") is disabled.\n"
+ " Check your score constraints manually.";
}
Collection<ConstraintMatchTotal> corruptedConstraintMatchTotals = getConstraintMatchTotals();
Collection<ConstraintMatchTotal> uncorruptedConstraintMatchTotals
= uncorruptedScoreDirector.getConstraintMatchTotals();
Map<List<Object>, ConstraintMatch> corruptedMap = createConstraintMatchMap(corruptedConstraintMatchTotals);
Map<List<Object>, ConstraintMatch> excessMap = new LinkedHashMap<List<Object>, ConstraintMatch>(
corruptedMap);
Map<List<Object>, ConstraintMatch> missingMap = createConstraintMatchMap(uncorruptedConstraintMatchTotals);
excessMap.keySet().removeAll(missingMap.keySet()); // missingMap == uncorruptedMap
missingMap.keySet().removeAll(corruptedMap.keySet());
final int CONSTRAINT_MATCH_DISPLAY_LIMIT = 8;
StringBuilder analysis = new StringBuilder();
if (excessMap.isEmpty()) {
analysis.append(" The corrupted scoreDirector has no ConstraintMatch(s) which are in excess.\n");
} else {
analysis.append(" The corrupted scoreDirector has ").append(excessMap.size())
.append(" ConstraintMatch(s) which are in excess (and should not be there):\n");
int count = 0;
for (ConstraintMatch constraintMatch : excessMap.values()) {
if (count >= CONSTRAINT_MATCH_DISPLAY_LIMIT) {
analysis.append(" ... ").append(excessMap.size() - CONSTRAINT_MATCH_DISPLAY_LIMIT)
.append(" more\n");
break;
}
analysis.append(" ").append(constraintMatch).append("\n");
count++;
}
}
if (missingMap.isEmpty()) {
analysis.append(" The corrupted scoreDirector has no ConstraintMatch(s) which are missing.\n");
} else {
analysis.append(" The corrupted scoreDirector has ").append(missingMap.size())
.append(" ConstraintMatch(s) which are missing:\n");
int count = 0;
for (ConstraintMatch constraintMatch : missingMap.values()) {
if (count >= CONSTRAINT_MATCH_DISPLAY_LIMIT) {
analysis.append(" ... ").append(missingMap.size() - CONSTRAINT_MATCH_DISPLAY_LIMIT)
.append(" more\n");
break;
}
analysis.append(" ").append(constraintMatch).append("\n");
count++;
}
}
if (excessMap.isEmpty() && missingMap.isEmpty()) {
analysis.append(" The corrupted scoreDirector has no ConstraintMatch(s) in excess or missing."
+ " That could be a bug in this class (").append(getClass()).append(").\n");
}
analysis.append(" Check your score constraints.");
return analysis.toString();
}
private Map<List<Object>, ConstraintMatch> createConstraintMatchMap(
Collection<ConstraintMatchTotal> constraintMatchTotals) {
Map<List<Object>, ConstraintMatch> constraintMatchMap
= new LinkedHashMap<List<Object>, ConstraintMatch>(constraintMatchTotals.size() * 16);
for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) {
for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) {
ConstraintMatch previousConstraintMatch = constraintMatchMap.put(
Arrays.<Object>asList(
constraintMatchTotal.getConstraintPackage(),
constraintMatchTotal.getConstraintName(),
constraintMatchTotal.getScoreLevel(),
constraintMatch.getJustificationList(),
constraintMatch.getWeightAsNumber()),
constraintMatch);
if (previousConstraintMatch != null) {
throw new IllegalStateException("Score corruption because the constraintMatch (" + constraintMatch
+ ") was added twice for constraintMatchTotal (" + constraintMatchTotal
+ ") without removal.");
}
}
}
return constraintMatchMap;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + calculateCount + ")";
}
}