proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/thread/OrderByMoveIndexBlockingQueue.java
|
OrderByMoveIndexBlockingQueue
|
take
|
class OrderByMoveIndexBlockingQueue<Solution_> {
private final BlockingQueue<MoveResult<Solution_>> innerQueue;
private final Map<Integer, MoveResult<Solution_>> backlog;
private int filterStepIndex = Integer.MIN_VALUE;
private int nextMoveIndex = Integer.MIN_VALUE;
public OrderByMoveIndexBlockingQueue(int capacity) {
innerQueue = new ArrayBlockingQueue<>(capacity);
backlog = new HashMap<>(capacity);
}
/**
* Not thread-safe. Can only be called from the solver thread.
*
* @param stepIndex at least 0
*/
public void startNextStep(int stepIndex) {
synchronized (this) {
if (filterStepIndex >= stepIndex) {
throw new IllegalStateException("The old filterStepIndex (" + filterStepIndex
+ ") must be less than the stepIndex (" + stepIndex + ")");
}
filterStepIndex = stepIndex;
MoveResult<Solution_> exceptionResult = innerQueue.stream().filter(MoveResult::hasThrownException)
.findFirst().orElse(null);
if (exceptionResult != null) {
throw new IllegalStateException("The move thread with moveThreadIndex ("
+ exceptionResult.getMoveThreadIndex() + ") has thrown an exception."
+ " Relayed here in the parent thread.",
exceptionResult.getThrowable());
}
innerQueue.clear();
}
nextMoveIndex = 0;
backlog.clear();
}
/**
* This method is thread-safe. It can be called from any move thread.
*
* @param moveThreadIndex {@code 0 <= moveThreadIndex < moveThreadCount}
* @param stepIndex at least 0
* @param moveIndex at least 0
* @param move never null
* @see BlockingQueue#add(Object)
*/
public void addUndoableMove(int moveThreadIndex, int stepIndex, int moveIndex, Move<Solution_> move) {
MoveResult<Solution_> result = new MoveResult<>(moveThreadIndex, stepIndex, moveIndex, move, false, null);
synchronized (this) {
if (result.getStepIndex() != filterStepIndex) {
// Discard element from previous step
return;
}
innerQueue.add(result);
}
}
/**
* This method is thread-safe. It can be called from any move thread.
*
* @param moveThreadIndex {@code 0 <= moveThreadIndex < moveThreadCount}
* @param stepIndex at least 0
* @param moveIndex at least 0
* @param move never null
* @param score never null
* @see BlockingQueue#add(Object)
*/
public void addMove(int moveThreadIndex, int stepIndex, int moveIndex, Move<Solution_> move, Score score) {
MoveResult<Solution_> result = new MoveResult<>(moveThreadIndex, stepIndex, moveIndex, move, true, score);
synchronized (this) {
if (result.getStepIndex() != filterStepIndex) {
// Discard element from previous step
return;
}
innerQueue.add(result);
}
}
/**
* This method is thread-safe. It can be called from any move thread.
* Previous results (that haven't been consumed yet), will still be returned during iteration
* before the iteration throws an exception,
* unless there's a lower moveIndex that isn't in the queue yet.
*
* @param moveThreadIndex {@code 0 <= moveThreadIndex < moveThreadCount}
* @param throwable never null
*/
public void addExceptionThrown(int moveThreadIndex, Throwable throwable) {
MoveResult<Solution_> result = new MoveResult<>(moveThreadIndex, throwable);
synchronized (this) {
innerQueue.add(result);
}
}
/**
* Not thread-safe. Can only be called from the solver thread.
*
* @return never null
* @throws InterruptedException if interrupted
* @see BlockingQueue#take()
*/
public MoveResult<Solution_> take() throws InterruptedException {<FILL_FUNCTION_BODY>}
public static class MoveResult<Solution_> {
private final int moveThreadIndex;
private final int stepIndex;
private final int moveIndex;
private final Move<Solution_> move;
private final boolean moveDoable;
private final Score score;
private final Throwable throwable;
public MoveResult(int moveThreadIndex, int stepIndex, int moveIndex, Move<Solution_> move, boolean moveDoable,
Score score) {
this.moveThreadIndex = moveThreadIndex;
this.stepIndex = stepIndex;
this.moveIndex = moveIndex;
this.move = move;
this.moveDoable = moveDoable;
this.score = score;
this.throwable = null;
}
public MoveResult(int moveThreadIndex, Throwable throwable) {
this.moveThreadIndex = moveThreadIndex;
this.stepIndex = -1;
this.moveIndex = -1;
this.move = null;
this.moveDoable = false;
this.score = null;
this.throwable = throwable;
}
private boolean hasThrownException() {
return throwable != null;
}
public int getMoveThreadIndex() {
return moveThreadIndex;
}
public int getStepIndex() {
return stepIndex;
}
public int getMoveIndex() {
return moveIndex;
}
public Move<Solution_> getMove() {
return move;
}
public boolean isMoveDoable() {
return moveDoable;
}
public Score getScore() {
return score;
}
private Throwable getThrowable() {
return throwable;
}
}
}
|
int moveIndex = nextMoveIndex;
nextMoveIndex++;
if (!backlog.isEmpty()) {
MoveResult<Solution_> result = backlog.remove(moveIndex);
if (result != null) {
return result;
}
}
while (true) {
MoveResult<Solution_> result = innerQueue.take();
// If 2 exceptions are added from different threads concurrently, either one could end up first.
// This is a known deviation from 100% reproducibility, that never occurs in a success scenario.
if (result.hasThrownException()) {
throw new IllegalStateException("The move thread with moveThreadIndex ("
+ result.getMoveThreadIndex() + ") has thrown an exception."
+ " Relayed here in the parent thread.",
result.getThrowable());
}
if (result.getMoveIndex() == moveIndex) {
return result;
} else {
backlog.put(result.getMoveIndex(), result);
}
}
| 1,535
| 257
| 1,792
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/io/jaxb/adapter/JaxbCustomPropertiesAdapter.java
|
JaxbCustomPropertiesAdapter
|
marshal
|
class JaxbCustomPropertiesAdapter extends XmlAdapter<JaxbCustomPropertiesAdapter.JaxbAdaptedMap, Map<String, String>> {
@Override
public Map<String, String> unmarshal(JaxbAdaptedMap jaxbAdaptedMap) {
if (jaxbAdaptedMap == null) {
return null;
}
return jaxbAdaptedMap.entries.stream()
.collect(Collectors.toMap(JaxbAdaptedMapEntry::getName, JaxbAdaptedMapEntry::getValue));
}
@Override
public JaxbAdaptedMap marshal(Map<String, String> originalMap) {<FILL_FUNCTION_BODY>}
// Required to generate the XSD type in the same namespace.
@XmlType(namespace = SolverConfig.XML_NAMESPACE)
static class JaxbAdaptedMap {
@XmlElement(name = "property", namespace = SolverConfig.XML_NAMESPACE)
private List<JaxbAdaptedMapEntry> entries;
private JaxbAdaptedMap() {
// Required by JAXB
}
public JaxbAdaptedMap(List<JaxbAdaptedMapEntry> entries) {
this.entries = entries;
}
}
// Required to generate the XSD type in the same namespace.
@XmlType(namespace = SolverConfig.XML_NAMESPACE)
static class JaxbAdaptedMapEntry {
@XmlAttribute
private String name;
@XmlAttribute
private String value;
public JaxbAdaptedMapEntry() {
}
public JaxbAdaptedMapEntry(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
}
|
if (originalMap == null) {
return null;
}
List<JaxbAdaptedMapEntry> entries = originalMap.entrySet().stream()
.map(entry -> new JaxbCustomPropertiesAdapter.JaxbAdaptedMapEntry(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
return new JaxbAdaptedMap(entries);
| 507
| 104
| 611
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/io/jaxb/adapter/JaxbLocaleAdapter.java
|
JaxbLocaleAdapter
|
marshal
|
class JaxbLocaleAdapter extends XmlAdapter<String, Locale> {
@Override
public Locale unmarshal(String localeString) {
if (localeString == null) {
return null;
}
return new Locale(localeString);
}
@Override
public String marshal(Locale locale) {<FILL_FUNCTION_BODY>}
}
|
if (locale == null) {
return null;
}
return locale.toString();
| 100
| 27
| 127
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/io/jaxb/adapter/JaxbOffsetDateTimeAdapter.java
|
JaxbOffsetDateTimeAdapter
|
unmarshal
|
class JaxbOffsetDateTimeAdapter extends XmlAdapter<String, OffsetDateTime> {
private final DateTimeFormatter formatter;
public JaxbOffsetDateTimeAdapter() {
formatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd'T'HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
.appendOffsetId()
.toFormatter();
}
@Override
public OffsetDateTime unmarshal(String offsetDateTimeString) {<FILL_FUNCTION_BODY>}
@Override
public String marshal(OffsetDateTime offsetDateTimeObject) {
if (offsetDateTimeObject == null) {
return null;
}
return formatter.format(offsetDateTimeObject);
}
}
|
if (offsetDateTimeString == null) {
return null;
}
try {
return OffsetDateTime.from(formatter.parse(offsetDateTimeString));
} catch (DateTimeException e) {
throw new IllegalStateException("Failed to convert string (" + offsetDateTimeString + ") to type ("
+ OffsetDateTime.class.getName() + ").");
}
| 209
| 94
| 303
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/LocalSearchDecider.java
|
LocalSearchDecider
|
doMove
|
class LocalSearchDecider<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final String logIndentation;
protected final Termination<Solution_> termination;
protected final MoveSelector<Solution_> moveSelector;
protected final Acceptor<Solution_> acceptor;
protected final LocalSearchForager<Solution_> forager;
protected boolean assertMoveScoreFromScratch = false;
protected boolean assertExpectedUndoMoveScore = false;
public LocalSearchDecider(String logIndentation, Termination<Solution_> termination,
MoveSelector<Solution_> moveSelector, Acceptor<Solution_> acceptor, LocalSearchForager<Solution_> forager) {
this.logIndentation = logIndentation;
this.termination = termination;
this.moveSelector = moveSelector;
this.acceptor = acceptor;
this.forager = forager;
}
public Termination<Solution_> getTermination() {
return termination;
}
public MoveSelector<Solution_> getMoveSelector() {
return moveSelector;
}
public Acceptor<Solution_> getAcceptor() {
return acceptor;
}
public LocalSearchForager<Solution_> getForager() {
return forager;
}
public void setAssertMoveScoreFromScratch(boolean assertMoveScoreFromScratch) {
this.assertMoveScoreFromScratch = assertMoveScoreFromScratch;
}
public void setAssertExpectedUndoMoveScore(boolean assertExpectedUndoMoveScore) {
this.assertExpectedUndoMoveScore = assertExpectedUndoMoveScore;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public void solvingStarted(SolverScope<Solution_> solverScope) {
moveSelector.solvingStarted(solverScope);
acceptor.solvingStarted(solverScope);
forager.solvingStarted(solverScope);
}
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
moveSelector.phaseStarted(phaseScope);
acceptor.phaseStarted(phaseScope);
forager.phaseStarted(phaseScope);
}
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
moveSelector.stepStarted(stepScope);
acceptor.stepStarted(stepScope);
forager.stepStarted(stepScope);
}
public void decideNextStep(LocalSearchStepScope<Solution_> stepScope) {
InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector();
scoreDirector.setAllChangesWillBeUndoneBeforeStepEnds(true);
int moveIndex = 0;
for (Move<Solution_> move : moveSelector) {
LocalSearchMoveScope<Solution_> moveScope = new LocalSearchMoveScope<>(stepScope, moveIndex, move);
moveIndex++;
// TODO use Selector filtering to filter out not doable moves
if (!move.isMoveDoable(scoreDirector)) {
logger.trace("{} Move index ({}) not doable, ignoring move ({}).",
logIndentation, moveScope.getMoveIndex(), move);
} else {
doMove(moveScope);
if (forager.isQuitEarly()) {
break;
}
}
stepScope.getPhaseScope().getSolverScope().checkYielding();
if (termination.isPhaseTerminated(stepScope.getPhaseScope())) {
break;
}
}
scoreDirector.setAllChangesWillBeUndoneBeforeStepEnds(false);
pickMove(stepScope);
}
protected <Score_ extends Score<Score_>> void doMove(LocalSearchMoveScope<Solution_> moveScope) {<FILL_FUNCTION_BODY>}
protected void pickMove(LocalSearchStepScope<Solution_> stepScope) {
LocalSearchMoveScope<Solution_> pickedMoveScope = forager.pickMove(stepScope);
if (pickedMoveScope != null) {
Move<Solution_> step = pickedMoveScope.getMove();
stepScope.setStep(step);
if (logger.isDebugEnabled()) {
stepScope.setStepString(step.toString());
}
stepScope.setScore(pickedMoveScope.getScore());
}
}
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
moveSelector.stepEnded(stepScope);
acceptor.stepEnded(stepScope);
forager.stepEnded(stepScope);
}
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
moveSelector.phaseEnded(phaseScope);
acceptor.phaseEnded(phaseScope);
forager.phaseEnded(phaseScope);
}
public void solvingEnded(SolverScope<Solution_> solverScope) {
moveSelector.solvingEnded(solverScope);
acceptor.solvingEnded(solverScope);
forager.solvingEnded(solverScope);
}
public void solvingError(SolverScope<Solution_> solverScope, Exception exception) {
// Overridable by a subclass.
}
}
|
InnerScoreDirector<Solution_, Score_> scoreDirector = moveScope.getScoreDirector();
scoreDirector.doAndProcessMove(moveScope.getMove(), assertMoveScoreFromScratch, score -> {
moveScope.setScore(score);
boolean accepted = acceptor.isAccepted(moveScope);
moveScope.setAccepted(accepted);
forager.addMove(moveScope);
});
if (assertExpectedUndoMoveScore) {
scoreDirector.assertExpectedUndoMoveScore(moveScope.getMove(),
(Score_) moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore());
}
logger.trace("{} Move index ({}), score ({}), accepted ({}), move ({}).",
logIndentation,
moveScope.getMoveIndex(), moveScope.getScore(), moveScope.getAccepted(),
moveScope.getMove());
| 1,382
| 236
| 1,618
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/greatdeluge/GreatDelugeAcceptor.java
|
GreatDelugeAcceptor
|
isAccepted
|
class GreatDelugeAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
private Score initialWaterLevel;
private Score waterLevelIncrementScore;
private Double waterLevelIncrementRatio;
private Score startingWaterLevel = null;
private Score currentWaterLevel = null;
private Double currentWaterLevelRatio = null;
public Score getWaterLevelIncrementScore() {
return this.waterLevelIncrementScore;
}
public void setWaterLevelIncrementScore(Score waterLevelIncrementScore) {
this.waterLevelIncrementScore = waterLevelIncrementScore;
}
public Score getInitialWaterLevel() {
return this.initialWaterLevel;
}
public void setInitialWaterLevel(Score initialLevel) {
this.initialWaterLevel = initialLevel;
}
public Double getWaterLevelIncrementRatio() {
return this.waterLevelIncrementRatio;
}
public void setWaterLevelIncrementRatio(Double waterLevelIncrementRatio) {
this.waterLevelIncrementRatio = waterLevelIncrementRatio;
}
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
startingWaterLevel = initialWaterLevel != null ? initialWaterLevel : phaseScope.getBestScore();
if (waterLevelIncrementRatio != null) {
currentWaterLevelRatio = 0.0;
}
currentWaterLevel = startingWaterLevel;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
startingWaterLevel = null;
if (waterLevelIncrementRatio != null) {
currentWaterLevelRatio = null;
}
currentWaterLevel = null;
}
@Override
public boolean isAccepted(LocalSearchMoveScope moveScope) {<FILL_FUNCTION_BODY>}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
if (waterLevelIncrementScore != null) {
currentWaterLevel = currentWaterLevel.add(waterLevelIncrementScore);
} else {
// Avoid numerical instability: SimpleScore.of(500).multiply(0.000_001) underflows to zero
currentWaterLevelRatio += waterLevelIncrementRatio;
currentWaterLevel = startingWaterLevel.add(
// TODO targetWaterLevel.subtract(startingWaterLevel).multiply(waterLevelIncrementRatio);
// Use startingWaterLevel.abs() to keep the number being positive.
startingWaterLevel.abs().multiply(currentWaterLevelRatio));
}
}
}
|
Score moveScore = moveScope.getScore();
if (moveScore.compareTo(currentWaterLevel) >= 0) {
return true;
}
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
if (moveScore.compareTo(lastStepScore) > 0) {
// Aspiration
return true;
}
return false;
| 734
| 109
| 843
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/hillclimbing/HillClimbingAcceptor.java
|
HillClimbingAcceptor
|
isAccepted
|
class HillClimbingAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {<FILL_FUNCTION_BODY>}
}
|
Score moveScore = moveScope.getScore();
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
return moveScore.compareTo(lastStepScore) >= 0;
| 85
| 62
| 147
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/lateacceptance/LateAcceptanceAcceptor.java
|
LateAcceptanceAcceptor
|
phaseStarted
|
class LateAcceptanceAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected int lateAcceptanceSize = -1;
protected boolean hillClimbingEnabled = true;
protected Score[] previousScores;
protected int lateScoreIndex = -1;
public void setLateAcceptanceSize(int lateAcceptanceSize) {
this.lateAcceptanceSize = lateAcceptanceSize;
}
public void setHillClimbingEnabled(boolean hillClimbingEnabled) {
this.hillClimbingEnabled = hillClimbingEnabled;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {<FILL_FUNCTION_BODY>}
private void validate() {
if (lateAcceptanceSize <= 0) {
throw new IllegalArgumentException("The lateAcceptanceSize (" + lateAcceptanceSize
+ ") cannot be negative or zero.");
}
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
Score moveScore = moveScope.getScore();
Score lateScore = previousScores[lateScoreIndex];
if (moveScore.compareTo(lateScore) >= 0) {
return true;
}
if (hillClimbingEnabled) {
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
if (moveScore.compareTo(lastStepScore) >= 0) {
return true;
}
}
return false;
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
previousScores[lateScoreIndex] = stepScope.getScore();
lateScoreIndex = (lateScoreIndex + 1) % lateAcceptanceSize;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
previousScores = null;
lateScoreIndex = -1;
}
}
|
super.phaseStarted(phaseScope);
validate();
previousScores = new Score[lateAcceptanceSize];
Score initialScore = phaseScope.getBestScore();
for (int i = 0; i < previousScores.length; i++) {
previousScores[i] = initialScore;
}
lateScoreIndex = 0;
| 558
| 94
| 652
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/simulatedannealing/SimulatedAnnealingAcceptor.java
|
SimulatedAnnealingAcceptor
|
isAccepted
|
class SimulatedAnnealingAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected Score startingTemperature;
protected int levelsLength = -1;
protected double[] startingTemperatureLevels;
// No protected Score temperature do avoid rounding errors when using Score.multiply(double)
protected double[] temperatureLevels;
protected double temperatureMinimum = 1.0E-100; // Double.MIN_NORMAL is E-308
public void setStartingTemperature(Score startingTemperature) {
this.startingTemperature = startingTemperature;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
for (double startingTemperatureLevel : startingTemperature.toLevelDoubles()) {
if (startingTemperatureLevel < 0.0) {
throw new IllegalArgumentException("The startingTemperature (" + startingTemperature
+ ") cannot have negative level (" + startingTemperatureLevel + ").");
}
}
startingTemperatureLevels = startingTemperature.toLevelDoubles();
temperatureLevels = startingTemperatureLevels;
levelsLength = startingTemperatureLevels.length;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
startingTemperatureLevels = null;
temperatureLevels = null;
levelsLength = -1;
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {<FILL_FUNCTION_BODY>}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
// TimeGradient only refreshes at the beginning of a step, so this code is in stepStarted instead of stepEnded
double timeGradient = stepScope.getTimeGradient();
double reverseTimeGradient = 1.0 - timeGradient;
temperatureLevels = new double[levelsLength];
for (int i = 0; i < levelsLength; i++) {
temperatureLevels[i] = startingTemperatureLevels[i] * reverseTimeGradient;
if (temperatureLevels[i] < temperatureMinimum) {
temperatureLevels[i] = temperatureMinimum;
}
}
// TODO implement reheating
}
}
|
LocalSearchPhaseScope<Solution_> phaseScope = moveScope.getStepScope().getPhaseScope();
Score lastStepScore = phaseScope.getLastCompletedStepScope().getScore();
Score moveScore = moveScope.getScore();
if (moveScore.compareTo(lastStepScore) >= 0) {
return true;
}
Score moveScoreDifference = lastStepScore.subtract(moveScore);
double[] moveScoreDifferenceLevels = moveScoreDifference.toLevelDoubles();
double acceptChance = 1.0;
for (int i = 0; i < levelsLength; i++) {
double moveScoreDifferenceLevel = moveScoreDifferenceLevels[i];
double temperatureLevel = temperatureLevels[i];
double acceptChanceLevel;
if (moveScoreDifferenceLevel <= 0.0) {
// In this level, moveScore is better than the lastStepScore, so do not disrupt the acceptChance
acceptChanceLevel = 1.0;
} else {
acceptChanceLevel = Math.exp(-moveScoreDifferenceLevel / temperatureLevel);
}
acceptChance *= acceptChanceLevel;
}
if (moveScope.getWorkingRandom().nextDouble() < acceptChance) {
return true;
} else {
return false;
}
| 640
| 332
| 972
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/stepcountinghillclimbing/StepCountingHillClimbingAcceptor.java
|
StepCountingHillClimbingAcceptor
|
stepEnded
|
class StepCountingHillClimbingAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected int stepCountingHillClimbingSize = -1;
protected StepCountingHillClimbingType stepCountingHillClimbingType;
protected Score thresholdScore;
protected int count = -1;
public StepCountingHillClimbingAcceptor(int stepCountingHillClimbingSize,
StepCountingHillClimbingType stepCountingHillClimbingType) {
this.stepCountingHillClimbingSize = stepCountingHillClimbingSize;
this.stepCountingHillClimbingType = stepCountingHillClimbingType;
if (stepCountingHillClimbingSize <= 0) {
throw new IllegalArgumentException("The stepCountingHillClimbingSize (" + stepCountingHillClimbingSize
+ ") cannot be negative or zero.");
}
if (stepCountingHillClimbingType == null) {
throw new IllegalArgumentException("The stepCountingHillClimbingType (" + stepCountingHillClimbingType
+ ") cannot be null.");
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
thresholdScore = phaseScope.getBestScore();
count = 0;
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
Score moveScore = moveScope.getScore();
if (moveScore.compareTo(lastStepScore) >= 0) {
return true;
}
return moveScore.compareTo(thresholdScore) >= 0;
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {<FILL_FUNCTION_BODY>}
private int determineCountIncrement(LocalSearchStepScope<Solution_> stepScope) {
switch (stepCountingHillClimbingType) {
case SELECTED_MOVE:
long selectedMoveCount = stepScope.getSelectedMoveCount();
return selectedMoveCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) selectedMoveCount;
case ACCEPTED_MOVE:
long acceptedMoveCount = stepScope.getAcceptedMoveCount();
return acceptedMoveCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) acceptedMoveCount;
case STEP:
return 1;
case EQUAL_OR_IMPROVING_STEP:
return ((Score) stepScope.getScore()).compareTo(
stepScope.getPhaseScope().getLastCompletedStepScope().getScore()) >= 0 ? 1 : 0;
case IMPROVING_STEP:
return ((Score) stepScope.getScore()).compareTo(
stepScope.getPhaseScope().getLastCompletedStepScope().getScore()) > 0 ? 1 : 0;
default:
throw new IllegalStateException("The stepCountingHillClimbingType (" + stepCountingHillClimbingType
+ ") is not implemented.");
}
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
thresholdScore = null;
count = -1;
}
}
|
super.stepEnded(stepScope);
count += determineCountIncrement(stepScope);
if (count >= stepCountingHillClimbingSize) {
thresholdScore = stepScope.getScore();
count = 0;
}
| 905
| 64
| 969
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/tabu/MoveTabuAcceptor.java
|
MoveTabuAcceptor
|
findNewTabu
|
class MoveTabuAcceptor<Solution_> extends AbstractTabuAcceptor<Solution_> {
protected boolean useUndoMoveAsTabuMove = true;
public MoveTabuAcceptor(String logIndentation) {
super(logIndentation);
}
public void setUseUndoMoveAsTabuMove(boolean useUndoMoveAsTabuMove) {
this.useUndoMoveAsTabuMove = useUndoMoveAsTabuMove;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
protected Collection<? extends Object> findTabu(LocalSearchMoveScope<Solution_> moveScope) {
return Collections.singletonList(moveScope.getMove());
}
@Override
protected Collection<? extends Object> findNewTabu(LocalSearchStepScope<Solution_> stepScope) {<FILL_FUNCTION_BODY>}
}
|
Move<?> tabuMove;
if (useUndoMoveAsTabuMove) {
tabuMove = stepScope.getUndoStep();
} else {
tabuMove = stepScope.getStep();
}
return Collections.singletonList(tabuMove);
| 243
| 77
| 320
|
<methods>public void <init>(java.lang.String) ,public boolean isAccepted(LocalSearchMoveScope<Solution_>) ,public void phaseEnded(LocalSearchPhaseScope<Solution_>) ,public void phaseStarted(LocalSearchPhaseScope<Solution_>) ,public void setAspirationEnabled(boolean) ,public void setAssertTabuHashCodeCorrectness(boolean) ,public void setFadingTabuSizeStrategy(TabuSizeStrategy<Solution_>) ,public void setTabuSizeStrategy(TabuSizeStrategy<Solution_>) ,public void stepEnded(LocalSearchStepScope<Solution_>) <variables>protected boolean aspirationEnabled,protected boolean assertTabuHashCodeCorrectness,protected TabuSizeStrategy<Solution_> fadingTabuSizeStrategy,protected final non-sealed java.lang.String logIndentation,protected Deque<java.lang.Object> tabuSequenceDeque,protected TabuSizeStrategy<Solution_> tabuSizeStrategy,protected Map<java.lang.Object,java.lang.Integer> tabuToStepIndexMap,protected int workingFadingTabuSize,protected int workingTabuSize
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/tabu/size/AbstractTabuSizeStrategy.java
|
AbstractTabuSizeStrategy
|
protectTabuSizeCornerCases
|
class AbstractTabuSizeStrategy<Solution_> implements TabuSizeStrategy<Solution_> {
protected int protectTabuSizeCornerCases(int totalSize, int tabuSize) {<FILL_FUNCTION_BODY>}
}
|
if (tabuSize < 1) {
// At least one object should be tabu, even if totalSize is 0
tabuSize = 1;
} else if (tabuSize > totalSize - 1) {
// At least one object should not be tabu
tabuSize = totalSize - 1;
}
return tabuSize;
| 62
| 92
| 154
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/acceptor/tabu/size/ValueRatioTabuSizeStrategy.java
|
ValueRatioTabuSizeStrategy
|
determineTabuSize
|
class ValueRatioTabuSizeStrategy<Solution_> extends AbstractTabuSizeStrategy<Solution_> {
protected final double tabuRatio;
public ValueRatioTabuSizeStrategy(double tabuRatio) {
this.tabuRatio = tabuRatio;
if (tabuRatio <= 0.0 || tabuRatio >= 1.0) {
throw new IllegalArgumentException("The tabuRatio (" + tabuRatio
+ ") must be between 0.0 and 1.0.");
}
}
@Override
public int determineTabuSize(LocalSearchStepScope<Solution_> stepScope) {<FILL_FUNCTION_BODY>}
}
|
// TODO we might want to cache the valueCount if and only if moves don't add/remove entities
int valueCount = stepScope.getPhaseScope().getWorkingValueCount();
int tabuSize = (int) Math.round(valueCount * tabuRatio);
return protectTabuSizeCornerCases(valueCount, tabuSize);
| 176
| 88
| 264
|
<methods>public non-sealed void <init>() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/forager/AcceptedLocalSearchForager.java
|
AcceptedLocalSearchForager
|
toString
|
class AcceptedLocalSearchForager<Solution_> extends AbstractLocalSearchForager<Solution_> {
protected final FinalistPodium<Solution_> finalistPodium;
protected final LocalSearchPickEarlyType pickEarlyType;
protected final int acceptedCountLimit;
protected final boolean breakTieRandomly;
protected long selectedMoveCount;
protected long acceptedMoveCount;
protected LocalSearchMoveScope<Solution_> earlyPickedMoveScope;
public AcceptedLocalSearchForager(FinalistPodium<Solution_> finalistPodium,
LocalSearchPickEarlyType pickEarlyType, int acceptedCountLimit, boolean breakTieRandomly) {
this.finalistPodium = finalistPodium;
this.pickEarlyType = pickEarlyType;
this.acceptedCountLimit = acceptedCountLimit;
if (acceptedCountLimit < 1) {
throw new IllegalArgumentException("The acceptedCountLimit (" + acceptedCountLimit
+ ") cannot be negative or zero.");
}
this.breakTieRandomly = breakTieRandomly;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
finalistPodium.solvingStarted(solverScope);
}
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
finalistPodium.phaseStarted(phaseScope);
}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
finalistPodium.stepStarted(stepScope);
selectedMoveCount = 0L;
acceptedMoveCount = 0L;
earlyPickedMoveScope = null;
}
@Override
public boolean supportsNeverEndingMoveSelector() {
// TODO FIXME magical value Integer.MAX_VALUE coming from ForagerConfig
return acceptedCountLimit < Integer.MAX_VALUE;
}
@Override
public void addMove(LocalSearchMoveScope<Solution_> moveScope) {
selectedMoveCount++;
if (moveScope.getAccepted()) {
acceptedMoveCount++;
checkPickEarly(moveScope);
}
finalistPodium.addMove(moveScope);
}
protected void checkPickEarly(LocalSearchMoveScope<Solution_> moveScope) {
switch (pickEarlyType) {
case NEVER:
break;
case FIRST_BEST_SCORE_IMPROVING:
Score bestScore = moveScope.getStepScope().getPhaseScope().getBestScore();
if (moveScope.getScore().compareTo(bestScore) > 0) {
earlyPickedMoveScope = moveScope;
}
break;
case FIRST_LAST_STEP_SCORE_IMPROVING:
Score lastStepScore = moveScope.getStepScope().getPhaseScope()
.getLastCompletedStepScope().getScore();
if (moveScope.getScore().compareTo(lastStepScore) > 0) {
earlyPickedMoveScope = moveScope;
}
break;
default:
throw new IllegalStateException("The pickEarlyType (" + pickEarlyType + ") is not implemented.");
}
}
@Override
public boolean isQuitEarly() {
return earlyPickedMoveScope != null || acceptedMoveCount >= acceptedCountLimit;
}
@Override
public LocalSearchMoveScope<Solution_> pickMove(LocalSearchStepScope<Solution_> stepScope) {
stepScope.setSelectedMoveCount(selectedMoveCount);
stepScope.setAcceptedMoveCount(acceptedMoveCount);
if (earlyPickedMoveScope != null) {
return earlyPickedMoveScope;
}
List<LocalSearchMoveScope<Solution_>> finalistList = finalistPodium.getFinalistList();
if (finalistList.isEmpty()) {
return null;
}
if (finalistList.size() == 1 || !breakTieRandomly) {
return finalistList.get(0);
}
int randomIndex = stepScope.getWorkingRandom().nextInt(finalistList.size());
return finalistList.get(randomIndex);
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
finalistPodium.stepEnded(stepScope);
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
finalistPodium.phaseEnded(phaseScope);
selectedMoveCount = 0L;
acceptedMoveCount = 0L;
earlyPickedMoveScope = null;
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
finalistPodium.solvingEnded(solverScope);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + "(" + pickEarlyType + ", " + acceptedCountLimit + ")";
| 1,342
| 31
| 1,373
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/forager/finalist/AbstractFinalistPodium.java
|
AbstractFinalistPodium
|
addFinalist
|
class AbstractFinalistPodium<Solution_> extends LocalSearchPhaseLifecycleListenerAdapter<Solution_>
implements FinalistPodium<Solution_> {
protected static final int FINALIST_LIST_MAX_SIZE = 1_024_000;
protected boolean finalistIsAccepted;
protected List<LocalSearchMoveScope<Solution_>> finalistList = new ArrayList<>(1024);
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
finalistIsAccepted = false;
finalistList.clear();
}
protected void clearAndAddFinalist(LocalSearchMoveScope<Solution_> moveScope) {
finalistList.clear();
finalistList.add(moveScope);
}
protected void addFinalist(LocalSearchMoveScope<Solution_> moveScope) {<FILL_FUNCTION_BODY>}
@Override
public List<LocalSearchMoveScope<Solution_>> getFinalistList() {
return finalistList;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
finalistIsAccepted = false;
finalistList.clear();
}
}
|
if (finalistList.size() >= FINALIST_LIST_MAX_SIZE) {
// Avoid unbounded growth and OutOfMemoryException
return;
}
finalistList.add(moveScope);
| 342
| 57
| 399
|
<methods>public non-sealed void <init>() ,public void phaseEnded(LocalSearchPhaseScope<Solution_>) ,public void phaseStarted(LocalSearchPhaseScope<Solution_>) ,public void stepEnded(LocalSearchStepScope<Solution_>) ,public void stepStarted(LocalSearchStepScope<Solution_>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/localsearch/decider/forager/finalist/StrategicOscillationByLevelFinalistPodium.java
|
StrategicOscillationByLevelFinalistPodium
|
doComparison
|
class StrategicOscillationByLevelFinalistPodium<Solution_> extends AbstractFinalistPodium<Solution_> {
protected final boolean referenceBestScoreInsteadOfLastStepScore;
protected Score referenceScore;
protected Number[] referenceLevelNumbers;
protected Score finalistScore;
protected Number[] finalistLevelNumbers;
protected boolean finalistImprovesUponReference;
public StrategicOscillationByLevelFinalistPodium(boolean referenceBestScoreInsteadOfLastStepScore) {
this.referenceBestScoreInsteadOfLastStepScore = referenceBestScoreInsteadOfLastStepScore;
}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
referenceScore = referenceBestScoreInsteadOfLastStepScore
? stepScope.getPhaseScope().getBestScore()
: stepScope.getPhaseScope().getLastCompletedStepScope().getScore();
referenceLevelNumbers = referenceBestScoreInsteadOfLastStepScore
? stepScope.getPhaseScope().getBestScore().toLevelNumbers()
: stepScope.getPhaseScope().getLastCompletedStepScope().getScore().toLevelNumbers();
finalistScore = null;
finalistLevelNumbers = null;
finalistImprovesUponReference = false;
}
@Override
public void addMove(LocalSearchMoveScope<Solution_> moveScope) {
boolean accepted = moveScope.getAccepted();
if (finalistIsAccepted && !accepted) {
return;
}
if (accepted && !finalistIsAccepted) {
finalistIsAccepted = true;
finalistScore = null;
finalistLevelNumbers = null;
}
Score moveScore = moveScope.getScore();
Number[] moveLevelNumbers = moveScore.toLevelNumbers();
int comparison = doComparison(moveScore, moveLevelNumbers);
if (comparison > 0) {
finalistScore = moveScore;
finalistLevelNumbers = moveLevelNumbers;
finalistImprovesUponReference = (moveScore.compareTo(referenceScore) > 0);
clearAndAddFinalist(moveScope);
} else if (comparison == 0) {
addFinalist(moveScope);
}
}
private int doComparison(Score moveScore, Number[] moveLevelNumbers) {<FILL_FUNCTION_BODY>}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
referenceScore = null;
referenceLevelNumbers = null;
finalistScore = null;
finalistLevelNumbers = null;
}
}
|
if (finalistScore == null) {
return 1;
}
// If there is an improving move, do not oscillate
if (!finalistImprovesUponReference && moveScore.compareTo(referenceScore) < 0) {
for (int i = 0; i < referenceLevelNumbers.length; i++) {
boolean moveIsHigher = ((Comparable) moveLevelNumbers[i]).compareTo(referenceLevelNumbers[i]) > 0;
boolean finalistIsHigher = ((Comparable) finalistLevelNumbers[i]).compareTo(referenceLevelNumbers[i]) > 0;
if (moveIsHigher) {
if (finalistIsHigher) {
// Both are higher, take the best one but do not ignore higher levels
break;
} else {
// The move has the first level which is higher while the finalist is lower than the reference
return 1;
}
} else {
if (finalistIsHigher) {
// The finalist has the first level which is higher while the move is lower than the reference
return -1;
} else {
// Both are lower, ignore this level
}
}
}
}
return moveScore.compareTo(finalistScore);
| 690
| 320
| 1,010
|
<methods>public non-sealed void <init>() ,public List<LocalSearchMoveScope<Solution_>> getFinalistList() ,public void phaseEnded(LocalSearchPhaseScope<Solution_>) ,public void stepStarted(LocalSearchStepScope<Solution_>) <variables>protected static final int FINALIST_LIST_MAX_SIZE,protected boolean finalistIsAccepted,protected List<LocalSearchMoveScope<Solution_>> finalistList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/partitionedsearch/DefaultPartitionedSearchPhaseFactory.java
|
DefaultPartitionedSearchPhaseFactory
|
resolveActiveThreadCount
|
class DefaultPartitionedSearchPhaseFactory<Solution_>
extends AbstractPhaseFactory<Solution_, PartitionedSearchPhaseConfig> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPartitionedSearchPhaseFactory.class);
public DefaultPartitionedSearchPhaseFactory(PartitionedSearchPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public PartitionedSearchPhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) {
HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
ThreadFactory threadFactory = solverConfigPolicy.buildThreadFactory(ChildThreadType.PART_THREAD);
Termination<Solution_> phaseTermination = buildPhaseTermination(phaseConfigPolicy, solverTermination);
Integer resolvedActiveThreadCount = resolveActiveThreadCount(phaseConfig.getRunnablePartThreadLimit());
List<PhaseConfig> phaseConfigList_ = phaseConfig.getPhaseConfigList();
if (ConfigUtils.isEmptyCollection(phaseConfigList_)) {
phaseConfigList_ = Arrays.asList(new ConstructionHeuristicPhaseConfig(), new LocalSearchPhaseConfig());
}
DefaultPartitionedSearchPhase.Builder<Solution_> builder = new DefaultPartitionedSearchPhase.Builder<>(phaseIndex,
solverConfigPolicy.getLogIndentation(), phaseTermination, buildSolutionPartitioner(), threadFactory,
resolvedActiveThreadCount, phaseConfigList_,
phaseConfigPolicy.createChildThreadConfigPolicy(ChildThreadType.PART_THREAD));
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
builder.setAssertStepScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
builder.setAssertExpectedStepScore(true);
builder.setAssertShadowVariablesAreNotStaleAfterStep(true);
}
return builder.build();
}
private SolutionPartitioner<Solution_> buildSolutionPartitioner() {
if (phaseConfig.getSolutionPartitionerClass() != null) {
SolutionPartitioner<?> solutionPartitioner =
ConfigUtils.newInstance(phaseConfig, "solutionPartitionerClass", phaseConfig.getSolutionPartitionerClass());
ConfigUtils.applyCustomProperties(solutionPartitioner, "solutionPartitionerClass",
phaseConfig.getSolutionPartitionerCustomProperties(), "solutionPartitionerCustomProperties");
return (SolutionPartitioner<Solution_>) solutionPartitioner;
} else {
if (phaseConfig.getSolutionPartitionerCustomProperties() != null) {
throw new IllegalStateException(
"If there is no solutionPartitionerClass (" + phaseConfig.getSolutionPartitionerClass()
+ "), then there can be no solutionPartitionerCustomProperties ("
+ phaseConfig.getSolutionPartitionerCustomProperties() + ") either.");
}
// TODO Implement generic partitioner
throw new UnsupportedOperationException();
}
}
protected Integer resolveActiveThreadCount(String runnablePartThreadLimit) {<FILL_FUNCTION_BODY>}
protected int getAvailableProcessors() {
return Runtime.getRuntime().availableProcessors();
}
}
|
int availableProcessorCount = getAvailableProcessors();
Integer resolvedActiveThreadCount;
final boolean threadLimitNullOrAuto =
runnablePartThreadLimit == null || runnablePartThreadLimit.equals(ACTIVE_THREAD_COUNT_AUTO);
if (threadLimitNullOrAuto) {
// Leave one for the Operating System and 1 for the solver thread, take the rest
resolvedActiveThreadCount = Math.max(1, availableProcessorCount - 2);
} else if (runnablePartThreadLimit.equals(ACTIVE_THREAD_COUNT_UNLIMITED)) {
resolvedActiveThreadCount = null;
} else {
resolvedActiveThreadCount = ConfigUtils.resolvePoolSize("runnablePartThreadLimit",
runnablePartThreadLimit, ACTIVE_THREAD_COUNT_AUTO, ACTIVE_THREAD_COUNT_UNLIMITED);
if (resolvedActiveThreadCount < 1) {
throw new IllegalArgumentException("The runnablePartThreadLimit (" + runnablePartThreadLimit
+ ") resulted in a resolvedActiveThreadCount (" + resolvedActiveThreadCount
+ ") that is lower than 1.");
}
if (resolvedActiveThreadCount > availableProcessorCount) {
LOGGER.debug("The resolvedActiveThreadCount ({}) is higher than "
+ "the availableProcessorCount ({}), so the JVM will "
+ "round-robin the CPU instead.", resolvedActiveThreadCount, availableProcessorCount);
}
}
return resolvedActiveThreadCount;
| 858
| 364
| 1,222
|
<methods>public void <init>(org.optaplanner.core.config.partitionedsearch.PartitionedSearchPhaseConfig) <variables>protected final non-sealed org.optaplanner.core.config.partitionedsearch.PartitionedSearchPhaseConfig phaseConfig
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/partitionedsearch/queue/PartitionQueue.java
|
PartitionQueueIterator
|
createUpcomingSelection
|
class PartitionQueueIterator extends UpcomingSelectionIterator<PartitionChangeMove<Solution_>> {
@Override
protected PartitionChangeMove<Solution_> createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
while (true) {
PartitionChangedEvent<Solution_> triggerEvent;
try {
triggerEvent = queue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solver thread was interrupted in Partitioned Search.", e);
}
switch (triggerEvent.getType()) {
case MOVE:
int partIndex = triggerEvent.getPartIndex();
long processedEventIndex = processedEventIndexMap.get(partIndex);
if (triggerEvent.getEventIndex() <= processedEventIndex) {
// Skip this one because it or a better version was already processed
LOGGER.trace(" Skipped event of partIndex ({}).", partIndex);
continue;
}
PartitionChangedEvent<Solution_> latestMoveEvent = moveEventMap.get(partIndex);
processedEventIndexMap.put(partIndex, latestMoveEvent.getEventIndex());
return latestMoveEvent.getMove();
case FINISHED:
openPartCount--;
partsCalculationCount += triggerEvent.getPartCalculationCount();
if (openPartCount <= 0) {
return noUpcomingSelection();
} else {
continue;
}
case EXCEPTION_THROWN:
throw new IllegalStateException("The partition child thread with partIndex ("
+ triggerEvent.getPartIndex() + ") has thrown an exception."
+ " Relayed here in the parent thread.",
triggerEvent.getThrowable());
default:
throw new IllegalStateException("The partitionChangedEventType ("
+ triggerEvent.getType() + ") is not implemented.");
}
}
| 60
| 411
| 471
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/partitionedsearch/scope/PartitionChangeMove.java
|
PartitionChangeMove
|
rebase
|
class PartitionChangeMove<Solution_> extends AbstractMove<Solution_> {
public static <Solution_> PartitionChangeMove<Solution_> createMove(InnerScoreDirector<Solution_, ?> scoreDirector,
int partIndex) {
SolutionDescriptor<Solution_> solutionDescriptor = scoreDirector.getSolutionDescriptor();
Solution_ workingSolution = scoreDirector.getWorkingSolution();
int entityCount = solutionDescriptor.getEntityCount(workingSolution);
Map<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> changeMap = new LinkedHashMap<>(
solutionDescriptor.getEntityDescriptors().size() * 3);
for (EntityDescriptor<Solution_> entityDescriptor : solutionDescriptor.getEntityDescriptors()) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : entityDescriptor
.getDeclaredGenuineVariableDescriptors()) {
changeMap.put(variableDescriptor, new ArrayList<>(entityCount));
}
}
solutionDescriptor.visitAllEntities(workingSolution, entity -> {
EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(
entity.getClass());
if (entityDescriptor.isMovable(scoreDirector, entity)) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : entityDescriptor
.getGenuineVariableDescriptorList()) {
Object value = variableDescriptor.getValue(entity);
changeMap.get(variableDescriptor).add(Pair.of(entity, value));
}
}
});
return new PartitionChangeMove<>(changeMap, partIndex);
}
private final Map<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> changeMap;
private final int partIndex;
public PartitionChangeMove(Map<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> changeMap,
int partIndex) {
this.changeMap = changeMap;
this.partIndex = partIndex;
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
for (Map.Entry<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> entry : changeMap.entrySet()) {
GenuineVariableDescriptor<Solution_> variableDescriptor = entry.getKey();
for (Pair<Object, Object> pair : entry.getValue()) {
Object entity = pair.getKey();
Object value = pair.getValue();
innerScoreDirector.changeVariableFacade(variableDescriptor, entity, value);
}
}
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
@Override
protected PartitionChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
throw new UnsupportedOperationException("Impossible state: undo move should not be called.");
}
@Override
public PartitionChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public Collection<? extends Object> getPlanningEntities() {
throw new UnsupportedOperationException("Impossible situation: " + PartitionChangeMove.class.getSimpleName()
+ " is only used to communicate between a part thread and the solver thread, it's never used in Tabu Search.");
}
@Override
public Collection<? extends Object> getPlanningValues() {
throw new UnsupportedOperationException("Impossible situation: " + PartitionChangeMove.class.getSimpleName()
+ " is only used to communicate between a part thread and the solver thread, it's never used in Tabu Search.");
}
@Override
public String toString() {
int changeCount = changeMap.values().stream().mapToInt(List::size).sum();
return "part-" + partIndex + " {" + changeCount + " variables changed}";
}
}
|
Map<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> destinationChangeMap = new LinkedHashMap<>(
changeMap.size());
for (Map.Entry<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> entry : changeMap.entrySet()) {
GenuineVariableDescriptor<Solution_> variableDescriptor = entry.getKey();
List<Pair<Object, Object>> originPairList = entry.getValue();
List<Pair<Object, Object>> destinationPairList = new ArrayList<>(originPairList.size());
for (Pair<Object, Object> pair : originPairList) {
Object originEntity = pair.getKey();
Object destinationEntity = destinationScoreDirector.lookUpWorkingObject(originEntity);
if (destinationEntity == null && originEntity != null) {
throw new IllegalStateException("The destinationEntity (" + destinationEntity
+ ") cannot be null if the originEntity (" + originEntity + ") is not null.");
}
Object originValue = pair.getValue();
Object destinationValue = destinationScoreDirector.lookUpWorkingObject(originValue);
if (destinationValue == null && originValue != null) {
throw new IllegalStateException("The destinationEntity (" + destinationEntity
+ ")'s destinationValue (" + destinationValue
+ ") cannot be null if the originEntity (" + originEntity
+ ")'s originValue (" + originValue + ") is not null.\n"
+ "Maybe add the originValue (" + originValue + ") of class (" + originValue.getClass()
+ ") as problem fact in the planning solution with a "
+ ProblemFactCollectionProperty.class.getSimpleName() + " annotation.");
}
destinationPairList.add(Pair.of(destinationEntity, destinationValue));
}
destinationChangeMap.put(variableDescriptor, destinationPairList);
}
return new PartitionChangeMove<>(destinationChangeMap, partIndex);
| 1,055
| 472
| 1,527
|
<methods>public non-sealed void <init>() ,public final AbstractMove<Solution_> doMove(ScoreDirector<Solution_>) ,public final void doMoveOnly(ScoreDirector<Solution_>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/phase/AbstractPhaseFactory.java
|
AbstractPhaseFactory
|
buildPhaseTermination
|
class AbstractPhaseFactory<Solution_, PhaseConfig_ extends PhaseConfig<PhaseConfig_>>
implements PhaseFactory<Solution_> {
protected final PhaseConfig_ phaseConfig;
public AbstractPhaseFactory(PhaseConfig_ phaseConfig) {
this.phaseConfig = phaseConfig;
}
protected Termination<Solution_> buildPhaseTermination(HeuristicConfigPolicy<Solution_> configPolicy,
Termination<Solution_> solverTermination) {<FILL_FUNCTION_BODY>}
}
|
TerminationConfig terminationConfig_ =
Objects.requireNonNullElseGet(phaseConfig.getTerminationConfig(), TerminationConfig::new);
// In case of childThread PART_THREAD, the solverTermination is actually the parent phase's phaseTermination
// with the bridge removed, so it's ok to add it again
Termination<Solution_> phaseTermination = new PhaseToSolverTerminationBridge<>(solverTermination);
return TerminationFactory.<Solution_> create(terminationConfig_).buildTermination(configPolicy, phaseTermination);
| 137
| 143
| 280
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/phase/custom/DefaultCustomPhase.java
|
DefaultCustomPhase
|
phaseEnded
|
class DefaultCustomPhase<Solution_> extends AbstractPhase<Solution_> implements CustomPhase<Solution_> {
private final List<CustomPhaseCommand<Solution_>> customPhaseCommandList;
private DefaultCustomPhase(Builder<Solution_> builder) {
super(builder);
customPhaseCommandList = builder.customPhaseCommandList;
}
@Override
public String getPhaseTypeString() {
return "Custom";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
CustomPhaseScope<Solution_> phaseScope = new CustomPhaseScope<>(solverScope);
phaseStarted(phaseScope);
for (CustomPhaseCommand<Solution_> customPhaseCommand : customPhaseCommandList) {
solverScope.checkYielding();
if (phaseTermination.isPhaseTerminated(phaseScope)) {
break;
}
CustomStepScope<Solution_> stepScope = new CustomStepScope<>(phaseScope);
stepStarted(stepScope);
doStep(stepScope, customPhaseCommand);
stepEnded(stepScope);
phaseScope.setLastCompletedStepScope(stepScope);
}
phaseEnded(phaseScope);
}
private void doStep(CustomStepScope<Solution_> stepScope, CustomPhaseCommand<Solution_> customPhaseCommand) {
InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector();
customPhaseCommand.changeWorkingSolution(scoreDirector);
calculateWorkingStepScore(stepScope, customPhaseCommand);
solver.getBestSolutionRecaller().processWorkingSolutionDuringStep(stepScope);
}
public void stepEnded(CustomStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
CustomPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
if (logger.isDebugEnabled()) {
logger.debug("{} Custom step ({}), time spent ({}), score ({}), {} best score ({}).",
logIndentation,
stepScope.getStepIndex(),
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
stepScope.getScore(),
stepScope.getBestScoreImproved() ? "new" : " ",
phaseScope.getBestScore());
}
}
public void phaseEnded(CustomPhaseScope<Solution_> phaseScope) {<FILL_FUNCTION_BODY>}
public static final class Builder<Solution_> extends AbstractPhase.Builder<Solution_> {
private final List<CustomPhaseCommand<Solution_>> customPhaseCommandList;
public Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination,
List<CustomPhaseCommand<Solution_>> customPhaseCommandList) {
super(phaseIndex, logIndentation, phaseTermination);
this.customPhaseCommandList = List.copyOf(customPhaseCommandList);
}
@Override
public DefaultCustomPhase<Solution_> build() {
return new DefaultCustomPhase<>(this);
}
}
}
|
super.phaseEnded(phaseScope);
phaseScope.endingNow();
logger.info("{}Custom phase ({}) ended: time spent ({}), best score ({}),"
+ " score calculation speed ({}/sec), step total ({}).",
logIndentation,
phaseIndex,
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
phaseScope.getBestScore(),
phaseScope.getPhaseScoreCalculationSpeed(),
phaseScope.getNextStepIndex());
| 839
| 127
| 966
|
<methods>public void addPhaseLifecycleListener(PhaseLifecycleListener<Solution_>) ,public int getPhaseIndex() ,public Termination<Solution_> getPhaseTermination() ,public abstract java.lang.String getPhaseTypeString() ,public AbstractSolver<Solution_> getSolver() ,public boolean isAssertExpectedStepScore() ,public boolean isAssertShadowVariablesAreNotStaleAfterStep() ,public boolean isAssertStepScoreFromScratch() ,public void phaseEnded(AbstractPhaseScope<Solution_>) ,public void phaseStarted(AbstractPhaseScope<Solution_>) ,public void removePhaseLifecycleListener(PhaseLifecycleListener<Solution_>) ,public void setSolver(AbstractSolver<Solution_>) ,public void solvingEnded(SolverScope<Solution_>) ,public void solvingStarted(SolverScope<Solution_>) ,public void stepEnded(AbstractStepScope<Solution_>) ,public void stepStarted(AbstractStepScope<Solution_>) <variables>protected final non-sealed boolean assertExpectedStepScore,protected final non-sealed boolean assertShadowVariablesAreNotStaleAfterStep,protected final non-sealed boolean assertStepScoreFromScratch,protected final non-sealed java.lang.String logIndentation,protected final transient Logger logger,protected final non-sealed int phaseIndex,protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport,protected final non-sealed Termination<Solution_> phaseTermination,protected AbstractSolver<Solution_> solver
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/phase/scope/AbstractMoveScope.java
|
AbstractMoveScope
|
toString
|
class AbstractMoveScope<Solution_> {
protected final int moveIndex;
protected final Move<Solution_> move;
protected Score<?> score = null;
public AbstractMoveScope(int moveIndex, Move<Solution_> move) {
this.moveIndex = moveIndex;
this.move = move;
}
public abstract AbstractStepScope<Solution_> getStepScope();
public int getMoveIndex() {
return moveIndex;
}
public Move<Solution_> getMove() {
return move;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public int getStepIndex() {
return getStepScope().getStepIndex();
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return getStepScope().getScoreDirector();
}
public Solution_ getWorkingSolution() {
return getStepScope().getWorkingSolution();
}
public Random getWorkingRandom() {
return getStepScope().getWorkingRandom();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + "(" + getStepScope().getStepIndex() + "/" + moveIndex + ")";
| 363
| 34
| 397
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/phase/scope/AbstractPhaseScope.java
|
AbstractPhaseScope
|
reset
|
class AbstractPhaseScope<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final SolverScope<Solution_> solverScope;
protected Long startingSystemTimeMillis;
protected Long startingScoreCalculationCount;
protected Score startingScore;
protected Long endingSystemTimeMillis;
protected Long endingScoreCalculationCount;
protected long childThreadsScoreCalculationCount = 0;
protected int bestSolutionStepIndex;
public AbstractPhaseScope(SolverScope<Solution_> solverScope) {
this.solverScope = solverScope;
}
public SolverScope<Solution_> getSolverScope() {
return solverScope;
}
public Long getStartingSystemTimeMillis() {
return startingSystemTimeMillis;
}
public <Score_ extends Score<Score_>> Score_ getStartingScore() {
return (Score_) startingScore;
}
public Long getEndingSystemTimeMillis() {
return endingSystemTimeMillis;
}
public int getBestSolutionStepIndex() {
return bestSolutionStepIndex;
}
public void setBestSolutionStepIndex(int bestSolutionStepIndex) {
this.bestSolutionStepIndex = bestSolutionStepIndex;
}
public abstract AbstractStepScope<Solution_> getLastCompletedStepScope();
// ************************************************************************
// Calculated methods
// ************************************************************************
public void reset() {<FILL_FUNCTION_BODY>}
public void startingNow() {
startingSystemTimeMillis = System.currentTimeMillis();
startingScoreCalculationCount = getScoreDirector().getCalculationCount();
}
public void endingNow() {
endingSystemTimeMillis = System.currentTimeMillis();
endingScoreCalculationCount = getScoreDirector().getCalculationCount();
}
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solverScope.getSolutionDescriptor();
}
public long calculateSolverTimeMillisSpentUpToNow() {
return solverScope.calculateTimeMillisSpentUpToNow();
}
public long calculatePhaseTimeMillisSpentUpToNow() {
long now = System.currentTimeMillis();
return now - startingSystemTimeMillis;
}
public long getPhaseTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
public void addChildThreadsScoreCalculationCount(long addition) {
solverScope.addChildThreadsScoreCalculationCount(addition);
childThreadsScoreCalculationCount += addition;
}
public long getPhaseScoreCalculationCount() {
return endingScoreCalculationCount - startingScoreCalculationCount + childThreadsScoreCalculationCount;
}
/**
* @return at least 0, per second
*/
public long getPhaseScoreCalculationSpeed() {
long timeMillisSpent = getPhaseTimeMillisSpent();
// Avoid divide by zero exception on a fast CPU
return getPhaseScoreCalculationCount() * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent);
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return solverScope.getScoreDirector();
}
public Solution_ getWorkingSolution() {
return solverScope.getWorkingSolution();
}
public int getWorkingEntityCount() {
return solverScope.getWorkingEntityCount();
}
public int getWorkingValueCount() {
return solverScope.getWorkingValueCount();
}
public <Score_ extends Score<Score_>> Score_ calculateScore() {
return (Score_) solverScope.calculateScore();
}
public <Score_ extends Score<Score_>> void assertExpectedWorkingScore(Score_ expectedWorkingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertExpectedWorkingScore(expectedWorkingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertWorkingScoreFromScratch(Score_ workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertWorkingScoreFromScratch(workingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertPredictedScoreFromScratch(Score_ workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertPredictedScoreFromScratch(workingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertShadowVariablesAreNotStale(Score_ workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertShadowVariablesAreNotStale(workingScore, completedAction);
}
public Random getWorkingRandom() {
return getSolverScope().getWorkingRandom();
}
public boolean isBestSolutionInitialized() {
return solverScope.isBestSolutionInitialized();
}
public <Score_ extends Score<Score_>> Score_ getBestScore() {
return (Score_) solverScope.getBestScore();
}
public long getPhaseBestSolutionTimeMillis() {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
// If the termination is explicitly phase configured, previous phases must not affect it
if (bestSolutionTimeMillis < startingSystemTimeMillis) {
bestSolutionTimeMillis = startingSystemTimeMillis;
}
return bestSolutionTimeMillis;
}
public int getNextStepIndex() {
return getLastCompletedStepScope().getStepIndex() + 1;
}
@Override
public String toString() {
return getClass().getSimpleName(); // TODO add + "(" + phaseIndex + ")"
}
}
|
bestSolutionStepIndex = -1;
// solverScope.getBestScore() is null with an uninitialized score
startingScore = solverScope.getBestScore() == null ? solverScope.calculateScore() : solverScope.getBestScore();
if (getLastCompletedStepScope().getStepIndex() < 0) {
getLastCompletedStepScope().setScore(startingScore);
}
| 1,623
| 104
| 1,727
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/DefaultScoreExplanation.java
|
DefaultScoreExplanation
|
explainScore
|
class DefaultScoreExplanation<Solution_, Score_ extends Score<Score_>>
implements ScoreExplanation<Solution_, Score_> {
private static final int DEFAULT_SCORE_EXPLANATION_INDICTMENT_LIMIT = 5;
private static final int DEFAULT_SCORE_EXPLANATION_CONSTRAINT_MATCH_LIMIT = 2;
private final Solution_ solution;
private final Score_ score;
private final Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap;
private final List<ConstraintJustification> constraintJustificationList;
private final Map<Object, Indictment<Score_>> indictmentMap;
private final AtomicReference<String> summary = new AtomicReference<>(); // Will be calculated lazily.
public static <Score_ extends Score<Score_>> String explainScore(Score_ workingScore,
Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection,
Collection<Indictment<Score_>> indictmentCollection) {
return explainScore(workingScore, constraintMatchTotalCollection, indictmentCollection,
DEFAULT_SCORE_EXPLANATION_INDICTMENT_LIMIT, DEFAULT_SCORE_EXPLANATION_CONSTRAINT_MATCH_LIMIT);
}
public static <Score_ extends Score<Score_>> String explainScore(Score_ workingScore,
Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection,
Collection<Indictment<Score_>> indictmentCollection, int indictmentLimit, int constraintMatchLimit) {<FILL_FUNCTION_BODY>}
public DefaultScoreExplanation(InnerScoreDirector<Solution_, Score_> scoreDirector) {
this.solution = scoreDirector.getWorkingSolution();
this.score = scoreDirector.calculateScore();
this.constraintMatchTotalMap = scoreDirector.getConstraintMatchTotalMap();
this.constraintJustificationList = constraintMatchTotalMap.values()
.stream()
.flatMap(constraintMatchTotal -> constraintMatchTotal.getConstraintMatchSet().stream())
.map(constraintMatch -> (ConstraintJustification) constraintMatch.getJustification())
.collect(Collectors.toList());
this.indictmentMap = scoreDirector.getIndictmentMap();
}
@Override
public Solution_ getSolution() {
return solution;
}
@Override
public Score_ getScore() {
return score;
}
@Override
public Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() {
return constraintMatchTotalMap;
}
@Override
public List<ConstraintJustification> getJustificationList() {
return constraintJustificationList;
}
@Override
public Map<Object, Indictment<Score_>> getIndictmentMap() {
return indictmentMap;
}
@Override
public String getSummary() {
return summary.updateAndGet(currentSummary -> {
if (currentSummary != null) {
return currentSummary;
}
return explainScore(score, constraintMatchTotalMap.values(), indictmentMap.values());
});
}
@Override
public String toString() {
return getSummary(); // So that this class can be used in strings directly.
}
}
|
StringBuilder scoreExplanation =
new StringBuilder((constraintMatchTotalCollection.size() + 4 + 2 * indictmentLimit) * 80);
scoreExplanation.append("Explanation of score (").append(workingScore).append("):\n");
scoreExplanation.append(" Constraint match totals:\n");
Comparator<ConstraintMatchTotal<Score_>> constraintMatchTotalComparator = comparing(ConstraintMatchTotal::getScore);
Comparator<ConstraintMatch<Score_>> constraintMatchComparator = comparing(ConstraintMatch::getScore);
constraintMatchTotalCollection.stream()
.sorted(constraintMatchTotalComparator)
.forEach(constraintMatchTotal -> {
Set<ConstraintMatch<Score_>> constraintMatchSet = constraintMatchTotal.getConstraintMatchSet();
scoreExplanation
.append(" ").append(constraintMatchTotal.getScore().toShortString())
.append(": constraint (").append(constraintMatchTotal.getConstraintName())
.append(") has ").append(constraintMatchSet.size()).append(" matches:\n");
constraintMatchSet.stream()
.sorted(constraintMatchComparator)
.limit(constraintMatchLimit)
.forEach(constraintMatch -> scoreExplanation
.append(" ")
.append(constraintMatch.getScore().toShortString())
.append(": justifications (")
.append(constraintMatch.getJustification().toString())
.append(")\n"));
if (constraintMatchSet.size() > constraintMatchLimit) {
scoreExplanation.append(" ...\n");
}
});
int indictmentCount = indictmentCollection.size();
if (indictmentLimit < indictmentCount) {
scoreExplanation.append(" Indictments (top ").append(indictmentLimit)
.append(" of ").append(indictmentCount).append("):\n");
} else {
scoreExplanation.append(" Indictments:\n");
}
Comparator<Indictment<Score_>> indictmentComparator = comparing(Indictment::getScore);
Comparator<ConstraintMatch<Score_>> constraintMatchScoreComparator = comparing(ConstraintMatch::getScore);
indictmentCollection.stream()
.sorted(indictmentComparator)
.limit(indictmentLimit)
.forEach(indictment -> {
Set<ConstraintMatch<Score_>> constraintMatchSet = indictment.getConstraintMatchSet();
scoreExplanation
.append(" ").append(indictment.getScore().toShortString())
.append(": indicted object (").append(indictment.getIndictedObject().toString())
.append(") has ").append(constraintMatchSet.size()).append(" matches:\n");
constraintMatchSet.stream()
.sorted(constraintMatchScoreComparator)
.limit(constraintMatchLimit)
.forEach(constraintMatch -> scoreExplanation
.append(" ").append(constraintMatch.getScore().toShortString())
.append(": constraint (").append(constraintMatch.getConstraintName())
.append(")\n"));
if (constraintMatchSet.size() > constraintMatchLimit) {
scoreExplanation.append(" ...\n");
}
});
if (indictmentCount > indictmentLimit) {
scoreExplanation.append(" ...\n");
}
return scoreExplanation.toString();
| 835
| 860
| 1,695
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/BendableBigDecimalScoreDefinition.java
|
BendableBigDecimalScoreDefinition
|
fromLevelNumbers
|
class BendableBigDecimalScoreDefinition extends AbstractBendableScoreDefinition<BendableBigDecimalScore> {
public BendableBigDecimalScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableBigDecimalScore> getScoreClass() {
return BendableBigDecimalScore.class;
}
@Override
public BendableBigDecimalScore getZeroScore() {
return BendableBigDecimalScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableBigDecimalScore getOneSoftestScore() {
return BendableBigDecimalScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, BigDecimal.ONE);
}
@Override
public BendableBigDecimalScore parseScore(String scoreString) {
BendableBigDecimalScore score = BendableBigDecimalScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableBigDecimalScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableBigDecimalScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) {<FILL_FUNCTION_BODY>}
public BendableBigDecimalScore createScore(BigDecimal... scores) {
return createScoreUninitialized(0, scores);
}
public BendableBigDecimalScore createScoreUninitialized(int initScore, BigDecimal... scores) {
int levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableBigDecimalScore.ofUninitialized(initScore,
Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public BendableBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public BendableBigDecimalScore divideBySanitizedDivisor(BendableBigDecimalScore dividend,
BendableBigDecimalScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
BigDecimal[] hardScores = new BigDecimal[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
BigDecimal[] softScores = new BigDecimal[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
BigDecimal[] levels = Stream.concat(Arrays.stream(hardScores), Arrays.stream(softScores))
.toArray(BigDecimal[]::new);
return createScoreUninitialized(divide(dividendInitScore, divisorInitScore), levels);
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
BigDecimal[] hardScores = new BigDecimal[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (BigDecimal) levelNumbers[i];
}
BigDecimal[] softScores = new BigDecimal[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (BigDecimal) levelNumbers[hardLevelsSize + i];
}
return BendableBigDecimalScore.ofUninitialized(initScore, hardScores, softScores);
| 1,336
| 242
| 1,578
|
<methods>public void <init>(int, int) ,public int getFeasibleLevelsSize() ,public int getHardLevelsSize() ,public int getLevelsSize() ,public int getSoftLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) <variables>protected final non-sealed int hardLevelsSize,protected final non-sealed int softLevelsSize
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/BendableScoreDefinition.java
|
BendableScoreDefinition
|
buildOptimisticBound
|
class BendableScoreDefinition extends AbstractBendableScoreDefinition<BendableScore> {
public BendableScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableScore> getScoreClass() {
return BendableScore.class;
}
@Override
public BendableScore getZeroScore() {
return BendableScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableScore getOneSoftestScore() {
return BendableScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, 1);
}
@Override
public BendableScore parseScore(String scoreString) {
BendableScore score = BendableScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (Integer) levelNumbers[i];
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (Integer) levelNumbers[hardLevelsSize + i];
}
return BendableScore.ofUninitialized(initScore, hardScores, softScores);
}
public BendableScore createScore(int... scores) {
return createScoreUninitialized(0, scores);
}
public BendableScore createScoreUninitialized(int initScore, int... scores) {
int levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableScore.ofUninitialized(initScore,
Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, BendableScore score) {<FILL_FUNCTION_BODY>}
@Override
public BendableScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, BendableScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_UP)
? score.hardScore(i)
: Integer.MIN_VALUE;
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_UP)
? score.softScore(i)
: Integer.MIN_VALUE;
}
return BendableScore.ofUninitialized(0, hardScores, softScores);
}
@Override
public BendableScore divideBySanitizedDivisor(BendableScore dividend, BendableScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
int[] levels = IntStream.concat(Arrays.stream(hardScores), Arrays.stream(softScores)).toArray();
return createScoreUninitialized(divide(dividendInitScore, divisorInitScore), levels);
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.hardScore(i)
: Integer.MAX_VALUE;
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.softScore(i)
: Integer.MAX_VALUE;
}
return BendableScore.ofUninitialized(0, hardScores, softScores);
| 1,562
| 240
| 1,802
|
<methods>public void <init>(int, int) ,public int getFeasibleLevelsSize() ,public int getHardLevelsSize() ,public int getLevelsSize() ,public int getSoftLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) <variables>protected final non-sealed int hardLevelsSize,protected final non-sealed int softLevelsSize
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/HardMediumSoftBigDecimalScoreDefinition.java
|
HardMediumSoftBigDecimalScoreDefinition
|
buildPessimisticBound
|
class HardMediumSoftBigDecimalScoreDefinition extends AbstractScoreDefinition<HardMediumSoftBigDecimalScore> {
public HardMediumSoftBigDecimalScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftBigDecimalScore> getScoreClass() {
return HardMediumSoftBigDecimalScore.class;
}
@Override
public HardMediumSoftBigDecimalScore getZeroScore() {
return HardMediumSoftBigDecimalScore.ZERO;
}
@Override
public HardMediumSoftBigDecimalScore getOneSoftestScore() {
return HardMediumSoftBigDecimalScore.ONE_SOFT;
}
@Override
public HardMediumSoftBigDecimalScore parseScore(String scoreString) {
return HardMediumSoftBigDecimalScore.parseScore(scoreString);
}
@Override
public HardMediumSoftBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftBigDecimalScore.ofUninitialized(initScore, (BigDecimal) levelNumbers[0],
(BigDecimal) levelNumbers[1], (BigDecimal) levelNumbers[2]);
}
@Override
public HardMediumSoftBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public HardMediumSoftBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftBigDecimalScore score) {<FILL_FUNCTION_BODY>}
@Override
public HardMediumSoftBigDecimalScore divideBySanitizedDivisor(HardMediumSoftBigDecimalScore dividend,
HardMediumSoftBigDecimalScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
BigDecimal dividendHardScore = dividend.hardScore();
BigDecimal divisorHardScore = sanitize(divisor.hardScore());
BigDecimal dividendMediumScore = dividend.mediumScore();
BigDecimal divisorMediumScore = sanitize(divisor.mediumScore());
BigDecimal dividendSoftScore = dividend.softScore();
BigDecimal divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
| 946
| 65
| 1,011
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/HardMediumSoftLongScoreDefinition.java
|
HardMediumSoftLongScoreDefinition
|
fromLevelNumbers
|
class HardMediumSoftLongScoreDefinition extends AbstractScoreDefinition<HardMediumSoftLongScore> {
public HardMediumSoftLongScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftLongScore> getScoreClass() {
return HardMediumSoftLongScore.class;
}
@Override
public HardMediumSoftLongScore getZeroScore() {
return HardMediumSoftLongScore.ZERO;
}
@Override
public HardMediumSoftLongScore getOneSoftestScore() {
return HardMediumSoftLongScore.ONE_SOFT;
}
@Override
public HardMediumSoftLongScore parseScore(String scoreString) {
return HardMediumSoftLongScore.parseScore(scoreString);
}
@Override
public HardMediumSoftLongScore fromLevelNumbers(int initScore, Number[] levelNumbers) {<FILL_FUNCTION_BODY>}
@Override
public HardMediumSoftLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftLongScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardMediumSoftLongScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Long.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.mediumScore() : Long.MAX_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Long.MAX_VALUE);
}
@Override
public HardMediumSoftLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftLongScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardMediumSoftLongScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Long.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.mediumScore() : Long.MIN_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Long.MIN_VALUE);
}
@Override
public HardMediumSoftLongScore divideBySanitizedDivisor(HardMediumSoftLongScore dividend,
HardMediumSoftLongScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
long dividendHardScore = dividend.hardScore();
long divisorHardScore = sanitize(divisor.hardScore());
long dividendMediumScore = dividend.mediumScore();
long divisorMediumScore = sanitize(divisor.mediumScore());
long dividendSoftScore = dividend.softScore();
long divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftLongScore.ofUninitialized(initScore, (Long) levelNumbers[0], (Long) levelNumbers[1],
(Long) levelNumbers[2]);
| 987
| 125
| 1,112
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/HardMediumSoftScoreDefinition.java
|
HardMediumSoftScoreDefinition
|
fromLevelNumbers
|
class HardMediumSoftScoreDefinition extends AbstractScoreDefinition<HardMediumSoftScore> {
public HardMediumSoftScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftScore> getScoreClass() {
return HardMediumSoftScore.class;
}
@Override
public HardMediumSoftScore getZeroScore() {
return HardMediumSoftScore.ZERO;
}
@Override
public HardMediumSoftScore getOneSoftestScore() {
return HardMediumSoftScore.ONE_SOFT;
}
@Override
public HardMediumSoftScore parseScore(String scoreString) {
return HardMediumSoftScore.parseScore(scoreString);
}
@Override
public HardMediumSoftScore fromLevelNumbers(int initScore, Number[] levelNumbers) {<FILL_FUNCTION_BODY>}
@Override
public HardMediumSoftScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardMediumSoftScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Integer.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.mediumScore() : Integer.MAX_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Integer.MAX_VALUE);
}
@Override
public HardMediumSoftScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardMediumSoftScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Integer.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.mediumScore() : Integer.MIN_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Integer.MIN_VALUE);
}
@Override
public HardMediumSoftScore divideBySanitizedDivisor(HardMediumSoftScore dividend, HardMediumSoftScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
int dividendHardScore = dividend.hardScore();
int divisorHardScore = sanitize(divisor.hardScore());
int dividendMediumScore = dividend.mediumScore();
int divisorMediumScore = sanitize(divisor.mediumScore());
int dividendSoftScore = dividend.softScore();
int divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftScore.ofUninitialized(initScore, (Integer) levelNumbers[0], (Integer) levelNumbers[1],
(Integer) levelNumbers[2]);
| 964
| 124
| 1,088
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/HardSoftLongScoreDefinition.java
|
HardSoftLongScoreDefinition
|
fromLevelNumbers
|
class HardSoftLongScoreDefinition extends AbstractScoreDefinition<HardSoftLongScore> {
public HardSoftLongScoreDefinition() {
super(new String[] { "hard score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 2;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardSoftLongScore> getScoreClass() {
return HardSoftLongScore.class;
}
@Override
public HardSoftLongScore getZeroScore() {
return HardSoftLongScore.ZERO;
}
@Override
public HardSoftLongScore getOneSoftestScore() {
return HardSoftLongScore.ONE_SOFT;
}
@Override
public HardSoftLongScore parseScore(String scoreString) {
return HardSoftLongScore.parseScore(scoreString);
}
@Override
public HardSoftLongScore fromLevelNumbers(int initScore, Number[] levelNumbers) {<FILL_FUNCTION_BODY>}
@Override
public HardSoftLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardSoftLongScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardSoftLongScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Long.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Long.MAX_VALUE);
}
@Override
public HardSoftLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardSoftLongScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardSoftLongScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Long.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Long.MIN_VALUE);
}
@Override
public HardSoftLongScore divideBySanitizedDivisor(HardSoftLongScore dividend, HardSoftLongScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
long dividendHardScore = dividend.hardScore();
long divisorHardScore = sanitize(divisor.hardScore());
long dividendSoftScore = dividend.softScore();
long divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardSoftLongScore.ofUninitialized(initScore, (Long) levelNumbers[0], (Long) levelNumbers[1]);
| 821
| 112
| 933
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/HardSoftScoreDefinition.java
|
HardSoftScoreDefinition
|
buildOptimisticBound
|
class HardSoftScoreDefinition extends AbstractScoreDefinition<HardSoftScore> {
public HardSoftScoreDefinition() {
super(new String[] { "hard score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardSoftScore> getScoreClass() {
return HardSoftScore.class;
}
@Override
public HardSoftScore getZeroScore() {
return HardSoftScore.ZERO;
}
@Override
public HardSoftScore getOneSoftestScore() {
return HardSoftScore.ONE_SOFT;
}
@Override
public HardSoftScore parseScore(String scoreString) {
return HardSoftScore.parseScore(scoreString);
}
@Override
public HardSoftScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardSoftScore.ofUninitialized(initScore, (Integer) levelNumbers[0], (Integer) levelNumbers[1]);
}
@Override
public HardSoftScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftScore score) {<FILL_FUNCTION_BODY>}
@Override
public HardSoftScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardSoftScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Integer.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Integer.MIN_VALUE);
}
@Override
public HardSoftScore divideBySanitizedDivisor(HardSoftScore dividend, HardSoftScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
int dividendHardScore = dividend.hardScore();
int divisorHardScore = sanitize(divisor.hardScore());
int dividendSoftScore = dividend.softScore();
int divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return HardSoftScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Integer.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Integer.MAX_VALUE);
| 773
| 110
| 883
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/SimpleBigDecimalScoreDefinition.java
|
SimpleBigDecimalScoreDefinition
|
buildPessimisticBound
|
class SimpleBigDecimalScoreDefinition extends AbstractScoreDefinition<SimpleBigDecimalScore> {
public SimpleBigDecimalScoreDefinition() {
super(new String[] { "score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 1;
}
@Override
public int getFeasibleLevelsSize() {
return 0;
}
@Override
public Class<SimpleBigDecimalScore> getScoreClass() {
return SimpleBigDecimalScore.class;
}
@Override
public SimpleBigDecimalScore getZeroScore() {
return SimpleBigDecimalScore.ZERO;
}
@Override
public SimpleBigDecimalScore getOneSoftestScore() {
return SimpleBigDecimalScore.ONE;
}
@Override
public SimpleBigDecimalScore parseScore(String scoreString) {
return SimpleBigDecimalScore.parseScore(scoreString);
}
@Override
public SimpleBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return SimpleBigDecimalScore.ofUninitialized(initScore, (BigDecimal) levelNumbers[0]);
}
@Override
public SimpleBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
SimpleBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public SimpleBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
SimpleBigDecimalScore score) {<FILL_FUNCTION_BODY>}
@Override
public SimpleBigDecimalScore divideBySanitizedDivisor(SimpleBigDecimalScore dividend,
SimpleBigDecimalScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
BigDecimal dividendScore = dividend.score();
BigDecimal divisorScore = sanitize(divisor.score());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendScore, divisorScore)
});
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
| 738
| 65
| 803
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/buildin/SimpleScoreDefinition.java
|
SimpleScoreDefinition
|
fromLevelNumbers
|
class SimpleScoreDefinition extends AbstractScoreDefinition<SimpleScore> {
public SimpleScoreDefinition() {
super(new String[] { "score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 1;
}
@Override
public int getFeasibleLevelsSize() {
return 0;
}
@Override
public Class<SimpleScore> getScoreClass() {
return SimpleScore.class;
}
@Override
public SimpleScore getZeroScore() {
return SimpleScore.ZERO;
}
@Override
public SimpleScore getOneSoftestScore() {
return SimpleScore.ONE;
}
@Override
public SimpleScore parseScore(String scoreString) {
return SimpleScore.parseScore(scoreString);
}
@Override
public SimpleScore fromLevelNumbers(int initScore, Number[] levelNumbers) {<FILL_FUNCTION_BODY>}
@Override
public SimpleScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return SimpleScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.score() : Integer.MAX_VALUE);
}
@Override
public SimpleScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
return SimpleScore.ofUninitialized(0,
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.score() : Integer.MIN_VALUE);
}
@Override
public SimpleScore divideBySanitizedDivisor(SimpleScore dividend, SimpleScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
int dividendScore = dividend.score();
int divisorScore = sanitize(divisor.score());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendScore, divisorScore)
});
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return SimpleScore.ofUninitialized(initScore, (Integer) levelNumbers[0]);
| 645
| 101
| 746
|
<methods>public void <init>(java.lang.String[]) ,public java.lang.String formatScore(org.optaplanner.core.api.score.buildin.simple.SimpleScore) ,public java.lang.String getInitLabel() ,public java.lang.String[] getLevelLabels() ,public int getLevelsSize() ,public boolean isCompatibleArithmeticArgument(Score#RAW) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String[] levelLabels
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/constraint/DefaultConstraintMatchTotal.java
|
DefaultConstraintMatchTotal
|
addConstraintMatch
|
class DefaultConstraintMatchTotal<Score_ extends Score<Score_>> implements ConstraintMatchTotal<Score_>,
Comparable<DefaultConstraintMatchTotal<Score_>> {
private final String constraintPackage;
private final String constraintName;
private final String constraintId;
private final Score_ constraintWeight;
private final Set<ConstraintMatch<Score_>> constraintMatchSet = new LinkedHashSet<>();
private Score_ score;
public DefaultConstraintMatchTotal(String constraintPackage, String constraintName) {
this.constraintPackage = requireNonNull(constraintPackage);
this.constraintName = requireNonNull(constraintName);
this.constraintId = ConstraintMatchTotal.composeConstraintId(constraintPackage, constraintName);
this.constraintWeight = null;
}
public DefaultConstraintMatchTotal(String constraintPackage, String constraintName, Score_ constraintWeight) {
this.constraintPackage = requireNonNull(constraintPackage);
this.constraintName = requireNonNull(constraintName);
this.constraintId = ConstraintMatchTotal.composeConstraintId(constraintPackage, constraintName);
this.constraintWeight = requireNonNull(constraintWeight);
this.score = constraintWeight.zero();
}
@Override
public String getConstraintPackage() {
return constraintPackage;
}
@Override
public String getConstraintName() {
return constraintName;
}
@Override
public Score_ getConstraintWeight() {
return constraintWeight;
}
@Override
public Set<ConstraintMatch<Score_>> getConstraintMatchSet() {
return constraintMatchSet;
}
@Override
public Score_ getScore() {
return score;
}
// ************************************************************************
// Worker methods
// ************************************************************************
/**
* Creates a {@link ConstraintMatch} and adds it to the collection returned by {@link #getConstraintMatchSet()}.
* It will use {@link DefaultConstraintJustification},
* whose {@link DefaultConstraintJustification#getFacts()} method will return the given list of justifications.
* Additionally, the constraint match will indict the objects in the given list of justifications.
*
* @param justifications never null, never empty
* @param score never null
* @return never null
*/
public ConstraintMatch<Score_> addConstraintMatch(List<Object> justifications, Score_ score) {
return addConstraintMatch(DefaultConstraintJustification.of(score, justifications), justifications, score);
}
/**
* Creates a {@link ConstraintMatch} and adds it to the collection returned by {@link #getConstraintMatchSet()}.
* It will the provided {@link ConstraintJustification}.
* Additionally, the constraint match will indict the objects in the given list of indicted objects.
*
* @param indictedObjects never null, may be empty
* @param score never null
* @return never null
*/
public ConstraintMatch<Score_> addConstraintMatch(ConstraintJustification justification, Collection<Object> indictedObjects,
Score_ score) {<FILL_FUNCTION_BODY>}
public void removeConstraintMatch(ConstraintMatch<Score_> constraintMatch) {
score = score.subtract(constraintMatch.getScore());
boolean removed = constraintMatchSet.remove(constraintMatch);
if (!removed) {
throw new IllegalStateException("The constraintMatchTotal (" + this
+ ") could not remove constraintMatch (" + constraintMatch
+ ") from its constraintMatchSet (" + constraintMatchSet + ").");
}
}
// ************************************************************************
// Infrastructure methods
// ************************************************************************
@Override
public String getConstraintId() {
return constraintId;
}
@Override
public int compareTo(DefaultConstraintMatchTotal<Score_> other) {
return constraintId.compareTo(other.constraintId);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof DefaultConstraintMatchTotal) {
DefaultConstraintMatchTotal<Score_> other = (DefaultConstraintMatchTotal<Score_>) o;
return constraintPackage.equals(other.constraintPackage)
&& constraintName.equals(other.constraintName);
} else {
return false;
}
}
@Override
public int hashCode() {
return hash(constraintPackage, constraintName);
}
@Override
public String toString() {
return getConstraintId() + "=" + score;
}
}
|
this.score = this.score == null ? score : this.score.add(score);
ConstraintMatch<Score_> constraintMatch = new ConstraintMatch<>(constraintPackage, constraintName,
justification, indictedObjects, score);
constraintMatchSet.add(constraintMatch);
return constraintMatch;
| 1,133
| 77
| 1,210
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/constraint/DefaultIndictment.java
|
DefaultIndictment
|
addConstraintMatch
|
class DefaultIndictment<Score_ extends Score<Score_>> implements Indictment<Score_> {
private final Object indictedObject;
private final Set<ConstraintMatch<Score_>> constraintMatchSet = new LinkedHashSet<>();
private List<ConstraintJustification> constraintJustificationList;
private Score_ score;
public DefaultIndictment(Object indictedObject, Score_ zeroScore) {
this.indictedObject = indictedObject;
this.score = zeroScore;
}
@Override
public <IndictedObject_> IndictedObject_ getIndictedObject() {
return (IndictedObject_) indictedObject;
}
@Override
public Set<ConstraintMatch<Score_>> getConstraintMatchSet() {
return constraintMatchSet;
}
@Override
public List<ConstraintJustification> getJustificationList() {
if (constraintJustificationList == null) {
constraintJustificationList = constraintMatchSet.stream()
.map(s -> (ConstraintJustification) s.getJustification())
.distinct()
.collect(Collectors.toList());
}
return constraintJustificationList;
}
@Override
public Score_ getScore() {
return score;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public void addConstraintMatch(ConstraintMatch<Score_> constraintMatch) {<FILL_FUNCTION_BODY>}
public void removeConstraintMatch(ConstraintMatch<Score_> constraintMatch) {
score = score.subtract(constraintMatch.getScore());
boolean removed = constraintMatchSet.remove(constraintMatch);
if (!removed) {
throw new IllegalStateException("The indictment (" + this
+ ") could not remove constraintMatch (" + constraintMatch
+ ") from its constraintMatchSet (" + constraintMatchSet + ").");
}
constraintJustificationList = null; // Rebuild later.
}
// ************************************************************************
// Infrastructure methods
// ************************************************************************
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof DefaultIndictment) {
DefaultIndictment<Score_> other = (DefaultIndictment<Score_>) o;
return indictedObject.equals(other.indictedObject);
} else {
return false;
}
}
@Override
public int hashCode() {
return indictedObject.hashCode();
}
@Override
public String toString() {
return indictedObject + "=" + score;
}
}
|
score = score.add(constraintMatch.getScore());
boolean added = constraintMatchSet.add(constraintMatch);
if (!added) {
throw new IllegalStateException("The indictment (" + this
+ ") could not add constraintMatch (" + constraintMatch
+ ") to its constraintMatchSet (" + constraintMatchSet + ").");
}
constraintJustificationList = null; // Rebuild later.
| 666
| 101
| 767
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/director/AbstractScoreDirectorFactory.java
|
AbstractScoreDirectorFactory
|
assertScoreFromScratch
|
class AbstractScoreDirectorFactory<Solution_, Score_ extends Score<Score_>>
implements InnerScoreDirectorFactory<Solution_, Score_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected SolutionDescriptor<Solution_> solutionDescriptor;
protected InitializingScoreTrend initializingScoreTrend;
protected InnerScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory = null;
protected boolean assertClonedSolution = false;
public AbstractScoreDirectorFactory(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
}
@Override
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solutionDescriptor;
}
@Override
public ScoreDefinition<Score_> getScoreDefinition() {
return solutionDescriptor.getScoreDefinition();
}
@Override
public InitializingScoreTrend getInitializingScoreTrend() {
return initializingScoreTrend;
}
public void setInitializingScoreTrend(InitializingScoreTrend initializingScoreTrend) {
this.initializingScoreTrend = initializingScoreTrend;
}
public InnerScoreDirectorFactory<Solution_, Score_> getAssertionScoreDirectorFactory() {
return assertionScoreDirectorFactory;
}
public void setAssertionScoreDirectorFactory(InnerScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory) {
this.assertionScoreDirectorFactory = assertionScoreDirectorFactory;
}
public boolean isAssertClonedSolution() {
return assertClonedSolution;
}
public void setAssertClonedSolution(boolean assertClonedSolution) {
this.assertClonedSolution = assertClonedSolution;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public InnerScoreDirector<Solution_, Score_> buildScoreDirector() {
return buildScoreDirector(true, true);
}
@Override
public void assertScoreFromScratch(Solution_ solution) {<FILL_FUNCTION_BODY>}
}
|
// Get the score before uncorruptedScoreDirector.calculateScore() modifies it
Score_ score = (Score_) getSolutionDescriptor().getScore(solution);
try (InnerScoreDirector<Solution_, Score_> uncorruptedScoreDirector = buildScoreDirector(false, true)) {
uncorruptedScoreDirector.setWorkingSolution(solution);
Score_ uncorruptedScore = uncorruptedScoreDirector.calculateScore();
if (!score.equals(uncorruptedScore)) {
throw new IllegalStateException(
"Score corruption (" + score.subtract(uncorruptedScore).toShortString()
+ "): the solution's score (" + score + ") is not the uncorruptedScore ("
+ uncorruptedScore + ").");
}
}
| 560
| 201
| 761
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/director/easy/EasyScoreDirector.java
|
EasyScoreDirector
|
calculateScore
|
class EasyScoreDirector<Solution_, Score_ extends Score<Score_>>
extends AbstractScoreDirector<Solution_, Score_, EasyScoreDirectorFactory<Solution_, Score_>> {
private final EasyScoreCalculator<Solution_, Score_> easyScoreCalculator;
public EasyScoreDirector(EasyScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory,
boolean lookUpEnabled, boolean constraintMatchEnabledPreference,
EasyScoreCalculator<Solution_, Score_> easyScoreCalculator) {
super(scoreDirectorFactory, lookUpEnabled, constraintMatchEnabledPreference);
this.easyScoreCalculator = easyScoreCalculator;
}
public EasyScoreCalculator<Solution_, Score_> getEasyScoreCalculator() {
return easyScoreCalculator;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public Score_ calculateScore() {<FILL_FUNCTION_BODY>}
/**
* Always false, {@link ConstraintMatchTotal}s are not supported by this {@link ScoreDirector} implementation.
*
* @return false
*/
@Override
public boolean isConstraintMatchEnabled() {
return false;
}
/**
* {@link ConstraintMatch}s are not supported by this {@link ScoreDirector} implementation.
*
* @throws IllegalStateException always
* @return throws {@link IllegalStateException}
*/
@Override
public Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() {
throw new IllegalStateException(ConstraintMatch.class.getSimpleName()
+ " is not supported by " + EasyScoreDirector.class.getSimpleName() + ".");
}
/**
* {@link ConstraintMatch}s are not supported by this {@link ScoreDirector} implementation.
*
* @throws IllegalStateException always
* @return throws {@link IllegalStateException}
*/
@Override
public Map<Object, Indictment<Score_>> getIndictmentMap() {
throw new IllegalStateException(ConstraintMatch.class.getSimpleName()
+ " is not supported by " + EasyScoreDirector.class.getSimpleName() + ".");
}
@Override
public boolean requiresFlushing() {
return false; // Every score calculation starts from scratch; nothing is saved.
}
}
|
variableListenerSupport.assertNotificationQueuesAreEmpty();
Score_ score = easyScoreCalculator.calculateScore(workingSolution);
if (score == null) {
throw new IllegalStateException("The easyScoreCalculator (" + easyScoreCalculator.getClass()
+ ") must return a non-null score (" + score + ") in the method calculateScore().");
} else if (!score.isSolutionInitialized()) {
throw new IllegalStateException("The score (" + this + ")'s initScore (" + score.initScore()
+ ") should be 0.\n"
+ "Maybe the score calculator (" + easyScoreCalculator.getClass() + ") is calculating "
+ "the initScore too, although it's the score director's responsibility.");
}
if (workingInitScore != 0) {
score = score.withInitScore(workingInitScore);
}
setCalculatedScore(score);
return score;
| 604
| 233
| 837
|
<methods>public final void afterEntityAdded(java.lang.Object) ,public void afterEntityAdded(EntityDescriptor<Solution_>, java.lang.Object) ,public final void afterEntityRemoved(java.lang.Object) ,public void afterEntityRemoved(EntityDescriptor<Solution_>, java.lang.Object) ,public void afterListVariableChanged(java.lang.Object, java.lang.String, int, int) ,public void afterListVariableChanged(ListVariableDescriptor<Solution_>, java.lang.Object, int, int) ,public void afterListVariableElementAssigned(java.lang.Object, java.lang.String, java.lang.Object) ,public void afterListVariableElementAssigned(ListVariableDescriptor<Solution_>, java.lang.Object) ,public void afterListVariableElementUnassigned(java.lang.Object, java.lang.String, java.lang.Object) ,public void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_>, java.lang.Object) ,public void afterProblemFactAdded(java.lang.Object) ,public void afterProblemFactRemoved(java.lang.Object) ,public void afterProblemPropertyChanged(java.lang.Object) ,public final void afterVariableChanged(java.lang.Object, java.lang.String) ,public void afterVariableChanged(VariableDescriptor<Solution_>, java.lang.Object) ,public void assertExpectedUndoMoveScore(Move<Solution_>, Score_) ,public void assertExpectedWorkingScore(Score_, java.lang.Object) ,public void assertNonNullPlanningIds() ,public void assertPredictedScoreFromScratch(Score_, java.lang.Object) ,public void assertShadowVariablesAreNotStale(Score_, java.lang.Object) ,public void assertWorkingScoreFromScratch(Score_, java.lang.Object) ,public final void beforeEntityAdded(java.lang.Object) ,public void beforeEntityAdded(EntityDescriptor<Solution_>, java.lang.Object) ,public final void beforeEntityRemoved(java.lang.Object) ,public void beforeEntityRemoved(EntityDescriptor<Solution_>, java.lang.Object) ,public void beforeListVariableChanged(java.lang.Object, java.lang.String, int, int) ,public void beforeListVariableChanged(ListVariableDescriptor<Solution_>, java.lang.Object, int, int) ,public void beforeListVariableElementAssigned(java.lang.Object, java.lang.String, java.lang.Object) ,public void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_>, java.lang.Object) ,public void beforeListVariableElementUnassigned(java.lang.Object, java.lang.String, java.lang.Object) ,public void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_>, java.lang.Object) ,public void beforeProblemFactAdded(java.lang.Object) ,public void beforeProblemFactRemoved(java.lang.Object) ,public void beforeProblemPropertyChanged(java.lang.Object) ,public final void beforeVariableChanged(java.lang.Object, java.lang.String) ,public void beforeVariableChanged(VariableDescriptor<Solution_>, java.lang.Object) ,public void changeVariableFacade(VariableDescriptor<Solution_>, java.lang.Object, java.lang.Object) ,public AbstractScoreDirector<Solution_,Score_,EasyScoreDirectorFactory<Solution_,Score_>> clone() ,public Solution_ cloneSolution(Solution_) ,public Solution_ cloneWorkingSolution() ,public void close() ,public InnerScoreDirector<Solution_,Score_> createChildThreadScoreDirector(org.optaplanner.core.impl.solver.thread.ChildThreadType) ,public Score_ doAndProcessMove(Move<Solution_>, boolean) ,public void doAndProcessMove(Move<Solution_>, boolean, Consumer<Score_>) ,public void forceTriggerVariableListeners() ,public long getCalculationCount() ,public ScoreDefinition<Score_> getScoreDefinition() ,public EasyScoreDirectorFactory<Solution_,Score_> getScoreDirectorFactory() ,public SolutionDescriptor<Solution_> getSolutionDescriptor() ,public org.optaplanner.core.impl.domain.variable.supply.SupplyManager getSupplyManager() ,public long getWorkingEntityListRevision() ,public Solution_ getWorkingSolution() ,public void incrementCalculationCount() ,public boolean isWorkingEntityListDirty(long) ,public E lookUpWorkingObject(E) ,public E lookUpWorkingObjectOrReturnNull(E) ,public void overwriteConstraintMatchEnabledPreference(boolean) ,public void resetCalculationCount() ,public void setAllChangesWillBeUndoneBeforeStepEnds(boolean) ,public void setWorkingSolution(Solution_) ,public java.lang.String toString() ,public void triggerVariableListeners() <variables>protected boolean allChangesWillBeUndoneBeforeStepEnds,protected long calculationCount,protected boolean constraintMatchEnabledPreference,protected final transient Logger logger,protected final non-sealed boolean lookUpEnabled,protected final non-sealed org.optaplanner.core.impl.domain.lookup.LookUpManager lookUpManager,private final Map<Class#RAW,org.optaplanner.core.impl.domain.common.accessor.MemberAccessor> planningIdAccessorCacheMap,protected final non-sealed EasyScoreDirectorFactory<Solution_,Score_> scoreDirectorFactory,protected final non-sealed VariableListenerSupport<Solution_> variableListenerSupport,protected long workingEntityListRevision,protected java.lang.Integer workingInitScore,protected Solution_ workingSolution
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/director/incremental/IncrementalScoreDirectorFactoryService.java
|
IncrementalScoreDirectorFactoryService
|
buildScoreDirectorFactory
|
class IncrementalScoreDirectorFactoryService<Solution_, Score_ extends Score<Score_>>
implements ScoreDirectorFactoryService<Solution_, Score_> {
@Override
public ScoreDirectorType getSupportedScoreDirectorType() {
return ScoreDirectorType.INCREMENTAL;
}
@Override
public Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> buildScoreDirectorFactory(ClassLoader classLoader,
SolutionDescriptor<Solution_> solutionDescriptor, ScoreDirectorFactoryConfig config,
EnvironmentMode environmentMode) {<FILL_FUNCTION_BODY>}
}
|
if (config.getIncrementalScoreCalculatorClass() != null) {
if (!IncrementalScoreCalculator.class.isAssignableFrom(config.getIncrementalScoreCalculatorClass())) {
throw new IllegalArgumentException(
"The incrementalScoreCalculatorClass (" + config.getIncrementalScoreCalculatorClass()
+ ") does not implement " + IncrementalScoreCalculator.class.getSimpleName() + ".");
}
return () -> new IncrementalScoreDirectorFactory<>(solutionDescriptor, () -> {
IncrementalScoreCalculator<Solution_, Score_> incrementalScoreCalculator = ConfigUtils.newInstance(config,
"incrementalScoreCalculatorClass", config.getIncrementalScoreCalculatorClass());
ConfigUtils.applyCustomProperties(incrementalScoreCalculator, "incrementalScoreCalculatorClass",
config.getIncrementalScoreCalculatorCustomProperties(), "incrementalScoreCalculatorCustomProperties");
return incrementalScoreCalculator;
});
} else {
if (config.getIncrementalScoreCalculatorCustomProperties() != null) {
throw new IllegalStateException(
"If there is no incrementalScoreCalculatorClass (" + config.getIncrementalScoreCalculatorClass()
+ "), then there can be no incrementalScoreCalculatorCustomProperties ("
+ config.getIncrementalScoreCalculatorCustomProperties() + ") either.");
}
return null;
}
| 159
| 366
| 525
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/score/stream/JoinerSupport.java
|
JoinerSupport
|
getJoinerService
|
class JoinerSupport {
private static volatile JoinerService INSTANCE;
public static JoinerService getJoinerService() {<FILL_FUNCTION_BODY>}
}
|
if (INSTANCE == null) {
synchronized (JoinerSupport.class) {
if (INSTANCE == null) {
Iterator<JoinerService> servicesIterator = ServiceLoader.load(JoinerService.class).iterator();
if (!servicesIterator.hasNext()) {
throw new IllegalStateException("Joiners not found.\n"
+ "Maybe include org.optaplanner:optaplanner-constraint-streams dependency in your project?\n"
+ "Maybe ensure your uberjar bundles META-INF/services from included JAR files?");
} else {
INSTANCE = servicesIterator.next();
}
}
}
}
return INSTANCE;
| 47
| 177
| 224
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/BestSolutionHolder.java
|
BestSolutionHolder
|
addProblemChange
|
class BestSolutionHolder<Solution_> {
private final Lock problemChangesLock = new ReentrantLock();
private final AtomicReference<VersionedBestSolution<Solution_>> versionedBestSolutionRef = new AtomicReference<>();
private final SortedMap<BigInteger, List<CompletableFuture<Void>>> problemChangesPerVersion =
new TreeMap<>();
private BigInteger currentVersion = BigInteger.ZERO;
boolean isEmpty() {
return versionedBestSolutionRef.get() == null;
}
/**
* NOT thread-safe.
*
* @return the last best solution together with problem changes the solution contains.
*/
BestSolutionContainingProblemChanges<Solution_> take() {
VersionedBestSolution<Solution_> versionedBestSolution = versionedBestSolutionRef.getAndSet(null);
if (versionedBestSolution == null) {
return null;
}
SortedMap<BigInteger, List<CompletableFuture<Void>>> containedProblemChangesPerVersion =
problemChangesPerVersion.headMap(versionedBestSolution.getVersion().add(BigInteger.ONE));
List<CompletableFuture<Void>> containedProblemChanges = new ArrayList<>();
for (Map.Entry<BigInteger, List<CompletableFuture<Void>>> entry : containedProblemChangesPerVersion.entrySet()) {
containedProblemChanges.addAll(entry.getValue());
problemChangesPerVersion.remove(entry.getKey());
}
return new BestSolutionContainingProblemChanges<>(versionedBestSolution.getBestSolution(),
containedProblemChanges);
}
/**
* Sets the new best solution if all known problem changes have been processed and thus are contained in this
* best solution.
*
* @param bestSolution the new best solution that replaces the previous one if there is any
* @param isEveryProblemChangeProcessed a supplier that tells if all problem changes have been processed
*/
void set(Solution_ bestSolution, BooleanSupplier isEveryProblemChangeProcessed) {
problemChangesLock.lock();
try {
/*
* The new best solution can be accepted only if there are no pending problem changes nor any additional
* changes may come during this operation. Otherwise, a race condition might occur that leads to associating
* problem changes with a solution that was created later, but does not contain them yet.
* As a result, CompletableFutures representing these changes would be completed too early.
*/
if (isEveryProblemChangeProcessed.getAsBoolean()) {
versionedBestSolutionRef.set(new VersionedBestSolution(bestSolution, currentVersion));
currentVersion = currentVersion.add(BigInteger.ONE);
}
} finally {
problemChangesLock.unlock();
}
}
/**
* Adds a new problem change to a solver and registers the problem change to be later retrieved together with
* a relevant best solution by the {@link #take()} method.
*
* @return CompletableFuture that will be completed after the best solution containing this change is passed to
* a user-defined Consumer.
*/
CompletableFuture<Void> addProblemChange(Solver<Solution_> solver, ProblemChange<Solution_> problemChange) {<FILL_FUNCTION_BODY>}
void cancelPendingChanges() {
problemChangesLock.lock();
try {
problemChangesPerVersion.values()
.stream()
.flatMap(Collection::stream)
.forEach(pendingProblemChange -> pendingProblemChange.cancel(false));
problemChangesPerVersion.clear();
} finally {
problemChangesLock.unlock();
}
}
private static final class VersionedBestSolution<Solution_> {
final Solution_ bestSolution;
final BigInteger version;
public VersionedBestSolution(Solution_ bestSolution, BigInteger version) {
this.bestSolution = bestSolution;
this.version = version;
}
public Solution_ getBestSolution() {
return bestSolution;
}
public BigInteger getVersion() {
return version;
}
}
}
|
problemChangesLock.lock();
try {
CompletableFuture<Void> futureProblemChange = new CompletableFuture<>();
problemChangesPerVersion.compute(currentVersion, (version, futureProblemChangeList) -> {
if (futureProblemChangeList == null) {
futureProblemChangeList = new ArrayList<>();
}
futureProblemChangeList.add(futureProblemChange);
return futureProblemChangeList;
});
solver.addProblemChange(problemChange);
return futureProblemChange;
} finally {
problemChangesLock.unlock();
}
| 1,066
| 154
| 1,220
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/ConsumerSupport.java
|
ConsumerSupport
|
scheduleIntermediateBestSolutionConsumption
|
class ConsumerSupport<Solution_, ProblemId_> implements AutoCloseable {
private final ProblemId_ problemId;
private final Consumer<? super Solution_> bestSolutionConsumer;
private final Consumer<? super Solution_> finalBestSolutionConsumer;
private final BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler;
private final Semaphore activeConsumption = new Semaphore(1);
private final BestSolutionHolder<Solution_> bestSolutionHolder;
private final ExecutorService consumerExecutor = Executors.newSingleThreadExecutor();
public ConsumerSupport(ProblemId_ problemId, Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler,
BestSolutionHolder<Solution_> bestSolutionHolder) {
this.problemId = problemId;
this.bestSolutionConsumer = bestSolutionConsumer;
this.finalBestSolutionConsumer = finalBestSolutionConsumer == null ? finalBestSolution -> {
} : finalBestSolutionConsumer;
this.exceptionHandler = exceptionHandler;
this.bestSolutionHolder = bestSolutionHolder;
}
// Called on the Solver thread.
void consumeIntermediateBestSolution(Solution_ bestSolution, BooleanSupplier isEveryProblemChangeProcessed) {
/*
* If the bestSolutionConsumer is not provided, the best solution is still set for the purpose of recording
* problem changes.
*/
bestSolutionHolder.set(bestSolution, isEveryProblemChangeProcessed);
if (bestSolutionConsumer != null) {
tryConsumeWaitingIntermediateBestSolution();
}
}
// Called on the Solver thread after Solver#solve() returns.
void consumeFinalBestSolution(Solution_ finalBestSolution) {
try {
// Wait for the previous consumption to complete.
// As the solver has already finished, holding the solver thread is not an issue.
activeConsumption.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted when waiting for the final best solution consumption.");
}
// Make sure the final best solution is consumed by the intermediate best solution consumer first.
// Situation:
// The consumer is consuming the last but one best solution. The final best solution is waiting for the consumer.
if (bestSolutionConsumer != null) {
scheduleIntermediateBestSolutionConsumption();
}
consumerExecutor.submit(() -> {
try {
finalBestSolutionConsumer.accept(finalBestSolution);
} catch (Throwable throwable) {
exceptionHandler.accept(problemId, throwable);
} finally {
// If there is no intermediate best solution consumer, complete the problem changes now.
if (bestSolutionConsumer == null) {
bestSolutionHolder.take().completeProblemChanges();
}
// Cancel problem changes that arrived after the solver terminated.
bestSolutionHolder.cancelPendingChanges();
activeConsumption.release();
disposeConsumerThread();
}
});
}
// Called both on the Solver thread and the Consumer thread.
private void tryConsumeWaitingIntermediateBestSolution() {
if (bestSolutionHolder.isEmpty()) {
return; // There is no best solution to consume.
}
if (activeConsumption.tryAcquire()) {
scheduleIntermediateBestSolutionConsumption().thenRunAsync(this::tryConsumeWaitingIntermediateBestSolution,
consumerExecutor);
}
}
/**
* Called both on the Solver thread and the Consumer thread.
* Don't call without locking, otherwise multiple consumptions may be scheduled.
*/
private CompletableFuture<Void> scheduleIntermediateBestSolutionConsumption() {<FILL_FUNCTION_BODY>}
@Override
public void close() {
disposeConsumerThread();
bestSolutionHolder.cancelPendingChanges();
}
private void disposeConsumerThread() {
consumerExecutor.shutdownNow();
}
}
|
return CompletableFuture.runAsync(() -> {
BestSolutionContainingProblemChanges<Solution_> bestSolutionContainingProblemChanges = bestSolutionHolder.take();
if (bestSolutionContainingProblemChanges != null) {
try {
bestSolutionConsumer.accept(bestSolutionContainingProblemChanges.getBestSolution());
bestSolutionContainingProblemChanges.completeProblemChanges();
} catch (Throwable throwable) {
if (exceptionHandler != null) {
exceptionHandler.accept(problemId, throwable);
}
bestSolutionContainingProblemChanges.completeProblemChangesExceptionally(throwable);
} finally {
activeConsumption.release();
}
}
}, consumerExecutor);
| 1,050
| 199
| 1,249
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/DefaultSolutionManager.java
|
DefaultSolutionManager
|
update
|
class DefaultSolutionManager<Solution_, Score_ extends Score<Score_>>
implements SolutionManager<Solution_, Score_> {
private final InnerScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory;
public <ProblemId_> DefaultSolutionManager(SolverManager<Solution_, ProblemId_> solverManager) {
this(((DefaultSolverManager<Solution_, ProblemId_>) solverManager).getSolverFactory());
}
public DefaultSolutionManager(SolverFactory<Solution_> solverFactory) {
this.scoreDirectorFactory = ((DefaultSolverFactory<Solution_>) solverFactory).getScoreDirectorFactory();
}
public InnerScoreDirectorFactory<Solution_, Score_> getScoreDirectorFactory() {
return scoreDirectorFactory;
}
@Override
public Score_ update(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) {<FILL_FUNCTION_BODY>}
@Override
public ScoreExplanation<Solution_, Score_> explain(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) {
Score_ currentScore = (Score_) scoreDirectorFactory.getSolutionDescriptor().getScore(solution);
ScoreExplanation<Solution_, Score_> explanation =
callScoreDirector(solution, solutionUpdatePolicy, DefaultScoreExplanation::new, true);
if (!solutionUpdatePolicy.isScoreUpdateEnabled() && currentScore != null) {
// Score update is not enabled and score is not null; this means the score is supposed to be valid.
// Yet it is different from a freshly calculated score, suggesting previous score corruption.
Score_ freshScore = explanation.getScore();
if (!freshScore.equals(currentScore)) {
throw new IllegalStateException("Current score (" + currentScore + ") and freshly calculated score ("
+ freshScore + ") for solution (" + solution + ") do not match.\n"
+ "Maybe run " + EnvironmentMode.FULL_ASSERT + " to check for score corruptions.\n"
+ "Otherwise enable " + SolutionUpdatePolicy.class.getSimpleName()
+ "." + SolutionUpdatePolicy.UPDATE_ALL + " to update the stale score.");
}
}
return explanation;
}
private <Result_> Result_ callScoreDirector(Solution_ solution,
SolutionUpdatePolicy solutionUpdatePolicy, Function<InnerScoreDirector<Solution_, Score_>, Result_> function,
boolean enableConstraintMatch) {
Solution_ nonNullSolution = Objects.requireNonNull(solution);
try (InnerScoreDirector<Solution_, Score_> scoreDirector =
scoreDirectorFactory.buildScoreDirector(false, enableConstraintMatch)) {
scoreDirector.setWorkingSolution(nonNullSolution); // Init the ScoreDirector first, else NPEs may be thrown.
if (enableConstraintMatch && !scoreDirector.isConstraintMatchEnabled()) {
throw new IllegalStateException("When constraintMatchEnabled is disabled, this method should not be called.");
}
if (solutionUpdatePolicy.isShadowVariableUpdateEnabled()) {
scoreDirector.forceTriggerVariableListeners();
}
if (solutionUpdatePolicy.isScoreUpdateEnabled()) {
scoreDirector.calculateScore();
}
return function.apply(scoreDirector);
}
}
}
|
if (solutionUpdatePolicy == SolutionUpdatePolicy.NO_UPDATE) {
throw new IllegalArgumentException("Can not call " + this.getClass().getSimpleName()
+ ".update() with this solutionUpdatePolicy (" + solutionUpdatePolicy + ").");
}
return callScoreDirector(solution, solutionUpdatePolicy,
s -> (Score_) s.getSolutionDescriptor().getScore(s.getWorkingSolution()),
false);
| 849
| 111
| 960
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/DefaultSolverManager.java
|
DefaultSolverManager
|
solve
|
class DefaultSolverManager<Solution_, ProblemId_> implements SolverManager<Solution_, ProblemId_> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSolverManager.class);
private final BiConsumer<ProblemId_, Throwable> defaultExceptionHandler;
private final SolverFactory<Solution_> solverFactory;
private final ExecutorService solverThreadPool;
private final ConcurrentMap<Object, DefaultSolverJob<Solution_, ProblemId_>> problemIdToSolverJobMap;
public DefaultSolverManager(SolverFactory<Solution_> solverFactory,
SolverManagerConfig solverManagerConfig) {
defaultExceptionHandler = (problemId, throwable) -> LOGGER.error(
"Solving failed for problemId ({}).", problemId, throwable);
this.solverFactory = solverFactory;
validateSolverFactory();
int parallelSolverCount = solverManagerConfig.resolveParallelSolverCount();
solverThreadPool = Executors.newFixedThreadPool(parallelSolverCount);
problemIdToSolverJobMap = new ConcurrentHashMap<>(parallelSolverCount * 10);
}
public SolverFactory<Solution_> getSolverFactory() {
return solverFactory;
}
private void validateSolverFactory() {
solverFactory.buildSolver();
}
private ProblemId_ getProblemIdOrThrow(ProblemId_ problemId) {
if (problemId != null) {
return problemId;
}
throw new NullPointerException("Invalid problemId (null) given to SolverManager.");
}
private DefaultSolverJob<Solution_, ProblemId_> getSolverJob(ProblemId_ problemId) {
return problemIdToSolverJobMap.get(getProblemIdOrThrow(problemId));
}
@Override
public SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {
return solve(getProblemIdOrThrow(problemId), problemFinder, null, finalBestSolutionConsumer, exceptionHandler);
}
@Override
public SolverJob<Solution_, ProblemId_> solveAndListen(ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {
return solve(getProblemIdOrThrow(problemId), problemFinder, bestSolutionConsumer, finalBestSolutionConsumer,
exceptionHandler);
}
protected SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {<FILL_FUNCTION_BODY>}
@Override
public SolverStatus getSolverStatus(ProblemId_ problemId) {
DefaultSolverJob<Solution_, ProblemId_> solverJob = getSolverJob(problemId);
if (solverJob == null) {
return SolverStatus.NOT_SOLVING;
}
return solverJob.getSolverStatus();
}
// TODO Future features
// @Override
// public void reloadProblem(ProblemId_ problemId, Function<? super ProblemId_, Solution_> problemFinder) {
// DefaultSolverJob<Solution_, ProblemId_> solverJob = problemIdToSolverJobMap.get(problemId);
// if (solverJob == null) {
// // We cannot distinguish between "already terminated" and "never solved" without causing a memory leak.
// logger.debug("Ignoring reloadProblem() call because problemId ({}) is not solving.", problemId);
// return;
// }
// solverJob.reloadProblem(problemFinder);
// }
@Override
public CompletableFuture<Void> addProblemChange(ProblemId_ problemId, ProblemChange<Solution_> problemChange) {
DefaultSolverJob<Solution_, ProblemId_> solverJob = getSolverJob(problemId);
if (solverJob == null) {
// We cannot distinguish between "already terminated" and "never solved" without causing a memory leak.
throw new IllegalStateException(
"Cannot add the problem change (" + problemChange + ") because there is no solver solving the problemId ("
+ problemId + ").");
}
return solverJob.addProblemChange(problemChange);
}
@Override
public void terminateEarly(ProblemId_ problemId) {
DefaultSolverJob<Solution_, ProblemId_> solverJob = getSolverJob(problemId);
if (solverJob == null) {
// We cannot distinguish between "already terminated" and "never solved" without causing a memory leak.
LOGGER.debug("Ignoring terminateEarly() call because problemId ({}) is not solving.", problemId);
return;
}
solverJob.terminateEarly();
}
@Override
public void close() {
solverThreadPool.shutdownNow();
problemIdToSolverJobMap.values().forEach(DefaultSolverJob::close);
}
void unregisterSolverJob(ProblemId_ problemId) {
problemIdToSolverJobMap.remove(getProblemIdOrThrow(problemId));
}
}
|
Solver<Solution_> solver = solverFactory.buildSolver();
((DefaultSolver<Solution_>) solver).setMonitorTagMap(Map.of("problem.id", problemId.toString()));
BiConsumer<? super ProblemId_, ? super Throwable> finalExceptionHandler = (exceptionHandler != null)
? exceptionHandler
: defaultExceptionHandler;
DefaultSolverJob<Solution_, ProblemId_> solverJob = problemIdToSolverJobMap
.compute(problemId, (key, oldSolverJob) -> {
if (oldSolverJob != null) {
// TODO Future features: automatically restart solving by calling reloadProblem()
throw new IllegalStateException("The problemId (" + problemId + ") is already solving.");
} else {
return new DefaultSolverJob<>(this, solver, problemId, problemFinder,
bestSolutionConsumer, finalBestSolutionConsumer, finalExceptionHandler);
}
});
Future<Solution_> future = solverThreadPool.submit(solverJob);
solverJob.setFinalBestSolutionFuture(future);
return solverJob;
| 1,485
| 283
| 1,768
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/change/DefaultProblemChangeDirector.java
|
DefaultProblemChangeDirector
|
changeProblemProperty
|
class DefaultProblemChangeDirector<Solution_> implements ProblemChangeDirector {
private final InnerScoreDirector<Solution_, ?> scoreDirector;
public DefaultProblemChangeDirector(InnerScoreDirector<Solution_, ?> scoreDirector) {
this.scoreDirector = scoreDirector;
}
@Override
public <Entity> void addEntity(Entity entity, Consumer<Entity> entityConsumer) {
Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null.");
Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null.");
scoreDirector.beforeEntityAdded(entity);
entityConsumer.accept(entity);
scoreDirector.afterEntityAdded(entity);
}
@Override
public <Entity> void removeEntity(Entity entity, Consumer<Entity> entityConsumer) {
Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null.");
Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null.");
Entity workingEntity = lookUpWorkingObjectOrFail(entity);
scoreDirector.beforeEntityRemoved(workingEntity);
entityConsumer.accept(workingEntity);
scoreDirector.afterEntityRemoved(workingEntity);
}
@Override
public <Entity> void changeVariable(Entity entity, String variableName, Consumer<Entity> entityConsumer) {
Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null.");
Objects.requireNonNull(variableName, () -> "Planning variable name (" + variableName + ") cannot be null.");
Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null.");
Entity workingEntity = lookUpWorkingObjectOrFail(entity);
scoreDirector.beforeVariableChanged(workingEntity, variableName);
entityConsumer.accept(workingEntity);
scoreDirector.afterVariableChanged(workingEntity, variableName);
}
@Override
public <ProblemFact> void addProblemFact(ProblemFact problemFact, Consumer<ProblemFact> problemFactConsumer) {
Objects.requireNonNull(problemFact, () -> "Problem fact (" + problemFact + ") cannot be null.");
Objects.requireNonNull(problemFactConsumer, () -> "Problem fact consumer (" + problemFactConsumer
+ ") cannot be null.");
scoreDirector.beforeProblemFactAdded(problemFact);
problemFactConsumer.accept(problemFact);
scoreDirector.afterProblemFactAdded(problemFact);
}
@Override
public <ProblemFact> void removeProblemFact(ProblemFact problemFact, Consumer<ProblemFact> problemFactConsumer) {
Objects.requireNonNull(problemFact, () -> "Problem fact (" + problemFact + ") cannot be null.");
Objects.requireNonNull(problemFactConsumer, () -> "Problem fact consumer (" + problemFactConsumer
+ ") cannot be null.");
ProblemFact workingProblemFact = lookUpWorkingObjectOrFail(problemFact);
scoreDirector.beforeProblemFactRemoved(workingProblemFact);
problemFactConsumer.accept(workingProblemFact);
scoreDirector.afterProblemFactRemoved(workingProblemFact);
}
@Override
public <EntityOrProblemFact> void changeProblemProperty(EntityOrProblemFact problemFactOrEntity,
Consumer<EntityOrProblemFact> problemFactOrEntityConsumer) {<FILL_FUNCTION_BODY>}
@Override
public <EntityOrProblemFact> EntityOrProblemFact lookUpWorkingObjectOrFail(EntityOrProblemFact externalObject) {
return scoreDirector.lookUpWorkingObject(externalObject);
}
@Override
public <EntityOrProblemFact> Optional<EntityOrProblemFact>
lookUpWorkingObject(EntityOrProblemFact externalObject) {
return Optional.ofNullable(scoreDirector.lookUpWorkingObjectOrReturnNull(externalObject));
}
@Override
public void updateShadowVariables() {
scoreDirector.triggerVariableListeners();
}
public Score<?> doProblemChange(ProblemChange<Solution_> problemChange) {
problemChange.doChange(scoreDirector.getWorkingSolution(), this);
updateShadowVariables();
return scoreDirector.calculateScore();
}
}
|
Objects.requireNonNull(problemFactOrEntity,
() -> "Problem fact or entity (" + problemFactOrEntity + ") cannot be null.");
Objects.requireNonNull(problemFactOrEntityConsumer, () -> "Problem fact or entity consumer ("
+ problemFactOrEntityConsumer + ") cannot be null.");
EntityOrProblemFact workingEntityOrProblemFact = lookUpWorkingObjectOrFail(problemFactOrEntity);
scoreDirector.beforeProblemPropertyChanged(workingEntityOrProblemFact);
problemFactOrEntityConsumer.accept(workingEntityOrProblemFact);
scoreDirector.afterProblemPropertyChanged(workingEntityOrProblemFact);
| 1,111
| 163
| 1,274
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/event/SolverEventSupport.java
|
SolverEventSupport
|
fireBestSolutionChanged
|
class SolverEventSupport<Solution_> extends AbstractEventSupport<SolverEventListener<Solution_>> {
private final Solver<Solution_> solver;
public SolverEventSupport(Solver<Solution_> solver) {
this.solver = solver;
}
public void fireBestSolutionChanged(SolverScope<Solution_> solverScope, Solution_ newBestSolution) {<FILL_FUNCTION_BODY>}
}
|
final Iterator<SolverEventListener<Solution_>> it = getEventListeners().iterator();
long timeMillisSpent = solverScope.getBestSolutionTimeMillisSpent();
Score bestScore = solverScope.getBestScore();
if (it.hasNext()) {
final BestSolutionChangedEvent<Solution_> event = new BestSolutionChangedEvent<>(solver,
timeMillisSpent, newBestSolution, bestScore);
do {
it.next().bestSolutionChanged(event);
} while (it.hasNext());
}
| 120
| 146
| 266
|
<methods>public non-sealed void <init>() ,public void addEventListener(SolverEventListener<Solution_>) ,public void removeEventListener(SolverEventListener<Solution_>) <variables>private final List<SolverEventListener<Solution_>> eventListenerList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/random/DefaultRandomFactory.java
|
DefaultRandomFactory
|
createRandom
|
class DefaultRandomFactory implements RandomFactory {
protected final RandomType randomType;
protected final Long randomSeed;
/**
* @param randomType never null
* @param randomSeed null if no seed
*/
public DefaultRandomFactory(RandomType randomType, Long randomSeed) {
this.randomType = randomType;
this.randomSeed = randomSeed;
}
@Override
public Random createRandom() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return randomType.name() + (randomSeed == null ? "" : " with seed " + randomSeed);
}
}
|
switch (randomType) {
case JDK:
return randomSeed == null ? new Random() : new Random(randomSeed);
case MERSENNE_TWISTER:
return new RandomAdaptor(randomSeed == null ? new MersenneTwister() : new MersenneTwister(randomSeed));
case WELL512A:
return new RandomAdaptor(randomSeed == null ? new Well512a() : new Well512a(randomSeed));
case WELL1024A:
return new RandomAdaptor(randomSeed == null ? new Well1024a() : new Well1024a(randomSeed));
case WELL19937A:
return new RandomAdaptor(randomSeed == null ? new Well19937a() : new Well19937a(randomSeed));
case WELL19937C:
return new RandomAdaptor(randomSeed == null ? new Well19937c() : new Well19937c(randomSeed));
case WELL44497A:
return new RandomAdaptor(randomSeed == null ? new Well44497a() : new Well44497a(randomSeed));
case WELL44497B:
return new RandomAdaptor(randomSeed == null ? new Well44497b() : new Well44497b(randomSeed));
default:
throw new IllegalStateException("The randomType (" + randomType + ") is not implemented.");
}
| 170
| 405
| 575
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/random/RandomUtils.java
|
RandomUtils
|
nextLong
|
class RandomUtils {
/**
* Mimics {@link Random#nextInt(int)} for longs.
*
* @param random never null
* @param n {@code > 0L}
* @return like {@link Random#nextInt(int)} but for a long
* @see Random#nextInt(int)
*/
public static long nextLong(Random random, long n) {<FILL_FUNCTION_BODY>}
/**
* Mimics {@link Random#nextInt(int)} for doubles.
*
* @param random never null
* @param n {@code > 0.0}
* @return like {@link Random#nextInt(int)} but for a double
* @see Random#nextInt(int)
*/
public static double nextDouble(Random random, double n) {
// This code is based on java.util.Random#nextInt(int)'s javadoc.
if (n <= 0.0) {
throw new IllegalArgumentException("n must be positive");
}
return random.nextDouble() * n;
}
private RandomUtils() {
}
}
|
// This code is based on java.util.Random#nextInt(int)'s javadoc.
if (n <= 0L) {
throw new IllegalArgumentException("n must be positive");
}
if (n < Integer.MAX_VALUE) {
return random.nextInt((int) n);
}
long bits;
long val;
do {
bits = (random.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits - val + (n - 1L) < 0L);
return val;
| 285
| 145
| 430
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/AbstractTermination.java
|
AbstractTermination
|
createChildThreadTermination
|
class AbstractTermination<Solution_> extends PhaseLifecycleListenerAdapter<Solution_>
implements Termination<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {<FILL_FUNCTION_BODY>}
}
|
throw new UnsupportedOperationException("This terminationClass (" + getClass()
+ ") does not yet support being used in child threads of type (" + childThreadType + ").");
| 133
| 44
| 177
|
<methods>public non-sealed void <init>() ,public void phaseEnded(AbstractPhaseScope<Solution_>) ,public void phaseStarted(AbstractPhaseScope<Solution_>) ,public void stepEnded(AbstractStepScope<Solution_>) ,public void stepStarted(AbstractStepScope<Solution_>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/BestScoreFeasibleTermination.java
|
BestScoreFeasibleTermination
|
calculateFeasibilityTimeGradient
|
class BestScoreFeasibleTermination<Solution_> extends AbstractTermination<Solution_> {
private final int feasibleLevelsSize;
private final double[] timeGradientWeightFeasibleNumbers;
public BestScoreFeasibleTermination(ScoreDefinition scoreDefinition, double[] timeGradientWeightFeasibleNumbers) {
feasibleLevelsSize = scoreDefinition.getFeasibleLevelsSize();
this.timeGradientWeightFeasibleNumbers = timeGradientWeightFeasibleNumbers;
if (timeGradientWeightFeasibleNumbers.length != feasibleLevelsSize - 1) {
throw new IllegalStateException(
"The timeGradientWeightNumbers (" + Arrays.toString(timeGradientWeightFeasibleNumbers)
+ ")'s length (" + timeGradientWeightFeasibleNumbers.length
+ ") is not 1 less than the feasibleLevelsSize (" + scoreDefinition.getFeasibleLevelsSize()
+ ").");
}
}
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverScope.getBestScore());
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated((Score) phaseScope.getBestScore());
}
protected boolean isTerminated(Score bestScore) {
return bestScore.isFeasible();
}
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return calculateFeasibilityTimeGradient(solverScope.getStartingInitializedScore(), solverScope.getBestScore());
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return calculateFeasibilityTimeGradient((Score) phaseScope.getStartingScore(), (Score) phaseScope.getBestScore());
}
protected <Score_ extends Score<Score_>> double calculateFeasibilityTimeGradient(Score_ startScore, Score_ score) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
// TODO FIXME through some sort of solverlistener and async behaviour...
throw new UnsupportedOperationException("This terminationClass (" + getClass()
+ ") does not yet support being used in child threads of type (" + childThreadType + ").");
}
@Override
public String toString() {
return "BestScoreFeasible()";
}
}
|
if (startScore == null || !startScore.isSolutionInitialized()) {
return 0.0;
}
Score_ totalDiff = startScore.negate();
Number[] totalDiffNumbers = totalDiff.toLevelNumbers();
Score_ scoreDiff = score.subtract(startScore);
Number[] scoreDiffNumbers = scoreDiff.toLevelNumbers();
if (scoreDiffNumbers.length != totalDiffNumbers.length) {
throw new IllegalStateException("The startScore (" + startScore + ") and score (" + score
+ ") don't have the same levelsSize.");
}
return BestScoreTermination.calculateTimeGradient(totalDiffNumbers, scoreDiffNumbers,
timeGradientWeightFeasibleNumbers, feasibleLevelsSize);
| 692
| 198
| 890
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/BestScoreTermination.java
|
BestScoreTermination
|
createChildThreadTermination
|
class BestScoreTermination<Solution_> extends AbstractTermination<Solution_> {
private final int levelsSize;
private final Score bestScoreLimit;
private final double[] timeGradientWeightNumbers;
public BestScoreTermination(ScoreDefinition scoreDefinition, Score bestScoreLimit, double[] timeGradientWeightNumbers) {
levelsSize = scoreDefinition.getLevelsSize();
this.bestScoreLimit = bestScoreLimit;
if (bestScoreLimit == null) {
throw new IllegalArgumentException("The bestScoreLimit (" + bestScoreLimit
+ ") cannot be null.");
}
this.timeGradientWeightNumbers = timeGradientWeightNumbers;
if (timeGradientWeightNumbers.length != levelsSize - 1) {
throw new IllegalStateException(
"The timeGradientWeightNumbers (" + Arrays.toString(timeGradientWeightNumbers)
+ ")'s length (" + timeGradientWeightNumbers.length
+ ") is not 1 less than the levelsSize (" + scoreDefinition.getLevelsSize() + ").");
}
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverScope.isBestSolutionInitialized(), solverScope.getBestScore());
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated(phaseScope.isBestSolutionInitialized(), (Score) phaseScope.getBestScore());
}
protected boolean isTerminated(boolean bestSolutionInitialized, Score bestScore) {
return bestSolutionInitialized && bestScore.compareTo(bestScoreLimit) >= 0;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
Score startingInitializedScore = solverScope.getStartingInitializedScore();
Score bestScore = solverScope.getBestScore();
return calculateTimeGradient(startingInitializedScore, bestScoreLimit, bestScore);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
Score startingInitializedScore = phaseScope.getStartingScore();
Score bestScore = phaseScope.getBestScore();
return calculateTimeGradient(startingInitializedScore, bestScoreLimit, bestScore);
}
protected <Score_ extends Score<Score_>> double calculateTimeGradient(Score_ startScore, Score_ endScore,
Score_ score) {
Score_ totalDiff = endScore.subtract(startScore);
Number[] totalDiffNumbers = totalDiff.toLevelNumbers();
Score_ scoreDiff = score.subtract(startScore);
Number[] scoreDiffNumbers = scoreDiff.toLevelNumbers();
if (scoreDiffNumbers.length != totalDiffNumbers.length) {
throw new IllegalStateException("The startScore (" + startScore + "), endScore (" + endScore
+ ") and score (" + score + ") don't have the same levelsSize.");
}
return calculateTimeGradient(totalDiffNumbers, scoreDiffNumbers, timeGradientWeightNumbers,
levelsSize);
}
/**
*
* @param totalDiffNumbers never null
* @param scoreDiffNumbers never null
* @param timeGradientWeightNumbers never null
* @param levelDepth The number of levels of the diffNumbers that are included
* @return {@code 0.0 <= value <= 1.0}
*/
static double calculateTimeGradient(Number[] totalDiffNumbers, Number[] scoreDiffNumbers,
double[] timeGradientWeightNumbers, int levelDepth) {
double timeGradient = 0.0;
double remainingTimeGradient = 1.0;
for (int i = 0; i < levelDepth; i++) {
double levelTimeGradientWeight;
if (i != (levelDepth - 1)) {
levelTimeGradientWeight = remainingTimeGradient * timeGradientWeightNumbers[i];
remainingTimeGradient -= levelTimeGradientWeight;
} else {
levelTimeGradientWeight = remainingTimeGradient;
remainingTimeGradient = 0.0;
}
double totalDiffLevel = totalDiffNumbers[i].doubleValue();
double scoreDiffLevel = scoreDiffNumbers[i].doubleValue();
if (scoreDiffLevel == totalDiffLevel) {
// Max out this level
timeGradient += levelTimeGradientWeight;
} else if (scoreDiffLevel > totalDiffLevel) {
// Max out this level and all softer levels too
timeGradient += levelTimeGradientWeight + remainingTimeGradient;
break;
} else if (scoreDiffLevel == 0.0) {
// Ignore this level
// timeGradient += 0.0
} else if (scoreDiffLevel < 0.0) {
// Ignore this level and all softer levels too
// timeGradient += 0.0
break;
} else {
double levelTimeGradient = scoreDiffLevel / totalDiffLevel;
timeGradient += levelTimeGradient * levelTimeGradientWeight;
}
}
if (timeGradient > 1.0) {
// Rounding error due to calculating with doubles
timeGradient = 1.0;
}
return timeGradient;
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "BestScore(" + bestScoreLimit + ")";
}
}
|
// TODO FIXME through some sort of solverlistener and async behaviour...
throw new UnsupportedOperationException("This terminationClass (" + getClass()
+ ") does not yet support being used in child threads of type (" + childThreadType + ").");
| 1,495
| 63
| 1,558
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/ChildThreadPlumbingTermination.java
|
ChildThreadPlumbingTermination
|
isSolverTerminated
|
class ChildThreadPlumbingTermination<Solution_> extends AbstractTermination<Solution_> {
protected boolean terminateChildren = false;
// ************************************************************************
// Plumbing worker methods
// ************************************************************************
/**
* This method is thread-safe.
*
* @return true if termination hasn't been requested previously
*/
public synchronized boolean terminateChildren() {
boolean terminationEarlySuccessful = !terminateChildren;
terminateChildren = true;
return terminationEarlySuccessful;
}
// ************************************************************************
// Termination worker methods
// ************************************************************************
@Override
public synchronized boolean isSolverTerminated(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
throw new IllegalStateException(ChildThreadPlumbingTermination.class.getSimpleName()
+ " configured only as solver termination."
+ " It is always bridged to phase termination.");
}
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return -1.0; // Not supported
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
throw new IllegalStateException(ChildThreadPlumbingTermination.class.getSimpleName()
+ " configured only as solver termination."
+ " It is always bridged to phase termination.");
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return this;
}
@Override
public String toString() {
return "ChildThreadPlumbing()";
}
}
|
// Destroying a thread pool with solver threads will only cause it to interrupt those child solver threads
if (Thread.currentThread().isInterrupted()) { // Does not clear the interrupted flag
logger.info("A child solver thread got interrupted, so these child solvers are terminating early.");
terminateChildren = true;
}
return terminateChildren;
| 495
| 90
| 585
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/OrCompositeTermination.java
|
OrCompositeTermination
|
calculatePhaseTimeGradient
|
class OrCompositeTermination<Solution_> extends AbstractCompositeTermination<Solution_> {
public OrCompositeTermination(List<Termination<Solution_>> terminationList) {
super(terminationList);
}
public OrCompositeTermination(Termination<Solution_>... terminations) {
super(terminations);
}
// ************************************************************************
// Terminated methods
// ************************************************************************
/**
* @param solverScope never null
* @return true if any of the Termination is terminated.
*/
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
for (Termination<Solution_> termination : terminationList) {
if (termination.isSolverTerminated(solverScope)) {
return true;
}
}
return false;
}
/**
* @param phaseScope never null
* @return true if any of the Termination is terminated.
*/
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
for (Termination<Solution_> termination : terminationList) {
if (termination.isPhaseTerminated(phaseScope)) {
return true;
}
}
return false;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
/**
* Calculates the maximum timeGradient of all Terminations.
* Not supported timeGradients (-1.0) are ignored.
*
* @param solverScope never null
* @return the maximum timeGradient of the Terminations.
*/
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
double timeGradient = 0.0;
for (Termination<Solution_> termination : terminationList) {
double nextTimeGradient = termination.calculateSolverTimeGradient(solverScope);
if (nextTimeGradient >= 0.0) {
timeGradient = Math.max(timeGradient, nextTimeGradient);
}
}
return timeGradient;
}
/**
* Calculates the maximum timeGradient of all Terminations.
* Not supported timeGradients (-1.0) are ignored.
*
* @param phaseScope never null
* @return the maximum timeGradient of the Terminations.
*/
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public OrCompositeTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new OrCompositeTermination<>(createChildThreadTerminationList(solverScope, childThreadType));
}
@Override
public String toString() {
return "Or(" + terminationList + ")";
}
}
|
double timeGradient = 0.0;
for (Termination<Solution_> termination : terminationList) {
double nextTimeGradient = termination.calculatePhaseTimeGradient(phaseScope);
if (nextTimeGradient >= 0.0) {
timeGradient = Math.max(timeGradient, nextTimeGradient);
}
}
return timeGradient;
| 782
| 98
| 880
|
<methods>public transient void <init>(Termination<Solution_>[]) ,public void phaseEnded(AbstractPhaseScope<Solution_>) ,public void phaseStarted(AbstractPhaseScope<Solution_>) ,public void solvingEnded(SolverScope<Solution_>) ,public void solvingStarted(SolverScope<Solution_>) ,public void stepEnded(AbstractStepScope<Solution_>) ,public void stepStarted(AbstractStepScope<Solution_>) <variables>protected final non-sealed List<Termination<Solution_>> terminationList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/PhaseToSolverTerminationBridge.java
|
PhaseToSolverTerminationBridge
|
createChildThreadTermination
|
class PhaseToSolverTerminationBridge<Solution_> extends AbstractTermination<Solution_> {
private final Termination<Solution_> solverTermination;
public PhaseToSolverTerminationBridge(Termination<Solution_> solverTermination) {
this.solverTermination = solverTermination;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
// Do not propagate any of the lifecycle events up to the solverTermination,
// because it already gets the solver events from the DefaultSolver
// and the phase/step events - if ever needed - should also come through the DefaultSolver
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return solverTermination.isSolverTerminated(phaseScope.getSolverScope());
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return solverTermination.calculateSolverTimeGradient(phaseScope.getSolverScope());
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Bridge(" + solverTermination + ")";
}
}
|
if (childThreadType == ChildThreadType.PART_THREAD) {
// Remove of the bridge (which is nested if there's a phase termination), PhaseConfig will add it again
return solverTermination.createChildThreadTermination(solverScope, childThreadType);
} else {
throw new IllegalStateException("The childThreadType (" + childThreadType + ") is not implemented.");
}
| 550
| 100
| 650
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/ScoreCalculationCountTermination.java
|
ScoreCalculationCountTermination
|
createChildThreadTermination
|
class ScoreCalculationCountTermination<Solution_> extends AbstractTermination<Solution_> {
private final long scoreCalculationCountLimit;
public ScoreCalculationCountTermination(long scoreCalculationCountLimit) {
this.scoreCalculationCountLimit = scoreCalculationCountLimit;
if (scoreCalculationCountLimit < 0L) {
throw new IllegalArgumentException("The scoreCalculationCountLimit (" + scoreCalculationCountLimit
+ ") cannot be negative.");
}
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverScope.getScoreDirector());
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated(phaseScope.getScoreDirector());
}
protected boolean isTerminated(InnerScoreDirector<Solution_, ?> scoreDirector) {
long scoreCalculationCount = scoreDirector.getCalculationCount();
return scoreCalculationCount >= scoreCalculationCountLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return calculateTimeGradient(solverScope.getScoreDirector());
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return calculateTimeGradient(phaseScope.getScoreDirector());
}
protected double calculateTimeGradient(InnerScoreDirector<Solution_, ?> scoreDirector) {
long scoreCalculationCount = scoreDirector.getCalculationCount();
double timeGradient = scoreCalculationCount / ((double) scoreCalculationCountLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public ScoreCalculationCountTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "ScoreCalculationCount(" + scoreCalculationCountLimit + ")";
}
}
|
if (childThreadType == ChildThreadType.PART_THREAD) {
// The ScoreDirector.calculationCount of partitions is maxed, not summed.
return new ScoreCalculationCountTermination<>(scoreCalculationCountLimit);
} else {
throw new IllegalStateException("The childThreadType (" + childThreadType + ") is not implemented.");
}
| 609
| 93
| 702
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/StepCountTermination.java
|
StepCountTermination
|
isSolverTerminated
|
class StepCountTermination<Solution_> extends AbstractTermination<Solution_> {
private final int stepCountLimit;
public StepCountTermination(int stepCountLimit) {
this.stepCountLimit = stepCountLimit;
if (stepCountLimit < 0) {
throw new IllegalArgumentException("The stepCountLimit (" + stepCountLimit
+ ") cannot be negative.");
}
}
public int getStepCountLimit() {
return stepCountLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
int nextStepIndex = phaseScope.getNextStepIndex();
return nextStepIndex >= stepCountLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
int nextStepIndex = phaseScope.getNextStepIndex();
double timeGradient = nextStepIndex / ((double) stepCountLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public StepCountTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new StepCountTermination<>(stepCountLimit);
}
@Override
public String toString() {
return "StepCount(" + stepCountLimit + ")";
}
}
|
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
| 515
| 31
| 546
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/TimeMillisSpentTermination.java
|
TimeMillisSpentTermination
|
calculateTimeGradient
|
class TimeMillisSpentTermination<Solution_> extends AbstractTermination<Solution_> {
private final long timeMillisSpentLimit;
public TimeMillisSpentTermination(long timeMillisSpentLimit) {
this.timeMillisSpentLimit = timeMillisSpentLimit;
if (timeMillisSpentLimit < 0L) {
throw new IllegalArgumentException("The timeMillisSpentLimit (" + timeMillisSpentLimit
+ ") cannot be negative.");
}
}
public long getTimeMillisSpentLimit() {
return timeMillisSpentLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
long solverTimeMillisSpent = solverScope.calculateTimeMillisSpentUpToNow();
return isTerminated(solverTimeMillisSpent);
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
long phaseTimeMillisSpent = phaseScope.calculatePhaseTimeMillisSpentUpToNow();
return isTerminated(phaseTimeMillisSpent);
}
protected boolean isTerminated(long timeMillisSpent) {
return timeMillisSpent >= timeMillisSpentLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
long solverTimeMillisSpent = solverScope.calculateTimeMillisSpentUpToNow();
return calculateTimeGradient(solverTimeMillisSpent);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
long phaseTimeMillisSpent = phaseScope.calculatePhaseTimeMillisSpentUpToNow();
return calculateTimeGradient(phaseTimeMillisSpent);
}
protected double calculateTimeGradient(long timeMillisSpent) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public TimeMillisSpentTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new TimeMillisSpentTermination<>(timeMillisSpentLimit);
}
@Override
public String toString() {
return "TimeMillisSpent(" + timeMillisSpentLimit + ")";
}
}
|
double timeGradient = timeMillisSpent / ((double) timeMillisSpentLimit);
return Math.min(timeGradient, 1.0);
| 682
| 42
| 724
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/solver/termination/UnimprovedTimeMillisSpentTermination.java
|
UnimprovedTimeMillisSpentTermination
|
calculateTimeGradient
|
class UnimprovedTimeMillisSpentTermination<Solution_> extends AbstractTermination<Solution_> {
private final long unimprovedTimeMillisSpentLimit;
private final Clock clock;
public UnimprovedTimeMillisSpentTermination(long unimprovedTimeMillisSpentLimit) {
this(unimprovedTimeMillisSpentLimit, Clock.systemUTC());
}
protected UnimprovedTimeMillisSpentTermination(long unimprovedTimeMillisSpentLimit, Clock clock) {
this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit;
if (unimprovedTimeMillisSpentLimit < 0L) {
throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (" + unimprovedTimeMillisSpentLimit
+ ") cannot be negative.");
}
this.clock = clock;
}
public long getUnimprovedTimeMillisSpentLimit() {
return unimprovedTimeMillisSpentLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
return isTerminated(bestSolutionTimeMillis);
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
long bestSolutionTimeMillis = phaseScope.getPhaseBestSolutionTimeMillis();
return isTerminated(bestSolutionTimeMillis);
}
protected boolean isTerminated(long bestSolutionTimeMillis) {
long now = clock.millis();
long unimprovedTimeMillisSpent = now - bestSolutionTimeMillis;
return unimprovedTimeMillisSpent >= unimprovedTimeMillisSpentLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
return calculateTimeGradient(bestSolutionTimeMillis);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
long bestSolutionTimeMillis = phaseScope.getPhaseBestSolutionTimeMillis();
return calculateTimeGradient(bestSolutionTimeMillis);
}
protected double calculateTimeGradient(long bestSolutionTimeMillis) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public UnimprovedTimeMillisSpentTermination<Solution_> createChildThreadTermination(
SolverScope<Solution_> solverScope, ChildThreadType childThreadType) {
return new UnimprovedTimeMillisSpentTermination<>(unimprovedTimeMillisSpentLimit);
}
@Override
public String toString() {
return "UnimprovedTimeMillisSpent(" + unimprovedTimeMillisSpentLimit + ")";
}
}
|
long now = clock.millis();
long unimprovedTimeMillisSpent = now - bestSolutionTimeMillis;
double timeGradient = unimprovedTimeMillisSpent / ((double) unimprovedTimeMillisSpentLimit);
return Math.min(timeGradient, 1.0);
| 824
| 79
| 903
|
<methods>public non-sealed void <init>() ,public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_>, org.optaplanner.core.impl.solver.thread.ChildThreadType) <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/statistic/BestScoreStatistic.java
|
BestScoreStatistic
|
register
|
class BestScoreStatistic<Solution_> implements SolverStatistic<Solution_> {
private final Map<Tags, List<AtomicReference<Number>>> tagsToBestScoreMap = new ConcurrentHashMap<>();
private final Map<Solver<Solution_>, SolverEventListener<Solution_>> solverToEventListenerMap = new WeakHashMap<>();
@Override
public void unregister(Solver<Solution_> solver) {
SolverEventListener<Solution_> listener = solverToEventListenerMap.remove(solver);
if (listener != null) {
solver.removeEventListener(listener);
}
}
@Override
public void register(Solver<Solution_> solver) {<FILL_FUNCTION_BODY>}
}
|
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
ScoreDefinition<?> scoreDefinition = defaultSolver.getSolverScope().getScoreDefinition();
SolverEventListener<Solution_> listener = event -> SolverMetric.registerScoreMetrics(SolverMetric.BEST_SCORE,
defaultSolver.getSolverScope().getMonitoringTags(),
scoreDefinition, tagsToBestScoreMap, event.getNewBestScore());
solverToEventListenerMap.put(defaultSolver, listener);
defaultSolver.addEventListener(listener);
| 197
| 151
| 348
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/statistic/PickedMoveBestScoreDiffStatistic.java
|
PickedMoveBestScoreDiffStatisticListener
|
phaseStarted
|
class PickedMoveBestScoreDiffStatisticListener<Solution_, Score_ extends Score<Score_>>
extends PhaseLifecycleListenerAdapter<Solution_> {
private Score_ oldBestScore = null;
private final ScoreDefinition<Score_> scoreDefinition;
private final Map<Tags, List<AtomicReference<Number>>> tagsToMoveScoreMap = new ConcurrentHashMap<>();
public PickedMoveBestScoreDiffStatisticListener(ScoreDefinition<Score_> scoreDefinition) {
this.scoreDefinition = scoreDefinition;
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {<FILL_FUNCTION_BODY>}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
if (phaseScope instanceof LocalSearchPhaseScope) {
oldBestScore = null;
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (stepScope instanceof LocalSearchStepScope) {
localSearchStepEnded((LocalSearchStepScope<Solution_>) stepScope);
}
}
@SuppressWarnings("unchecked")
private void localSearchStepEnded(LocalSearchStepScope<Solution_> stepScope) {
if (stepScope.getBestScoreImproved()) {
String moveType = stepScope.getStep().getSimpleMoveTypeDescription();
Score_ newBestScore = (Score_) stepScope.getScore();
Score_ bestScoreDiff = newBestScore.subtract(oldBestScore);
oldBestScore = newBestScore;
SolverMetric.registerScoreMetrics(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF,
stepScope.getPhaseScope().getSolverScope().getMonitoringTags()
.and("move.type", moveType),
scoreDefinition,
tagsToMoveScoreMap,
bestScoreDiff);
}
}
}
|
if (phaseScope instanceof LocalSearchPhaseScope) {
oldBestScore = phaseScope.getBestScore();
}
| 504
| 33
| 537
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/statistic/PickedMoveStepScoreDiffStatistic.java
|
PickedMoveStepScoreDiffStatisticListener
|
phaseEnded
|
class PickedMoveStepScoreDiffStatisticListener<Solution_, Score_ extends Score<Score_>>
extends PhaseLifecycleListenerAdapter<Solution_> {
private Score_ oldStepScore = null;
private final ScoreDefinition<Score_> scoreDefinition;
private final Map<Tags, List<AtomicReference<Number>>> tagsToMoveScoreMap = new ConcurrentHashMap<>();
public PickedMoveStepScoreDiffStatisticListener(ScoreDefinition<Score_> scoreDefinition) {
this.scoreDefinition = scoreDefinition;
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
if (phaseScope instanceof LocalSearchPhaseScope) {
oldStepScore = phaseScope.getStartingScore();
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {<FILL_FUNCTION_BODY>}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (stepScope instanceof LocalSearchStepScope) {
localSearchStepEnded((LocalSearchStepScope<Solution_>) stepScope);
}
}
@SuppressWarnings("unchecked")
private void localSearchStepEnded(LocalSearchStepScope<Solution_> stepScope) {
String moveType = stepScope.getStep().getSimpleMoveTypeDescription();
Score_ newStepScore = (Score_) stepScope.getScore();
Score_ stepScoreDiff = newStepScore.subtract(oldStepScore);
oldStepScore = newStepScore;
SolverMetric.registerScoreMetrics(SolverMetric.PICKED_MOVE_TYPE_STEP_SCORE_DIFF,
stepScope.getPhaseScope().getSolverScope().getMonitoringTags()
.and("move.type", moveType),
scoreDefinition,
tagsToMoveScoreMap,
stepScoreDiff);
}
}
|
if (phaseScope instanceof LocalSearchPhaseScope) {
oldStepScore = null;
}
| 493
| 28
| 521
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/CollectionUtils.java
|
CollectionUtils
|
copy
|
class CollectionUtils {
/**
* Creates a copy of the list, optionally in reverse order.
*
* @param originalList the list to copy, preferably {@link ArrayList}
* @param reverse true if the resulting list should have its order reversed
* @return mutable list, never null
* @param <E> the type of elements in the list
*/
public static <E> List<E> copy(List<E> originalList, boolean reverse) {<FILL_FUNCTION_BODY>}
public static <T> List<T> concat(List<T> left, List<T> right) {
List<T> result = new ArrayList<>(left.size() + right.size());
result.addAll(left);
result.addAll(right);
return result;
}
private CollectionUtils() {
// No external instances.
}
}
|
if (!reverse) {
return new ArrayList<>(originalList);
}
/*
* Some move implementations on the hot path rely heavily on list reversal.
* As such, the following implementation was benchmarked to perform as well as possible for lists of all sizes.
* See PLANNER-2808 for details.
*/
switch (originalList.size()) {
case 0:
return new ArrayList<>(0);
case 1:
List<E> singletonList = new ArrayList<>(1);
singletonList.add(originalList.get(0));
return singletonList;
case 2:
List<E> smallList = new ArrayList<>(2);
smallList.add(originalList.get(1));
smallList.add(originalList.get(0));
return smallList;
default:
List<E> largeList = new ArrayList<>(originalList);
Collections.reverse(largeList);
return largeList;
}
| 225
| 251
| 476
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/ListBasedScalingOrderedSet.java
|
ListBasedScalingOrderedSet
|
addAll
|
class ListBasedScalingOrderedSet<E> implements Set<E> {
protected static final int LIST_SIZE_THRESHOLD = 16;
private boolean belowThreshold;
private List<E> list;
private Set<E> set;
public ListBasedScalingOrderedSet() {
belowThreshold = true;
list = new ArrayList<>(LIST_SIZE_THRESHOLD);
set = null;
}
@Override
public int size() {
return belowThreshold ? list.size() : set.size();
}
@Override
public boolean isEmpty() {
return belowThreshold ? list.isEmpty() : set.isEmpty();
}
@Override
public boolean contains(Object o) {
return belowThreshold ? list.contains(o) : set.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return belowThreshold ? list.containsAll(c) : set.containsAll(c);
}
@Override
public Iterator<E> iterator() {
final Iterator<E> childIterator = belowThreshold ? list.iterator() : set.iterator();
return new Iterator<E>() {
@Override
public boolean hasNext() {
return childIterator.hasNext();
}
@Override
public E next() {
return childIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public Object[] toArray() {
return belowThreshold ? list.toArray() : set.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return belowThreshold ? list.toArray(a) : set.toArray(a);
}
@Override
public boolean add(E e) {
if (belowThreshold) {
int newSize = list.size() + 1;
if (newSize > LIST_SIZE_THRESHOLD) {
set = new LinkedHashSet<>(list);
list = null;
belowThreshold = false;
return set.add(e);
} else {
if (list.contains(e)) {
return false;
}
return list.add(e);
}
} else {
return set.add(e);
}
}
@Override
public boolean addAll(Collection<? extends E> c) {<FILL_FUNCTION_BODY>}
@Override
public boolean remove(Object o) {
if (belowThreshold) {
return list.remove(o);
} else {
int newSize = set.size() - 1;
if (newSize <= LIST_SIZE_THRESHOLD) {
set.remove(o);
list = new ArrayList<>(set);
set = null;
belowThreshold = true;
return true;
} else {
return set.remove(o);
}
}
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("retainAll() not yet implemented");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("removeAll() not yet implemented");
}
@Override
public void clear() {
if (belowThreshold) {
list.clear();
} else {
list = new ArrayList<>(LIST_SIZE_THRESHOLD);
set = null;
belowThreshold = true;
}
}
}
|
if (belowThreshold) {
int newSize = list.size() + c.size();
if (newSize > LIST_SIZE_THRESHOLD) {
set = new LinkedHashSet<>(newSize);
set.addAll(list);
list = null;
belowThreshold = false;
return set.addAll(c);
} else {
boolean changed = false;
for (E e : c) {
if (!list.contains(e)) {
changed = true;
list.add(e);
}
}
return changed;
}
} else {
return set.addAll(c);
}
| 925
| 170
| 1,095
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/MemoizingSupply.java
|
MemoizingSupply
|
read
|
class MemoizingSupply<T> implements Supply {
private final Supplier<T> valueSupplier;
private boolean cached = false;
private T memoizedValue;
public MemoizingSupply(Supplier<T> supplier) {
this.valueSupplier = Objects.requireNonNull(supplier);
}
public T read() {<FILL_FUNCTION_BODY>}
}
|
if (!cached) {
cached = true; // Don't re-compute the supply even if the value was null.
memoizedValue = valueSupplier.get();
}
return memoizedValue;
| 107
| 57
| 164
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/MutablePairImpl.java
|
MutablePairImpl
|
hashCode
|
class MutablePairImpl<A, B> implements MutablePair<A, B> {
private A key;
private B value;
MutablePairImpl(A key, B value) {
this.key = key;
this.value = value;
}
@Override
public MutablePair<A, B> setKey(A key) {
this.key = key;
return this;
}
@Override
public MutablePair<A, B> setValue(B value) {
this.value = value;
return this;
}
@Override
public A getKey() {
return key;
}
@Override
public B getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MutablePairImpl<?, ?> that = (MutablePairImpl<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "(" + key + ", " + value + ")";
}
}
|
// Not using Objects.hash(Object...) as that would create an array on the hot path.
int result = Objects.hashCode(key);
result = 31 * result + Objects.hashCode(value);
return result;
| 350
| 59
| 409
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/MutableReference.java
|
MutableReference
|
equals
|
class MutableReference<Value_> {
private Value_ value;
public MutableReference(Value_ value) {
this.value = value;
}
public Value_ getValue() {
return value;
}
public void setValue(Value_ value) {
this.value = value;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return value.toString();
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MutableReference<?> that = (MutableReference<?>) o;
return Objects.equals(value, that.value);
| 163
| 73
| 236
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/PairImpl.java
|
PairImpl
|
equals
|
class PairImpl<A, B> implements Pair<A, B> {
private final A key;
private final B value;
PairImpl(A key, B value) {
this.key = key;
this.value = value;
}
@Override
public A getKey() {
return key;
}
@Override
public B getValue() {
return value;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() { // Not using Objects.hash(Object...) as that would create an array on the hot path.
int result = Objects.hashCode(key);
result = 31 * result + Objects.hashCode(value);
return result;
}
@Override
public String toString() {
return "(" + key + ", " + value + ")";
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PairImpl<?, ?> that = (PairImpl<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
| 241
| 86
| 327
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/QuadrupleImpl.java
|
QuadrupleImpl
|
hashCode
|
class QuadrupleImpl<A, B, C, D> implements Quadruple<A, B, C, D> {
private final A a;
private final B b;
private final C c;
private final D d;
QuadrupleImpl(A a, B b, C c, D d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
@Override
public A getA() {
return a;
}
@Override
public B getB() {
return b;
}
@Override
public C getC() {
return c;
}
@Override
public D getD() {
return d;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
QuadrupleImpl<A, B, C, D> that = (QuadrupleImpl<A, B, C, D>) o;
return Objects.equals(a, that.a)
&& Objects.equals(b, that.b)
&& Objects.equals(c, that.c)
&& Objects.equals(d, that.d);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "(" + a + ", " + b + ", " + c + ", " + d + ")";
}
}
|
// Not using Objects.hash(Object...) as that would create an array on the hot path.
int result = Objects.hashCode(a);
result = 31 * result + Objects.hashCode(b);
result = 31 * result + Objects.hashCode(c);
result = 31 * result + Objects.hashCode(d);
return result;
| 416
| 93
| 509
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/util/TripleImpl.java
|
TripleImpl
|
hashCode
|
class TripleImpl<A, B, C> implements Triple<A, B, C> {
private final A a;
private final B b;
private final C c;
TripleImpl(A a, B b, C c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public A getA() {
return a;
}
@Override
public B getB() {
return b;
}
@Override
public C getC() {
return c;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
TripleImpl<A, B, C> that = (TripleImpl<A, B, C>) o;
return Objects.equals(a, that.a)
&& Objects.equals(b, that.b)
&& Objects.equals(c, that.c);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "(" + a + ", " + b + ", " + c + ")";
}
}
|
// Not using Objects.hash(Object...) as that would create an array on the hot path.
int result = Objects.hashCode(a);
result = 31 * result + Objects.hashCode(b);
result = 31 * result + Objects.hashCode(c);
return result;
| 340
| 76
| 416
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/config/ProblemBenchmarksConfig.java
|
ProblemBenchmarksConfig
|
determineProblemStatisticTypeList
|
class ProblemBenchmarksConfig extends AbstractConfig<ProblemBenchmarksConfig> {
private Class<? extends SolutionFileIO<?>> solutionFileIOClass = null;
private Boolean writeOutputSolutionEnabled = null;
@XmlElement(name = "inputSolutionFile")
private List<File> inputSolutionFileList = null;
private Boolean problemStatisticEnabled = null;
@XmlElement(name = "problemStatisticType")
private List<ProblemStatisticType> problemStatisticTypeList = null;
@XmlElement(name = "singleStatisticType")
private List<SingleStatisticType> singleStatisticTypeList = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public Class<? extends SolutionFileIO<?>> getSolutionFileIOClass() {
return solutionFileIOClass;
}
public void setSolutionFileIOClass(Class<? extends SolutionFileIO<?>> solutionFileIOClass) {
this.solutionFileIOClass = solutionFileIOClass;
}
public Boolean getWriteOutputSolutionEnabled() {
return writeOutputSolutionEnabled;
}
public void setWriteOutputSolutionEnabled(Boolean writeOutputSolutionEnabled) {
this.writeOutputSolutionEnabled = writeOutputSolutionEnabled;
}
public List<File> getInputSolutionFileList() {
return inputSolutionFileList;
}
public void setInputSolutionFileList(List<File> inputSolutionFileList) {
this.inputSolutionFileList = inputSolutionFileList;
}
public Boolean getProblemStatisticEnabled() {
return problemStatisticEnabled;
}
public void setProblemStatisticEnabled(Boolean problemStatisticEnabled) {
this.problemStatisticEnabled = problemStatisticEnabled;
}
public List<ProblemStatisticType> getProblemStatisticTypeList() {
return problemStatisticTypeList;
}
public void setProblemStatisticTypeList(List<ProblemStatisticType> problemStatisticTypeList) {
this.problemStatisticTypeList = problemStatisticTypeList;
}
public List<SingleStatisticType> getSingleStatisticTypeList() {
return singleStatisticTypeList;
}
public void setSingleStatisticTypeList(List<SingleStatisticType> singleStatisticTypeList) {
this.singleStatisticTypeList = singleStatisticTypeList;
}
// ************************************************************************
// With methods
// ************************************************************************
public ProblemBenchmarksConfig withSolutionFileIOClass(Class<? extends SolutionFileIO<?>> solutionFileIOClass) {
this.setSolutionFileIOClass(solutionFileIOClass);
return this;
}
public ProblemBenchmarksConfig withWriteOutputSolutionEnabled(Boolean writeOutputSolutionEnabled) {
this.setWriteOutputSolutionEnabled(writeOutputSolutionEnabled);
return this;
}
public ProblemBenchmarksConfig withInputSolutionFileList(List<File> inputSolutionFileList) {
this.setInputSolutionFileList(inputSolutionFileList);
return this;
}
public ProblemBenchmarksConfig withInputSolutionFiles(File... inputSolutionFiles) {
this.setInputSolutionFileList(List.of(inputSolutionFiles));
return this;
}
public ProblemBenchmarksConfig withProblemStatisticsEnabled(Boolean problemStatisticEnabled) {
this.setProblemStatisticEnabled(problemStatisticEnabled);
return this;
}
public ProblemBenchmarksConfig withProblemStatisticTypeList(List<ProblemStatisticType> problemStatisticTypeList) {
this.setProblemStatisticTypeList(problemStatisticTypeList);
return this;
}
public ProblemBenchmarksConfig withProblemStatisticTypes(ProblemStatisticType... problemStatisticTypes) {
this.setProblemStatisticTypeList(List.of(problemStatisticTypes));
return this;
}
public ProblemBenchmarksConfig withSingleStatisticTypeList(List<SingleStatisticType> singleStatisticTypeList) {
this.setSingleStatisticTypeList(singleStatisticTypeList);
return this;
}
public ProblemBenchmarksConfig withSingleStatisticTypes(SingleStatisticType... singleStatisticTypes) {
this.setSingleStatisticTypeList(List.of(singleStatisticTypes));
return this;
}
// ************************************************************************
// Complex methods
// ************************************************************************
/**
* Return the problem statistic type list, or a list containing default metrics if problemStatisticEnabled
* is not false. If problemStatisticEnabled is false, an empty list is returned.
*
* @return never null
*/
public List<ProblemStatisticType> determineProblemStatisticTypeList() {<FILL_FUNCTION_BODY>}
/**
* Return the single statistic type list, or an empty list if it is null
*
* @return never null
*/
public List<SingleStatisticType> determineSingleStatisticTypeList() {
return Objects.requireNonNullElse(singleStatisticTypeList, Collections.emptyList());
}
@Override
public ProblemBenchmarksConfig inherit(ProblemBenchmarksConfig inheritedConfig) {
solutionFileIOClass = ConfigUtils.inheritOverwritableProperty(solutionFileIOClass,
inheritedConfig.getSolutionFileIOClass());
writeOutputSolutionEnabled = ConfigUtils.inheritOverwritableProperty(writeOutputSolutionEnabled,
inheritedConfig.getWriteOutputSolutionEnabled());
inputSolutionFileList = ConfigUtils.inheritMergeableListProperty(inputSolutionFileList,
inheritedConfig.getInputSolutionFileList());
problemStatisticEnabled = ConfigUtils.inheritOverwritableProperty(problemStatisticEnabled,
inheritedConfig.getProblemStatisticEnabled());
problemStatisticTypeList = ConfigUtils.inheritMergeableListProperty(problemStatisticTypeList,
inheritedConfig.getProblemStatisticTypeList());
singleStatisticTypeList = ConfigUtils.inheritMergeableListProperty(singleStatisticTypeList,
inheritedConfig.getSingleStatisticTypeList());
return this;
}
@Override
public ProblemBenchmarksConfig copyConfig() {
return new ProblemBenchmarksConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(solutionFileIOClass);
}
}
|
if (problemStatisticEnabled != null && !problemStatisticEnabled) {
return Collections.emptyList();
}
if (problemStatisticTypeList == null || problemStatisticTypeList.isEmpty()) {
return ProblemStatisticType.defaultList();
}
return problemStatisticTypeList;
| 1,640
| 80
| 1,720
|
<methods>public non-sealed void <init>() ,public abstract org.optaplanner.benchmark.config.ProblemBenchmarksConfig copyConfig() ,public abstract org.optaplanner.benchmark.config.ProblemBenchmarksConfig inherit(org.optaplanner.benchmark.config.ProblemBenchmarksConfig) ,public java.lang.String toString() ,public abstract void visitReferencedClasses(Consumer<Class<?>>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/config/SolverBenchmarkConfig.java
|
SolverBenchmarkConfig
|
visitReferencedClasses
|
class SolverBenchmarkConfig extends AbstractConfig<SolverBenchmarkConfig> {
private String name = null;
@XmlElement(name = SolverConfig.XML_ELEMENT_NAME, namespace = SolverConfig.XML_NAMESPACE)
private SolverConfig solverConfig = null;
@XmlElement(name = "problemBenchmarks")
private ProblemBenchmarksConfig problemBenchmarksConfig = null;
private Integer subSingleCount = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SolverConfig getSolverConfig() {
return solverConfig;
}
public void setSolverConfig(SolverConfig solverConfig) {
this.solverConfig = solverConfig;
}
public ProblemBenchmarksConfig getProblemBenchmarksConfig() {
return problemBenchmarksConfig;
}
public void setProblemBenchmarksConfig(ProblemBenchmarksConfig problemBenchmarksConfig) {
this.problemBenchmarksConfig = problemBenchmarksConfig;
}
public Integer getSubSingleCount() {
return subSingleCount;
}
public void setSubSingleCount(Integer subSingleCount) {
this.subSingleCount = subSingleCount;
}
// ************************************************************************
// With methods
// ************************************************************************
public SolverBenchmarkConfig withName(String name) {
this.setName(name);
return this;
}
public SolverBenchmarkConfig withSolverConfig(SolverConfig solverConfig) {
this.setSolverConfig(solverConfig);
return this;
}
public SolverBenchmarkConfig withProblemBenchmarksConfig(ProblemBenchmarksConfig problemBenchmarksConfig) {
this.setProblemBenchmarksConfig(problemBenchmarksConfig);
return this;
}
public SolverBenchmarkConfig withSubSingleCount(Integer subSingleCount) {
this.setSubSingleCount(subSingleCount);
return this;
}
@Override
public SolverBenchmarkConfig inherit(SolverBenchmarkConfig inheritedConfig) {
solverConfig = ConfigUtils.inheritConfig(solverConfig, inheritedConfig.getSolverConfig());
problemBenchmarksConfig = ConfigUtils.inheritConfig(problemBenchmarksConfig,
inheritedConfig.getProblemBenchmarksConfig());
subSingleCount = ConfigUtils.inheritOverwritableProperty(subSingleCount, inheritedConfig.getSubSingleCount());
return this;
}
@Override
public SolverBenchmarkConfig copyConfig() {
return new SolverBenchmarkConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {<FILL_FUNCTION_BODY>}
}
|
if (solverConfig != null) {
solverConfig.visitReferencedClasses(classVisitor);
}
if (problemBenchmarksConfig != null) {
problemBenchmarksConfig.visitReferencedClasses(classVisitor);
}
| 758
| 71
| 829
|
<methods>public non-sealed void <init>() ,public abstract org.optaplanner.benchmark.config.SolverBenchmarkConfig copyConfig() ,public abstract org.optaplanner.benchmark.config.SolverBenchmarkConfig inherit(org.optaplanner.benchmark.config.SolverBenchmarkConfig) ,public java.lang.String toString() ,public abstract void visitReferencedClasses(Consumer<Class<?>>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/config/blueprint/SolverBenchmarkBluePrintConfig.java
|
SolverBenchmarkBluePrintConfig
|
validate
|
class SolverBenchmarkBluePrintConfig {
protected SolverBenchmarkBluePrintType solverBenchmarkBluePrintType = null;
public SolverBenchmarkBluePrintType getSolverBenchmarkBluePrintType() {
return solverBenchmarkBluePrintType;
}
public void setSolverBenchmarkBluePrintType(SolverBenchmarkBluePrintType solverBenchmarkBluePrintType) {
this.solverBenchmarkBluePrintType = solverBenchmarkBluePrintType;
}
// ************************************************************************
// Builder methods
// ************************************************************************
public List<SolverBenchmarkConfig> buildSolverBenchmarkConfigList() {
validate();
return solverBenchmarkBluePrintType.buildSolverBenchmarkConfigList();
}
protected void validate() {<FILL_FUNCTION_BODY>}
// ************************************************************************
// With methods
// ************************************************************************
public SolverBenchmarkBluePrintConfig withSolverBenchmarkBluePrintType(
SolverBenchmarkBluePrintType solverBenchmarkBluePrintType) {
this.solverBenchmarkBluePrintType = solverBenchmarkBluePrintType;
return this;
}
}
|
if (solverBenchmarkBluePrintType == null) {
throw new IllegalArgumentException(
"The solverBenchmarkBluePrint must have"
+ " a solverBenchmarkBluePrintType (" + solverBenchmarkBluePrintType + ").");
}
| 316
| 70
| 386
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/config/report/BenchmarkReportConfig.java
|
BenchmarkReportConfig
|
inherit
|
class BenchmarkReportConfig extends AbstractConfig<BenchmarkReportConfig> {
@XmlJavaTypeAdapter(JaxbLocaleAdapter.class)
private Locale locale = null;
private SolverRankingType solverRankingType = null;
private Class<? extends Comparator<SolverBenchmarkResult>> solverRankingComparatorClass = null;
private Class<? extends SolverRankingWeightFactory> solverRankingWeightFactoryClass = null;
public BenchmarkReportConfig() {
}
public BenchmarkReportConfig(BenchmarkReportConfig inheritedConfig) {
inherit(inheritedConfig);
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public SolverRankingType getSolverRankingType() {
return solverRankingType;
}
public void setSolverRankingType(SolverRankingType solverRankingType) {
this.solverRankingType = solverRankingType;
}
public Class<? extends Comparator<SolverBenchmarkResult>> getSolverRankingComparatorClass() {
return solverRankingComparatorClass;
}
public void setSolverRankingComparatorClass(
Class<? extends Comparator<SolverBenchmarkResult>> solverRankingComparatorClass) {
this.solverRankingComparatorClass = solverRankingComparatorClass;
}
public Class<? extends SolverRankingWeightFactory> getSolverRankingWeightFactoryClass() {
return solverRankingWeightFactoryClass;
}
public void setSolverRankingWeightFactoryClass(
Class<? extends SolverRankingWeightFactory> solverRankingWeightFactoryClass) {
this.solverRankingWeightFactoryClass = solverRankingWeightFactoryClass;
}
public Locale determineLocale() {
return getLocale() == null ? Locale.getDefault() : getLocale();
}
// ************************************************************************
// With methods
// ************************************************************************
public BenchmarkReportConfig withLocale(Locale locale) {
this.setLocale(locale);
return this;
}
public BenchmarkReportConfig withSolverRankingType(SolverRankingType solverRankingType) {
this.setSolverRankingType(solverRankingType);
return this;
}
public BenchmarkReportConfig withSolverRankingComparatorClass(
Class<? extends Comparator<SolverBenchmarkResult>> solverRankingComparatorClass) {
this.setSolverRankingComparatorClass(solverRankingComparatorClass);
return this;
}
public BenchmarkReportConfig withSolverRankingWeightFactoryClass(
Class<? extends SolverRankingWeightFactory> solverRankingWeightFactoryClass) {
this.setSolverRankingWeightFactoryClass(solverRankingWeightFactoryClass);
return this;
}
@Override
public BenchmarkReportConfig inherit(BenchmarkReportConfig inheritedConfig) {<FILL_FUNCTION_BODY>}
@Override
public BenchmarkReportConfig copyConfig() {
return new BenchmarkReportConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(solverRankingComparatorClass);
classVisitor.accept(solverRankingWeightFactoryClass);
}
}
|
locale = ConfigUtils.inheritOverwritableProperty(locale, inheritedConfig.getLocale());
solverRankingType = ConfigUtils.inheritOverwritableProperty(solverRankingType,
inheritedConfig.getSolverRankingType());
solverRankingComparatorClass = ConfigUtils.inheritOverwritableProperty(solverRankingComparatorClass,
inheritedConfig.getSolverRankingComparatorClass());
solverRankingWeightFactoryClass = ConfigUtils.inheritOverwritableProperty(solverRankingWeightFactoryClass,
inheritedConfig.getSolverRankingWeightFactoryClass());
return this;
| 952
| 159
| 1,111
|
<methods>public non-sealed void <init>() ,public abstract org.optaplanner.benchmark.config.report.BenchmarkReportConfig copyConfig() ,public abstract org.optaplanner.benchmark.config.report.BenchmarkReportConfig inherit(org.optaplanner.benchmark.config.report.BenchmarkReportConfig) ,public java.lang.String toString() ,public abstract void visitReferencedClasses(Consumer<Class<?>>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/aggregator/swingui/CheckBoxTree.java
|
CheckBoxTree
|
resolveNewCheckBoxState
|
class CheckBoxTree extends JTree {
private static final Color TREE_SELECTION_COLOR = UIManager.getColor("Tree.selectionBackground");
private Set<DefaultMutableTreeNode> selectedSingleBenchmarkNodes = new HashSet<>();
public CheckBoxTree(DefaultMutableTreeNode root) {
super(root);
addMouseListener(new CheckBoxTreeMouseListener(this));
setCellRenderer(new CheckBoxTreeCellRenderer());
setToggleClickCount(0);
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}
public Set<DefaultMutableTreeNode> getSelectedSingleBenchmarkNodes() {
return selectedSingleBenchmarkNodes;
}
public void setSelectedSingleBenchmarkNodes(Set<DefaultMutableTreeNode> selectedSingleBenchmarkNodes) {
this.selectedSingleBenchmarkNodes = selectedSingleBenchmarkNodes;
}
public void expandNodes() {
expandSubtree(null, true);
}
public void collapseNodes() {
expandSubtree(null, false);
}
private void expandSubtree(TreePath path, boolean expand) {
if (path == null) {
TreePath selectionPath = getSelectionPath();
path = selectionPath == null ? new TreePath(treeModel.getRoot()) : selectionPath;
}
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
Enumeration children = currentNode.children();
while (children.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
TreePath expandedPath = path.pathByAddingChild(child);
expandSubtree(expandedPath, expand);
}
if (expand) {
expandPath(path);
} else if (path.getParentPath() != null) {
collapsePath(path);
}
}
public void updateHierarchyCheckBoxStates() {
for (DefaultMutableTreeNode currentNode : selectedSingleBenchmarkNodes) {
resolveNewCheckBoxState(currentNode, CHECKED, MIXED);
}
treeDidChange();
}
private void resolveNewCheckBoxState(DefaultMutableTreeNode currentNode, MixedCheckBox.MixedCheckBoxStatus newStatus,
MixedCheckBox.MixedCheckBoxStatus mixedStatus) {<FILL_FUNCTION_BODY>}
private void selectChildren(DefaultMutableTreeNode parent, MixedCheckBox.MixedCheckBoxStatus status) {
MixedCheckBox box = (MixedCheckBox) parent.getUserObject();
if (box.getBenchmarkResult() instanceof SingleBenchmarkResult) {
if (status == CHECKED) {
selectedSingleBenchmarkNodes.add(parent);
} else if (status == UNCHECKED) {
selectedSingleBenchmarkNodes.remove(parent);
}
}
Enumeration children = parent.children();
while (children.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
MixedCheckBox childCheckBox = (MixedCheckBox) child.getUserObject();
childCheckBox.setStatus(status);
selectChildren(child, status);
}
}
private boolean checkChildren(DefaultMutableTreeNode parent, MixedCheckBox.MixedCheckBoxStatus status) {
boolean childrenCheck = true;
Enumeration children = parent.children();
while (children.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
MixedCheckBox checkBox = (MixedCheckBox) child.getUserObject();
if (checkBox.getStatus() != status) {
childrenCheck = false;
break;
}
}
return childrenCheck;
}
private class CheckBoxTreeMouseListener extends MouseAdapter {
private CheckBoxTree tree;
private double unlabeledMixedCheckBoxWidth;
public CheckBoxTreeMouseListener(CheckBoxTree tree) {
this.tree = tree;
unlabeledMixedCheckBoxWidth = new MixedCheckBox().getPreferredSize().getWidth();
}
@Override
public void mousePressed(MouseEvent e) {
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path != null) {
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
MixedCheckBox checkBox = (MixedCheckBox) currentNode.getUserObject();
// ignore clicks on checkbox's label - enables to select it without changing the state
if (e.getX() - tree.getPathBounds(path).getX() > unlabeledMixedCheckBoxWidth) {
return;
}
switch (checkBox.getStatus()) {
case CHECKED:
resolveNewCheckBoxState(currentNode, UNCHECKED, MIXED);
break;
case UNCHECKED:
resolveNewCheckBoxState(currentNode, CHECKED, MIXED);
break;
case MIXED:
resolveNewCheckBoxState(currentNode, CHECKED, null);
break;
default:
throw new IllegalStateException("The status (" + checkBox.getStatus() + ") is not implemented.");
}
tree.treeDidChange();
}
}
}
private static class CheckBoxTreeCellRenderer implements TreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
MixedCheckBox checkBox = (MixedCheckBox) node.getUserObject();
checkBox.setBackground(selected ? TREE_SELECTION_COLOR : Color.WHITE);
return checkBox;
}
}
}
|
MixedCheckBox checkBox = (MixedCheckBox) currentNode.getUserObject();
checkBox.setStatus(newStatus);
selectChildren(currentNode, newStatus);
TreeNode[] ancestorNodes = currentNode.getPath();
// examine ancestors, don't lose track of most recent changes - bottom-up approach
for (int i = ancestorNodes.length - 2; i >= 0; i--) {
DefaultMutableTreeNode ancestorNode = (DefaultMutableTreeNode) ancestorNodes[i];
MixedCheckBox ancestorCheckbox = (MixedCheckBox) ancestorNode.getUserObject();
if (checkChildren(ancestorNode, newStatus)) {
ancestorCheckbox.setStatus(newStatus);
} else {
if (mixedStatus == null) {
break;
}
ancestorCheckbox.setStatus(mixedStatus);
}
}
| 1,487
| 228
| 1,715
|
<methods>public void <init>() ,public void <init>(java.lang.Object[]) ,public void <init>(Vector<?>) ,public void <init>(Hashtable<?,?>) ,public void <init>(javax.swing.tree.TreeNode) ,public void <init>(javax.swing.tree.TreeModel) ,public void <init>(javax.swing.tree.TreeNode, boolean) ,public void addSelectionInterval(int, int) ,public void addSelectionPath(javax.swing.tree.TreePath) ,public void addSelectionPaths(javax.swing.tree.TreePath[]) ,public void addSelectionRow(int) ,public void addSelectionRows(int[]) ,public void addTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void addTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void addTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void cancelEditing() ,public void clearSelection() ,public void collapsePath(javax.swing.tree.TreePath) ,public void collapseRow(int) ,public java.lang.String convertValueToText(java.lang.Object, boolean, boolean, boolean, int, boolean) ,public void expandPath(javax.swing.tree.TreePath) ,public void expandRow(int) ,public void fireTreeCollapsed(javax.swing.tree.TreePath) ,public void fireTreeExpanded(javax.swing.tree.TreePath) ,public void fireTreeWillCollapse(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public void fireTreeWillExpand(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.tree.TreePath getAnchorSelectionPath() ,public javax.swing.tree.TreeCellEditor getCellEditor() ,public javax.swing.tree.TreeCellRenderer getCellRenderer() ,public javax.swing.tree.TreePath getClosestPathForLocation(int, int) ,public int getClosestRowForLocation(int, int) ,public boolean getDragEnabled() ,public final javax.swing.JTree.DropLocation getDropLocation() ,public final javax.swing.DropMode getDropMode() ,public javax.swing.tree.TreePath getEditingPath() ,public Enumeration<javax.swing.tree.TreePath> getExpandedDescendants(javax.swing.tree.TreePath) ,public boolean getExpandsSelectedPaths() ,public boolean getInvokesStopCellEditing() ,public java.lang.Object getLastSelectedPathComponent() ,public javax.swing.tree.TreePath getLeadSelectionPath() ,public int getLeadSelectionRow() ,public int getMaxSelectionRow() ,public int getMinSelectionRow() ,public javax.swing.tree.TreeModel getModel() ,public javax.swing.tree.TreePath getNextMatch(java.lang.String, int, javax.swing.text.Position.Bias) ,public java.awt.Rectangle getPathBounds(javax.swing.tree.TreePath) ,public javax.swing.tree.TreePath getPathForLocation(int, int) ,public javax.swing.tree.TreePath getPathForRow(int) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public java.awt.Rectangle getRowBounds(int) ,public int getRowCount() ,public int getRowForLocation(int, int) ,public int getRowForPath(javax.swing.tree.TreePath) ,public int getRowHeight() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollsOnExpand() ,public int getSelectionCount() ,public javax.swing.tree.TreeSelectionModel getSelectionModel() ,public javax.swing.tree.TreePath getSelectionPath() ,public javax.swing.tree.TreePath[] getSelectionPaths() ,public int[] getSelectionRows() ,public boolean getShowsRootHandles() ,public int getToggleClickCount() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public javax.swing.event.TreeExpansionListener[] getTreeExpansionListeners() ,public javax.swing.event.TreeSelectionListener[] getTreeSelectionListeners() ,public javax.swing.event.TreeWillExpandListener[] getTreeWillExpandListeners() ,public javax.swing.plaf.TreeUI getUI() ,public java.lang.String getUIClassID() ,public int getVisibleRowCount() ,public boolean hasBeenExpanded(javax.swing.tree.TreePath) ,public boolean isCollapsed(javax.swing.tree.TreePath) ,public boolean isCollapsed(int) ,public boolean isEditable() ,public boolean isEditing() ,public boolean isExpanded(javax.swing.tree.TreePath) ,public boolean isExpanded(int) ,public boolean isFixedRowHeight() ,public boolean isLargeModel() ,public boolean isPathEditable(javax.swing.tree.TreePath) ,public boolean isPathSelected(javax.swing.tree.TreePath) ,public boolean isRootVisible() ,public boolean isRowSelected(int) ,public boolean isSelectionEmpty() ,public boolean isVisible(javax.swing.tree.TreePath) ,public void makeVisible(javax.swing.tree.TreePath) ,public void removeSelectionInterval(int, int) ,public void removeSelectionPath(javax.swing.tree.TreePath) ,public void removeSelectionPaths(javax.swing.tree.TreePath[]) ,public void removeSelectionRow(int) ,public void removeSelectionRows(int[]) ,public void removeTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void removeTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void removeTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void scrollPathToVisible(javax.swing.tree.TreePath) ,public void scrollRowToVisible(int) ,public void setAnchorSelectionPath(javax.swing.tree.TreePath) ,public void setCellEditor(javax.swing.tree.TreeCellEditor) ,public void setCellRenderer(javax.swing.tree.TreeCellRenderer) ,public void setDragEnabled(boolean) ,public final void setDropMode(javax.swing.DropMode) ,public void setEditable(boolean) ,public void setExpandsSelectedPaths(boolean) ,public void setInvokesStopCellEditing(boolean) ,public void setLargeModel(boolean) ,public void setLeadSelectionPath(javax.swing.tree.TreePath) ,public void setModel(javax.swing.tree.TreeModel) ,public void setRootVisible(boolean) ,public void setRowHeight(int) ,public void setScrollsOnExpand(boolean) ,public void setSelectionInterval(int, int) ,public void setSelectionModel(javax.swing.tree.TreeSelectionModel) ,public void setSelectionPath(javax.swing.tree.TreePath) ,public void setSelectionPaths(javax.swing.tree.TreePath[]) ,public void setSelectionRow(int) ,public void setSelectionRows(int[]) ,public void setShowsRootHandles(boolean) ,public void setToggleClickCount(int) ,public void setUI(javax.swing.plaf.TreeUI) ,public void setVisibleRowCount(int) ,public void startEditingAtPath(javax.swing.tree.TreePath) ,public boolean stopEditing() ,public void treeDidChange() ,public void updateUI() <variables>static final boolean $assertionsDisabled,public static final java.lang.String ANCHOR_SELECTION_PATH_PROPERTY,public static final java.lang.String CELL_EDITOR_PROPERTY,public static final java.lang.String CELL_RENDERER_PROPERTY,public static final java.lang.String EDITABLE_PROPERTY,public static final java.lang.String EXPANDS_SELECTED_PATHS_PROPERTY,public static final java.lang.String INVOKES_STOP_CELL_EDITING_PROPERTY,public static final java.lang.String LARGE_MODEL_PROPERTY,public static final java.lang.String LEAD_SELECTION_PATH_PROPERTY,public static final java.lang.String ROOT_VISIBLE_PROPERTY,public static final java.lang.String ROW_HEIGHT_PROPERTY,public static final java.lang.String SCROLLS_ON_EXPAND_PROPERTY,public static final java.lang.String SELECTION_MODEL_PROPERTY,public static final java.lang.String SHOWS_ROOT_HANDLES_PROPERTY,private static int TEMP_STACK_SIZE,public static final java.lang.String TOGGLE_CLICK_COUNT_PROPERTY,public static final java.lang.String TREE_MODEL_PROPERTY,public static final java.lang.String VISIBLE_ROW_COUNT_PROPERTY,private javax.swing.tree.TreePath anchorPath,protected transient javax.swing.tree.TreeCellEditor cellEditor,protected transient javax.swing.tree.TreeCellRenderer cellRenderer,private boolean dragEnabled,private transient javax.swing.JTree.DropLocation dropLocation,private javax.swing.DropMode dropMode,private javax.swing.JTree.TreeTimer dropTimer,protected boolean editable,private int expandRow,private transient Stack<Stack<javax.swing.tree.TreePath>> expandedStack,private transient Hashtable<javax.swing.tree.TreePath,java.lang.Boolean> expandedState,private boolean expandsSelectedPaths,protected boolean invokesStopCellEditing,protected boolean largeModel,private javax.swing.tree.TreePath leadPath,protected boolean rootVisible,protected int rowHeight,private boolean rowHeightSet,protected boolean scrollsOnExpand,private boolean scrollsOnExpandSet,protected transient javax.swing.tree.TreeSelectionModel selectionModel,protected transient javax.swing.JTree.TreeSelectionRedirector selectionRedirector,private boolean settingUI,protected boolean showsRootHandles,private boolean showsRootHandlesSet,protected int toggleClickCount,protected transient javax.swing.tree.TreeModel treeModel,protected transient javax.swing.event.TreeModelListener treeModelListener,private static final java.lang.String uiClassID,private transient javax.swing.event.TreeExpansionListener uiTreeExpansionListener,private transient boolean updateInProgress,protected int visibleRowCount
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/aggregator/swingui/MixedCheckBox.java
|
MixedCheckBoxModel
|
setStatus
|
class MixedCheckBoxModel extends ToggleButtonModel {
private MixedCheckBoxStatus getStatus() {
return isSelected() ? (isArmed() ? MixedCheckBoxStatus.MIXED : MixedCheckBoxStatus.CHECKED)
: MixedCheckBoxStatus.UNCHECKED;
}
private void setStatus(MixedCheckBoxStatus status) {<FILL_FUNCTION_BODY>}
private void switchStatus() {
switch (getStatus()) {
case CHECKED:
setStatus(MixedCheckBoxStatus.UNCHECKED);
break;
case UNCHECKED:
setStatus(MixedCheckBoxStatus.CHECKED);
break;
case MIXED:
setStatus(MixedCheckBoxStatus.CHECKED);
break;
default:
throw new IllegalStateException("The status (" + getStatus() + ") is not implemented.");
}
}
}
|
if (status == MixedCheckBoxStatus.CHECKED) {
setSelected(true);
setArmed(false);
setPressed(false);
} else if (status == MixedCheckBoxStatus.UNCHECKED) {
setSelected(false);
setArmed(false);
setPressed(false);
} else if (status == MixedCheckBoxStatus.MIXED) {
setSelected(true);
setArmed(true);
setPressed(true);
} else {
throw new IllegalArgumentException("Invalid argument ("
+ status + ") supplied.");
}
| 228
| 152
| 380
|
<methods>public void <init>() ,public void <init>(javax.swing.Icon) ,public void <init>(java.lang.String) ,public void <init>(javax.swing.Action) ,public void <init>(javax.swing.Icon, boolean) ,public void <init>(java.lang.String, boolean) ,public void <init>(java.lang.String, javax.swing.Icon) ,public void <init>(java.lang.String, javax.swing.Icon, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.lang.String getUIClassID() ,public boolean isBorderPaintedFlat() ,public void setBorderPaintedFlat(boolean) ,public void updateUI() <variables>public static final java.lang.String BORDER_PAINTED_FLAT_CHANGED_PROPERTY,private boolean flat,private static final java.lang.String uiClassID
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/cli/OptaPlannerBenchmarkCli.java
|
OptaPlannerBenchmarkCli
|
main
|
class OptaPlannerBenchmarkCli {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
if (args.length != 2) {
System.err.println("Usage: OptaPlannerBenchmarkCli benchmarkConfigFile benchmarkDirectory");
System.exit(1);
}
File benchmarkConfigFile = new File(args[0]);
if (!benchmarkConfigFile.exists()) {
System.err.println("The benchmarkConfigFile (" + benchmarkConfigFile + ") does not exist.");
System.exit(1);
}
File benchmarkDirectory = new File(args[1]);
PlannerBenchmarkConfig benchmarkConfig;
if (benchmarkConfigFile.getName().endsWith(".ftl")) {
benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(benchmarkConfigFile);
} else {
benchmarkConfig = PlannerBenchmarkConfig.createFromXmlFile(benchmarkConfigFile);
}
benchmarkConfig.setBenchmarkDirectory(benchmarkDirectory);
PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.create(benchmarkConfig);
PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark();
benchmark.benchmark();
| 40
| 275
| 315
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/io/PlannerBenchmarkConfigIO.java
|
PlannerBenchmarkConfigIO
|
read
|
class PlannerBenchmarkConfigIO implements JaxbIO<PlannerBenchmarkConfig> {
private static final String BENCHMARK_XSD_RESOURCE = "/benchmark.xsd";
private final GenericJaxbIO<PlannerBenchmarkConfig> genericJaxbIO = new GenericJaxbIO<>(PlannerBenchmarkConfig.class);
@Override
public PlannerBenchmarkConfig read(Reader reader) {<FILL_FUNCTION_BODY>}
@Override
public void write(PlannerBenchmarkConfig plannerBenchmarkConfig, Writer writer) {
genericJaxbIO.writeWithoutNamespaces(plannerBenchmarkConfig, writer);
}
}
|
Document document = genericJaxbIO.parseXml(reader);
String rootElementNamespace = document.getDocumentElement().getNamespaceURI();
if (PlannerBenchmarkConfig.XML_NAMESPACE.equals(rootElementNamespace)) { // If there is the correct namespace, validate.
genericJaxbIO.validate(document, BENCHMARK_XSD_RESOURCE);
/*
* In JAXB annotations the SolverConfig belongs to a different namespace than the PlannerBenchmarkConfig.
* However, benchmark.xsd merges both namespaces into a single one. As a result, JAXB is incapable of matching
* the solver element in benchmark configuration and thus the solver element's namespace needs to be overridden.
*/
return genericJaxbIO.readOverridingNamespace(document,
ElementNamespaceOverride.of(SolverConfig.XML_ELEMENT_NAME, SolverConfig.XML_NAMESPACE));
} else if (rootElementNamespace == null || rootElementNamespace.isEmpty()) {
// If not, add the missing namespace to maintain backward compatibility.
return genericJaxbIO.readOverridingNamespace(document,
ElementNamespaceOverride.of(PlannerBenchmarkConfig.XML_ELEMENT_NAME, PlannerBenchmarkConfig.XML_NAMESPACE),
ElementNamespaceOverride.of(SolverConfig.XML_ELEMENT_NAME, SolverConfig.XML_NAMESPACE));
} else { // If there is an unexpected namespace, fail fast.
String errorMessage = String.format("The <%s/> element belongs to a different namespace (%s) than expected (%s).",
PlannerBenchmarkConfig.XML_ELEMENT_NAME, rootElementNamespace, PlannerBenchmarkConfig.XML_NAMESPACE);
throw new IllegalArgumentException(errorMessage);
}
| 180
| 447
| 627
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/measurement/ScoreDifferencePercentage.java
|
ScoreDifferencePercentage
|
calculateScoreDifferencePercentage
|
class ScoreDifferencePercentage {
public static <Score_ extends Score<Score_>> ScoreDifferencePercentage calculateScoreDifferencePercentage(
Score_ baseScore, Score_ valueScore) {<FILL_FUNCTION_BODY>}
public static double calculateDifferencePercentage(double base, double value) {
double difference = value - base;
if (base < 0.0) {
return difference / -base;
} else if (base == 0.0) {
if (difference == 0.0) {
return 0.0;
} else {
// percentageLevel will return Infinity or -Infinity
return difference / base;
}
} else {
return difference / base;
}
}
private final double[] percentageLevels;
public ScoreDifferencePercentage(double[] percentageLevels) {
this.percentageLevels = percentageLevels;
}
public double[] getPercentageLevels() {
return percentageLevels;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public ScoreDifferencePercentage add(ScoreDifferencePercentage addend) {
if (percentageLevels.length != addend.getPercentageLevels().length) {
throw new IllegalStateException("The addend (" + addend + ")'s levelsLength (" +
addend.getPercentageLevels().length + ") is different from the base (" +
this + ")'s levelsLength (" + percentageLevels.length + ").");
}
double[] newPercentageLevels = new double[percentageLevels.length];
for (int i = 0; i < percentageLevels.length; i++) {
newPercentageLevels[i] = percentageLevels[i] + addend.percentageLevels[i];
}
return new ScoreDifferencePercentage(newPercentageLevels);
}
public ScoreDifferencePercentage subtract(ScoreDifferencePercentage subtrahend) {
if (percentageLevels.length != subtrahend.getPercentageLevels().length) {
throw new IllegalStateException("The subtrahend (" + subtrahend + ")'s levelsLength (" +
subtrahend.getPercentageLevels().length + ") is different from the base (" +
this + ")'s levelsLength (" + percentageLevels.length + ").");
}
double[] newPercentageLevels = new double[percentageLevels.length];
for (int i = 0; i < percentageLevels.length; i++) {
newPercentageLevels[i] = percentageLevels[i] - subtrahend.percentageLevels[i];
}
return new ScoreDifferencePercentage(newPercentageLevels);
}
public ScoreDifferencePercentage multiply(double multiplicand) {
double[] newPercentageLevels = new double[percentageLevels.length];
for (int i = 0; i < percentageLevels.length; i++) {
newPercentageLevels[i] = percentageLevels[i] * multiplicand;
}
return new ScoreDifferencePercentage(newPercentageLevels);
}
public ScoreDifferencePercentage divide(double divisor) {
double[] newPercentageLevels = new double[percentageLevels.length];
for (int i = 0; i < percentageLevels.length; i++) {
newPercentageLevels[i] = percentageLevels[i] / divisor;
}
return new ScoreDifferencePercentage(newPercentageLevels);
}
@Override
public String toString() {
return toString(Locale.US);
}
public String toString(Locale locale) {
StringBuilder s = new StringBuilder(percentageLevels.length * 8);
DecimalFormat decimalFormat = new DecimalFormat("0.00%", DecimalFormatSymbols.getInstance(locale));
for (int i = 0; i < percentageLevels.length; i++) {
if (i > 0) {
s.append("/");
}
s.append(decimalFormat.format(percentageLevels[i]));
}
return s.toString();
}
}
|
double[] baseLevels = baseScore.toLevelDoubles();
double[] valueLevels = valueScore.toLevelDoubles();
if (baseLevels.length != valueLevels.length) {
throw new IllegalStateException("The baseScore (" + baseScore + ")'s levelsLength (" + baseLevels.length
+ ") is different from the valueScore (" + valueScore + ")'s levelsLength (" + valueLevels.length
+ ").");
}
double[] percentageLevels = new double[baseLevels.length];
for (int i = 0; i < baseLevels.length; i++) {
percentageLevels[i] = calculateDifferencePercentage(baseLevels[i], valueLevels[i]);
}
return new ScoreDifferencePercentage(percentageLevels);
| 1,098
| 205
| 1,303
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/ResilientScoreComparator.java
|
ResilientScoreComparator
|
compare
|
class ResilientScoreComparator implements Comparator<Score> {
private final ScoreDefinition aScoreDefinition;
public ResilientScoreComparator(ScoreDefinition aScoreDefinition) {
this.aScoreDefinition = aScoreDefinition;
}
@Override
public int compare(Score a, Score b) {<FILL_FUNCTION_BODY>}
}
|
if (a == null) {
return b == null ? 0 : -1;
} else if (b == null) {
return 1;
}
if (!aScoreDefinition.isCompatibleArithmeticArgument(a) ||
!aScoreDefinition.isCompatibleArithmeticArgument(b)) {
Number[] aNumbers = a.toLevelNumbers();
Number[] bNumbers = b.toLevelNumbers();
for (int i = 0; i < aNumbers.length || i < bNumbers.length; i++) {
Number aToken = i < aNumbers.length ? aNumbers[i] : 0;
Number bToken = i < bNumbers.length ? bNumbers[i] : 0;
int comparison;
if (aToken.getClass().equals(bToken.getClass())) {
comparison = ((Comparable) aToken).compareTo(bToken);
} else {
comparison = Double.compare(aToken.doubleValue(), bToken.doubleValue());
}
if (comparison != 0) {
return comparison;
}
}
return 0;
}
return a.compareTo(b);
| 97
| 298
| 395
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/TotalRankSolverRankingWeightFactory.java
|
TotalRankSolverRankingWeightFactory
|
createRankingWeight
|
class TotalRankSolverRankingWeightFactory implements SolverRankingWeightFactory {
private final Comparator<SingleBenchmarkResult> singleBenchmarkRankingComparator =
new TotalScoreSingleBenchmarkRankingComparator();
@Override
public Comparable createRankingWeight(List<SolverBenchmarkResult> solverBenchmarkResultList,
SolverBenchmarkResult solverBenchmarkResult) {<FILL_FUNCTION_BODY>}
public static class TotalRankSolverRankingWeight implements Comparable<TotalRankSolverRankingWeight> {
private final Comparator<SolverBenchmarkResult> totalScoreSolverRankingComparator =
new TotalScoreSolverRankingComparator();
private SolverBenchmarkResult solverBenchmarkResult;
private int betterCount;
private int equalCount;
private int lowerCount;
public SolverBenchmarkResult getSolverBenchmarkResult() {
return solverBenchmarkResult;
}
public int getBetterCount() {
return betterCount;
}
public int getEqualCount() {
return equalCount;
}
public int getLowerCount() {
return lowerCount;
}
public TotalRankSolverRankingWeight(SolverBenchmarkResult solverBenchmarkResult,
int betterCount, int equalCount, int lowerCount) {
this.solverBenchmarkResult = solverBenchmarkResult;
this.betterCount = betterCount;
this.equalCount = equalCount;
this.lowerCount = lowerCount;
}
@Override
public int compareTo(TotalRankSolverRankingWeight other) {
return Comparator
.comparingInt(TotalRankSolverRankingWeight::getBetterCount)
.thenComparingInt(TotalRankSolverRankingWeight::getEqualCount)
.thenComparingInt(TotalRankSolverRankingWeight::getLowerCount)
.thenComparing(TotalRankSolverRankingWeight::getSolverBenchmarkResult, totalScoreSolverRankingComparator) // Tie-breaker
.compare(this, other);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof TotalRankSolverRankingWeight) {
TotalRankSolverRankingWeight other = (TotalRankSolverRankingWeight) o;
return this.compareTo(other) == 0;
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(betterCount, equalCount, lowerCount);
}
}
}
|
int betterCount = 0;
int equalCount = 0;
int lowerCount = 0;
List<SingleBenchmarkResult> singleBenchmarkResultList = solverBenchmarkResult.getSingleBenchmarkResultList();
for (SingleBenchmarkResult single : singleBenchmarkResultList) {
List<SingleBenchmarkResult> otherSingleList = single.getProblemBenchmarkResult().getSingleBenchmarkResultList();
for (SingleBenchmarkResult otherSingle : otherSingleList) {
if (single == otherSingle) {
continue;
}
int scoreComparison = singleBenchmarkRankingComparator.compare(single, otherSingle);
if (scoreComparison > 0) {
betterCount++;
} else if (scoreComparison == 0) {
equalCount++;
} else {
lowerCount++;
}
}
}
return new TotalRankSolverRankingWeight(solverBenchmarkResult, betterCount, equalCount, lowerCount);
| 711
| 252
| 963
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/TotalScoreSolverRankingComparator.java
|
TotalScoreSolverRankingComparator
|
compare
|
class TotalScoreSolverRankingComparator implements Comparator<SolverBenchmarkResult> {
private final Comparator<SolverBenchmarkResult> worstScoreSolverRankingComparator = new WorstScoreSolverRankingComparator();
@Override
public int compare(SolverBenchmarkResult a, SolverBenchmarkResult b) {<FILL_FUNCTION_BODY>}
}
|
ScoreDefinition aScoreDefinition = a.getScoreDefinition();
return Comparator
.comparing(SolverBenchmarkResult::getFailureCount, Comparator.reverseOrder())
.thenComparing(SolverBenchmarkResult::getTotalScore,
new ResilientScoreComparator(aScoreDefinition))
.thenComparing(worstScoreSolverRankingComparator)
.compare(a, b);
| 109
| 112
| 221
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/WorstScoreSolverRankingComparator.java
|
WorstScoreSolverRankingComparator
|
compare
|
class WorstScoreSolverRankingComparator implements Comparator<SolverBenchmarkResult> {
private final Comparator<SingleBenchmarkResult> singleBenchmarkComparator =
new TotalScoreSingleBenchmarkRankingComparator();
@Override
public int compare(SolverBenchmarkResult a, SolverBenchmarkResult b) {<FILL_FUNCTION_BODY>}
}
|
List<SingleBenchmarkResult> aSingleBenchmarkResultList = a.getSingleBenchmarkResultList();
List<SingleBenchmarkResult> bSingleBenchmarkResultList = b.getSingleBenchmarkResultList();
// Order scores from worst to best
aSingleBenchmarkResultList.sort(singleBenchmarkComparator);
bSingleBenchmarkResultList.sort(singleBenchmarkComparator);
int aSize = aSingleBenchmarkResultList.size();
int bSize = bSingleBenchmarkResultList.size();
for (int i = 0; i < aSize && i < bSize; i++) {
int comparison = singleBenchmarkComparator.compare(aSingleBenchmarkResultList.get(i),
bSingleBenchmarkResultList.get(i));
if (comparison != 0) {
return comparison;
}
}
return Integer.compare(aSize, bSize);
| 109
| 239
| 348
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/report/MillisecondDurationNumberFormatFactory.java
|
MillisecondDurationNumberFormat
|
processNonZeroMillis
|
class MillisecondDurationNumberFormat extends TemplateNumberFormat {
static final MillisecondDurationNumberFormat INSTANCE = new MillisecondDurationNumberFormat();
@Override
public String formatToPlainText(TemplateNumberModel templateNumberModel) throws TemplateModelException {
Number n = templateNumberModel.getAsNumber();
if (n == null) {
return "None.";
}
long millis = n.longValue();
if (millis == 0L) {
return "0 ms.";
}
return processNonZeroMillis(millis);
}
private static String processNonZeroMillis(long millis) {<FILL_FUNCTION_BODY>}
@Override
public boolean isLocaleBound() {
return true;
}
@Override
public String getDescription() {
return "Millisecond Duration";
}
}
|
Duration duration = Duration.ofMillis(millis);
long daysPart = duration.toDaysPart();
long hoursPart = duration.toHoursPart();
long minutesPart = duration.toMinutesPart();
double seconds = duration.toSecondsPart() + (duration.toMillisPart() / 1000.0d);
if (daysPart > 0) {
return String.format("%02d:%02d:%02d:%06.3f s. (%,d ms.)",
daysPart,
hoursPart,
minutesPart,
seconds,
millis);
} else if (hoursPart > 0) {
return String.format("%02d:%02d:%06.3f s. (%,d ms.)",
hoursPart,
minutesPart,
seconds,
millis);
} else if (minutesPart > 0) {
return String.format("%02d:%06.3f s. (%,d ms.)",
minutesPart,
seconds,
millis);
} else {
return String.format("%.3f s. (%,d ms.)",
seconds,
millis);
}
| 220
| 306
| 526
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/report/WebsiteResourceUtils.java
|
WebsiteResourceUtils
|
copyResourcesTo
|
class WebsiteResourceUtils {
private static final String RESOURCE_NAMESPACE = "/org/optaplanner/benchmark/impl/report/";
public static void copyResourcesTo(File benchmarkReportDirectory) {<FILL_FUNCTION_BODY>}
private static void copyResource(File benchmarkReportDirectory, String websiteResource) {
File outputFile = new File(benchmarkReportDirectory, websiteResource);
outputFile.getParentFile().mkdirs();
try (InputStream in = WebsiteResourceUtils.class.getResourceAsStream(RESOURCE_NAMESPACE + websiteResource)) {
if (in == null) {
throw new IllegalStateException("The websiteResource (" + websiteResource
+ ") does not exist.");
}
Files.copy(in, outputFile.toPath());
} catch (IOException e) {
throw new IllegalStateException("Could not copy websiteResource (" + websiteResource
+ ") to outputFile (" + outputFile + ").", e);
}
}
private WebsiteResourceUtils() {
}
}
|
// Twitter Bootstrap
copyResource(benchmarkReportDirectory, "twitterbootstrap/css/bootstrap-responsive.css");
// copyResource(benchmarkReportDirectory, "twitterbootstrap/css/bootstrap-responsive.min.css");
copyResource(benchmarkReportDirectory, "twitterbootstrap/css/bootstrap.css");
// copyResource(benchmarkReportDirectory, "twitterbootstrap/css/bootstrap.min.css");
copyResource(benchmarkReportDirectory, "twitterbootstrap/css/prettify.css");
copyResource(benchmarkReportDirectory, "twitterbootstrap/img/glyphicons-halflings-white.png");
copyResource(benchmarkReportDirectory, "twitterbootstrap/img/glyphicons-halflings.png");
copyResource(benchmarkReportDirectory, "twitterbootstrap/js/bootstrap.js");
// copyResource(benchmarkReportDirectory, "twitterbootstrap/js/bootstrap.min.js");
copyResource(benchmarkReportDirectory, "twitterbootstrap/js/jquery.js");
// copyResource(benchmarkReportDirectory, "twitterbootstrap/js/jquery.min.js");
copyResource(benchmarkReportDirectory, "twitterbootstrap/js/prettify.js");
// Website resources
copyResource(benchmarkReportDirectory, "website/css/benchmarkReport.css");
copyResource(benchmarkReportDirectory, "website/img/optaPlannerLogo.png");
| 259
| 333
| 592
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/result/BenchmarkResultIO.java
|
BenchmarkResultIO
|
readPlannerBenchmarkResultList
|
class BenchmarkResultIO {
// BenchmarkResult contains <solverConfig/> element instead of the default SolverConfig.XML_ELEMENT_NAME.
private static final String SOLVER_CONFIG_XML_ELEMENT_NAME = "solverConfig";
private static final String PLANNER_BENCHMARK_RESULT_FILENAME = "plannerBenchmarkResult.xml";
private static final Logger LOGGER = LoggerFactory.getLogger(BenchmarkResultIO.class);
private final GenericJaxbIO<PlannerBenchmarkResult> genericJaxbIO = new GenericJaxbIO<>(PlannerBenchmarkResult.class);
public void writePlannerBenchmarkResult(File benchmarkReportDirectory,
PlannerBenchmarkResult plannerBenchmarkResult) {
File plannerBenchmarkResultFile = new File(benchmarkReportDirectory, PLANNER_BENCHMARK_RESULT_FILENAME);
try (Writer writer = new OutputStreamWriter(new FileOutputStream(plannerBenchmarkResultFile), StandardCharsets.UTF_8)) {
write(plannerBenchmarkResult, writer);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed writing plannerBenchmarkResultFile (" + plannerBenchmarkResultFile + ").", e);
}
}
public List<PlannerBenchmarkResult> readPlannerBenchmarkResultList(File benchmarkDirectory) {<FILL_FUNCTION_BODY>}
protected PlannerBenchmarkResult readPlannerBenchmarkResult(File plannerBenchmarkResultFile) {
if (!plannerBenchmarkResultFile.exists()) {
throw new IllegalArgumentException("The plannerBenchmarkResultFile (" + plannerBenchmarkResultFile
+ ") does not exist.");
}
PlannerBenchmarkResult plannerBenchmarkResult;
try (Reader reader = new InputStreamReader(new FileInputStream(plannerBenchmarkResultFile), StandardCharsets.UTF_8)) {
plannerBenchmarkResult = read(reader);
} catch (OptaPlannerXmlSerializationException e) {
LOGGER.warn("Failed reading plannerBenchmarkResultFile ({}).", plannerBenchmarkResultFile, e);
// If the plannerBenchmarkResultFile's format has changed, the app should not crash entirely
String benchmarkReportDirectoryName = plannerBenchmarkResultFile.getParentFile().getName();
plannerBenchmarkResult = PlannerBenchmarkResult.createUnmarshallingFailedResult(
benchmarkReportDirectoryName);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed reading plannerBenchmarkResultFile (" + plannerBenchmarkResultFile + ").", e);
}
plannerBenchmarkResult.setBenchmarkReportDirectory(plannerBenchmarkResultFile.getParentFile());
restoreOmittedBidirectionalFields(plannerBenchmarkResult);
restoreOtherOmittedFields(plannerBenchmarkResult);
return plannerBenchmarkResult;
}
protected PlannerBenchmarkResult read(Reader reader) {
return genericJaxbIO.readOverridingNamespace(reader,
ElementNamespaceOverride.of(SOLVER_CONFIG_XML_ELEMENT_NAME, SolverConfig.XML_NAMESPACE));
}
protected void write(PlannerBenchmarkResult plannerBenchmarkResult, Writer writer) {
genericJaxbIO.writeWithoutNamespaces(plannerBenchmarkResult, writer);
}
private void restoreOmittedBidirectionalFields(PlannerBenchmarkResult plannerBenchmarkResult) {
for (ProblemBenchmarkResult<Object> problemBenchmarkResult : plannerBenchmarkResult
.getUnifiedProblemBenchmarkResultList()) {
problemBenchmarkResult.setPlannerBenchmarkResult(plannerBenchmarkResult);
if (problemBenchmarkResult.getProblemStatisticList() == null) {
problemBenchmarkResult.setProblemStatisticList(new ArrayList<>(0));
}
for (ProblemStatistic problemStatistic : problemBenchmarkResult.getProblemStatisticList()) {
problemStatistic.setProblemBenchmarkResult(problemBenchmarkResult);
}
for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) {
singleBenchmarkResult.setProblemBenchmarkResult(problemBenchmarkResult);
}
}
for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) {
solverBenchmarkResult.setPlannerBenchmarkResult(plannerBenchmarkResult);
for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) {
singleBenchmarkResult.setSolverBenchmarkResult(solverBenchmarkResult);
for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult
.getSubSingleBenchmarkResultList()) {
if (subSingleBenchmarkResult.getPureSubSingleStatisticList() == null) {
subSingleBenchmarkResult.setPureSubSingleStatisticList(new ArrayList<>(0));
}
}
for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult
.getSubSingleBenchmarkResultList()) {
for (PureSubSingleStatistic pureSubSingleStatistic : subSingleBenchmarkResult
.getPureSubSingleStatisticList()) {
pureSubSingleStatistic.setSubSingleBenchmarkResult(subSingleBenchmarkResult);
}
}
}
}
}
private void restoreOtherOmittedFields(PlannerBenchmarkResult plannerBenchmarkResult) {
for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) {
SolverConfig solverConfig = solverBenchmarkResult.getSolverConfig();
DefaultSolverFactory<?> defaultSolverFactory = new DefaultSolverFactory<>(solverConfig);
solverBenchmarkResult.setScoreDefinition(defaultSolverFactory.getSolutionDescriptor().getScoreDefinition());
}
}
}
|
if (!benchmarkDirectory.exists() || !benchmarkDirectory.isDirectory()) {
throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory
+ ") does not exist or is not a directory.");
}
File[] benchmarkReportDirectories = benchmarkDirectory.listFiles(File::isDirectory);
if (benchmarkReportDirectories == null) {
throw new IllegalStateException("Unable to list the subdirectories in the benchmarkDirectory ("
+ benchmarkDirectory.getAbsolutePath() + ").");
}
Arrays.sort(benchmarkReportDirectories);
List<PlannerBenchmarkResult> plannerBenchmarkResultList = new ArrayList<>(benchmarkReportDirectories.length);
for (File benchmarkReportDirectory : benchmarkReportDirectories) {
File plannerBenchmarkResultFile = new File(benchmarkReportDirectory, PLANNER_BENCHMARK_RESULT_FILENAME);
if (plannerBenchmarkResultFile.exists()) {
PlannerBenchmarkResult plannerBenchmarkResult = readPlannerBenchmarkResult(plannerBenchmarkResultFile);
plannerBenchmarkResultList.add(plannerBenchmarkResult);
}
}
return plannerBenchmarkResultList;
| 1,557
| 300
| 1,857
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/PureSubSingleStatistic.java
|
PureSubSingleStatistic
|
getGraphFile
|
class PureSubSingleStatistic<Solution_, StatisticPoint_ extends StatisticPoint>
extends SubSingleStatistic<Solution_, StatisticPoint_> {
protected SingleStatisticType singleStatisticType;
protected PureSubSingleStatistic() {
// For JAXB.
}
protected PureSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult,
SingleStatisticType singleStatisticType) {
super(subSingleBenchmarkResult);
this.singleStatisticType = singleStatisticType;
}
@Override
public SingleStatisticType getStatisticType() {
return singleStatisticType;
}
// ************************************************************************
// Write methods
// ************************************************************************
public abstract void writeGraphFiles(BenchmarkReport benchmarkReport);
protected File writeChartToImageFile(JFreeChart chart, String fileNameBase) {
File chartFile = new File(subSingleBenchmarkResult.getResultDirectory(), fileNameBase + ".png");
GraphSupport.writeChartToImageFile(chart, chartFile);
return chartFile;
}
public File getGraphFile() {<FILL_FUNCTION_BODY>}
public abstract List<File> getGraphFileList();
@Override
public String toString() {
return subSingleBenchmarkResult + "_" + singleStatisticType;
}
}
|
List<File> graphFileList = getGraphFileList();
if (graphFileList == null || graphFileList.isEmpty()) {
return null;
} else if (graphFileList.size() > 1) {
throw new IllegalStateException("Cannot get graph file for the PureSubSingleStatistic (" + this
+ ") because it has more than 1 graph file. See method getGraphList() and "
+ SingleStatisticType.class.getSimpleName() + ".hasScoreLevels()");
} else {
return graphFileList.get(0);
}
| 351
| 142
| 493
|
<methods>public void close(StatisticRegistry<Solution_>, Tags, Solver<Solution_>) ,public java.lang.String getAnchorId() ,public java.io.File getCsvFile() ,public java.lang.String getCsvFileName() ,public List<StatisticPoint_> getPointList() ,public java.lang.String getRelativeCsvFilePath() ,public abstract org.optaplanner.benchmark.impl.statistic.StatisticType getStatisticType() ,public org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult getSubSingleBenchmarkResult() ,public void hibernatePointList() ,public void initPointList() ,public abstract void open(StatisticRegistry<Solution_>, Tags, Solver<Solution_>) ,public void setPointList(List<StatisticPoint_>) ,public void setSubSingleBenchmarkResult(org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult) ,public void unhibernatePointList() <variables>private static final java.lang.String FAILED,protected final transient Logger logger,protected List<StatisticPoint_> pointList,protected org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult subSingleBenchmarkResult
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/StatisticPoint.java
|
StatisticPoint
|
parseCsvLine
|
class StatisticPoint {
private static final Pattern DOUBLE_QUOTE = Pattern.compile("\"\"");
private static final Pattern SINGLE_QUOTE = Pattern.compile("\"");
public abstract String toCsvLine();
public static String buildCsvLineWithLongs(long timeMillisSpent, long... values) {
return LongStream.concat(LongStream.of(timeMillisSpent), Arrays.stream(values))
.mapToObj(Long::toString)
.collect(Collectors.joining(","));
}
public static String buildCsvLineWithDoubles(long timeMillisSpent, double... values) {
return timeMillisSpent + "," + Arrays.stream(values)
.mapToObj(Double::toString)
.collect(Collectors.joining(","));
}
public static String buildCsvLineWithStrings(long timeMillisSpent, String... values) {
return Stream.concat(Stream.of(timeMillisSpent), Arrays.stream(values))
.map(Object::toString)
.collect(Collectors.joining(","));
}
public static String buildCsvLine(String... values) {
return Arrays.stream(values)
.map(s -> '"' + SINGLE_QUOTE.matcher(s).replaceAll("\"\"") + '"')
.collect(Collectors.joining(","));
}
public static List<String> parseCsvLine(String line) {<FILL_FUNCTION_BODY>}
}
|
String[] tokens = line.split(",");
List<String> csvLine = new ArrayList<>(tokens.length);
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
while (token.startsWith("\"") && !token.endsWith("\"")) {
i++;
if (i >= tokens.length) {
throw new IllegalArgumentException("The CSV line (" + line + ") is not a valid CSV line.");
}
token += "," + tokens[i].trim();
}
if (token.startsWith("\"") && token.endsWith("\"")) {
token = token.substring(1, token.length() - 1);
token = DOUBLE_QUOTE.matcher(token).replaceAll("\"");
}
csvLine.add(token);
}
return csvLine;
| 398
| 230
| 628
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestscore/BestScoreSubSingleStatistic.java
|
BestScoreSubSingleStatistic
|
open
|
class BestScoreSubSingleStatistic<Solution_>
extends ProblemBasedSubSingleStatistic<Solution_, BestScoreStatisticPoint> {
BestScoreSubSingleStatistic() {
// For JAXB.
}
public BestScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SCORE);
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void open(StatisticRegistry<Solution_> registry, Tags runTag, Solver<Solution_> solver) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return StatisticPoint.buildCsvLine("timeMillisSpent", "score");
}
@Override
protected BestScoreStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition,
List<String> csvLine) {
return new BestScoreStatisticPoint(Long.parseLong(csvLine.get(0)),
scoreDefinition.parseScore(csvLine.get(1)));
}
}
|
registry.addListener(SolverMetric.BEST_SCORE,
timestamp -> registry.extractScoreFromMeters(SolverMetric.BEST_SCORE, runTag,
score -> pointList.add(new BestScoreStatisticPoint(timestamp, score))));
| 320
| 73
| 393
|
<methods>public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getStatisticType() ,public java.lang.String toString() <variables>protected org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationProblemStatistic.java
|
BestSolutionMutationProblemStatistic
|
writeGraphFiles
|
class BestSolutionMutationProblemStatistic extends ProblemStatistic {
protected File graphFile = null;
public BestSolutionMutationProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) {
super(problemBenchmarkResult, ProblemStatisticType.BEST_SOLUTION_MUTATION);
}
@Override
public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
return new BestSolutionMutationSubSingleStatistic(subSingleBenchmarkResult);
}
/**
* @return never null
*/
@Override
public List<File> getGraphFileList() {
return Collections.singletonList(graphFile);
}
// ************************************************************************
// Write methods
// ************************************************************************
@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {<FILL_FUNCTION_BODY>}
private XYPlot createPlot(BenchmarkReport benchmarkReport) {
Locale locale = benchmarkReport.getLocale();
NumberAxis xAxis = new NumberAxis("Time spent");
xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
NumberAxis yAxis = new NumberAxis("Best solution mutation count");
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(true);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
return plot;
}
}
|
XYPlot plot = createPlot(benchmarkReport);
int seriesIndex = 0;
for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) {
XYIntervalSeries series = new XYIntervalSeries(
singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix());
XYItemRenderer renderer = new YIntervalRenderer();
if (singleBenchmarkResult.hasAllSuccess()) {
BestSolutionMutationSubSingleStatistic subSingleStatistic =
(BestSolutionMutationSubSingleStatistic) singleBenchmarkResult
.getSubSingleStatistic(problemStatisticType);
List<BestSolutionMutationStatisticPoint> points = subSingleStatistic.getPointList();
for (BestSolutionMutationStatisticPoint point : points) {
long timeMillisSpent = point.getTimeMillisSpent();
long mutationCount = point.getMutationCount();
double yValue = mutationCount;
// In an XYInterval the yLow must be lower than yHigh
series.add(timeMillisSpent, timeMillisSpent, timeMillisSpent,
yValue, (yValue > 0.0) ? 0.0 : yValue, (yValue > 0.0) ? yValue : 0.0);
}
}
XYIntervalSeriesCollection dataset = new XYIntervalSeriesCollection();
dataset.addSeries(series);
plot.setDataset(seriesIndex, dataset);
if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) {
// Make the favorite more obvious
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
}
plot.setRenderer(seriesIndex, renderer);
seriesIndex++;
}
JFreeChart chart = new JFreeChart(problemBenchmarkResult.getName() + " best solution mutation statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
graphFile = writeChartToImageFile(chart, problemBenchmarkResult.getName() + "BestSolutionMutationStatistic");
| 407
| 538
| 945
|
<methods>public void <init>() ,public void accumulateResults(org.optaplanner.benchmark.impl.report.BenchmarkReport) ,public abstract SubSingleStatistic#RAW createSubSingleStatistic(org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult) ,public java.lang.String getAnchorId() ,public java.io.File getGraphFile() ,public abstract List<java.io.File> getGraphFileList() ,public ProblemBenchmarkResult#RAW getProblemBenchmarkResult() ,public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getProblemStatisticType() ,public List<SubSingleStatistic#RAW> getSubSingleStatisticList() ,public List<java.lang.String> getWarningList() ,public void setProblemBenchmarkResult(ProblemBenchmarkResult#RAW) ,public java.lang.String toString() ,public abstract void writeGraphFiles(org.optaplanner.benchmark.impl.report.BenchmarkReport) <variables>protected ProblemBenchmarkResult<java.lang.Object> problemBenchmarkResult,protected final non-sealed org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType,protected List<java.lang.String> warningList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationSubSingleStatistic.java
|
BestSolutionMutationSubSingleStatistic
|
open
|
class BestSolutionMutationSubSingleStatistic<Solution_>
extends ProblemBasedSubSingleStatistic<Solution_, BestSolutionMutationStatisticPoint> {
BestSolutionMutationSubSingleStatistic() {
// For JAXB.
}
public BestSolutionMutationSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SOLUTION_MUTATION);
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void open(StatisticRegistry<Solution_> registry, Tags runTag, Solver<Solution_> solver) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return StatisticPoint.buildCsvLine("timeMillisSpent", "mutationCount");
}
@Override
protected BestSolutionMutationStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition,
List<String> csvLine) {
return new BestSolutionMutationStatisticPoint(Long.parseLong(csvLine.get(0)),
Integer.parseInt(csvLine.get(1)));
}
}
|
registry.addListener(SolverMetric.BEST_SOLUTION_MUTATION,
timestamp -> registry.getGaugeValue(SolverMetric.BEST_SOLUTION_MUTATION, runTag,
mutationCount -> pointList
.add(new BestSolutionMutationStatisticPoint(timestamp, mutationCount.intValue()))));
| 344
| 93
| 437
|
<methods>public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getStatisticType() ,public java.lang.String toString() <variables>protected org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/common/GraphSupport.java
|
GraphSupport
|
writeChartToImageFile
|
class GraphSupport {
public static void writeChartToImageFile(JFreeChart chart, File chartFile) {<FILL_FUNCTION_BODY>}
private GraphSupport() {
}
}
|
BufferedImage chartImage = chart.createBufferedImage(1024, 768);
try (OutputStream out = new FileOutputStream(chartFile)) {
ImageIO.write(chartImage, "png", out);
} catch (IOException e) {
throw new IllegalArgumentException("Failed writing chartFile (" + chartFile + ").", e);
}
| 53
| 91
| 144
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/common/MillisecondsSpentNumberFormat.java
|
MillisecondsSpentNumberFormat
|
format
|
class MillisecondsSpentNumberFormat extends NumberFormat {
private static final long DAY_MILLIS = 3600000L * 24L;
private static final long HOUR_MILLIS = 3600000L;
private static final long MINUTE_MILLIS = 60000L;
private static final long SECOND_MILLIS = 1000L;
private final Locale locale;
public MillisecondsSpentNumberFormat(Locale locale) {
this.locale = locale;
}
@Override
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
return format((long) number, toAppendTo, pos);
}
@Override
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {<FILL_FUNCTION_BODY>}
@Override
public Number parse(String source, ParsePosition parsePosition) {
throw new UnsupportedOperationException();
}
}
|
if (number == 0L) {
toAppendTo.append("0");
}
long rest = number;
long days = rest / DAY_MILLIS;
if (days > 0) {
toAppendTo.append(days).append("d");
rest %= DAY_MILLIS;
}
long hours = rest / HOUR_MILLIS;
if (hours > 0) {
toAppendTo.append(hours).append("h");
rest %= HOUR_MILLIS;
}
long minutes = rest / MINUTE_MILLIS;
if (minutes > 0) {
toAppendTo.append(minutes).append("m");
rest %= MINUTE_MILLIS;
}
long seconds = rest / SECOND_MILLIS;
if (seconds > 0) {
toAppendTo.append(seconds).append("s");
rest %= SECOND_MILLIS;
}
if (rest > 0) {
toAppendTo.append(rest).append("ms");
}
return toAppendTo;
| 258
| 278
| 536
|
<methods>public java.lang.Object clone() ,public boolean equals(java.lang.Object) ,public final java.lang.String format(double) ,public final java.lang.String format(long) ,public java.lang.StringBuffer format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition) ,public abstract java.lang.StringBuffer format(double, java.lang.StringBuffer, java.text.FieldPosition) ,public abstract java.lang.StringBuffer format(long, java.lang.StringBuffer, java.text.FieldPosition) ,public static java.util.Locale[] getAvailableLocales() ,public static java.text.NumberFormat getCompactNumberInstance() ,public static java.text.NumberFormat getCompactNumberInstance(java.util.Locale, java.text.NumberFormat.Style) ,public java.util.Currency getCurrency() ,public static final java.text.NumberFormat getCurrencyInstance() ,public static java.text.NumberFormat getCurrencyInstance(java.util.Locale) ,public static final java.text.NumberFormat getInstance() ,public static java.text.NumberFormat getInstance(java.util.Locale) ,public static final java.text.NumberFormat getIntegerInstance() ,public static java.text.NumberFormat getIntegerInstance(java.util.Locale) ,public int getMaximumFractionDigits() ,public int getMaximumIntegerDigits() ,public int getMinimumFractionDigits() ,public int getMinimumIntegerDigits() ,public static final java.text.NumberFormat getNumberInstance() ,public static java.text.NumberFormat getNumberInstance(java.util.Locale) ,public static final java.text.NumberFormat getPercentInstance() ,public static java.text.NumberFormat getPercentInstance(java.util.Locale) ,public java.math.RoundingMode getRoundingMode() ,public int hashCode() ,public boolean isGroupingUsed() ,public boolean isParseIntegerOnly() ,public java.lang.Number parse(java.lang.String) throws java.text.ParseException,public abstract java.lang.Number parse(java.lang.String, java.text.ParsePosition) ,public final java.lang.Object parseObject(java.lang.String, java.text.ParsePosition) ,public void setCurrency(java.util.Currency) ,public void setGroupingUsed(boolean) ,public void setMaximumFractionDigits(int) ,public void setMaximumIntegerDigits(int) ,public void setMinimumFractionDigits(int) ,public void setMinimumIntegerDigits(int) ,public void setParseIntegerOnly(boolean) ,public void setRoundingMode(java.math.RoundingMode) <variables>private static final int COMPACTSTYLE,private static final int CURRENCYSTYLE,public static final int FRACTION_FIELD,private static final int INTEGERSTYLE,public static final int INTEGER_FIELD,private static final int NUMBERSTYLE,private static final int PERCENTSTYLE,private static final int SCIENTIFICSTYLE,static final int currentSerialVersion,private boolean groupingUsed,private byte maxFractionDigits,private byte maxIntegerDigits,private int maximumFractionDigits,private int maximumIntegerDigits,private byte minFractionDigits,private byte minIntegerDigits,private int minimumFractionDigits,private int minimumIntegerDigits,private boolean parseIntegerOnly,private int serialVersionOnStream,static final long serialVersionUID
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/memoryuse/MemoryUseProblemStatistic.java
|
MemoryUseProblemStatistic
|
writeGraphFiles
|
class MemoryUseProblemStatistic extends ProblemStatistic {
protected File graphFile = null;
public MemoryUseProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) {
super(problemBenchmarkResult, ProblemStatisticType.MEMORY_USE);
}
@Override
public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
return new MemoryUseSubSingleStatistic(subSingleBenchmarkResult);
}
/**
* @return never null
*/
@Override
public List<File> getGraphFileList() {
return Collections.singletonList(graphFile);
}
// ************************************************************************
// Write methods
// ************************************************************************
@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {<FILL_FUNCTION_BODY>}
@Override
protected void fillWarningList() {
if (problemBenchmarkResult.getPlannerBenchmarkResult().hasMultipleParallelBenchmarks()) {
warningList.add("This memory use statistic shows the sum of the memory of all benchmarks "
+ "that ran in parallel, due to parallelBenchmarkCount ("
+ problemBenchmarkResult.getPlannerBenchmarkResult().getParallelBenchmarkCount() + ").");
}
}
}
|
Locale locale = benchmarkReport.getLocale();
NumberAxis xAxis = new NumberAxis("Time spent");
xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
NumberAxis yAxis = new NumberAxis("Memory (bytes)");
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
int seriesIndex = 0;
for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) {
XYSeries usedSeries = new XYSeries(
singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " used");
// TODO enable max memory, but in the same color as used memory, but with a dotted line instead
// XYSeries maxSeries = new XYSeries(
// singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " max");
XYItemRenderer renderer = new XYLineAndShapeRenderer();
if (singleBenchmarkResult.hasAllSuccess()) {
MemoryUseSubSingleStatistic subSingleStatistic = (MemoryUseSubSingleStatistic) singleBenchmarkResult
.getSubSingleStatistic(problemStatisticType);
List<MemoryUseStatisticPoint> points = subSingleStatistic.getPointList();
for (MemoryUseStatisticPoint point : points) {
long timeMillisSpent = point.getTimeMillisSpent();
usedSeries.add(timeMillisSpent, point.getUsedMemory());
// maxSeries.add(timeMillisSpent, memoryUseMeasurement.getMaxMemory());
}
}
XYSeriesCollection seriesCollection = new XYSeriesCollection();
seriesCollection.addSeries(usedSeries);
// seriesCollection.addSeries(maxSeries);
plot.setDataset(seriesIndex, seriesCollection);
if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) {
// Make the favorite more obvious
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
// renderer.setSeriesStroke(1, new BasicStroke(2.0f));
}
plot.setRenderer(seriesIndex, renderer);
seriesIndex++;
}
JFreeChart chart = new JFreeChart(problemBenchmarkResult.getName() + " memory use statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
graphFile = writeChartToImageFile(chart, problemBenchmarkResult.getName() + "MemoryUseStatistic");
| 343
| 678
| 1,021
|
<methods>public void <init>() ,public void accumulateResults(org.optaplanner.benchmark.impl.report.BenchmarkReport) ,public abstract SubSingleStatistic#RAW createSubSingleStatistic(org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult) ,public java.lang.String getAnchorId() ,public java.io.File getGraphFile() ,public abstract List<java.io.File> getGraphFileList() ,public ProblemBenchmarkResult#RAW getProblemBenchmarkResult() ,public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getProblemStatisticType() ,public List<SubSingleStatistic#RAW> getSubSingleStatisticList() ,public List<java.lang.String> getWarningList() ,public void setProblemBenchmarkResult(ProblemBenchmarkResult#RAW) ,public java.lang.String toString() ,public abstract void writeGraphFiles(org.optaplanner.benchmark.impl.report.BenchmarkReport) <variables>protected ProblemBenchmarkResult<java.lang.Object> problemBenchmarkResult,protected final non-sealed org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType,protected List<java.lang.String> warningList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/memoryuse/MemoryUseStatisticPoint.java
|
MemoryUseStatisticPoint
|
create
|
class MemoryUseStatisticPoint extends StatisticPoint {
public static MemoryUseStatisticPoint create(long timeMillisSpent) {<FILL_FUNCTION_BODY>}
private final long timeMillisSpent;
private final long usedMemory;
private final long maxMemory;
public MemoryUseStatisticPoint(long timeMillisSpent, long usedMemory, long maxMemory) {
this.timeMillisSpent = timeMillisSpent;
this.usedMemory = usedMemory;
this.maxMemory = maxMemory;
}
public long getTimeMillisSpent() {
return timeMillisSpent;
}
public long getUsedMemory() {
return usedMemory;
}
public long getMaxMemory() {
return maxMemory;
}
@Override
public String toCsvLine() {
return buildCsvLineWithLongs(timeMillisSpent, usedMemory, maxMemory);
}
}
|
Runtime runtime = Runtime.getRuntime();
return new MemoryUseStatisticPoint(timeMillisSpent, runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory());
| 244
| 45
| 289
|
<methods>public non-sealed void <init>() ,public static transient java.lang.String buildCsvLine(java.lang.String[]) ,public static transient java.lang.String buildCsvLineWithDoubles(long, double[]) ,public static transient java.lang.String buildCsvLineWithLongs(long, long[]) ,public static transient java.lang.String buildCsvLineWithStrings(long, java.lang.String[]) ,public static List<java.lang.String> parseCsvLine(java.lang.String) ,public abstract java.lang.String toCsvLine() <variables>private static final java.util.regex.Pattern DOUBLE_QUOTE,private static final java.util.regex.Pattern SINGLE_QUOTE
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/memoryuse/MemoryUseSubSingleStatistic.java
|
MemoryUseSubSingleStatisticListener
|
accept
|
class MemoryUseSubSingleStatisticListener implements Consumer<Long> {
private long nextTimeMillisThreshold = timeMillisThresholdInterval;
private final StatisticRegistry<?> registry;
private final Tags tags;
public MemoryUseSubSingleStatisticListener(StatisticRegistry<?> registry, Tags tags) {
this.registry = registry;
this.tags = tags;
}
@Override
public void accept(Long timeMillisSpent) {<FILL_FUNCTION_BODY>}
}
|
if (timeMillisSpent >= nextTimeMillisThreshold) {
registry.getGaugeValue(SolverMetric.MEMORY_USE, tags,
memoryUse -> pointList.add(
new MemoryUseStatisticPoint(timeMillisSpent, memoryUse.longValue(),
(long) registry.find("jvm.memory.max").tags(tags).gauge().value())));
nextTimeMillisThreshold += timeMillisThresholdInterval;
if (nextTimeMillisThreshold < timeMillisSpent) {
nextTimeMillisThreshold = timeMillisSpent;
}
}
| 135
| 156
| 291
|
<methods>public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getStatisticType() ,public java.lang.String toString() <variables>protected org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/movecountperstep/MoveCountPerStepSubSingleStatistic.java
|
MoveCountPerStepSubSingleStatistic
|
open
|
class MoveCountPerStepSubSingleStatistic<Solution_>
extends ProblemBasedSubSingleStatistic<Solution_, MoveCountPerStepStatisticPoint> {
MoveCountPerStepSubSingleStatistic() {
// For JAXB.
}
public MoveCountPerStepSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, ProblemStatisticType.MOVE_COUNT_PER_STEP);
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void open(StatisticRegistry<Solution_> registry, Tags runTag, Solver<Solution_> solver) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return StatisticPoint.buildCsvLine("timeMillisSpent", "acceptedMoveCount", "selectedMoveCount");
}
@Override
protected MoveCountPerStepStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition,
List<String> csvLine) {
return new MoveCountPerStepStatisticPoint(Long.parseLong(csvLine.get(0)), Long.parseLong(csvLine.get(1)),
Long.parseLong(csvLine.get(2)));
}
}
|
registry.addListener(SolverMetric.MOVE_COUNT_PER_STEP,
timeMillisSpent -> registry.getGaugeValue(SolverMetric.MOVE_COUNT_PER_STEP.getMeterId() + ".accepted", runTag,
accepted -> registry.getGaugeValue(SolverMetric.MOVE_COUNT_PER_STEP.getMeterId() + ".selected", runTag,
selected -> pointList.add(new MoveCountPerStepStatisticPoint(timeMillisSpent,
accepted.longValue(), selected.longValue())))));
| 354
| 146
| 500
|
<methods>public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getStatisticType() ,public java.lang.String toString() <variables>protected org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/scorecalculationspeed/ScoreCalculationSpeedSubSingleStatistic.java
|
ScoreCalculationSpeedSubSingleStatistic
|
accept
|
class ScoreCalculationSpeedSubSingleStatistic<Solution_>
extends ProblemBasedSubSingleStatistic<Solution_, ScoreCalculationSpeedStatisticPoint> {
private long timeMillisThresholdInterval;
ScoreCalculationSpeedSubSingleStatistic() {
// For JAXB.
}
public ScoreCalculationSpeedSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
this(subSingleBenchmarkResult, 1000L);
}
public ScoreCalculationSpeedSubSingleStatistic(SubSingleBenchmarkResult benchmarkResult, long timeMillisThresholdInterval) {
super(benchmarkResult, ProblemStatisticType.SCORE_CALCULATION_SPEED);
if (timeMillisThresholdInterval <= 0L) {
throw new IllegalArgumentException("The timeMillisThresholdInterval (" + timeMillisThresholdInterval
+ ") must be bigger than 0.");
}
this.timeMillisThresholdInterval = timeMillisThresholdInterval;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void open(StatisticRegistry<Solution_> registry, Tags runTag, Solver<Solution_> solver) {
registry.addListener(SolverMetric.SCORE_CALCULATION_COUNT, new Consumer<Long>() {
long nextTimeMillisThreshold = timeMillisThresholdInterval;
long lastTimeMillisSpent = 0;
final AtomicLong lastScoreCalculationCount = new AtomicLong(0);
@Override
public void accept(Long timeMillisSpent) {<FILL_FUNCTION_BODY>}
});
}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return StatisticPoint.buildCsvLine("timeMillisSpent", "scoreCalculationSpeed");
}
@Override
protected ScoreCalculationSpeedStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition,
List<String> csvLine) {
return new ScoreCalculationSpeedStatisticPoint(Long.parseLong(csvLine.get(0)),
Long.parseLong(csvLine.get(1)));
}
}
|
if (timeMillisSpent >= nextTimeMillisThreshold) {
registry.getGaugeValue(SolverMetric.SCORE_CALCULATION_COUNT, runTag, scoreCalculationCountNumber -> {
long scoreCalculationCount = scoreCalculationCountNumber.longValue();
long calculationCountInterval = scoreCalculationCount - lastScoreCalculationCount.get();
long timeMillisSpentInterval = timeMillisSpent - lastTimeMillisSpent;
if (timeMillisSpentInterval == 0L) {
// Avoid divide by zero exception on a fast CPU
timeMillisSpentInterval = 1L;
}
long scoreCalculationSpeed = calculationCountInterval * 1000L / timeMillisSpentInterval;
pointList.add(new ScoreCalculationSpeedStatisticPoint(timeMillisSpent, scoreCalculationSpeed));
lastScoreCalculationCount.set(scoreCalculationCount);
});
lastTimeMillisSpent = timeMillisSpent;
nextTimeMillisThreshold += timeMillisThresholdInterval;
if (nextTimeMillisThreshold < timeMillisSpent) {
nextTimeMillisThreshold = timeMillisSpent;
}
}
| 581
| 302
| 883
|
<methods>public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getStatisticType() ,public java.lang.String toString() <variables>protected org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/stepscore/StepScoreProblemStatistic.java
|
StepScoreProblemStatistic
|
writeGraphFiles
|
class StepScoreProblemStatistic extends ProblemStatistic {
protected List<File> graphFileList = null;
public StepScoreProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) {
super(problemBenchmarkResult, ProblemStatisticType.STEP_SCORE);
}
@Override
public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
return new StepScoreSubSingleStatistic(subSingleBenchmarkResult);
}
/**
* @return never null
*/
@Override
public List<File> getGraphFileList() {
return graphFileList;
}
// ************************************************************************
// Write methods
// ************************************************************************
@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {<FILL_FUNCTION_BODY>}
private XYPlot createPlot(BenchmarkReport benchmarkReport, int scoreLevelIndex) {
Locale locale = benchmarkReport.getLocale();
NumberAxis xAxis = new NumberAxis("Time spent");
xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
String scoreLevelLabel = problemBenchmarkResult.findScoreLevelLabel(scoreLevelIndex);
NumberAxis yAxis = new NumberAxis("Step " + scoreLevelLabel);
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(false);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
return plot;
}
}
|
List<XYPlot> plotList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE);
int seriesIndex = 0;
for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) {
List<XYSeries> seriesList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE);
// No direct ascending lines between 2 points, but a stepping line instead
XYItemRenderer renderer = new XYStepRenderer();
if (singleBenchmarkResult.hasAllSuccess()) {
StepScoreSubSingleStatistic subSingleStatistic = (StepScoreSubSingleStatistic) singleBenchmarkResult
.getSubSingleStatistic(problemStatisticType);
List<StepScoreStatisticPoint> points = subSingleStatistic.getPointList();
for (StepScoreStatisticPoint point : points) {
if (!point.getScore().isSolutionInitialized()) {
continue;
}
long timeMillisSpent = point.getTimeMillisSpent();
double[] levelValues = point.getScore().toLevelDoubles();
for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) {
if (i >= seriesList.size()) {
seriesList.add(new XYSeries(
singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix()));
}
seriesList.get(i).add(timeMillisSpent, levelValues[i]);
}
}
if (subSingleStatistic.getPointList().size() <= 1) {
// Workaround for https://sourceforge.net/tracker/?func=detail&aid=3387330&group_id=15494&atid=115494
renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);
}
}
if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) {
// Make the favorite more obvious
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
}
for (int i = 0; i < seriesList.size(); i++) {
if (i >= plotList.size()) {
plotList.add(createPlot(benchmarkReport, i));
}
plotList.get(i).setDataset(seriesIndex, new XYSeriesCollection(seriesList.get(i)));
plotList.get(i).setRenderer(seriesIndex, renderer);
}
seriesIndex++;
}
graphFileList = new ArrayList<>(plotList.size());
for (int scoreLevelIndex = 0; scoreLevelIndex < plotList.size(); scoreLevelIndex++) {
String scoreLevelLabel = problemBenchmarkResult.findScoreLevelLabel(scoreLevelIndex);
JFreeChart chart = new JFreeChart(
problemBenchmarkResult.getName() + " step " + scoreLevelLabel + " statistic",
JFreeChart.DEFAULT_TITLE_FONT, plotList.get(scoreLevelIndex), true);
graphFileList.add(writeChartToImageFile(chart,
problemBenchmarkResult.getName() + "StepScoreStatisticLevel" + scoreLevelIndex));
}
| 419
| 843
| 1,262
|
<methods>public void <init>() ,public void accumulateResults(org.optaplanner.benchmark.impl.report.BenchmarkReport) ,public abstract SubSingleStatistic#RAW createSubSingleStatistic(org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult) ,public java.lang.String getAnchorId() ,public java.io.File getGraphFile() ,public abstract List<java.io.File> getGraphFileList() ,public ProblemBenchmarkResult#RAW getProblemBenchmarkResult() ,public org.optaplanner.benchmark.config.statistic.ProblemStatisticType getProblemStatisticType() ,public List<SubSingleStatistic#RAW> getSubSingleStatisticList() ,public List<java.lang.String> getWarningList() ,public void setProblemBenchmarkResult(ProblemBenchmarkResult#RAW) ,public java.lang.String toString() ,public abstract void writeGraphFiles(org.optaplanner.benchmark.impl.report.BenchmarkReport) <variables>protected ProblemBenchmarkResult<java.lang.Object> problemBenchmarkResult,protected final non-sealed org.optaplanner.benchmark.config.statistic.ProblemStatisticType problemStatisticType,protected List<java.lang.String> warningList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/subsingle/constraintmatchtotalstepscore/ConstraintMatchTotalStepScoreSubSingleStatistic.java
|
ConstraintMatchTotalStepScoreSubSingleStatistic
|
writeGraphFiles
|
class ConstraintMatchTotalStepScoreSubSingleStatistic<Solution_>
extends PureSubSingleStatistic<Solution_, ConstraintMatchTotalStepScoreStatisticPoint> {
@XmlTransient
protected List<File> graphFileList = null;
ConstraintMatchTotalStepScoreSubSingleStatistic() {
// For JAXB.
}
public ConstraintMatchTotalStepScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, SingleStatisticType.CONSTRAINT_MATCH_TOTAL_STEP_SCORE);
}
/**
* @return never null
*/
@Override
public List<File> getGraphFileList() {
return graphFileList;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void open(StatisticRegistry<Solution_> registry, Tags runTag, Solver<Solution_> solver) {
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
defaultSolver.getSolverScope().getScoreDirector().overwriteConstraintMatchEnabledPreference(true);
registry.addListener(SolverMetric.CONSTRAINT_MATCH_TOTAL_STEP_SCORE,
timeMillisSpent -> registry.extractConstraintSummariesFromMeters(SolverMetric.CONSTRAINT_MATCH_TOTAL_STEP_SCORE,
runTag, constraintSummary -> pointList.add(new ConstraintMatchTotalStepScoreStatisticPoint(
timeMillisSpent,
constraintSummary.getConstraintPackage(),
constraintSummary.getConstraintName(),
constraintSummary.getCount(),
constraintSummary.getScore()))));
}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return ConstraintMatchTotalStepScoreStatisticPoint.buildCsvLine(
"timeMillisSpent", "constraintPackage", "constraintName",
"constraintMatchCount", "scoreTotal");
}
@Override
protected ConstraintMatchTotalStepScoreStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition,
List<String> csvLine) {
return new ConstraintMatchTotalStepScoreStatisticPoint(Long.parseLong(csvLine.get(0)),
csvLine.get(1), csvLine.get(2),
Integer.parseInt(csvLine.get(3)), scoreDefinition.parseScore(csvLine.get(4)));
}
// ************************************************************************
// Write methods
// ************************************************************************
@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {<FILL_FUNCTION_BODY>}
private XYPlot createPlot(BenchmarkReport benchmarkReport, int scoreLevelIndex) {
Locale locale = benchmarkReport.getLocale();
NumberAxis xAxis = new NumberAxis("Time spent");
xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult()
.findScoreLevelLabel(scoreLevelIndex);
NumberAxis yAxis = new NumberAxis("Constraint match total " + scoreLevelLabel);
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(false);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
return plot;
}
}
|
List<Map<String, XYSeries>> constraintIdToWeightSeriesMapList = new ArrayList<>(
BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE);
for (ConstraintMatchTotalStepScoreStatisticPoint point : getPointList()) {
long timeMillisSpent = point.getTimeMillisSpent();
double[] levelValues = point.getScoreTotal().toLevelDoubles();
for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) {
if (i >= constraintIdToWeightSeriesMapList.size()) {
constraintIdToWeightSeriesMapList.add(new LinkedHashMap<>());
}
Map<String, XYSeries> constraintIdToWeightSeriesMap = constraintIdToWeightSeriesMapList.get(i);
XYSeries weightSeries = constraintIdToWeightSeriesMap.computeIfAbsent(point.getConstraintId(),
k -> new XYSeries(point.getConstraintName() + " weight"));
// Only add changes
if (levelValues[i] != ((weightSeries.getItemCount() == 0) ? 0.0
: weightSeries.getY(weightSeries.getItemCount() - 1).doubleValue())) {
weightSeries.add(timeMillisSpent, levelValues[i]);
}
}
}
long timeMillisSpent = subSingleBenchmarkResult.getTimeMillisSpent();
for (Map<String, XYSeries> constraintIdToWeightSeriesMap : constraintIdToWeightSeriesMapList) {
for (Iterator<Map.Entry<String, XYSeries>> it = constraintIdToWeightSeriesMap.entrySet().iterator(); it
.hasNext();) {
XYSeries weightSeries = it.next().getValue();
if (weightSeries.getItemCount() == 0) {
// Only show the constraint type on the score levels that it affects
it.remove();
} else {
// Draw a horizontal line from the last new best step to how long the solver actually ran
weightSeries.add(timeMillisSpent, weightSeries.getY(weightSeries.getItemCount() - 1).doubleValue());
}
}
}
graphFileList = new ArrayList<>(constraintIdToWeightSeriesMapList.size());
for (int scoreLevelIndex = 0; scoreLevelIndex < constraintIdToWeightSeriesMapList.size(); scoreLevelIndex++) {
XYPlot plot = createPlot(benchmarkReport, scoreLevelIndex);
// No direct ascending lines between 2 points, but a stepping line instead
XYItemRenderer renderer = new XYStepRenderer();
plot.setRenderer(renderer);
XYSeriesCollection seriesCollection = new XYSeriesCollection();
for (XYSeries series : constraintIdToWeightSeriesMapList.get(scoreLevelIndex).values()) {
seriesCollection.addSeries(series);
}
plot.setDataset(seriesCollection);
String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult()
.findScoreLevelLabel(scoreLevelIndex);
JFreeChart chart = new JFreeChart(subSingleBenchmarkResult.getName()
+ " constraint match total step " + scoreLevelLabel + " diff statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
graphFileList.add(writeChartToImageFile(chart,
"ConstraintMatchTotalStepScoreStatisticLevel" + scoreLevelIndex));
}
| 924
| 862
| 1,786
|
<methods>public java.io.File getGraphFile() ,public abstract List<java.io.File> getGraphFileList() ,public org.optaplanner.benchmark.config.statistic.SingleStatisticType getStatisticType() ,public java.lang.String toString() ,public abstract void writeGraphFiles(org.optaplanner.benchmark.impl.report.BenchmarkReport) <variables>protected org.optaplanner.benchmark.config.statistic.SingleStatisticType singleStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/subsingle/pickedmovetypebestscore/PickedMoveTypeBestScoreDiffSubSingleStatistic.java
|
PickedMoveTypeBestScoreDiffSubSingleStatistic
|
writeGraphFiles
|
class PickedMoveTypeBestScoreDiffSubSingleStatistic<Solution_>
extends PureSubSingleStatistic<Solution_, PickedMoveTypeBestScoreDiffStatisticPoint> {
@XmlTransient
protected List<File> graphFileList = null;
PickedMoveTypeBestScoreDiffSubSingleStatistic() {
// For JAXB.
}
public PickedMoveTypeBestScoreDiffSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, SingleStatisticType.PICKED_MOVE_TYPE_BEST_SCORE_DIFF);
}
/**
* @return never null
*/
@Override
public List<File> getGraphFileList() {
return graphFileList;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void open(StatisticRegistry<Solution_> registry, Tags runTag, Solver<Solution_> solver) {
registry.addListener(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF, (timeMillisSpent, stepScope) -> {
if (stepScope instanceof LocalSearchStepScope) {
String moveType = ((LocalSearchStepScope<Solution_>) stepScope).getStep().getSimpleMoveTypeDescription();
registry.extractScoreFromMeters(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF,
runTag.and(Tag.of("move.type", moveType)),
score -> pointList.add(new PickedMoveTypeBestScoreDiffStatisticPoint(
timeMillisSpent, moveType, score)));
}
});
}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return PickedMoveTypeBestScoreDiffStatisticPoint.buildCsvLine("timeMillisSpent", "moveType", "bestScoreDiff");
}
@Override
protected PickedMoveTypeBestScoreDiffStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition,
List<String> csvLine) {
return new PickedMoveTypeBestScoreDiffStatisticPoint(Long.parseLong(csvLine.get(0)),
csvLine.get(1), scoreDefinition.parseScore(csvLine.get(2)));
}
// ************************************************************************
// Write methods
// ************************************************************************
@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {<FILL_FUNCTION_BODY>}
private XYPlot createPlot(BenchmarkReport benchmarkReport, int scoreLevelIndex) {
Locale locale = benchmarkReport.getLocale();
NumberAxis xAxis = new NumberAxis("Time spent");
xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult()
.findScoreLevelLabel(scoreLevelIndex);
NumberAxis yAxis = new NumberAxis("Best " + scoreLevelLabel + " diff");
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(true);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
return plot;
}
}
|
List<Map<String, XYIntervalSeries>> moveTypeToSeriesMapList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE);
for (PickedMoveTypeBestScoreDiffStatisticPoint point : getPointList()) {
long timeMillisSpent = point.getTimeMillisSpent();
String moveType = point.getMoveType();
double[] levelValues = point.getBestScoreDiff().toLevelDoubles();
for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) {
if (i >= moveTypeToSeriesMapList.size()) {
moveTypeToSeriesMapList.add(new LinkedHashMap<>());
}
Map<String, XYIntervalSeries> moveTypeToSeriesMap = moveTypeToSeriesMapList.get(i);
XYIntervalSeries series = moveTypeToSeriesMap.computeIfAbsent(moveType,
k -> new XYIntervalSeries(moveType));
double yValue = levelValues[i];
// In an XYInterval the yLow must be lower than yHigh
series.add(timeMillisSpent, timeMillisSpent, timeMillisSpent,
yValue, Math.min(yValue, 0.0), Math.max(yValue, 0.0));
}
}
graphFileList = new ArrayList<>(moveTypeToSeriesMapList.size());
for (int scoreLevelIndex = 0; scoreLevelIndex < moveTypeToSeriesMapList.size(); scoreLevelIndex++) {
XYPlot plot = createPlot(benchmarkReport, scoreLevelIndex);
XYItemRenderer renderer = new YIntervalRenderer();
plot.setRenderer(renderer);
XYIntervalSeriesCollection seriesCollection = new XYIntervalSeriesCollection();
for (XYIntervalSeries series : moveTypeToSeriesMapList.get(scoreLevelIndex).values()) {
seriesCollection.addSeries(series);
}
plot.setDataset(seriesCollection);
String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult()
.findScoreLevelLabel(scoreLevelIndex);
JFreeChart chart = new JFreeChart(subSingleBenchmarkResult.getName()
+ " picked move type best " + scoreLevelLabel + " diff statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
graphFileList.add(writeChartToImageFile(chart,
"PickedMoveTypeBestScoreDiffStatisticLevel" + scoreLevelIndex));
}
| 884
| 639
| 1,523
|
<methods>public java.io.File getGraphFile() ,public abstract List<java.io.File> getGraphFileList() ,public org.optaplanner.benchmark.config.statistic.SingleStatisticType getStatisticType() ,public java.lang.String toString() ,public abstract void writeGraphFiles(org.optaplanner.benchmark.impl.report.BenchmarkReport) <variables>protected org.optaplanner.benchmark.config.statistic.SingleStatisticType singleStatisticType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/swing/impl/SwingUncaughtExceptionHandler.java
|
SwingUncaughtExceptionHandler
|
displayException
|
class SwingUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final Semaphore windowCountSemaphore = new Semaphore(5);
public static void register() {
SwingUncaughtExceptionHandler exceptionHandler = new SwingUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
System.setProperty("sun.awt.exception.handler", SwingUncaughtExceptionHandler.class.getName());
}
@Override
public void uncaughtException(Thread t, Throwable e) {
StringWriter stringWriter = new StringWriter();
stringWriter.append("Exception in thread \"").append(t.getName()).append("\" ");
e.printStackTrace(new PrintWriter(stringWriter));
String trace = stringWriter.toString();
// Not logger.error() because it needs to show up red (and linked) in the IDE console
System.err.print(trace);
displayException(e, trace);
}
private void displayException(Throwable e, String trace) {<FILL_FUNCTION_BODY>}
}
|
if (!windowCountSemaphore.tryAcquire()) {
System.err.println("Too many exception windows open, failed to display the latest exception.");
return;
}
final JFrame exceptionFrame = new JFrame("Uncaught exception: " + e.getMessage());
Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
BufferedImage errorImage = new BufferedImage(
errorIcon.getIconWidth(), errorIcon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
errorIcon.paintIcon(null, errorImage.getGraphics(), 0, 0);
exceptionFrame.setIconImage(errorImage);
exceptionFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel contentPanel = new JPanel(new BorderLayout(5, 5));
contentPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel toolsPanel = new JPanel(new BorderLayout());
toolsPanel.add(new JLabel("An uncaught exception has occurred: "), BorderLayout.LINE_START);
toolsPanel.add(new JButton(new AbstractAction("Copy to clipboard") {
@Override
public void actionPerformed(ActionEvent e1) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(trace), null);
}
}), BorderLayout.LINE_END);
contentPanel.add(toolsPanel, BorderLayout.PAGE_START);
JTextArea stackTraceTextArea = new JTextArea(30, 80);
stackTraceTextArea.setEditable(false);
stackTraceTextArea.setTabSize(4);
stackTraceTextArea.append(trace);
JScrollPane stackTraceScrollPane = new JScrollPane(stackTraceTextArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
contentPanel.add(stackTraceScrollPane, BorderLayout.CENTER);
stackTraceTextArea.setCaretPosition(0); // Scroll to top
JPanel buttonPanel = new JPanel(new GridLayout(1, 0));
JButton closeButton = new JButton(new AbstractAction("Close") {
@Override
public void actionPerformed(ActionEvent e) {
exceptionFrame.setVisible(false);
exceptionFrame.dispose();
}
});
buttonPanel.add(closeButton);
JButton exitApplicationButton = new JButton(new AbstractAction("Exit application") {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
buttonPanel.add(exitApplicationButton);
contentPanel.add(buttonPanel, BorderLayout.PAGE_END);
exceptionFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
windowCountSemaphore.release();
}
});
exceptionFrame.setContentPane(contentPanel);
exceptionFrame.pack();
exceptionFrame.setLocationRelativeTo(null);
exceptionFrame.setVisible(true);
stackTraceTextArea.requestFocus();
| 273
| 811
| 1,084
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.