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/move/AbstractMove.java
|
AbstractMove
|
rebaseList
|
class AbstractMove<Solution_> implements Move<Solution_> {
@Override
public final AbstractMove<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) {
AbstractMove<Solution_> undoMove = createUndoMove(scoreDirector);
doMoveOnly(scoreDirector);
return undoMove;
}
@Override
public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) {
doMoveOnGenuineVariables(scoreDirector);
scoreDirector.triggerVariableListeners();
}
/**
* Called before the move is done, so the move can be evaluated and then be undone
* without resulting into a permanent change in the solution.
*
* @param scoreDirector the {@link ScoreDirector} not yet modified by the move.
* @return an undoMove which does the exact opposite of this move.
*/
protected abstract AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector);
/**
* Like {@link #doMoveOnly(ScoreDirector)} but without the {@link ScoreDirector#triggerVariableListeners()} call
* (because {@link #doMoveOnly(ScoreDirector)} already does that).
*
* @param scoreDirector never null
*/
protected abstract void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector);
// ************************************************************************
// Util methods
// ************************************************************************
public static <E> List<E> rebaseList(List<E> externalObjectList, ScoreDirector<?> destinationScoreDirector) {<FILL_FUNCTION_BODY>}
public static Object[] rebaseArray(Object[] externalObjects, ScoreDirector<?> destinationScoreDirector) {
Object[] rebasedObjects = new Object[externalObjects.length];
for (int i = 0; i < externalObjects.length; i++) {
rebasedObjects[i] = destinationScoreDirector.lookUpWorkingObject(externalObjects[i]);
}
return rebasedObjects;
}
}
|
List<E> rebasedObjectList = new ArrayList<>(externalObjectList.size());
for (E entity : externalObjectList) {
rebasedObjectList.add(destinationScoreDirector.lookUpWorkingObject(entity));
}
return rebasedObjectList;
| 536
| 70
| 606
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/move/CompositeMove.java
|
CompositeMove
|
isMoveDoable
|
class CompositeMove<Solution_> implements Move<Solution_> {
/**
* @param moves never null, sometimes empty. Do not modify this argument afterwards or the CompositeMove corrupts.
* @return never null
*/
@SafeVarargs
public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(Move_... moves) {
int size = moves.length;
if (size > 1) {
return new CompositeMove<>(moves);
} else if (size == 1) {
return moves[0];
} else {
return new NoChangeMove<>();
}
}
/**
* @param moveList never null, sometimes empty
* @return never null
*/
public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(List<Move_> moveList) {
int size = moveList.size();
if (size > 1) {
return new CompositeMove<>(moveList.toArray(new Move[0]));
} else if (size == 1) {
return moveList.get(0);
} else {
return new NoChangeMove<>();
}
}
// ************************************************************************
// Non-static members
// ************************************************************************
protected final Move<Solution_>[] moves;
/**
* @param moves never null, never empty. Do not modify this argument afterwards or this CompositeMove corrupts.
*/
@SafeVarargs
public CompositeMove(Move<Solution_>... moves) {
this.moves = moves;
}
public Move<Solution_>[] getMoves() {
return moves;
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public CompositeMove<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) {
Move<Solution_>[] undoMoves = new Move[moves.length];
int doableCount = 0;
for (Move<Solution_> move : moves) {
if (!move.isMoveDoable(scoreDirector)) {
continue;
}
// Calls scoreDirector.triggerVariableListeners() between moves
// because a later move can depend on the shadow variables changed by an earlier move
Move<Solution_> undoMove = move.doMove(scoreDirector);
// Undo in reverse order and each undoMove is created after previous moves have been done
undoMoves[moves.length - 1 - doableCount] = undoMove;
doableCount++;
}
if (doableCount < undoMoves.length) {
undoMoves = Arrays.copyOfRange(undoMoves, undoMoves.length - doableCount, undoMoves.length);
}
// No need to call scoreDirector.triggerVariableListeners() because Move.doMove() already does it for every move.
return new CompositeMove<>(undoMoves);
}
@Override
public CompositeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
Move<Solution_>[] rebasedMoves = new Move[moves.length];
for (int i = 0; i < moves.length; i++) {
rebasedMoves[i] = moves[i].rebase(destinationScoreDirector);
}
return new CompositeMove<>(rebasedMoves);
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
Set<String> childMoveTypeDescriptionSet = new TreeSet<>();
for (Move<Solution_> move : moves) {
childMoveTypeDescriptionSet.add(move.getSimpleMoveTypeDescription());
}
StringBuilder moveTypeDescription = new StringBuilder(20 * (moves.length + 1));
moveTypeDescription.append(getClass().getSimpleName()).append("(");
String delimiter = "";
for (String childMoveTypeDescription : childMoveTypeDescriptionSet) {
moveTypeDescription.append(delimiter).append("* ").append(childMoveTypeDescription);
delimiter = ", ";
}
moveTypeDescription.append(")");
return moveTypeDescription.toString();
}
@Override
public Collection<? extends Object> getPlanningEntities() {
Set<Object> entities = new LinkedHashSet<>(moves.length * 2);
for (Move<Solution_> move : moves) {
entities.addAll(move.getPlanningEntities());
}
return entities;
}
@Override
public Collection<? extends Object> getPlanningValues() {
Set<Object> values = new LinkedHashSet<>(moves.length * 2);
for (Move<Solution_> move : moves) {
values.addAll(move.getPlanningValues());
}
return values;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof CompositeMove) {
CompositeMove<Solution_> other = (CompositeMove<Solution_>) o;
return Arrays.equals(moves, other.moves);
} else {
return false;
}
}
@Override
public int hashCode() {
return Arrays.hashCode(moves);
}
@Override
public String toString() {
return Arrays.toString(moves);
}
}
|
for (Move<Solution_> move : moves) {
if (move.isMoveDoable(scoreDirector)) {
return true;
}
}
return false;
| 1,440
| 50
| 1,490
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/AbstractSelectorFactory.java
|
AbstractSelectorFactory
|
validateCacheTypeVersusSelectionOrder
|
class AbstractSelectorFactory<Solution_, SelectorConfig_ extends SelectorConfig<SelectorConfig_>>
extends AbstractFromConfigFactory<Solution_, SelectorConfig_> {
protected AbstractSelectorFactory(SelectorConfig_ selectorConfig) {
super(selectorConfig);
}
protected void validateCacheTypeVersusSelectionOrder(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder) {<FILL_FUNCTION_BODY>}
}
|
switch (resolvedSelectionOrder) {
case INHERIT:
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") has a resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") which should have been resolved by now.");
case ORIGINAL:
case RANDOM:
break;
case SORTED:
case SHUFFLED:
case PROBABILISTIC:
if (resolvedCacheType.isNotCached()) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") has a resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") which does not support the resolvedCacheType (" + resolvedCacheType + ").");
}
break;
default:
throw new IllegalStateException("The resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") is not implemented.");
}
| 108
| 205
| 313
|
<methods>public void <init>(SelectorConfig_) ,public static org.optaplanner.core.config.heuristic.selector.entity.EntitySelectorConfig getDefaultEntitySelectorConfigForEntity(HeuristicConfigPolicy<Solution_>, EntityDescriptor<Solution_>) <variables>protected final non-sealed SelectorConfig_ config
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/decorator/ComparatorSelectionSorter.java
|
ComparatorSelectionSorter
|
equals
|
class ComparatorSelectionSorter<Solution_, T> implements SelectionSorter<Solution_, T> {
private final Comparator<T> appliedComparator;
public ComparatorSelectionSorter(Comparator<T> comparator, SelectionSorterOrder selectionSorterOrder) {
switch (selectionSorterOrder) {
case ASCENDING:
this.appliedComparator = comparator;
break;
case DESCENDING:
this.appliedComparator = Collections.reverseOrder(comparator);
break;
default:
throw new IllegalStateException("The selectionSorterOrder (" + selectionSorterOrder
+ ") is not implemented.");
}
}
@Override
public void sort(ScoreDirector<Solution_> scoreDirector, List<T> selectionList) {
selectionList.sort(appliedComparator);
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(appliedComparator);
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ComparatorSelectionSorter<?, ?> that = (ComparatorSelectionSorter<?, ?>) other;
return Objects.equals(appliedComparator, that.appliedComparator);
| 283
| 89
| 372
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/decorator/WeightFactorySelectionSorter.java
|
WeightFactorySelectionSorter
|
equals
|
class WeightFactorySelectionSorter<Solution_, T> implements SelectionSorter<Solution_, T> {
private final SelectionSorterWeightFactory<Solution_, T> selectionSorterWeightFactory;
private final Comparator<Comparable> appliedWeightComparator;
public WeightFactorySelectionSorter(SelectionSorterWeightFactory<Solution_, T> selectionSorterWeightFactory,
SelectionSorterOrder selectionSorterOrder) {
this.selectionSorterWeightFactory = selectionSorterWeightFactory;
switch (selectionSorterOrder) {
case ASCENDING:
this.appliedWeightComparator = Comparator.naturalOrder();
break;
case DESCENDING:
this.appliedWeightComparator = Collections.reverseOrder();
break;
default:
throw new IllegalStateException("The selectionSorterOrder (" + selectionSorterOrder
+ ") is not implemented.");
}
}
@Override
public void sort(ScoreDirector<Solution_> scoreDirector, List<T> selectionList) {
sort(scoreDirector.getWorkingSolution(), selectionList);
}
/**
* @param solution never null, the {@link PlanningSolution} to which the selections belong or apply to
* @param selectionList never null, a {@link List}
* of {@link PlanningEntity}, planningValue, {@link Move} or {@link Selector}
*/
public void sort(Solution_ solution, List<T> selectionList) {
SortedMap<Comparable, T> selectionMap = new TreeMap<>(appliedWeightComparator);
for (T selection : selectionList) {
Comparable difficultyWeight = selectionSorterWeightFactory.createSorterWeight(solution, selection);
T previous = selectionMap.put(difficultyWeight, selection);
if (previous != null) {
throw new IllegalStateException("The selectionList contains 2 times the same selection ("
+ previous + ") and (" + selection + ").");
}
}
selectionList.clear();
selectionList.addAll(selectionMap.values());
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(selectionSorterWeightFactory, appliedWeightComparator);
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
WeightFactorySelectionSorter<?, ?> that = (WeightFactorySelectionSorter<?, ?>) other;
return Objects.equals(selectionSorterWeightFactory, that.selectionSorterWeightFactory)
&& Objects.equals(appliedWeightComparator, that.appliedWeightComparator);
| 583
| 111
| 694
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/iterator/AbstractOriginalSwapIterator.java
|
AbstractOriginalSwapIterator
|
createUpcomingSelection
|
class AbstractOriginalSwapIterator<Solution_, Move_ extends Move<Solution_>, SubSelection_>
extends UpcomingSelectionIterator<Move_> {
public static <Solution_, SubSelection_> long getSize(ListIterableSelector<Solution_, SubSelection_> leftSubSelector,
ListIterableSelector<Solution_, SubSelection_> rightSubSelector) {
if (leftSubSelector != rightSubSelector) {
return leftSubSelector.getSize() * rightSubSelector.getSize();
} else {
long leftSize = leftSubSelector.getSize();
return leftSize * (leftSize - 1L) / 2L;
}
}
protected final ListIterable<SubSelection_> leftSubSelector;
protected final ListIterable<SubSelection_> rightSubSelector;
protected final boolean leftEqualsRight;
private final ListIterator<SubSelection_> leftSubSelectionIterator;
private ListIterator<SubSelection_> rightSubSelectionIterator;
private SubSelection_ leftSubSelection;
public AbstractOriginalSwapIterator(ListIterable<SubSelection_> leftSubSelector,
ListIterable<SubSelection_> rightSubSelector) {
this.leftSubSelector = leftSubSelector;
this.rightSubSelector = rightSubSelector;
leftEqualsRight = (leftSubSelector == rightSubSelector);
leftSubSelectionIterator = leftSubSelector.listIterator();
rightSubSelectionIterator = Collections.<SubSelection_> emptyList().listIterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
}
@Override
protected Move_ createUpcomingSelection() {<FILL_FUNCTION_BODY>}
protected abstract Move_ newSwapSelection(SubSelection_ leftSubSelection, SubSelection_ rightSubSelection);
}
|
if (!rightSubSelectionIterator.hasNext()) {
if (!leftSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
leftSubSelection = leftSubSelectionIterator.next();
if (!leftEqualsRight) {
rightSubSelectionIterator = rightSubSelector.listIterator();
if (!rightSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
} else {
// Select A-B, A-C, B-C. Do not select B-A, C-A, C-B. Do not select A-A, B-B, C-C.
if (!leftSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
rightSubSelectionIterator = rightSubSelector.listIterator(leftSubSelectionIterator.nextIndex());
// rightEntityIterator's first hasNext() always returns true because of the nextIndex()
}
}
SubSelection_ rightSubSelection = rightSubSelectionIterator.next();
return newSwapSelection(leftSubSelection, rightSubSelection);
| 443
| 257
| 700
|
<methods>public non-sealed void <init>() ,public boolean hasNext() ,public Move_ next() ,public java.lang.String toString() <variables>protected boolean hasUpcomingSelection,protected boolean upcomingCreated,protected Move_ upcomingSelection
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/iterator/AbstractRandomChangeIterator.java
|
AbstractRandomChangeIterator
|
createUpcomingSelection
|
class AbstractRandomChangeIterator<Solution_, Move_ extends Move<Solution_>>
extends UpcomingSelectionIterator<Move_> {
private final EntitySelector<Solution_> entitySelector;
private final ValueSelector<Solution_> valueSelector;
private Iterator<Object> entityIterator;
public AbstractRandomChangeIterator(EntitySelector<Solution_> entitySelector,
ValueSelector<Solution_> valueSelector) {
this.entitySelector = entitySelector;
this.valueSelector = valueSelector;
entityIterator = entitySelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
}
@Override
protected Move_ createUpcomingSelection() {<FILL_FUNCTION_BODY>}
protected abstract Move_ newChangeSelection(Object entity, Object toValue);
}
|
// Ideally, this code should have read:
// Object entity = entityIterator.next();
// Iterator<Object> valueIterator = valueSelector.iterator(entity);
// Object toValue = valueIterator.next();
// But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
if (!entityIterator.hasNext()) {
entityIterator = entitySelector.iterator();
if (!entityIterator.hasNext()) {
return noUpcomingSelection();
}
}
Object entity = entityIterator.next();
Iterator<Object> valueIterator = valueSelector.iterator(entity);
int entityIteratorCreationCount = 0;
// This loop is mostly only relevant when the entityIterator or valueIterator is non-random or shuffled
while (!valueIterator.hasNext()) {
// Try the next entity
if (!entityIterator.hasNext()) {
entityIterator = entitySelector.iterator();
entityIteratorCreationCount++;
if (entityIteratorCreationCount >= 2) {
// All entity-value combinations have been tried (some even more than once)
return noUpcomingSelection();
}
}
entity = entityIterator.next();
valueIterator = valueSelector.iterator(entity);
}
Object toValue = valueIterator.next();
return newChangeSelection(entity, toValue);
| 210
| 334
| 544
|
<methods>public non-sealed void <init>() ,public boolean hasNext() ,public Move_ next() ,public java.lang.String toString() <variables>protected boolean hasUpcomingSelection,protected boolean upcomingCreated,protected Move_ upcomingSelection
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/iterator/CachedListRandomIterator.java
|
CachedListRandomIterator
|
next
|
class CachedListRandomIterator<S> extends SelectionIterator<S> {
protected final List<S> cachedList;
protected final Random workingRandom;
protected final boolean empty;
public CachedListRandomIterator(List<S> cachedList, Random workingRandom) {
this.cachedList = cachedList;
this.workingRandom = workingRandom;
empty = cachedList.isEmpty();
}
@Override
public boolean hasNext() {
return !empty;
}
@Override
public S next() {<FILL_FUNCTION_BODY>}
}
|
if (empty) {
throw new NoSuchElementException();
}
int index = workingRandom.nextInt(cachedList.size());
return cachedList.get(index);
| 149
| 49
| 198
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/iterator/SingletonIterator.java
|
SingletonIterator
|
next
|
class SingletonIterator<T> implements ListIterator<T> {
private final T singleton;
private boolean hasNext;
private boolean hasPrevious;
public SingletonIterator(T singleton) {
this.singleton = singleton;
hasNext = true;
hasPrevious = true;
}
public SingletonIterator(T singleton, int index) {
this.singleton = singleton;
if (index < 0 || index > 1) {
throw new IllegalArgumentException("The index (" + index + ") is invalid.");
}
hasNext = (index == 0);
hasPrevious = !hasNext;
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {<FILL_FUNCTION_BODY>}
@Override
public boolean hasPrevious() {
return hasPrevious;
}
@Override
public T previous() {
if (!hasPrevious) {
throw new NoSuchElementException();
}
hasNext = true;
hasPrevious = false;
return singleton;
}
@Override
public int nextIndex() {
return hasNext ? 0 : 1;
}
@Override
public int previousIndex() {
return hasPrevious ? 0 : -1;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(T t) {
throw new UnsupportedOperationException();
}
@Override
public void add(T t) {
throw new UnsupportedOperationException();
}
}
|
if (!hasNext) {
throw new NoSuchElementException();
}
hasNext = false;
hasPrevious = true;
return singleton;
| 420
| 43
| 463
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/iterator/UpcomingSelectionIterator.java
|
UpcomingSelectionIterator
|
toString
|
class UpcomingSelectionIterator<S> extends SelectionIterator<S> {
protected boolean upcomingCreated = false;
protected boolean hasUpcomingSelection = true;
protected S upcomingSelection;
@Override
public boolean hasNext() {
if (!upcomingCreated) {
upcomingSelection = createUpcomingSelection();
upcomingCreated = true;
}
return hasUpcomingSelection;
}
@Override
public S next() {
if (!hasUpcomingSelection) {
throw new NoSuchElementException();
}
if (!upcomingCreated) {
upcomingSelection = createUpcomingSelection();
}
upcomingCreated = false;
return upcomingSelection;
}
protected abstract S createUpcomingSelection();
protected S noUpcomingSelection() {
hasUpcomingSelection = false;
return null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (!upcomingCreated) {
return "Next upcoming (?)";
} else if (!hasUpcomingSelection) {
return "No next upcoming";
} else {
return "Next upcoming (" + upcomingSelection + ")";
}
| 237
| 62
| 299
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/AbstractNearbyDistanceMatrixDemand.java
|
AbstractNearbyDistanceMatrixDemand
|
equals
|
class AbstractNearbyDistanceMatrixDemand<Origin_, Destination_, ChildSelector_, ReplayingSelector_>
implements Demand<NearbyDistanceMatrix<Origin_, Destination_>> {
protected final NearbyDistanceMeter<Origin_, Destination_> meter;
protected final NearbyRandom random;
protected final ChildSelector_ childSelector;
protected final ReplayingSelector_ replayingSelector;
protected AbstractNearbyDistanceMatrixDemand(NearbyDistanceMeter<Origin_, Destination_> meter, NearbyRandom random,
ChildSelector_ childSelector, ReplayingSelector_ replayingSelector) {
this.meter = meter;
this.random = random;
this.childSelector = childSelector;
this.replayingSelector = replayingSelector;
}
@Override
public final NearbyDistanceMatrix<Origin_, Destination_> createExternalizedSupply(SupplyManager supplyManager) {
return supplyNearbyDistanceMatrix();
}
protected abstract NearbyDistanceMatrix<Origin_, Destination_> supplyNearbyDistanceMatrix();
/**
* Two instances of this class are considered equal if and only if:
*
* <ul>
* <li>Their meter instances are equal.</li>
* <li>Their nearby randoms represent the same distribution.</li>
* <li>Their child selectors are equal.</li>
* <li>Their replaying origin entity selectors are equal.</li>
* </ul>
*
* Otherwise as defined by {@link Object#equals(Object)}.
*
* @see ClassInstanceCache for how we ensure equality for meter instances in particular and selectors in general.
*/
@Override
public final boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public final int hashCode() {
return Objects.hash(meter, random, childSelector, replayingSelector);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AbstractNearbyDistanceMatrixDemand<?, ?, ?, ?> that = (AbstractNearbyDistanceMatrixDemand<?, ?, ?, ?>) o;
return Objects.equals(meter, that.meter)
&& Objects.equals(random, that.random)
&& Objects.equals(childSelector, that.childSelector)
&& Objects.equals(replayingSelector, that.replayingSelector);
| 483
| 143
| 626
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/BetaDistributionNearbyRandom.java
|
BetaDistributionNearbyRandom
|
equals
|
class BetaDistributionNearbyRandom implements NearbyRandom {
private final BetaDistribution betaDistribution;
public BetaDistributionNearbyRandom(double betaDistributionAlpha, double betaDistributionBeta) {
if (betaDistributionAlpha <= 0) {
throw new IllegalArgumentException("The betaDistributionAlpha (" + betaDistributionAlpha
+ ") must be greater than 0.");
}
if (betaDistributionBeta <= 0) {
throw new IllegalArgumentException("The betaDistributionBeta (" + betaDistributionBeta
+ ") must be greater than 0.");
}
betaDistribution = new BetaDistribution(betaDistributionAlpha, betaDistributionBeta);
}
@Override
public int nextInt(Random random, int nearbySize) {
double d = betaDistribution.inverseCumulativeProbability(random.nextDouble());
int next = (int) (d * nearbySize);
// The method inverseCumulativeProbability() might return 1.0
if (next >= nearbySize) {
next = nearbySize - 1;
}
return next;
}
@Override
public int getOverallSizeMaximum() {
return Integer.MAX_VALUE;
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(betaDistribution.getAlpha(), betaDistribution.getBeta());
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
BetaDistributionNearbyRandom that = (BetaDistributionNearbyRandom) other;
return Objects.equals(betaDistribution.getAlpha(), that.betaDistribution.getAlpha())
&& Objects.equals(betaDistribution.getBeta(), that.betaDistribution.getBeta());
| 380
| 115
| 495
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/BlockDistributionNearbyRandom.java
|
BlockDistributionNearbyRandom
|
equals
|
class BlockDistributionNearbyRandom implements NearbyRandom {
private final int sizeMinimum;
private final int sizeMaximum;
private final double sizeRatio;
private final double uniformDistributionProbability;
public BlockDistributionNearbyRandom(int sizeMinimum, int sizeMaximum, double sizeRatio,
double uniformDistributionProbability) {
this.sizeMinimum = sizeMinimum;
this.sizeMaximum = sizeMaximum;
this.sizeRatio = sizeRatio;
this.uniformDistributionProbability = uniformDistributionProbability;
if (sizeMinimum < 1) {
throw new IllegalArgumentException("The sizeMinimum (" + sizeMinimum
+ ") must be at least 1.");
}
if (sizeMaximum < sizeMinimum) {
throw new IllegalArgumentException("The sizeMaximum (" + sizeMaximum
+ ") must be at least the sizeMinimum (" + sizeMinimum + ").");
}
if (sizeRatio < 0.0 || sizeRatio > 1.0) {
throw new IllegalArgumentException("The sizeRatio (" + sizeRatio
+ ") must be between 0.0 and 1.0.");
}
if (uniformDistributionProbability < 0.0 || uniformDistributionProbability > 1.0) {
throw new IllegalArgumentException("The uniformDistributionProbability (" + uniformDistributionProbability
+ ") must be between 0.0 and 1.0.");
}
}
@Override
public int nextInt(Random random, int nearbySize) {
if (uniformDistributionProbability > 0.0) {
if (random.nextDouble() < uniformDistributionProbability) {
return random.nextInt(nearbySize);
}
}
int size;
if (sizeRatio < 1.0) {
size = (int) (nearbySize * sizeRatio);
if (size < sizeMinimum) {
size = sizeMinimum;
if (size > nearbySize) {
size = nearbySize;
}
}
} else {
size = nearbySize;
}
if (size > sizeMaximum) {
size = sizeMaximum;
}
return random.nextInt(size);
}
@Override
public int getOverallSizeMaximum() {
if (uniformDistributionProbability > 0.0) {
return Integer.MAX_VALUE;
}
return sizeMaximum;
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(sizeMinimum, sizeMaximum, sizeRatio, uniformDistributionProbability);
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
BlockDistributionNearbyRandom that = (BlockDistributionNearbyRandom) other;
return sizeMinimum == that.sizeMinimum && sizeMaximum == that.sizeMaximum
&& Double.compare(that.sizeRatio, sizeRatio) == 0
&& Double.compare(that.uniformDistributionProbability, uniformDistributionProbability) == 0;
| 683
| 126
| 809
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/LinearDistributionNearbyRandom.java
|
LinearDistributionNearbyRandom
|
nextInt
|
class LinearDistributionNearbyRandom implements NearbyRandom {
private final int sizeMaximum;
public LinearDistributionNearbyRandom(int sizeMaximum) {
this.sizeMaximum = sizeMaximum;
if (sizeMaximum < 1) {
throw new IllegalArgumentException("The maximum (" + sizeMaximum
+ ") must be at least 1.");
}
}
@Override
public int nextInt(Random random, int nearbySize) {<FILL_FUNCTION_BODY>}
@Override
public int getOverallSizeMaximum() {
return sizeMaximum;
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
LinearDistributionNearbyRandom that = (LinearDistributionNearbyRandom) other;
return sizeMaximum == that.sizeMaximum;
}
@Override
public int hashCode() {
return Objects.hash(sizeMaximum);
}
}
|
int m = sizeMaximum <= nearbySize ? sizeMaximum : nearbySize;
double p = random.nextDouble();
double x = m * (1.0 - Math.sqrt(1.0 - p));
int next = (int) x;
// Due to a rounding error it might return m
if (next >= m) {
next = m - 1;
}
return next;
| 277
| 103
| 380
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/NearbyDistanceMatrix.java
|
NearbyDistanceMatrix
|
addAllDestinations
|
class NearbyDistanceMatrix<Origin, Destination> implements Supply {
private final NearbyDistanceMeter<Origin, Destination> nearbyDistanceMeter;
private final Map<Origin, Destination[]> originToDestinationsMap;
private final Function<Origin, Iterator<Destination>> destinationIteratorProvider;
private final ToIntFunction<Origin> destinationSizeFunction;
NearbyDistanceMatrix(NearbyDistanceMeter<Origin, Destination> nearbyDistanceMeter, int originSize,
List<Destination> destinationSelector, ToIntFunction<Origin> destinationSizeFunction) {
this(nearbyDistanceMeter, originSize, origin -> destinationSelector.iterator(), destinationSizeFunction);
}
public NearbyDistanceMatrix(NearbyDistanceMeter<Origin, Destination> nearbyDistanceMeter, int originSize,
Function<Origin, Iterator<Destination>> destinationIteratorProvider,
ToIntFunction<Origin> destinationSizeFunction) {
this.nearbyDistanceMeter = nearbyDistanceMeter;
this.originToDestinationsMap = new HashMap<>(originSize, 1.0f);
this.destinationIteratorProvider = destinationIteratorProvider;
this.destinationSizeFunction = destinationSizeFunction;
}
public void addAllDestinations(Origin origin) {<FILL_FUNCTION_BODY>}
public Object getDestination(Origin origin, int nearbyIndex) {
Destination[] destinations = originToDestinationsMap.get(origin);
if (destinations == null) {
/*
* The item may be missing in the distance matrix due to an underlying filtering selector.
* In such a case, the distance matrix needs to be updated.
*/
addAllDestinations(origin);
destinations = originToDestinationsMap.get(origin);
}
return destinations[nearbyIndex];
}
}
|
int destinationSize = destinationSizeFunction.applyAsInt(origin);
Destination[] destinations = (Destination[]) new Object[destinationSize];
double[] distances = new double[destinationSize];
Iterator<Destination> destinationIterator = destinationIteratorProvider.apply(origin);
int size = 0;
double highestDistance = Double.MAX_VALUE;
while (destinationIterator.hasNext()) {
Destination destination = destinationIterator.next();
double distance = nearbyDistanceMeter.getNearbyDistance(origin, destination);
if (distance < highestDistance || size < destinationSize) {
int insertIndex = Arrays.binarySearch(distances, 0, size, distance);
if (insertIndex < 0) {
insertIndex = -insertIndex - 1;
} else {
while (insertIndex < size && distances[insertIndex] == distance) {
insertIndex++;
}
}
if (size < destinationSize) {
size++;
}
System.arraycopy(destinations, insertIndex, destinations, insertIndex + 1,
size - insertIndex - 1);
System.arraycopy(distances, insertIndex, distances, insertIndex + 1,
size - insertIndex - 1);
destinations[insertIndex] = destination;
distances[insertIndex] = distance;
highestDistance = distances[size - 1];
}
}
if (size != destinationSize) {
throw new IllegalStateException("The destinationIterator's size (" + size
+ ") differs from the expected destinationSize (" + destinationSize + ").");
}
originToDestinationsMap.put(origin, destinations);
| 447
| 409
| 856
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/NearbyRandomFactory.java
|
NearbyRandomFactory
|
buildNearbyRandom
|
class NearbyRandomFactory {
public static NearbyRandomFactory create(NearbySelectionConfig nearbySelectionConfig) {
return new NearbyRandomFactory(nearbySelectionConfig);
}
private final NearbySelectionConfig nearbySelectionConfig;
public NearbyRandomFactory(NearbySelectionConfig nearbySelectionConfig) {
this.nearbySelectionConfig = nearbySelectionConfig;
}
public NearbyRandom buildNearbyRandom(boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
boolean blockDistributionEnabled =
nearbySelectionConfig.getNearbySelectionDistributionType() == NearbySelectionDistributionType.BLOCK_DISTRIBUTION
|| nearbySelectionConfig.getBlockDistributionSizeMinimum() != null
|| nearbySelectionConfig.getBlockDistributionSizeMaximum() != null
|| nearbySelectionConfig.getBlockDistributionSizeRatio() != null
|| nearbySelectionConfig.getBlockDistributionUniformDistributionProbability() != null;
boolean linearDistributionEnabled = nearbySelectionConfig
.getNearbySelectionDistributionType() == NearbySelectionDistributionType.LINEAR_DISTRIBUTION
|| nearbySelectionConfig.getLinearDistributionSizeMaximum() != null;
boolean parabolicDistributionEnabled = nearbySelectionConfig
.getNearbySelectionDistributionType() == NearbySelectionDistributionType.PARABOLIC_DISTRIBUTION
|| nearbySelectionConfig.getParabolicDistributionSizeMaximum() != null;
boolean betaDistributionEnabled =
nearbySelectionConfig.getNearbySelectionDistributionType() == NearbySelectionDistributionType.BETA_DISTRIBUTION
|| nearbySelectionConfig.getBetaDistributionAlpha() != null
|| nearbySelectionConfig.getBetaDistributionBeta() != null;
if (!randomSelection) {
if (blockDistributionEnabled || linearDistributionEnabled || parabolicDistributionEnabled
|| betaDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") with randomSelection (" + randomSelection
+ ") has distribution parameters.");
}
return null;
}
if (blockDistributionEnabled && linearDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") has both blockDistribution and linearDistribution parameters.");
}
if (blockDistributionEnabled && parabolicDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") has both blockDistribution and parabolicDistribution parameters.");
}
if (blockDistributionEnabled && betaDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") has both blockDistribution and betaDistribution parameters.");
}
if (linearDistributionEnabled && parabolicDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") has both linearDistribution and parabolicDistribution parameters.");
}
if (linearDistributionEnabled && betaDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") has both linearDistribution and betaDistribution parameters.");
}
if (parabolicDistributionEnabled && betaDistributionEnabled) {
throw new IllegalArgumentException("The nearbySelectorConfig (" + nearbySelectionConfig
+ ") has both parabolicDistribution and betaDistribution parameters.");
}
if (blockDistributionEnabled) {
int sizeMinimum = Objects.requireNonNullElse(nearbySelectionConfig.getBlockDistributionSizeMinimum(), 1);
int sizeMaximum =
Objects.requireNonNullElse(nearbySelectionConfig.getBlockDistributionSizeMaximum(), Integer.MAX_VALUE);
double sizeRatio = Objects.requireNonNullElse(nearbySelectionConfig.getBlockDistributionSizeRatio(), 1.0);
double uniformDistributionProbability =
Objects.requireNonNullElse(nearbySelectionConfig.getBlockDistributionUniformDistributionProbability(), 0.0);
return new BlockDistributionNearbyRandom(sizeMinimum, sizeMaximum, sizeRatio, uniformDistributionProbability);
} else if (linearDistributionEnabled) {
int sizeMaximum =
Objects.requireNonNullElse(nearbySelectionConfig.getLinearDistributionSizeMaximum(), Integer.MAX_VALUE);
return new LinearDistributionNearbyRandom(sizeMaximum);
} else if (parabolicDistributionEnabled) {
int sizeMaximum =
Objects.requireNonNullElse(nearbySelectionConfig.getParabolicDistributionSizeMaximum(), Integer.MAX_VALUE);
return new ParabolicDistributionNearbyRandom(sizeMaximum);
} else if (betaDistributionEnabled) {
double alpha = Objects.requireNonNullElse(nearbySelectionConfig.getBetaDistributionAlpha(), 1.0);
double beta = Objects.requireNonNullElse(nearbySelectionConfig.getBetaDistributionBeta(), 5.0);
return new BetaDistributionNearbyRandom(alpha, beta);
} else {
return new LinearDistributionNearbyRandom(Integer.MAX_VALUE);
}
| 125
| 1,138
| 1,263
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/ParabolicDistributionNearbyRandom.java
|
ParabolicDistributionNearbyRandom
|
equals
|
class ParabolicDistributionNearbyRandom implements NearbyRandom {
private final int sizeMaximum;
public ParabolicDistributionNearbyRandom(int sizeMaximum) {
this.sizeMaximum = sizeMaximum;
if (sizeMaximum < 1) {
throw new IllegalArgumentException("The maximum (" + sizeMaximum
+ ") must be at least 1.");
}
}
@Override
public int nextInt(Random random, int nearbySize) {
int m = sizeMaximum <= nearbySize ? sizeMaximum : nearbySize;
double p = random.nextDouble();
double x = m * (1.0 - Math.pow(1.0 - p, 1.0 / 3.0));
int next = (int) x;
// Due to a rounding error it might return m
if (next >= m) {
next = m - 1;
}
return next;
}
@Override
public int getOverallSizeMaximum() {
return sizeMaximum;
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(sizeMaximum);
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ParabolicDistributionNearbyRandom that = (ParabolicDistributionNearbyRandom) other;
return sizeMaximum == that.sizeMaximum;
| 315
| 76
| 391
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/nearby/RandomNearbyIterator.java
|
RandomNearbyIterator
|
next
|
class RandomNearbyIterator extends SelectionIterator<Object> {
private final NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix;
private final NearbyRandom nearbyRandom;
private final Random workingRandom;
private final Iterator<Object> replayingIterator;
private final int nearbySize;
private final boolean discardNearbyIndexZero;
private Object origin;
public RandomNearbyIterator(NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix, NearbyRandom nearbyRandom,
Random workingRandom, Iterator<Object> replayingIterator, long childSize, boolean discardNearbyIndexZero) {
this.nearbyDistanceMatrix = nearbyDistanceMatrix;
this.nearbyRandom = nearbyRandom;
this.workingRandom = workingRandom;
this.replayingIterator = replayingIterator;
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The valueSelector (" + this
+ ") has an entitySize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
this.nearbySize = (int) childSize - (discardNearbyIndexZero ? 1 : 0);
this.discardNearbyIndexZero = discardNearbyIndexZero;
}
@Override
public boolean hasNext() {
return (origin != null || replayingIterator.hasNext()) && nearbySize > 0;
}
@Override
public Object next() {<FILL_FUNCTION_BODY>}
}
|
/*
* The origin iterator is guaranteed to be a replaying iterator.
* Therefore next() will point to whatever that the related recording iterator was pointing to at the time
* when its next() was called.
* As a result, origin here will be constant unless next() on the original recording iterator is called
* first.
* If next() on the original recording iterator is not called, origin value from the previous call is stored and used
* instead.
* It enables to iterate over multiple nearby entities.
*/
if (replayingIterator.hasNext()) {
origin = replayingIterator.next();
}
int nearbyIndex = nearbyRandom.nextInt(workingRandom, nearbySize);
if (discardNearbyIndexZero) {
nearbyIndex++;
}
return nearbyDistanceMatrix.getDestination(origin, nearbyIndex);
| 376
| 214
| 590
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/decorator/ProbabilityEntitySelector.java
|
ProbabilityEntitySelector
|
constructCache
|
class ProbabilityEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_>, EntitySelector<Solution_> {
private final EntitySelector<Solution_> childEntitySelector;
private final SelectionCacheType cacheType;
private final SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory;
private NavigableMap<Double, Object> cachedEntityMap = null;
private double probabilityWeightTotal = -1.0;
public ProbabilityEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType,
SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory) {
this.childEntitySelector = childEntitySelector;
this.cacheType = cacheType;
this.probabilityWeightFactory = probabilityWeightFactory;
if (childEntitySelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childEntitySelector (" + childEntitySelector
+ ") with neverEnding (" + childEntitySelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childEntitySelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
probabilityWeightTotal = -1.0;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return true;
}
@Override
public long getSize() {
return cachedEntityMap.size();
}
@Override
public Iterator<Object> iterator() {
return new Iterator<>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public Object next() {
double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
Map.Entry<Double, Object> entry = cachedEntityMap.floorEntry(randomOffset);
// entry is never null because randomOffset < probabilityWeightTotal
return entry.getValue();
}
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
};
}
@Override
public ListIterator<Object> listIterator() {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (true).");
}
@Override
public ListIterator<Object> listIterator(int index) {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (true).");
}
@Override
public Iterator<Object> endingIterator() {
return childEntitySelector.endingIterator();
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ProbabilityEntitySelector<?> that = (ProbabilityEntitySelector<?>) other;
return Objects.equals(childEntitySelector, that.childEntitySelector) && cacheType == that.cacheType
&& Objects.equals(probabilityWeightFactory, that.probabilityWeightFactory);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, cacheType, probabilityWeightFactory);
}
@Override
public String toString() {
return "Probability(" + childEntitySelector + ")";
}
}
|
cachedEntityMap = new TreeMap<>();
ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector();
double probabilityWeightOffset = 0L;
for (Object entity : childEntitySelector) {
double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(
scoreDirector, entity);
cachedEntityMap.put(probabilityWeightOffset, entity);
probabilityWeightOffset += probabilityWeight;
}
probabilityWeightTotal = probabilityWeightOffset;
| 1,084
| 120
| 1,204
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/decorator/SelectedCountLimitEntitySelector.java
|
SelectedCountLimitEntitySelector
|
endingIterator
|
class SelectedCountLimitEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntitySelector<Solution_> {
private final EntitySelector<Solution_> childEntitySelector;
private final boolean randomSelection;
private final long selectedCountLimit;
public SelectedCountLimitEntitySelector(EntitySelector<Solution_> childEntitySelector, boolean randomSelection,
long selectedCountLimit) {
this.childEntitySelector = childEntitySelector;
this.randomSelection = randomSelection;
this.selectedCountLimit = selectedCountLimit;
if (selectedCountLimit < 0L) {
throw new IllegalArgumentException("The selector (" + this
+ ") has a negative selectedCountLimit (" + selectedCountLimit + ").");
}
phaseLifecycleSupport.addEventListener(childEntitySelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public long getSize() {
long childSize = childEntitySelector.getSize();
return Math.min(selectedCountLimit, childSize);
}
@Override
public Iterator<Object> iterator() {
return new SelectedCountLimitEntityIterator(childEntitySelector.iterator());
}
@Override
public ListIterator<Object> listIterator() {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public ListIterator<Object> listIterator(int index) {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public Iterator<Object> endingIterator() {<FILL_FUNCTION_BODY>}
private class SelectedCountLimitEntityIterator extends SelectionIterator<Object> {
private final Iterator<Object> childEntityIterator;
private long selectedSize;
public SelectedCountLimitEntityIterator(Iterator<Object> childEntityIterator) {
this.childEntityIterator = childEntityIterator;
selectedSize = 0L;
}
@Override
public boolean hasNext() {
return selectedSize < selectedCountLimit && childEntityIterator.hasNext();
}
@Override
public Object next() {
if (selectedSize >= selectedCountLimit) {
throw new NoSuchElementException();
}
selectedSize++;
return childEntityIterator.next();
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
SelectedCountLimitEntitySelector<?> that = (SelectedCountLimitEntitySelector<?>) other;
return randomSelection == that.randomSelection && selectedCountLimit == that.selectedCountLimit
&& Objects.equals(childEntitySelector, that.childEntitySelector);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, randomSelection, selectedCountLimit);
}
@Override
public String toString() {
return "SelectedCountLimit(" + childEntitySelector + ")";
}
}
|
if (randomSelection) {
// With random selection, the first n elements can differ between iterator calls,
// so it's illegal to only return the first n elements in original order (that breaks NearbySelection)
return childEntitySelector.endingIterator();
} else {
return new SelectedCountLimitEntityIterator(childEntitySelector.endingIterator());
}
| 849
| 90
| 939
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/decorator/ShufflingEntitySelector.java
|
ShufflingEntitySelector
|
listIterator
|
class ShufflingEntitySelector<Solution_> extends AbstractCachingEntitySelector<Solution_> {
public ShufflingEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType) {
super(childEntitySelector, cacheType);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator() {
Collections.shuffle(cachedEntityList, workingRandom);
logger.trace(" Shuffled cachedEntityList with size ({}) in entitySelector({}).",
cachedEntityList.size(), this);
return cachedEntityList.iterator();
}
@Override
public ListIterator<Object> listIterator() {
Collections.shuffle(cachedEntityList, workingRandom);
logger.trace(" Shuffled cachedEntityList with size ({}) in entitySelector({}).",
cachedEntityList.size(), this);
return cachedEntityList.listIterator();
}
@Override
public ListIterator<Object> listIterator(int index) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Shuffling(" + childEntitySelector + ")";
}
}
|
// Presumes that listIterator() has already been called and shuffling would be bad
return cachedEntityList.listIterator(index);
| 336
| 35
| 371
|
<methods>public void <init>(EntitySelector<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType) ,public void constructCache(SolverScope<Solution_>) ,public void disposeCache(SolverScope<Solution_>) ,public Iterator<java.lang.Object> endingIterator() ,public boolean equals(java.lang.Object) ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,public EntitySelector<Solution_> getChildEntitySelector() ,public EntityDescriptor<Solution_> getEntityDescriptor() ,public long getSize() ,public int hashCode() ,public boolean isCountable() <variables>protected final non-sealed org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType cacheType,protected List<java.lang.Object> cachedEntityList,protected final non-sealed EntitySelector<Solution_> childEntitySelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/decorator/SortingEntitySelector.java
|
SortingEntitySelector
|
constructCache
|
class SortingEntitySelector<Solution_> extends AbstractCachingEntitySelector<Solution_> {
private final SelectionSorter<Solution_, Object> sorter;
public SortingEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType,
SelectionSorter<Solution_, Object> sorter) {
super(childEntitySelector, cacheType);
this.sorter = sorter;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator() {
return cachedEntityList.iterator();
}
@Override
public ListIterator<Object> listIterator() {
return cachedEntityList.listIterator();
}
@Override
public ListIterator<Object> listIterator(int index) {
return cachedEntityList.listIterator(index);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
if (!super.equals(o))
return false;
SortingEntitySelector<?> that = (SortingEntitySelector<?>) o;
return Objects.equals(sorter, that.sorter);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sorter);
}
@Override
public String toString() {
return "Sorting(" + childEntitySelector + ")";
}
}
|
super.constructCache(solverScope);
sorter.sort(solverScope.getScoreDirector(), cachedEntityList);
logger.trace(" Sorted cachedEntityList: size ({}), entitySelector ({}).",
cachedEntityList.size(), this);
| 455
| 67
| 522
|
<methods>public void <init>(EntitySelector<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType) ,public void constructCache(SolverScope<Solution_>) ,public void disposeCache(SolverScope<Solution_>) ,public Iterator<java.lang.Object> endingIterator() ,public boolean equals(java.lang.Object) ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,public EntitySelector<Solution_> getChildEntitySelector() ,public EntityDescriptor<Solution_> getEntityDescriptor() ,public long getSize() ,public int hashCode() ,public boolean isCountable() <variables>protected final non-sealed org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType cacheType,protected List<java.lang.Object> cachedEntityList,protected final non-sealed EntitySelector<Solution_> childEntitySelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/mimic/MimicRecordingEntitySelector.java
|
RecordingEntityListIterator
|
hasPrevious
|
class RecordingEntityListIterator extends SelectionListIterator<Object> {
private final ListIterator<Object> childEntityIterator;
public RecordingEntityListIterator(ListIterator<Object> childEntityIterator) {
this.childEntityIterator = childEntityIterator;
}
@Override
public boolean hasNext() {
boolean hasNext = childEntityIterator.hasNext();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedHasNext(hasNext);
}
return hasNext;
}
@Override
public Object next() {
Object next = childEntityIterator.next();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedNext(next);
}
return next;
}
@Override
public boolean hasPrevious() {<FILL_FUNCTION_BODY>}
@Override
public Object previous() {
Object previous = childEntityIterator.previous();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
// The replay only cares that the recording changed, not in which direction
replayingEntitySelector.recordedNext(previous);
}
return previous;
}
@Override
public int nextIndex() {
return childEntityIterator.nextIndex();
}
@Override
public int previousIndex() {
return childEntityIterator.previousIndex();
}
}
|
boolean hasPrevious = childEntityIterator.hasPrevious();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
// The replay only cares that the recording changed, not in which direction
replayingEntitySelector.recordedHasNext(hasPrevious);
}
return hasPrevious;
| 406
| 89
| 495
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/nearby/EntityNearbyDistanceMatrixDemand.java
|
EntityNearbyDistanceMatrixDemand
|
supplyNearbyDistanceMatrix
|
class EntityNearbyDistanceMatrixDemand<Solution_, Origin_, Destination_>
extends
AbstractNearbyDistanceMatrixDemand<Origin_, Destination_, EntitySelector<Solution_>, EntitySelector<Solution_>> {
private final ToIntFunction<Origin_> destinationSizeFunction;
public EntityNearbyDistanceMatrixDemand(NearbyDistanceMeter<Origin_, Destination_> meter, NearbyRandom random,
EntitySelector<Solution_> childSelector, EntitySelector<Solution_> replayingOriginEntitySelector,
ToIntFunction<Origin_> destinationSizeFunction) {
super(meter, random, childSelector, replayingOriginEntitySelector);
this.destinationSizeFunction = destinationSizeFunction;
}
@Override
protected NearbyDistanceMatrix<Origin_, Destination_> supplyNearbyDistanceMatrix() {<FILL_FUNCTION_BODY>}
}
|
final long childSize = childSelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The childEntitySelector (" + childSelector
+ ") has an entitySize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
long originSize = replayingSelector.getSize();
if (originSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The originEntitySelector (" + replayingSelector
+ ") has an entitySize (" + originSize
+ ") which is higher than Integer.MAX_VALUE.");
}
// Destinations: entities extracted from an entity selector.
Function<Origin_, Iterator<Destination_>> destinationIteratorProvider =
origin -> (Iterator<Destination_>) childSelector.endingIterator();
NearbyDistanceMatrix<Origin_, Destination_> nearbyDistanceMatrix =
new NearbyDistanceMatrix<>(meter, (int) originSize, destinationIteratorProvider, destinationSizeFunction);
// Origins: entities extracted from an entity selector.
replayingSelector.endingIterator()
.forEachRemaining(origin -> nearbyDistanceMatrix.addAllDestinations((Origin_) origin));
return nearbyDistanceMatrix;
| 227
| 294
| 521
|
<methods>public final NearbyDistanceMatrix<Origin_,Destination_> createExternalizedSupply(org.optaplanner.core.impl.domain.variable.supply.SupplyManager) ,public final boolean equals(java.lang.Object) ,public final int hashCode() <variables>protected final non-sealed EntitySelector<Solution_> childSelector,protected final non-sealed NearbyDistanceMeter<Origin_,Destination_> meter,protected final non-sealed org.optaplanner.core.impl.heuristic.selector.common.nearby.NearbyRandom random,protected final non-sealed EntitySelector<Solution_> replayingSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/entity/nearby/NearEntityNearbyEntitySelector.java
|
NearEntityNearbyEntitySelector
|
castReplayingSelector
|
class NearEntityNearbyEntitySelector<Solution_>
extends AbstractNearbySelector<Solution_, EntitySelector<Solution_>, EntitySelector<Solution_>>
implements EntitySelector<Solution_> {
// TODO deactivate me when appropriate; consider if this field needs to be included in selector equality
private final boolean discardNearbyIndexZero = true;
public NearEntityNearbyEntitySelector(EntitySelector<Solution_> childEntitySelector,
EntitySelector<Solution_> originEntitySelector, NearbyDistanceMeter<?, ?> nearbyDistanceMeter,
NearbyRandom nearbyRandom, boolean randomSelection) {
super(childEntitySelector, originEntitySelector, nearbyDistanceMeter, nearbyRandom, randomSelection);
if (!childEntitySelector.getEntityDescriptor().getEntityClass().isAssignableFrom(
originEntitySelector.getEntityDescriptor().getEntityClass())) {
throw new IllegalArgumentException("The entitySelector (" + this
+ ") has an entityClass ("
+ childEntitySelector.getEntityDescriptor().getEntityClass()
+ ") which is not a superclass of the originEntitySelector's entityClass ("
+ originEntitySelector.getEntityDescriptor().getEntityClass() + ").");
}
}
@Override
protected EntitySelector<Solution_> castReplayingSelector(Object uncastReplayingSelector) {<FILL_FUNCTION_BODY>}
@Override
protected AbstractNearbyDistanceMatrixDemand<?, ?, ?, ?> createDemand() {
return new EntityNearbyDistanceMatrixDemand<>(
nearbyDistanceMeter,
nearbyRandom,
childSelector,
replayingSelector,
origin -> computeDestinationSize(childSelector.getSize()));
}
private int computeDestinationSize(long childSize) {
int destinationSize = (int) childSize;
if (randomSelection) {
// Reduce RAM memory usage by reducing destinationSize if nearbyRandom will never select a higher value
int overallSizeMaximum = nearbyRandom.getOverallSizeMaximum();
if (discardNearbyIndexZero) {
if (overallSizeMaximum != Integer.MAX_VALUE) {
overallSizeMaximum++;
}
}
if (destinationSize > overallSizeMaximum) {
destinationSize = overallSizeMaximum;
}
}
return destinationSize;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childSelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public long getSize() {
return childSelector.getSize() - (discardNearbyIndexZero ? 1 : 0);
}
@Override
public Iterator<Object> iterator() {
Iterator<Object> replayingOriginEntityIterator = replayingSelector.iterator();
if (!randomSelection) {
return new OriginalNearbyEntityIterator(nearbyDistanceMatrix, replayingOriginEntityIterator,
childSelector.getSize(), discardNearbyIndexZero);
} else {
return new RandomNearbyIterator(nearbyDistanceMatrix, nearbyRandom, workingRandom,
replayingOriginEntityIterator, childSelector.getSize(), discardNearbyIndexZero);
}
}
@Override
public ListIterator<Object> listIterator() {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public ListIterator<Object> listIterator(int index) {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public Iterator<Object> endingIterator() {
// TODO It should probably use nearby order
// It must include the origin entity too
return childSelector.endingIterator();
}
}
|
if (!(uncastReplayingSelector instanceof MimicReplayingEntitySelector)) {
// In order to select a nearby entity, we must first have something to be near by.
throw new IllegalStateException("Impossible state: Nearby entity selector (" + this +
") did not receive a replaying entity selector (" + uncastReplayingSelector + ").");
}
return (EntitySelector<Solution_>) uncastReplayingSelector;
| 951
| 112
| 1,063
|
<methods>public final boolean equals(java.lang.Object) ,public final AbstractNearbyDistanceMatrixDemand<?,?,?,?> getNearbyDistanceMatrixDemand() ,public final int hashCode() ,public final boolean isNeverEnding() ,public void phaseEnded(AbstractPhaseScope<Solution_>) ,public final void phaseStarted(AbstractPhaseScope<Solution_>) ,public final java.lang.String toString() <variables>protected final non-sealed EntitySelector<Solution_> childSelector,protected NearbyDistanceMatrix<java.lang.Object,java.lang.Object> nearbyDistanceMatrix,private final non-sealed AbstractNearbyDistanceMatrixDemand<?,?,?,?> nearbyDistanceMatrixDemand,protected final non-sealed NearbyDistanceMeter<?,?> nearbyDistanceMeter,protected final non-sealed org.optaplanner.core.impl.heuristic.selector.common.nearby.NearbyRandom nearbyRandom,protected final non-sealed boolean randomSelection,protected final non-sealed EntitySelector<Solution_> replayingSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/DestinationSelectorFactory.java
|
DestinationSelectorFactory
|
buildEntityIndependentValueSelector
|
class DestinationSelectorFactory<Solution_> extends AbstractSelectorFactory<Solution_, DestinationSelectorConfig> {
public static <Solution_> DestinationSelectorFactory<Solution_>
create(DestinationSelectorConfig destinationSelectorConfig) {
return new DestinationSelectorFactory<>(destinationSelectorConfig);
}
private DestinationSelectorFactory(DestinationSelectorConfig destinationSelectorConfig) {
super(destinationSelectorConfig);
}
public DestinationSelector<Solution_> buildDestinationSelector(
HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType,
boolean randomSelection) {
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
ElementDestinationSelector<Solution_> baseDestinationSelector =
buildBaseDestinationSelector(configPolicy, minimumCacheType, selectionOrder);
return applyNearbySelection(configPolicy, minimumCacheType, selectionOrder, baseDestinationSelector);
}
private ElementDestinationSelector<Solution_> buildBaseDestinationSelector(
HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType,
SelectionOrder selectionOrder) {
EntitySelector<Solution_> entitySelector = EntitySelectorFactory
.<Solution_> create(Objects.requireNonNull(config.getEntitySelectorConfig()))
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
EntityIndependentValueSelector<Solution_> valueSelector = buildEntityIndependentValueSelector(configPolicy,
entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder);
return new ElementDestinationSelector<>(
entitySelector,
valueSelector,
selectionOrder.toRandomSelectionBoolean());
}
private EntityIndependentValueSelector<Solution_> buildEntityIndependentValueSelector(
HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) {<FILL_FUNCTION_BODY>}
private DestinationSelector<Solution_> applyNearbySelection(
HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType,
SelectionOrder resolvedSelectionOrder,
ElementDestinationSelector<Solution_> destinationSelector) {
NearbySelectionConfig nearbySelectionConfig = config.getNearbySelectionConfig();
if (nearbySelectionConfig == null) {
return destinationSelector;
}
nearbySelectionConfig.validateNearby(minimumCacheType, resolvedSelectionOrder);
boolean randomSelection = resolvedSelectionOrder.toRandomSelectionBoolean();
NearbyDistanceMeter<?, ?> nearbyDistanceMeter =
configPolicy.getClassInstanceCache().newInstance(nearbySelectionConfig,
"nearbyDistanceMeterClass", nearbySelectionConfig.getNearbyDistanceMeterClass());
// TODO Check nearbyDistanceMeterClass.getGenericInterfaces() to confirm generic type S is an entityClass
NearbyRandom nearbyRandom = NearbyRandomFactory.create(nearbySelectionConfig).buildNearbyRandom(randomSelection);
if (nearbySelectionConfig.getOriginValueSelectorConfig() != null) {
ValueSelector<Solution_> originValueSelector = ValueSelectorFactory
.<Solution_> create(nearbySelectionConfig.getOriginValueSelectorConfig())
.buildValueSelector(configPolicy, destinationSelector.getEntityDescriptor(), minimumCacheType,
resolvedSelectionOrder);
return new NearValueNearbyDestinationSelector<>(
destinationSelector,
((EntityIndependentValueSelector<Solution_>) originValueSelector),
nearbyDistanceMeter,
nearbyRandom,
randomSelection);
} else if (nearbySelectionConfig.getOriginSubListSelectorConfig() != null) {
SubListSelector<Solution_> subListSelector = SubListSelectorFactory
.<Solution_> create(nearbySelectionConfig.getOriginSubListSelectorConfig())
// Entity selector not needed for replaying selector.
.buildSubListSelector(configPolicy, null, minimumCacheType, resolvedSelectionOrder);
return new NearSubListNearbyDestinationSelector<>(
destinationSelector,
subListSelector,
nearbyDistanceMeter,
nearbyRandom,
randomSelection);
} else {
throw new IllegalArgumentException("The destinationSelector (" + config
+ ")'s nearbySelectionConfig (" + nearbySelectionConfig
+ ") requires an originSubListSelector or an originValueSelector.");
}
}
}
|
ValueSelector<Solution_> valueSelector = ValueSelectorFactory
.<Solution_> create(Objects.requireNonNull(config.getValueSelectorConfig()))
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder,
// Do not override reinitializeVariableFilterEnabled.
configPolicy.isReinitializeVariableFilterEnabled(),
/*
* Filter assigned values (but only if this filtering type is allowed by the configPolicy).
*
* The destination selector requires the child value selector to only select assigned values.
* To guarantee this during CH, where not all values are assigned, the UnassignedValueSelector filter
* must be applied.
*
* In the LS phase, not only is the filter redundant because there are no unassigned values,
* but it would also crash if the base value selector inherits random selection order,
* because the filter cannot work on a never-ending child value selector.
* Therefore, it must not be applied even though it is requested here. This is accomplished by
* the configPolicy that only allows this filtering type in the CH phase.
*/
ValueSelectorFactory.ListValueFilteringType.ACCEPT_ASSIGNED);
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The destinationSelector (" + config
+ ") for a list variable needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
return (EntityIndependentValueSelector<Solution_>) valueSelector;
| 1,093
| 400
| 1,493
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/SubList.java
|
SubList
|
equals
|
class SubList {
private final Object entity;
private final int fromIndex;
private final int length;
public SubList(Object entity, int fromIndex, int length) {
this.entity = entity;
this.fromIndex = fromIndex;
this.length = length;
}
public Object getEntity() {
return entity;
}
public int getFromIndex() {
return fromIndex;
}
public int getLength() {
return length;
}
public int getToIndex() {
return fromIndex + length;
}
public SubList rebase(ScoreDirector<?> destinationScoreDirector) {
return new SubList(destinationScoreDirector.lookUpWorkingObject(entity), fromIndex, length);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(entity, fromIndex, length);
}
@Override
public String toString() {
return entity + "[" + fromIndex + ".." + getToIndex() + "]";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubList other = (SubList) o;
return fromIndex == other.fromIndex && length == other.length && entity.equals(other.entity);
| 298
| 84
| 382
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/TriangularNumbers.java
|
TriangularNumbers
|
triangularRoot
|
class TriangularNumbers {
/**
* This is the highest <em>n</em> for which the <em>n</em>th triangular number can be calculated using int arithmetic.
*/
static final int HIGHEST_SAFE_N = 46340;
/**
* Calculate <em>n</em>th <a href="https://en.wikipedia.org/wiki/Triangular_number">triangular number</a>.
* This is used to calculate the number of subLists for a given list variable of size <em>n</em>.
* To be able to use {@code int} arithmetic to calculate the triangular number, <em>n</em> must be less than or equal to
* {@link #HIGHEST_SAFE_N}. If the <em>n</em> is higher, the method throws an exception.
*
* @param n size of the triangle (the length of its side)
* @return <em>n</em>th triangular number
* @throws ArithmeticException if {@code n} is higher than {@link #HIGHEST_SAFE_N}
*/
public static int nthTriangle(int n) throws ArithmeticException {
return Math.multiplyExact(n, n + 1) / 2;
}
static double triangularRoot(int x) {<FILL_FUNCTION_BODY>}
private TriangularNumbers() {
}
}
|
return (Math.sqrt(8L * x + 1) - 1) / 2;
| 373
| 26
| 399
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/mimic/MimicRecordingSubListSelector.java
|
RecordingSubListIterator
|
next
|
class RecordingSubListIterator extends SelectionIterator<SubList> {
private final Iterator<SubList> childSubListIterator;
public RecordingSubListIterator(Iterator<SubList> childSubListIterator) {
this.childSubListIterator = childSubListIterator;
}
@Override
public boolean hasNext() {
boolean hasNext = childSubListIterator.hasNext();
for (MimicReplayingSubListSelector<Solution_> replayingValueSelector : replayingSubListSelectorList) {
replayingValueSelector.recordedHasNext(hasNext);
}
return hasNext;
}
@Override
public SubList next() {<FILL_FUNCTION_BODY>}
}
|
SubList next = childSubListIterator.next();
for (MimicReplayingSubListSelector<Solution_> replayingValueSelector : replayingSubListSelectorList) {
replayingValueSelector.recordedNext(next);
}
return next;
| 187
| 71
| 258
|
<methods>public non-sealed void <init>() ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,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 transient Logger logger,protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport,protected java.util.Random workingRandom
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/mimic/MimicReplayingSubListSelector.java
|
ReplayingSubListIterator
|
toString
|
class ReplayingSubListIterator extends SelectionIterator<SubList> {
private ReplayingSubListIterator() {
// Reset so the last recording plays again even if it has already played
recordingAlreadyReturned = false;
}
@Override
public boolean hasNext() {
if (!hasRecordingCreated) {
throw new IllegalStateException("Replay must occur after record."
+ " The recordingSubListSelector (" + subListMimicRecorder
+ ")'s hasNext() has not been called yet. ");
}
return hasRecording && !recordingAlreadyReturned;
}
@Override
public SubList next() {
if (!recordingCreated) {
throw new IllegalStateException("Replay must occur after record."
+ " The recordingSubListSelector (" + subListMimicRecorder
+ ")'s next() has not been called yet. ");
}
if (recordingAlreadyReturned) {
throw new NoSuchElementException("The recordingAlreadyReturned (" + recordingAlreadyReturned
+ ") is impossible. Check if hasNext() returns true before this call.");
}
// Until the recorder records something, this iterator has no next.
recordingAlreadyReturned = true;
return recording;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (hasRecordingCreated && !hasRecording) {
return "No next replay";
}
return "Next replay (" + (recordingCreated ? recording : "?") + ")";
| 344
| 52
| 396
|
<methods>public non-sealed void <init>() ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,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 transient Logger logger,protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport,protected java.util.Random workingRandom
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/nearby/ListNearbyDistanceMatrixDemand.java
|
ListNearbyDistanceMatrixDemand
|
supplyNearbyDistanceMatrix
|
class ListNearbyDistanceMatrixDemand<Solution_, Origin_, Destination_>
extends
AbstractNearbyDistanceMatrixDemand<Origin_, Destination_, ElementDestinationSelector<Solution_>, MimicReplayingValueSelector<Solution_>> {
private final ToIntFunction<Origin_> destinationSizeFunction;
public ListNearbyDistanceMatrixDemand(NearbyDistanceMeter<Origin_, Destination_> meter,
NearbyRandom random,
ElementDestinationSelector<Solution_> childDestinationSelector,
MimicReplayingValueSelector<Solution_> replayingOriginValueSelector,
ToIntFunction<Origin_> destinationSizeFunction) {
super(meter, random, childDestinationSelector, replayingOriginValueSelector);
this.destinationSizeFunction = destinationSizeFunction;
}
@Override
protected NearbyDistanceMatrix<Origin_, Destination_> supplyNearbyDistanceMatrix() {<FILL_FUNCTION_BODY>}
}
|
final long childSize = childSelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The childSize (" + childSize + ") is higher than Integer.MAX_VALUE.");
}
long originSize = replayingSelector.getSize();
if (originSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The originValueSelector (" + replayingSelector
+ ") has a valueSize (" + originSize
+ ") which is higher than Integer.MAX_VALUE.");
}
// Destinations: mix of planning entities and values extracted from a destination selector.
// Distance "matrix" elements must be user classes (entities and values) because they are exposed
// to the user-implemented NearbyDistanceMeter. Therefore, we cannot insert ElementRefs in the matrix.
// For this reason, destination selector's endingIterator() returns entities and values produced by
// its child selectors.
Function<Origin_, Iterator<Destination_>> destinationIteratorProvider =
origin -> (Iterator<Destination_>) childSelector.endingIterator();
NearbyDistanceMatrix<Origin_, Destination_> nearbyDistanceMatrix =
new NearbyDistanceMatrix<>(meter, (int) originSize, destinationIteratorProvider, destinationSizeFunction);
// Origins: values extracted from a value selector.
// Replaying selector's ending iterator uses the recording selector's ending iterator. Since list variables
// use entity independent value selectors, we can pass null here.
replayingSelector.endingIterator(null)
.forEachRemaining(origin -> nearbyDistanceMatrix.addAllDestinations((Origin_) origin));
return nearbyDistanceMatrix;
| 245
| 406
| 651
|
<methods>public final NearbyDistanceMatrix<Origin_,Destination_> createExternalizedSupply(org.optaplanner.core.impl.domain.variable.supply.SupplyManager) ,public final boolean equals(java.lang.Object) ,public final int hashCode() <variables>protected final non-sealed ElementDestinationSelector<Solution_> childSelector,protected final non-sealed NearbyDistanceMeter<Origin_,Destination_> meter,protected final non-sealed org.optaplanner.core.impl.heuristic.selector.common.nearby.NearbyRandom random,protected final non-sealed MimicReplayingValueSelector<Solution_> replayingSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/nearby/NearSubListNearbyDestinationSelector.java
|
NearSubListNearbyDestinationSelector
|
iterator
|
class NearSubListNearbyDestinationSelector<Solution_>
extends AbstractNearbyDestinationSelector<Solution_, MimicReplayingSubListSelector<Solution_>>
implements DestinationSelector<Solution_> {
public NearSubListNearbyDestinationSelector(ElementDestinationSelector<Solution_> childDestinationSelector,
SubListSelector<Solution_> originSubListSelector, NearbyDistanceMeter<?, ?> nearbyDistanceMeter,
NearbyRandom nearbyRandom, boolean randomSelection) {
super(childDestinationSelector, originSubListSelector, nearbyDistanceMeter, nearbyRandom, randomSelection);
}
@Override
protected MimicReplayingSubListSelector<Solution_> castReplayingSelector(Object uncastReplayingSelector) {
if (!(uncastReplayingSelector instanceof MimicReplayingSubListSelector)) {
// In order to select a nearby destination, we must first have something to be near by.
throw new IllegalStateException("Impossible state: Nearby destination selector (" + this +
") did not receive a replaying subList selector (" + uncastReplayingSelector + ").");
}
return (MimicReplayingSubListSelector<Solution_>) uncastReplayingSelector;
}
@Override
protected AbstractNearbyDistanceMatrixDemand<?, ?, ?, ?> createDemand() {
return new SubListNearbyDistanceMatrixDemand<>(nearbyDistanceMeter, nearbyRandom, childSelector, replayingSelector,
origin -> computeDestinationSize());
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Iterator<ElementRef> iterator() {<FILL_FUNCTION_BODY>}
private Object firstElement(SubList subList) {
return replayingSelector.getVariableDescriptor().getElement(subList.getEntity(), subList.getFromIndex());
}
}
|
Iterator<SubList> replayingOriginSubListIterator = replayingSelector.iterator();
Function<Iterator<?>, Object> originFunction = i -> {
SubList subList = (SubList) i.next();
// Origin is the subList's first element.
return firstElement(subList);
};
if (!randomSelection) {
return new OriginalNearbyDestinationIterator(nearbyDistanceMatrix, replayingOriginSubListIterator, originFunction,
this::elementRef, childSelector.getSize());
} else {
return new RandomNearbyDestinationIterator(nearbyDistanceMatrix, nearbyRandom, workingRandom,
replayingOriginSubListIterator, originFunction, this::elementRef, childSelector.getSize());
}
| 484
| 189
| 673
|
<methods>public void <init>(ElementDestinationSelector<Solution_>, java.lang.Object, NearbyDistanceMeter<?,?>, org.optaplanner.core.impl.heuristic.selector.common.nearby.NearbyRandom, boolean) ,public long getSize() ,public boolean isCountable() ,public void solvingEnded(SolverScope<Solution_>) ,public void solvingStarted(SolverScope<Solution_>) <variables>protected org.optaplanner.core.impl.domain.variable.index.IndexVariableSupply indexVariableSupply,protected org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply inverseVariableSupply
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/nearby/OriginalNearbyDestinationIterator.java
|
OriginalNearbyDestinationIterator
|
selectOrigin
|
class OriginalNearbyDestinationIterator extends SelectionIterator<ElementRef> {
private final NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix;
private final Iterator<?> replayingOriginValueIterator;
private final Function<Iterator<?>, Object> originFunction;
private final Function<Object, ElementRef> elementRefFunction;
private final long childSize;
private boolean originSelected = false;
private boolean originIsNotEmpty;
private Object origin;
private int nextNearbyIndex;
public OriginalNearbyDestinationIterator(NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix,
Iterator<?> replayingOriginValueIterator, Function<Object, ElementRef> elementRefFunction,
long childSize) {
this(nearbyDistanceMatrix, replayingOriginValueIterator, Iterator::next, elementRefFunction, childSize);
}
public OriginalNearbyDestinationIterator(NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix,
Iterator<?> replayingOriginValueIterator, Function<Iterator<?>, Object> originFunction,
Function<Object, ElementRef> elementRefFunction, long childSize) {
this.nearbyDistanceMatrix = nearbyDistanceMatrix;
this.replayingOriginValueIterator = replayingOriginValueIterator;
this.originFunction = originFunction;
this.elementRefFunction = elementRefFunction;
this.childSize = childSize;
nextNearbyIndex = 0;
}
private void selectOrigin() {<FILL_FUNCTION_BODY>}
@Override
public boolean hasNext() {
selectOrigin();
return originIsNotEmpty && nextNearbyIndex < childSize;
}
@Override
public ElementRef next() {
selectOrigin();
Object next = nearbyDistanceMatrix.getDestination(origin, nextNearbyIndex);
nextNearbyIndex++;
return elementRefFunction.apply(next);
}
}
|
if (originSelected) {
return;
}
/*
* The origin iterator is guaranteed to be a replaying iterator.
* Therefore next() will point to whatever that the related recording iterator was pointing to at the time
* when its next() was called.
* As a result, origin here will be constant unless next() on the original recording iterator is called
* first.
*/
originIsNotEmpty = replayingOriginValueIterator.hasNext();
origin = originFunction.apply(replayingOriginValueIterator);
originSelected = true;
| 486
| 142
| 628
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/list/nearby/RandomNearbyDestinationIterator.java
|
RandomNearbyDestinationIterator
|
next
|
class RandomNearbyDestinationIterator extends SelectionIterator<ElementRef> {
private final NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix;
private final NearbyRandom nearbyRandom;
private final Random workingRandom;
private final Iterator<?> replayingOriginValueIterator;
private final Function<Iterator<?>, Object> originFunction;
private final Function<Object, ElementRef> elementRefFunction;
private final int nearbySize;
public RandomNearbyDestinationIterator(NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix,
NearbyRandom nearbyRandom, Random workingRandom, Iterator<Object> replayingOriginValueIterator,
Function<Object, ElementRef> elementRefFunction, long childSize) {
this(nearbyDistanceMatrix, nearbyRandom, workingRandom, replayingOriginValueIterator, Iterator::next,
elementRefFunction, childSize);
}
public RandomNearbyDestinationIterator(NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix,
NearbyRandom nearbyRandom, Random workingRandom, Iterator<?> replayingOriginValueIterator,
Function<Iterator<?>, Object> originFunction, Function<Object, ElementRef> elementRefFunction,
long childSize) {
this.nearbyDistanceMatrix = nearbyDistanceMatrix;
this.nearbyRandom = nearbyRandom;
this.workingRandom = workingRandom;
this.replayingOriginValueIterator = replayingOriginValueIterator;
this.originFunction = originFunction;
this.elementRefFunction = elementRefFunction;
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The destinationSelector (" + this
+ ") has a destinationSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
nearbySize = (int) childSize;
}
@Override
public boolean hasNext() {
return replayingOriginValueIterator.hasNext() && nearbySize > 0;
}
@Override
public ElementRef next() {<FILL_FUNCTION_BODY>}
}
|
/*
* The origin iterator is guaranteed to be a replaying iterator.
* Therefore next() will point to whatever that the related recording iterator was pointing to at the time
* when its next() was called.
* As a result, origin here will be constant unless next() on the original recording iterator is called
* first.
*/
Object origin = originFunction.apply(replayingOriginValueIterator);
int nearbyIndex = nearbyRandom.nextInt(workingRandom, nearbySize);
Object next = nearbyDistanceMatrix.getDestination(origin, nearbyIndex);
return elementRefFunction.apply(next);
| 506
| 151
| 657
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/composite/AbstractCompositeMoveSelectorFactory.java
|
AbstractCompositeMoveSelectorFactory
|
buildInnerMoveSelectors
|
class AbstractCompositeMoveSelectorFactory<Solution_, MoveSelectorConfig_ extends MoveSelectorConfig<MoveSelectorConfig_>>
extends AbstractMoveSelectorFactory<Solution_, MoveSelectorConfig_> {
public AbstractCompositeMoveSelectorFactory(MoveSelectorConfig_ moveSelectorConfig) {
super(moveSelectorConfig);
}
protected List<MoveSelector<Solution_>> buildInnerMoveSelectors(List<MoveSelectorConfig> innerMoveSelectorList,
HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
return innerMoveSelectorList.stream()
.map(moveSelectorConfig -> {
MoveSelectorFactory<Solution_> innerMoveSelectorFactory = MoveSelectorFactory.create(moveSelectorConfig);
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
return innerMoveSelectorFactory.buildMoveSelector(configPolicy, minimumCacheType, selectionOrder);
}).collect(Collectors.toList());
| 146
| 103
| 249
|
<methods>public void <init>(MoveSelectorConfig_) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/composite/BiasedRandomUnionMoveIterator.java
|
BiasedRandomUnionMoveIterator
|
next
|
class BiasedRandomUnionMoveIterator<Solution_> extends SelectionIterator<Move<Solution_>> {
private final Map<Iterator<Move<Solution_>>, ProbabilityItem<Solution_>> probabilityItemMap;
private final NavigableMap<Double, Iterator<Move<Solution_>>> moveIteratorMap;
private final Random workingRandom;
private double probabilityWeightTotal;
private boolean stale;
public BiasedRandomUnionMoveIterator(List<MoveSelector<Solution_>> childMoveSelectorList,
ToDoubleFunction<MoveSelector<Solution_>> probabilityWeightFunction,
Random workingRandom) {
this.probabilityItemMap = new LinkedHashMap<>(childMoveSelectorList.size());
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
Iterator<Move<Solution_>> moveIterator = moveSelector.iterator();
ProbabilityItem<Solution_> probabilityItem = new ProbabilityItem<>();
probabilityItem.moveSelector = moveSelector;
probabilityItem.moveIterator = moveIterator;
probabilityItem.probabilityWeight = probabilityWeightFunction.applyAsDouble(moveSelector);
probabilityItemMap.put(moveIterator, probabilityItem);
}
this.moveIteratorMap = new TreeMap<>();
this.stale = true;
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
if (stale) {
refreshMoveIteratorMap();
}
return !moveIteratorMap.isEmpty();
}
@Override
public Move<Solution_> next() {<FILL_FUNCTION_BODY>}
private void refreshMoveIteratorMap() {
moveIteratorMap.clear();
double probabilityWeightOffset = 0.0;
for (ProbabilityItem<Solution_> probabilityItem : probabilityItemMap.values()) {
if (probabilityItem.probabilityWeight != 0.0
&& probabilityItem.moveIterator.hasNext()) {
moveIteratorMap.put(probabilityWeightOffset, probabilityItem.moveIterator);
probabilityWeightOffset += probabilityItem.probabilityWeight;
}
}
probabilityWeightTotal = probabilityWeightOffset;
}
private static final class ProbabilityItem<Solution_> {
MoveSelector<Solution_> moveSelector;
Iterator<Move<Solution_>> moveIterator;
double probabilityWeight;
}
}
|
if (stale) {
refreshMoveIteratorMap();
}
double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
Map.Entry<Double, Iterator<Move<Solution_>>> entry = moveIteratorMap.floorEntry(randomOffset);
// The entry is never null because randomOffset < probabilityWeightTotal
Iterator<Move<Solution_>> moveIterator = entry.getValue();
Move<Solution_> next = moveIterator.next();
if (!moveIterator.hasNext()) {
stale = true;
}
return next;
| 586
| 143
| 729
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/composite/CartesianProductMoveSelector.java
|
RandomCartesianProductMoveIterator
|
hasNext
|
class RandomCartesianProductMoveIterator extends SelectionIterator<Move<Solution_>> {
private List<Iterator<Move<Solution_>>> moveIteratorList;
private Boolean empty;
public RandomCartesianProductMoveIterator() {
moveIteratorList = new ArrayList<>(childMoveSelectorList.size());
empty = null;
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
moveIteratorList.add(moveSelector.iterator());
}
}
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
@Override
public Move<Solution_> next() {
List<Move<Solution_>> moveList = new ArrayList<>(moveIteratorList.size());
for (int i = 0; i < moveIteratorList.size(); i++) {
Iterator<Move<Solution_>> moveIterator = moveIteratorList.get(i);
boolean skip = false;
if (!moveIterator.hasNext()) {
MoveSelector<Solution_> moveSelector = childMoveSelectorList.get(i);
moveIterator = moveSelector.iterator();
moveIteratorList.set(i, moveIterator);
if (!moveIterator.hasNext()) {
if (ignoreEmptyChildIterators) {
skip = true;
} else {
throw new NoSuchElementException("The iterator of childMoveSelector (" + moveSelector
+ ") is empty.");
}
}
}
if (!skip) {
moveList.add(moveIterator.next());
}
}
if (ignoreEmptyChildIterators) {
if (moveList.isEmpty()) {
throw new NoSuchElementException("All iterators of childMoveSelectorList (" + childMoveSelectorList
+ ") are empty.");
} else if (moveList.size() == 1) {
return moveList.get(0);
}
}
return new CompositeMove<>(moveList.toArray(new Move[0]));
}
}
|
if (empty == null) { // Only done in the first call
int emptyCount = 0;
for (Iterator<Move<Solution_>> moveIterator : moveIteratorList) {
if (!moveIterator.hasNext()) {
emptyCount++;
if (!ignoreEmptyChildIterators) {
break;
}
}
}
empty = ignoreEmptyChildIterators ? emptyCount == moveIteratorList.size() : emptyCount > 0;
}
return !empty;
| 492
| 122
| 614
|
<methods>public List<MoveSelector<Solution_>> getChildMoveSelectorList() ,public boolean isCountable() ,public boolean supportsPhaseAndSolverCaching() ,public java.lang.String toString() <variables>protected final non-sealed List<MoveSelector<Solution_>> childMoveSelectorList,protected final non-sealed boolean randomSelection
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/composite/CartesianProductMoveSelectorFactory.java
|
CartesianProductMoveSelectorFactory
|
buildBaseMoveSelector
|
class CartesianProductMoveSelectorFactory<Solution_>
extends AbstractCompositeMoveSelectorFactory<Solution_, CartesianProductMoveSelectorConfig> {
public CartesianProductMoveSelectorFactory(CartesianProductMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
List<MoveSelector<Solution_>> moveSelectorList = buildInnerMoveSelectors(config.getMoveSelectorList(),
configPolicy, minimumCacheType, randomSelection);
boolean ignoreEmptyChildIterators_ = Objects.requireNonNullElse(config.getIgnoreEmptyChildIterators(), true);
return new CartesianProductMoveSelector<>(moveSelectorList, ignoreEmptyChildIterators_, randomSelection);
| 129
| 97
| 226
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/composite/UniformRandomUnionMoveIterator.java
|
UniformRandomUnionMoveIterator
|
next
|
class UniformRandomUnionMoveIterator<Solution_> extends SelectionIterator<Move<Solution_>> {
private final List<Iterator<Move<Solution_>>> moveIteratorList;
private final Random workingRandom;
public UniformRandomUnionMoveIterator(List<MoveSelector<Solution_>> childMoveSelectorList, Random workingRandom) {
this.moveIteratorList = childMoveSelectorList.stream()
.map(Iterable::iterator)
.filter(Iterator::hasNext)
.collect(Collectors.toList());
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return !moveIteratorList.isEmpty();
}
@Override
public Move<Solution_> next() {<FILL_FUNCTION_BODY>}
}
|
int index = workingRandom.nextInt(moveIteratorList.size());
Iterator<Move<Solution_>> moveIterator = moveIteratorList.get(index);
Move<Solution_> next = moveIterator.next();
if (!moveIterator.hasNext()) {
moveIteratorList.remove(index);
}
return next;
| 201
| 86
| 287
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/decorator/AbstractCachingMoveSelector.java
|
AbstractCachingMoveSelector
|
constructCache
|
class AbstractCachingMoveSelector<Solution_> extends AbstractMoveSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_> {
protected final MoveSelector<Solution_> childMoveSelector;
protected final SelectionCacheType cacheType;
protected List<Move<Solution_>> cachedMoveList = null;
public AbstractCachingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType) {
this.childMoveSelector = childMoveSelector;
this.cacheType = cacheType;
if (childMoveSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childMoveSelector (" + childMoveSelector
+ ") with neverEnding (" + childMoveSelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childMoveSelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
public MoveSelector<Solution_> getChildMoveSelector() {
return childMoveSelector;
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
cachedMoveList = null;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public long getSize() {
return cachedMoveList.size();
}
}
|
long childSize = childMoveSelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The selector (" + this
+ ") has a childMoveSelector (" + childMoveSelector
+ ") with childSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
cachedMoveList = new ArrayList<>((int) childSize);
childMoveSelector.iterator().forEachRemaining(cachedMoveList::add);
logger.trace(" Created cachedMoveList: size ({}), moveSelector ({}).",
cachedMoveList.size(), this);
| 491
| 152
| 643
|
<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/heuristic/selector/move/decorator/SelectedCountLimitMoveSelector.java
|
SelectedCountLimitMoveIterator
|
next
|
class SelectedCountLimitMoveIterator extends SelectionIterator<Move<Solution_>> {
private final Iterator<Move<Solution_>> childMoveIterator;
private long selectedSize;
public SelectedCountLimitMoveIterator(Iterator<Move<Solution_>> childMoveIterator) {
this.childMoveIterator = childMoveIterator;
selectedSize = 0L;
}
@Override
public boolean hasNext() {
return selectedSize < selectedCountLimit && childMoveIterator.hasNext();
}
@Override
public Move<Solution_> next() {<FILL_FUNCTION_BODY>}
}
|
if (selectedSize >= selectedCountLimit) {
throw new NoSuchElementException();
}
selectedSize++;
return childMoveIterator.next();
| 158
| 42
| 200
|
<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/heuristic/selector/move/decorator/ShufflingMoveSelector.java
|
ShufflingMoveSelector
|
iterator
|
class ShufflingMoveSelector<Solution_> extends AbstractCachingMoveSelector<Solution_> {
public ShufflingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType) {
super(childMoveSelector, cacheType);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Move<Solution_>> iterator() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Shuffling(" + childMoveSelector + ")";
}
}
|
Collections.shuffle(cachedMoveList, workingRandom);
logger.trace(" Shuffled cachedMoveList with size ({}) in moveSelector({}).",
cachedMoveList.size(), this);
return cachedMoveList.iterator();
| 178
| 62
| 240
|
<methods>public void <init>(MoveSelector<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType) ,public void constructCache(SolverScope<Solution_>) ,public void disposeCache(SolverScope<Solution_>) ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,public MoveSelector<Solution_> getChildMoveSelector() ,public long getSize() ,public boolean isCountable() <variables>protected final non-sealed org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType cacheType,protected List<Move<Solution_>> cachedMoveList,protected final non-sealed MoveSelector<Solution_> childMoveSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/decorator/SortingMoveSelector.java
|
SortingMoveSelector
|
constructCache
|
class SortingMoveSelector<Solution_> extends AbstractCachingMoveSelector<Solution_> {
protected final SelectionSorter<Solution_, Move<Solution_>> sorter;
public SortingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType,
SelectionSorter<Solution_, Move<Solution_>> sorter) {
super(childMoveSelector, cacheType);
this.sorter = sorter;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Move<Solution_>> iterator() {
return cachedMoveList.iterator();
}
@Override
public String toString() {
return "Sorting(" + childMoveSelector + ")";
}
}
|
super.constructCache(solverScope);
sorter.sort(solverScope.getScoreDirector(), cachedMoveList);
logger.trace(" Sorted cachedMoveList: size ({}), moveSelector ({}).",
cachedMoveList.size(), this);
| 263
| 67
| 330
|
<methods>public void <init>(MoveSelector<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType) ,public void constructCache(SolverScope<Solution_>) ,public void disposeCache(SolverScope<Solution_>) ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,public MoveSelector<Solution_> getChildMoveSelector() ,public long getSize() ,public boolean isCountable() <variables>protected final non-sealed org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType cacheType,protected List<Move<Solution_>> cachedMoveList,protected final non-sealed MoveSelector<Solution_> childMoveSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/factory/MoveIteratorFactoryFactory.java
|
MoveIteratorFactoryFactory
|
buildBaseMoveSelector
|
class MoveIteratorFactoryFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, MoveIteratorFactoryConfig> {
public MoveIteratorFactoryFactory(MoveIteratorFactoryConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
if (config.getMoveIteratorFactoryClass() == null) {
throw new IllegalArgumentException("The moveIteratorFactoryConfig (" + config
+ ") lacks a moveListFactoryClass (" + config.getMoveIteratorFactoryClass() + ").");
}
MoveIteratorFactory moveIteratorFactory = ConfigUtils.newInstance(config,
"moveIteratorFactoryClass", config.getMoveIteratorFactoryClass());
ConfigUtils.applyCustomProperties(moveIteratorFactory, "moveIteratorFactoryClass",
config.getMoveIteratorFactoryCustomProperties(), "moveIteratorFactoryCustomProperties");
return new MoveIteratorFactoryToMoveSelectorBridge<>(moveIteratorFactory, randomSelection);
| 119
| 153
| 272
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/factory/MoveIteratorFactoryToMoveSelectorBridge.java
|
MoveIteratorFactoryToMoveSelectorBridge
|
getSize
|
class MoveIteratorFactoryToMoveSelectorBridge<Solution_> extends AbstractMoveSelector<Solution_> {
protected final MoveIteratorFactory<Solution_, ?> moveIteratorFactory;
protected final boolean randomSelection;
protected ScoreDirector<Solution_> scoreDirector = null;
public MoveIteratorFactoryToMoveSelectorBridge(MoveIteratorFactory<Solution_, ?> moveIteratorFactory,
boolean randomSelection) {
this.moveIteratorFactory = moveIteratorFactory;
this.randomSelection = randomSelection;
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return true;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
scoreDirector = phaseScope.getScoreDirector();
super.phaseStarted(phaseScope);
moveIteratorFactory.phaseStarted(scoreDirector);
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
moveIteratorFactory.phaseEnded(scoreDirector);
super.phaseEnded(phaseScope);
scoreDirector = null;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return randomSelection;
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return (Iterator<Move<Solution_>>) moveIteratorFactory.createOriginalMoveIterator(scoreDirector);
} else {
return (Iterator<Move<Solution_>>) moveIteratorFactory.createRandomMoveIterator(scoreDirector,
workingRandom);
}
}
@Override
public String toString() {
return "MoveIteratorFactory(" + moveIteratorFactory.getClass() + ")";
}
}
|
long size = moveIteratorFactory.getSize(scoreDirector);
if (size < 0L) {
throw new IllegalStateException("The moveIteratorFactoryClass (" + moveIteratorFactory.getClass()
+ ") has size (" + size
+ ") which is negative, but a correct size is required in this Solver configuration.");
}
return size;
| 512
| 88
| 600
|
<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/heuristic/selector/move/factory/MoveListFactoryFactory.java
|
MoveListFactoryFactory
|
buildBaseMoveSelector
|
class MoveListFactoryFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, MoveListFactoryConfig> {
public MoveListFactoryFactory(MoveListFactoryConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isBaseInherentlyCached() {
return true;
}
}
|
if (config.getMoveListFactoryClass() == null) {
throw new IllegalArgumentException("The moveListFactoryConfig (" + config
+ ") lacks a moveListFactoryClass (" + config.getMoveListFactoryClass() + ").");
}
MoveListFactory<Solution_> moveListFactory =
ConfigUtils.newInstance(config, "moveListFactoryClass", config.getMoveListFactoryClass());
ConfigUtils.applyCustomProperties(moveListFactory, "moveListFactoryClass",
config.getMoveListFactoryCustomProperties(), "moveListFactoryCustomProperties");
// MoveListFactoryToMoveSelectorBridge caches by design, so it uses the minimumCacheType
if (minimumCacheType.compareTo(SelectionCacheType.STEP) < 0) {
// cacheType upgrades to SelectionCacheType.STEP (without shuffling) because JIT is not supported
minimumCacheType = SelectionCacheType.STEP;
}
return new MoveListFactoryToMoveSelectorBridge<>(moveListFactory, minimumCacheType, randomSelection);
| 145
| 250
| 395
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.factory.MoveListFactoryConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/factory/MoveListFactoryToMoveSelectorBridge.java
|
MoveListFactoryToMoveSelectorBridge
|
iterator
|
class MoveListFactoryToMoveSelectorBridge<Solution_> extends AbstractMoveSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_> {
protected final MoveListFactory<Solution_> moveListFactory;
protected final SelectionCacheType cacheType;
protected final boolean randomSelection;
protected List<Move<Solution_>> cachedMoveList = null;
public MoveListFactoryToMoveSelectorBridge(MoveListFactory<Solution_> moveListFactory,
SelectionCacheType cacheType, boolean randomSelection) {
this.moveListFactory = moveListFactory;
this.cacheType = cacheType;
this.randomSelection = randomSelection;
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return true;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
cachedMoveList =
(List<Move<Solution_>>) moveListFactory.createMoveList(solverScope.getScoreDirector().getWorkingSolution());
logger.trace(" Created cachedMoveList: size ({}), moveSelector ({}).",
cachedMoveList.size(), this);
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
cachedMoveList = null;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public long getSize() {
return cachedMoveList.size();
}
@Override
public Iterator<Move<Solution_>> iterator() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "MoveListFactory(" + moveListFactory.getClass() + ")";
}
}
|
if (!randomSelection) {
return cachedMoveList.iterator();
} else {
return new CachedListRandomIterator<>(cachedMoveList, workingRandom);
}
| 610
| 47
| 657
|
<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/heuristic/selector/move/generic/ChangeMove.java
|
ChangeMove
|
equals
|
class ChangeMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final Object entity;
protected final Object toPlanningValue;
public ChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue) {
this.variableDescriptor = variableDescriptor;
this.entity = entity;
this.toPlanningValue = toPlanningValue;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public Object getEntity() {
return entity;
}
public Object getToPlanningValue() {
return toPlanningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
Object oldValue = variableDescriptor.getValue(entity);
return !Objects.equals(oldValue, toPlanningValue);
}
@Override
public ChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
Object oldValue = variableDescriptor.getValue(entity);
return new ChangeMove<>(variableDescriptor, entity, oldValue);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
innerScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue);
}
@Override
public ChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ChangeMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(entity),
destinationScoreDirector.lookUpWorkingObject(toPlanningValue));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Collections.singletonList(entity);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toPlanningValue);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, entity, toPlanningValue);
}
@Override
public String toString() {
Object oldValue = variableDescriptor.getValue(entity);
return entity + " {" + oldValue + " -> " + toPlanningValue + "}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ChangeMove<?> other = (ChangeMove<?>) o;
return Objects.equals(variableDescriptor, other.variableDescriptor) &&
Objects.equals(entity, other.entity) &&
Objects.equals(toPlanningValue, other.toPlanningValue);
| 754
| 116
| 870
|
<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/heuristic/selector/move/generic/ChangeMoveSelector.java
|
ChangeMoveSelector
|
solvingStarted
|
class ChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final EntitySelector<Solution_> entitySelector;
protected final ValueSelector<Solution_> valueSelector;
protected final boolean randomSelection;
protected final boolean chained;
protected SingletonInverseVariableSupply inverseVariableSupply = null;
public ChangeMoveSelector(EntitySelector<Solution_> entitySelector, ValueSelector<Solution_> valueSelector,
boolean randomSelection) {
this.entitySelector = entitySelector;
this.valueSelector = valueSelector;
this.randomSelection = randomSelection;
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
chained = variableDescriptor.isChained();
phaseLifecycleSupport.addEventListener(entitySelector);
phaseLifecycleSupport.addEventListener(valueSelector);
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return !chained;
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
if (chained) {
inverseVariableSupply = null;
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return entitySelector.isCountable() && valueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || entitySelector.isNeverEnding() || valueSelector.isNeverEnding();
}
@Override
public long getSize() {
if (valueSelector instanceof IterableSelector) {
return entitySelector.getSize() * ((IterableSelector<Solution_, ?>) valueSelector).getSize();
} else {
long size = 0;
for (Iterator<?> it = entitySelector.endingIterator(); it.hasNext();) {
Object entity = it.next();
size += valueSelector.getSize(entity);
}
return size;
}
}
@Override
public Iterator<Move<Solution_>> iterator() {
final GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
if (!randomSelection) {
if (chained) {
return new AbstractOriginalChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChainedChangeMove<>(variableDescriptor, entity, toValue, inverseVariableSupply);
}
};
} else {
return new AbstractOriginalChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChangeMove<>(variableDescriptor, entity, toValue);
}
};
}
} else {
if (chained) {
return new AbstractRandomChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChainedChangeMove<>(variableDescriptor, entity, toValue, inverseVariableSupply);
}
};
} else {
return new AbstractRandomChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChangeMove<>(variableDescriptor, entity, toValue);
}
};
}
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entitySelector + ", " + valueSelector + ")";
}
}
|
super.solvingStarted(solverScope);
if (chained) {
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
inverseVariableSupply =
supplyManager.demand(new SingletonInverseVariableDemand<>(valueSelector.getVariableDescriptor()));
}
| 972
| 81
| 1,053
|
<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/heuristic/selector/move/generic/PillarChangeMove.java
|
PillarChangeMove
|
isMoveDoable
|
class PillarChangeMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final List<Object> pillar;
protected final Object toPlanningValue;
public PillarChangeMove(List<Object> pillar, GenuineVariableDescriptor<Solution_> variableDescriptor,
Object toPlanningValue) {
this.pillar = pillar;
this.variableDescriptor = variableDescriptor;
this.toPlanningValue = toPlanningValue;
}
public List<Object> getPillar() {
return pillar;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public Object getToPlanningValue() {
return toPlanningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public PillarChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
Object oldValue = variableDescriptor.getValue(pillar.get(0));
return new PillarChangeMove<>(pillar, variableDescriptor, oldValue);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
for (Object entity : pillar) {
innerScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue);
}
}
@Override
public PillarChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new PillarChangeMove<>(rebaseList(pillar, destinationScoreDirector), variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(toPlanningValue));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return pillar;
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toPlanningValue);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final PillarChangeMove<?> other = (PillarChangeMove<?>) o;
return Objects.equals(variableDescriptor, other.variableDescriptor) &&
Objects.equals(pillar, other.pillar) &&
Objects.equals(toPlanningValue, other.toPlanningValue);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, pillar, toPlanningValue);
}
@Override
public String toString() {
Object oldValue = variableDescriptor.getValue(pillar.get(0));
return pillar.toString() + " {" + oldValue + " -> " + toPlanningValue + "}";
}
}
|
Object oldValue = variableDescriptor.getValue(pillar.get(0));
if (Objects.equals(oldValue, toPlanningValue)) {
return false;
}
if (!variableDescriptor.isValueRangeEntityIndependent()) {
ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
Solution_ workingSolution = scoreDirector.getWorkingSolution();
for (Object entity : pillar) {
ValueRange rightValueRange = valueRangeDescriptor.extractValueRange(workingSolution, entity);
if (!rightValueRange.contains(toPlanningValue)) {
return false;
}
}
}
return true;
| 912
| 171
| 1,083
|
<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/heuristic/selector/move/generic/PillarChangeMoveSelector.java
|
PillarChangeMoveSelector
|
getSize
|
class PillarChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final PillarSelector<Solution_> pillarSelector;
protected final ValueSelector<Solution_> valueSelector;
protected final boolean randomSelection;
public PillarChangeMoveSelector(PillarSelector<Solution_> pillarSelector, ValueSelector<Solution_> valueSelector,
boolean randomSelection) {
this.pillarSelector = pillarSelector;
this.valueSelector = valueSelector;
this.randomSelection = randomSelection;
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
if (variableDescriptor.isChained()) {
throw new IllegalStateException("The selector (" + this
+ ") has a variableDescriptor (" + variableDescriptor
+ ") which is chained (" + variableDescriptor.isChained() + ").");
}
phaseLifecycleSupport.addEventListener(pillarSelector);
phaseLifecycleSupport.addEventListener(valueSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return pillarSelector.isCountable() && valueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || pillarSelector.isNeverEnding() || valueSelector.isNeverEnding();
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return new OriginalPillarChangeMoveIterator();
} else {
return new RandomPillarChangeMoveIterator();
}
}
private class OriginalPillarChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private Iterator<List<Object>> pillarIterator;
private Iterator<Object> valueIterator;
private List<Object> upcomingPillar;
private OriginalPillarChangeMoveIterator() {
pillarIterator = pillarSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
if (!valueIterator.hasNext()) {
if (!pillarIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingPillar = pillarIterator.next();
valueIterator = valueSelector.iterator(upcomingPillar.get(0));
if (!valueIterator.hasNext()) {
// valueSelector is completely empty
return noUpcomingSelection();
}
}
Object toValue = valueIterator.next();
return new PillarChangeMove<>(upcomingPillar, valueSelector.getVariableDescriptor(), toValue);
}
}
private class RandomPillarChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private Iterator<List<Object>> pillarIterator;
private Iterator<Object> valueIterator;
private RandomPillarChangeMoveIterator() {
pillarIterator = pillarSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
// Ideally, this code should have read:
// Object pillar = pillarIterator.next();
// Object toValue = valueIterator.next();
// But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
if (!pillarIterator.hasNext()) {
pillarIterator = pillarSelector.iterator();
if (!pillarIterator.hasNext()) {
// pillarSelector is completely empty
return noUpcomingSelection();
}
}
List<Object> pillar = pillarIterator.next();
if (!valueIterator.hasNext()) {
valueIterator = valueSelector.iterator(pillar.get(0));
if (!valueIterator.hasNext()) {
// valueSelector is completely empty
return noUpcomingSelection();
}
}
Object toValue = valueIterator.next();
return new PillarChangeMove<>(pillar, valueSelector.getVariableDescriptor(), toValue);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + pillarSelector + ", " + valueSelector + ")";
}
}
|
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("To use the method getSize(), the moveSelector (" + this
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
return pillarSelector.getSize() * ((EntityIndependentValueSelector) valueSelector).getSize();
| 1,161
| 126
| 1,287
|
<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/heuristic/selector/move/generic/PillarChangeMoveSelectorFactory.java
|
PillarChangeMoveSelectorFactory
|
buildBaseMoveSelector
|
class PillarChangeMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, PillarChangeMoveSelectorConfig> {
public PillarChangeMoveSelectorFactory(PillarChangeMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
PillarSelectorConfig pillarSelectorConfig =
Objects.requireNonNullElseGet(config.getPillarSelectorConfig(), PillarSelectorConfig::new);
ValueSelectorConfig valueSelectorConfig =
Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
List<String> variableNameIncludeList = config.getValueSelectorConfig() == null
|| config.getValueSelectorConfig().getVariableName() == null ? null
: Collections.singletonList(config.getValueSelectorConfig().getVariableName());
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
PillarSelector<Solution_> pillarSelector = PillarSelectorFactory.<Solution_> create(pillarSelectorConfig)
.buildPillarSelector(configPolicy, config.getSubPillarType(),
(Class<? extends Comparator<Object>>) config.getSubPillarSequenceComparatorClass(),
minimumCacheType, selectionOrder, variableNameIncludeList);
ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, pillarSelector.getEntityDescriptor(), minimumCacheType, selectionOrder);
return new PillarChangeMoveSelector<>(pillarSelector, valueSelector, randomSelection);
| 131
| 326
| 457
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/PillarDemand.java
|
PillarDemand
|
getMultiVariableValueState
|
class PillarDemand<Solution_> implements Demand<MemoizingSupply<List<List<Object>>>> {
private final EntitySelector<Solution_> entitySelector;
private final List<GenuineVariableDescriptor<Solution_>> variableDescriptors;
private final SubPillarConfigPolicy subpillarConfigPolicy;
public PillarDemand(EntitySelector<Solution_> entitySelector,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors, SubPillarConfigPolicy subpillarConfigPolicy) {
this.entitySelector = entitySelector;
this.variableDescriptors = variableDescriptors;
this.subpillarConfigPolicy = subpillarConfigPolicy;
}
@Override
public MemoizingSupply<List<List<Object>>> createExternalizedSupply(SupplyManager supplyManager) {
Supplier<List<List<Object>>> supplier = () -> {
long entitySize = entitySelector.getSize();
if (entitySize > Integer.MAX_VALUE) {
throw new IllegalStateException("The selector (" + this + ") has an entitySelector ("
+ entitySelector + ") with entitySize (" + entitySize
+ ") which is higher than Integer.MAX_VALUE.");
}
Stream<Object> entities = StreamSupport.stream(entitySelector.spliterator(), false);
Comparator<?> comparator = subpillarConfigPolicy.getEntityComparator();
if (comparator != null) {
/*
* The entity selection will be sorted. This will result in all the pillars being sorted without having to
* sort them individually later.
*/
entities = entities.sorted((Comparator<? super Object>) comparator);
}
// Create all the pillars from a stream of entities; if sorted, the pillars will be sequential.
Map<List<Object>, List<Object>> valueStateToPillarMap = new LinkedHashMap<>((int) entitySize);
int variableCount = variableDescriptors.size();
entities.forEach(entity -> {
List<Object> valueState = variableCount == 1 ? getSingleVariableValueState(entity, variableDescriptors)
: getMultiVariableValueState(entity, variableDescriptors, variableCount);
List<Object> pillar = valueStateToPillarMap.computeIfAbsent(valueState, key -> new ArrayList<>());
pillar.add(entity);
});
// Store the cache. Exclude pillars of size lower than the minimumSubPillarSize, as we shouldn't select those.
Collection<List<Object>> pillarLists = valueStateToPillarMap.values();
int minimumSubPillarSize = subpillarConfigPolicy.getMinimumSubPillarSize();
return minimumSubPillarSize > 1 ? pillarLists.stream()
.filter(pillar -> pillar.size() >= minimumSubPillarSize)
.collect(Collectors.toList())
: new ArrayList<>(pillarLists);
};
return new MemoizingSupply<>(supplier);
}
private static <Solution_> List<Object> getSingleVariableValueState(Object entity,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors) {
Object value = variableDescriptors.get(0).getValue(entity);
return Collections.singletonList(value);
}
private static <Solution_> List<Object> getMultiVariableValueState(Object entity,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors, int variableCount) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
PillarDemand<?> that = (PillarDemand<?>) other;
return Objects.equals(entitySelector, that.entitySelector)
&& Objects.equals(variableDescriptors, that.variableDescriptors)
&& Objects.equals(subpillarConfigPolicy, that.subpillarConfigPolicy);
}
@Override
public int hashCode() {
return Objects.hash(entitySelector, variableDescriptors, subpillarConfigPolicy);
}
}
|
List<Object> valueState = new ArrayList<>(variableCount);
for (int i = 0; i < variableCount; i++) {
Object value = variableDescriptors.get(i).getValue(entity);
valueState.add(value);
}
return valueState;
| 1,085
| 73
| 1,158
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/SwapMove.java
|
SwapMove
|
isMoveDoable
|
class SwapMove<Solution_> extends AbstractMove<Solution_> {
protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList;
protected final Object leftEntity;
protected final Object rightEntity;
public SwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, Object leftEntity, Object rightEntity) {
this.variableDescriptorList = variableDescriptorList;
this.leftEntity = leftEntity;
this.rightEntity = rightEntity;
}
public Object getLeftEntity() {
return leftEntity;
}
public Object getRightEntity() {
return rightEntity;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public SwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new SwapMove<>(variableDescriptorList, rightEntity, leftEntity);
}
@Override
public SwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SwapMove<>(variableDescriptorList,
destinationScoreDirector.lookUpWorkingObject(leftEntity),
destinationScoreDirector.lookUpWorkingObject(rightEntity));
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
Object oldLeftValue = variableDescriptor.getValue(leftEntity);
Object oldRightValue = variableDescriptor.getValue(rightEntity);
if (!Objects.equals(oldLeftValue, oldRightValue)) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue);
innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue);
}
}
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
StringBuilder moveTypeDescription = new StringBuilder(20 * (variableDescriptorList.size() + 1));
moveTypeDescription.append(getClass().getSimpleName()).append("(");
String delimiter = "";
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
moveTypeDescription.append(delimiter).append(variableDescriptor.getSimpleEntityAndVariableName());
delimiter = ", ";
}
moveTypeDescription.append(")");
return moveTypeDescription.toString();
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Arrays.asList(leftEntity, rightEntity);
}
@Override
public Collection<? extends Object> getPlanningValues() {
List<Object> values = new ArrayList<>(variableDescriptorList.size() * 2);
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
values.add(variableDescriptor.getValue(leftEntity));
values.add(variableDescriptor.getValue(rightEntity));
}
return values;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final SwapMove<?> swapMove = (SwapMove<?>) o;
return Objects.equals(variableDescriptorList, swapMove.variableDescriptorList) &&
Objects.equals(leftEntity, swapMove.leftEntity) &&
Objects.equals(rightEntity, swapMove.rightEntity);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptorList, leftEntity, rightEntity);
}
@Override
public String toString() {
StringBuilder s = new StringBuilder(variableDescriptorList.size() * 16);
s.append(leftEntity).append(" {");
appendVariablesToString(s, leftEntity);
s.append("} <-> ");
s.append(rightEntity).append(" {");
appendVariablesToString(s, rightEntity);
s.append("}");
return s.toString();
}
protected void appendVariablesToString(StringBuilder s, Object entity) {
boolean first = true;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
if (!first) {
s.append(", ");
}
s.append(variableDescriptor.getValue(entity));
first = false;
}
}
}
|
boolean movable = false;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
Object leftValue = variableDescriptor.getValue(leftEntity);
Object rightValue = variableDescriptor.getValue(rightEntity);
if (!Objects.equals(leftValue, rightValue)) {
movable = true;
if (!variableDescriptor.isValueRangeEntityIndependent()) {
ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
Solution_ workingSolution = scoreDirector.getWorkingSolution();
ValueRange rightValueRange = valueRangeDescriptor.extractValueRange(workingSolution, rightEntity);
if (!rightValueRange.contains(leftValue)) {
return false;
}
ValueRange leftValueRange = valueRangeDescriptor.extractValueRange(workingSolution, leftEntity);
if (!leftValueRange.contains(rightValue)) {
return false;
}
}
}
}
return movable;
| 1,236
| 245
| 1,481
|
<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/heuristic/selector/move/generic/SwapMoveSelector.java
|
SwapMoveSelector
|
solvingStarted
|
class SwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final EntitySelector<Solution_> leftEntitySelector;
protected final EntitySelector<Solution_> rightEntitySelector;
protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList;
protected final boolean randomSelection;
protected final boolean anyChained;
protected List<SingletonInverseVariableSupply> inverseVariableSupplyList = null;
public SwapMoveSelector(EntitySelector<Solution_> leftEntitySelector, EntitySelector<Solution_> rightEntitySelector,
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, boolean randomSelection) {
this.leftEntitySelector = leftEntitySelector;
this.rightEntitySelector = rightEntitySelector;
this.variableDescriptorList = variableDescriptorList;
this.randomSelection = randomSelection;
EntityDescriptor<Solution_> leftEntityDescriptor = leftEntitySelector.getEntityDescriptor();
EntityDescriptor<Solution_> rightEntityDescriptor = rightEntitySelector.getEntityDescriptor();
if (!leftEntityDescriptor.getEntityClass().equals(rightEntityDescriptor.getEntityClass())) {
throw new IllegalStateException("The selector (" + this
+ ") has a leftEntitySelector's entityClass (" + leftEntityDescriptor.getEntityClass()
+ ") which is not equal to the rightEntitySelector's entityClass ("
+ rightEntityDescriptor.getEntityClass() + ").");
}
boolean anyChained = false;
if (variableDescriptorList.isEmpty()) {
throw new IllegalStateException("The selector (" + this
+ ")'s variableDescriptors (" + variableDescriptorList + ") is empty.");
}
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
if (!variableDescriptor.getEntityDescriptor().getEntityClass().isAssignableFrom(
leftEntityDescriptor.getEntityClass())) {
throw new IllegalStateException("The selector (" + this
+ ") has a variableDescriptor with a entityClass ("
+ variableDescriptor.getEntityDescriptor().getEntityClass()
+ ") which is not equal or a superclass to the leftEntitySelector's entityClass ("
+ leftEntityDescriptor.getEntityClass() + ").");
}
if (variableDescriptor.isChained()) {
anyChained = true;
}
}
this.anyChained = anyChained;
phaseLifecycleSupport.addEventListener(leftEntitySelector);
if (leftEntitySelector != rightEntitySelector) {
phaseLifecycleSupport.addEventListener(rightEntitySelector);
}
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return !anyChained;
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
if (anyChained) {
inverseVariableSupplyList = null;
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return leftEntitySelector.isCountable() && rightEntitySelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || leftEntitySelector.isNeverEnding() || rightEntitySelector.isNeverEnding();
}
@Override
public long getSize() {
return AbstractOriginalSwapIterator.getSize(leftEntitySelector, rightEntitySelector);
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return new AbstractOriginalSwapIterator<>(leftEntitySelector, rightEntitySelector) {
@Override
protected Move<Solution_> newSwapSelection(Object leftSubSelection, Object rightSubSelection) {
return anyChained
? new ChainedSwapMove<>(variableDescriptorList, inverseVariableSupplyList, leftSubSelection,
rightSubSelection)
: new SwapMove<>(variableDescriptorList, leftSubSelection, rightSubSelection);
}
};
} else {
return new AbstractRandomSwapIterator<>(leftEntitySelector, rightEntitySelector) {
@Override
protected Move<Solution_> newSwapSelection(Object leftSubSelection, Object rightSubSelection) {
return anyChained
? new ChainedSwapMove<>(variableDescriptorList, inverseVariableSupplyList, leftSubSelection,
rightSubSelection)
: new SwapMove<>(variableDescriptorList, leftSubSelection, rightSubSelection);
}
};
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + leftEntitySelector + ", " + rightEntitySelector + ")";
}
}
|
super.solvingStarted(solverScope);
if (anyChained) {
inverseVariableSupplyList = new ArrayList<>(variableDescriptorList.size());
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
SingletonInverseVariableSupply inverseVariableSupply;
if (variableDescriptor.isChained()) {
inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor));
} else {
inverseVariableSupply = null;
}
inverseVariableSupplyList.add(inverseVariableSupply);
}
}
| 1,213
| 178
| 1,391
|
<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/heuristic/selector/move/generic/SwapMoveSelectorFactory.java
|
SwapMoveSelectorFactory
|
buildUnfoldedMoveSelectorConfig
|
class SwapMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, SwapMoveSelectorConfig> {
private static final Logger LOGGER = LoggerFactory.getLogger(SwapMoveSelectorFactory.class);
public SwapMoveSelectorFactory(SwapMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
EntitySelectorConfig entitySelectorConfig =
Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new);
EntitySelectorConfig secondaryEntitySelectorConfig =
Objects.requireNonNullElse(config.getSecondaryEntitySelectorConfig(), entitySelectorConfig);
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
EntitySelector<Solution_> leftEntitySelector =
EntitySelectorFactory.<Solution_> create(entitySelectorConfig)
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
EntitySelector<Solution_> rightEntitySelector =
EntitySelectorFactory.<Solution_> create(secondaryEntitySelectorConfig)
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
EntityDescriptor<Solution_> entityDescriptor = leftEntitySelector.getEntityDescriptor();
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList =
deduceVariableDescriptorList(entityDescriptor, config.getVariableNameIncludeList());
return new SwapMoveSelector<>(leftEntitySelector, rightEntitySelector, variableDescriptorList,
randomSelection);
}
@Override
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {
EntityDescriptor<Solution_> onlyEntityDescriptor = config.getEntitySelectorConfig() == null ? null
: EntitySelectorFactory.<Solution_> create(config.getEntitySelectorConfig())
.extractEntityDescriptor(configPolicy);
if (config.getSecondaryEntitySelectorConfig() != null) {
EntityDescriptor<Solution_> onlySecondaryEntityDescriptor =
EntitySelectorFactory.<Solution_> create(config.getSecondaryEntitySelectorConfig())
.extractEntityDescriptor(configPolicy);
if (onlyEntityDescriptor != onlySecondaryEntityDescriptor) {
throw new IllegalArgumentException("The entitySelector (" + config.getEntitySelectorConfig()
+ ")'s entityClass (" + (onlyEntityDescriptor == null ? null : onlyEntityDescriptor.getEntityClass())
+ ") and secondaryEntitySelectorConfig (" + config.getSecondaryEntitySelectorConfig()
+ ")'s entityClass ("
+ (onlySecondaryEntityDescriptor == null ? null : onlySecondaryEntityDescriptor.getEntityClass())
+ ") must be the same entity class.");
}
}
if (onlyEntityDescriptor != null) {
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList =
onlyEntityDescriptor.getGenuineVariableDescriptorList();
// If there is a single list variable, unfold to list swap move selector config.
if (variableDescriptorList.size() == 1 && variableDescriptorList.get(0).isListVariable()) {
return buildListSwapMoveSelectorConfig(variableDescriptorList.get(0), true);
}
// Otherwise, make sure there is no list variable, because SwapMove is not supposed to swap list variables.
failIfHasAnyGenuineListVariables(onlyEntityDescriptor);
// No need for unfolding or deducing
return null;
}
Collection<EntityDescriptor<Solution_>> entityDescriptors =
configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors();
return buildUnfoldedMoveSelectorConfig(entityDescriptors);
}
protected MoveSelectorConfig<?>
buildUnfoldedMoveSelectorConfig(Collection<EntityDescriptor<Solution_>> entityDescriptors) {<FILL_FUNCTION_BODY>}
private static void failIfHasAnyGenuineListVariables(EntityDescriptor<?> entityDescriptor) {
if (entityDescriptor.hasAnyGenuineListVariables()) {
throw new IllegalArgumentException(
"The variableDescriptorList (" + entityDescriptor.getGenuineVariableDescriptorList()
+ ") has multiple variables and one or more of them is a @"
+ PlanningListVariable.class.getSimpleName()
+ ", which is currently not supported.");
}
}
private ListSwapMoveSelectorConfig buildListSwapMoveSelectorConfig(VariableDescriptor<?> variableDescriptor,
boolean inheritFoldedConfig) {
LOGGER.warn("The swapMoveSelectorConfig ({}) is being used for a list variable."
+ " This was the only available option when the planning list variable was introduced."
+ " We are keeping this option through the 8.x release stream for backward compatibility reasons"
+ " but it will be removed in the next major release.\n"
+ "Please update your solver config to use ListSwapMoveSelectorConfig now.", config);
ListSwapMoveSelectorConfig listSwapMoveSelectorConfig = new ListSwapMoveSelectorConfig();
ValueSelectorConfig childValueSelectorConfig = new ValueSelectorConfig(
new ValueSelectorConfig(variableDescriptor.getVariableName()));
listSwapMoveSelectorConfig.setValueSelectorConfig(childValueSelectorConfig);
if (inheritFoldedConfig) {
listSwapMoveSelectorConfig.inheritFolded(config);
}
return listSwapMoveSelectorConfig;
}
}
|
List<MoveSelectorConfig> moveSelectorConfigList = new ArrayList<>(entityDescriptors.size());
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList =
entityDescriptors.iterator().next().getGenuineVariableDescriptorList();
// Only unfold into list swap move selector for the basic scenario with 1 entity and 1 list variable.
if (entityDescriptors.size() == 1 && variableDescriptorList.size() == 1
&& variableDescriptorList.get(0).isListVariable()) {
// No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded()
ListSwapMoveSelectorConfig childMoveSelectorConfig =
buildListSwapMoveSelectorConfig(variableDescriptorList.get(0), false);
moveSelectorConfigList.add(childMoveSelectorConfig);
} else {
// More complex scenarios do not support unfolding into list swap => fail fast if there is any list variable.
for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptors) {
failIfHasAnyGenuineListVariables(entityDescriptor);
// No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded()
SwapMoveSelectorConfig childMoveSelectorConfig = new SwapMoveSelectorConfig();
EntitySelectorConfig childEntitySelectorConfig = new EntitySelectorConfig(config.getEntitySelectorConfig());
if (childEntitySelectorConfig.getMimicSelectorRef() == null) {
childEntitySelectorConfig.setEntityClass(entityDescriptor.getEntityClass());
}
childMoveSelectorConfig.setEntitySelectorConfig(childEntitySelectorConfig);
if (config.getSecondaryEntitySelectorConfig() != null) {
EntitySelectorConfig childSecondaryEntitySelectorConfig =
new EntitySelectorConfig(config.getSecondaryEntitySelectorConfig());
if (childSecondaryEntitySelectorConfig.getMimicSelectorRef() == null) {
childSecondaryEntitySelectorConfig.setEntityClass(entityDescriptor.getEntityClass());
}
childMoveSelectorConfig.setSecondaryEntitySelectorConfig(childSecondaryEntitySelectorConfig);
}
childMoveSelectorConfig.setVariableNameIncludeList(config.getVariableNameIncludeList());
moveSelectorConfigList.add(childMoveSelectorConfig);
}
}
MoveSelectorConfig<?> unfoldedMoveSelectorConfig;
if (moveSelectorConfigList.size() == 1) {
unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0);
} else {
unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList);
}
unfoldedMoveSelectorConfig.inheritFolded(config);
return unfoldedMoveSelectorConfig;
| 1,356
| 657
| 2,013
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/chained/ChainedChangeMove.java
|
ChainedChangeMove
|
doMoveOnGenuineVariables
|
class ChainedChangeMove<Solution_> extends ChangeMove<Solution_> {
protected final Object oldTrailingEntity;
protected final Object newTrailingEntity;
public ChainedChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue,
SingletonInverseVariableSupply inverseVariableSupply) {
super(variableDescriptor, entity, toPlanningValue);
oldTrailingEntity = inverseVariableSupply.getInverseSingleton(entity);
newTrailingEntity = toPlanningValue == null ? null
: inverseVariableSupply.getInverseSingleton(toPlanningValue);
}
public ChainedChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue,
Object oldTrailingEntity, Object newTrailingEntity) {
super(variableDescriptor, entity, toPlanningValue);
this.oldTrailingEntity = oldTrailingEntity;
this.newTrailingEntity = newTrailingEntity;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return super.isMoveDoable(scoreDirector)
&& !Objects.equals(entity, toPlanningValue);
}
@Override
public ChainedChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
Object oldValue = variableDescriptor.getValue(entity);
return new ChainedChangeMove<>(variableDescriptor, entity, oldValue, newTrailingEntity, oldTrailingEntity);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public ChainedChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ChainedChangeMove<>(variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(entity),
destinationScoreDirector.lookUpWorkingObject(toPlanningValue),
destinationScoreDirector.lookUpWorkingObject(oldTrailingEntity),
destinationScoreDirector.lookUpWorkingObject(newTrailingEntity));
}
}
|
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
Object oldValue = variableDescriptor.getValue(entity);
// Close the old chain
if (oldTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingEntity, oldValue);
}
// Change the entity
innerScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue);
// Reroute the new chain
if (newTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, entity);
}
| 574
| 171
| 745
|
<methods>public void <init>(GenuineVariableDescriptor<Solution_>, java.lang.Object, java.lang.Object) ,public ChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_>) ,public boolean equals(java.lang.Object) ,public java.lang.Object getEntity() ,public Collection<? extends java.lang.Object> getPlanningEntities() ,public Collection<? extends java.lang.Object> getPlanningValues() ,public java.lang.String getSimpleMoveTypeDescription() ,public java.lang.Object getToPlanningValue() ,public java.lang.String getVariableName() ,public int hashCode() ,public boolean isMoveDoable(ScoreDirector<Solution_>) ,public ChangeMove<Solution_> rebase(ScoreDirector<Solution_>) ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object entity,protected final non-sealed java.lang.Object toPlanningValue,protected final non-sealed GenuineVariableDescriptor<Solution_> variableDescriptor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/chained/ChainedSwapMove.java
|
ChainedSwapMove
|
doMoveOnGenuineVariables
|
class ChainedSwapMove<Solution_> extends SwapMove<Solution_> {
protected final List<Object> oldLeftTrailingEntityList;
protected final List<Object> oldRightTrailingEntityList;
public ChainedSwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList,
List<SingletonInverseVariableSupply> inverseVariableSupplyList, Object leftEntity, Object rightEntity) {
super(variableDescriptorList, leftEntity, rightEntity);
oldLeftTrailingEntityList = new ArrayList<>(inverseVariableSupplyList.size());
oldRightTrailingEntityList = new ArrayList<>(inverseVariableSupplyList.size());
for (SingletonInverseVariableSupply inverseVariableSupply : inverseVariableSupplyList) {
boolean hasSupply = inverseVariableSupply != null;
oldLeftTrailingEntityList.add(hasSupply ? inverseVariableSupply.getInverseSingleton(leftEntity) : null);
oldRightTrailingEntityList.add(hasSupply ? inverseVariableSupply.getInverseSingleton(rightEntity) : null);
}
}
public ChainedSwapMove(List<GenuineVariableDescriptor<Solution_>> genuineVariableDescriptors,
Object leftEntity, Object rightEntity,
List<Object> oldLeftTrailingEntityList, List<Object> oldRightTrailingEntityList) {
super(genuineVariableDescriptors, leftEntity, rightEntity);
this.oldLeftTrailingEntityList = oldLeftTrailingEntityList;
this.oldRightTrailingEntityList = oldRightTrailingEntityList;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public ChainedSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new ChainedSwapMove<>(variableDescriptorList, rightEntity, leftEntity, oldLeftTrailingEntityList,
oldRightTrailingEntityList);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public ChainedSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ChainedSwapMove<>(variableDescriptorList,
destinationScoreDirector.lookUpWorkingObject(leftEntity),
destinationScoreDirector.lookUpWorkingObject(rightEntity),
rebaseList(oldLeftTrailingEntityList, destinationScoreDirector),
rebaseList(oldRightTrailingEntityList, destinationScoreDirector));
}
}
|
for (int i = 0; i < variableDescriptorList.size(); i++) {
GenuineVariableDescriptor<Solution_> variableDescriptor = variableDescriptorList.get(i);
Object oldLeftValue = variableDescriptor.getValue(leftEntity);
Object oldRightValue = variableDescriptor.getValue(rightEntity);
if (!Objects.equals(oldLeftValue, oldRightValue)) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
if (!variableDescriptor.isChained()) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue);
innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue);
} else {
Object oldLeftTrailingEntity = oldLeftTrailingEntityList.get(i);
Object oldRightTrailingEntity = oldRightTrailingEntityList.get(i);
if (oldRightValue == leftEntity) {
// Change the right entity
innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue);
// Change the left entity
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightEntity);
// Reroute the new left chain
if (oldRightTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldRightTrailingEntity, leftEntity);
}
} else if (oldLeftValue == rightEntity) {
// Change the right entity
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue);
// Change the left entity
innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftEntity);
// Reroute the new left chain
if (oldLeftTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldLeftTrailingEntity, rightEntity);
}
} else {
// Change the left entity
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue);
// Change the right entity
innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue);
// Reroute the new left chain
if (oldRightTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldRightTrailingEntity, leftEntity);
}
// Reroute the new right chain
if (oldLeftTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldLeftTrailingEntity, rightEntity);
}
}
}
}
}
| 657
| 648
| 1,305
|
<methods>public void <init>(List<GenuineVariableDescriptor<Solution_>>, java.lang.Object, java.lang.Object) ,public SwapMove<Solution_> createUndoMove(ScoreDirector<Solution_>) ,public boolean equals(java.lang.Object) ,public java.lang.Object getLeftEntity() ,public Collection<? extends java.lang.Object> getPlanningEntities() ,public Collection<? extends java.lang.Object> getPlanningValues() ,public java.lang.Object getRightEntity() ,public java.lang.String getSimpleMoveTypeDescription() ,public int hashCode() ,public boolean isMoveDoable(ScoreDirector<Solution_>) ,public SwapMove<Solution_> rebase(ScoreDirector<Solution_>) ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object leftEntity,protected final non-sealed java.lang.Object rightEntity,protected final non-sealed List<GenuineVariableDescriptor<Solution_>> variableDescriptorList
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/chained/KOptMove.java
|
KOptMove
|
createUndoMove
|
class KOptMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
// TODO remove me to enable multithreaded solving, but first fix https://issues.redhat.com/browse/PLANNER-1250
protected final SingletonInverseVariableSupply inverseVariableSupply;
protected final AnchorVariableSupply anchorVariableSupply;
protected final Object entity;
protected final Object[] values;
public KOptMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply, AnchorVariableSupply anchorVariableSupply,
Object entity, Object[] values) {
this.variableDescriptor = variableDescriptor;
this.inverseVariableSupply = inverseVariableSupply;
this.anchorVariableSupply = anchorVariableSupply;
this.entity = entity;
this.values = values;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public Object getEntity() {
return entity;
}
public Object[] getValues() {
return values;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public int getK() {
return 1 + values.length;
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
Object firstAnchor = anchorVariableSupply.getAnchor(entity);
Object firstValue = variableDescriptor.getValue(entity);
Object formerAnchor = firstAnchor;
Object formerValue = firstValue;
for (Object value : values) {
Object anchor = variableDescriptor.isValuePotentialAnchor(value)
? value
: anchorVariableSupply.getAnchor(value);
if (anchor == formerAnchor && compareValuesInSameChain(formerValue, value) >= 0) {
return false;
}
formerAnchor = anchor;
formerValue = value;
}
if (firstAnchor == formerAnchor && compareValuesInSameChain(formerValue, firstValue) >= 0) {
return false;
}
return true;
}
protected int compareValuesInSameChain(Object a, Object b) {
if (a == b) {
return 0;
}
Object afterA = inverseVariableSupply.getInverseSingleton(a);
while (afterA != null) {
if (afterA == b) {
return 1;
}
afterA = inverseVariableSupply.getInverseSingleton(afterA);
}
return -1;
}
@Override
public KOptMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
Object firstValue = variableDescriptor.getValue(entity);
Object formerEntity = entity;
for (int i = 0; i < values.length; i++) {
Object value = values[i];
if (formerEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, formerEntity, value);
}
formerEntity = inverseVariableSupply.getInverseSingleton(value);
}
if (formerEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, formerEntity, firstValue);
}
}
@Override
public KOptMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
throw new UnsupportedOperationException("https://issues.redhat.com/browse/PLANNER-1250"); // TODO test also disabled
// return new KOptMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply,
// destinationScoreDirector.lookUpWorkingObject(entity),
// rebaseArray(values, destinationScoreDirector));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
List<Object> allEntityList = new ArrayList<>(values.length + 1);
allEntityList.add(entity);
for (int i = 0; i < values.length; i++) {
Object value = values[i];
allEntityList.add(inverseVariableSupply.getInverseSingleton(value));
}
return allEntityList;
}
@Override
public Collection<? extends Object> getPlanningValues() {
List<Object> allValueList = new ArrayList<>(values.length + 1);
allValueList.add(variableDescriptor.getValue(entity));
Collections.addAll(allValueList, values);
return allValueList;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final KOptMove<?> kOptMove = (KOptMove<?>) o;
return Objects.equals(entity, kOptMove.entity) &&
Arrays.equals(values, kOptMove.values);
}
@Override
public int hashCode() {
return Objects.hash(entity, Arrays.hashCode(values));
}
@Override
public String toString() {
Object leftValue = variableDescriptor.getValue(entity);
StringBuilder builder = new StringBuilder(80 * values.length);
builder.append(entity).append(" {").append(leftValue);
for (int i = 0; i < values.length; i++) {
Object value = values[i];
Object oldEntity = inverseVariableSupply.getInverseSingleton(value);
builder.append("} -kOpt-> ").append(oldEntity).append(" {").append(value);
}
builder.append("}");
return builder.toString();
}
}
|
Object[] undoValues = new Object[values.length];
undoValues[0] = variableDescriptor.getValue(entity);
for (int i = 1; i < values.length; i++) {
undoValues[i] = values[values.length - i];
}
return new KOptMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply,
entity, undoValues);
| 1,620
| 103
| 1,723
|
<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/heuristic/selector/move/generic/chained/KOptMoveSelectorFactory.java
|
KOptMoveSelectorFactory
|
buildBaseMoveSelector
|
class KOptMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, KOptMoveSelectorConfig> {
private static final int K = 3;
public KOptMoveSelectorFactory(KOptMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
EntitySelectorConfig entitySelectorConfig =
Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new);
ValueSelectorConfig valueSelectorConfig =
Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
EntitySelector<Solution_> entitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig)
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
ValueSelector<Solution_>[] valueSelectors = new ValueSelector[K - 1];
for (int i = 0; i < valueSelectors.length; i++) {
valueSelectors[i] = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder);
}
return new KOptMoveSelector<>(entitySelector, valueSelectors, randomSelection);
| 134
| 254
| 388
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.chained.KOptMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/chained/SubChainChangeMoveSelector.java
|
RandomSubChainChangeMoveIterator
|
createUpcomingSelection
|
class RandomSubChainChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private Iterator<SubChain> subChainIterator;
private Iterator<Object> valueIterator;
private RandomSubChainChangeMoveIterator() {
subChainIterator = subChainSelector.iterator();
valueIterator = valueSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
// Ideally, this code should have read:
// SubChain subChain = subChainIterator.next();
// Object toValue = valueIterator.next();
// But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
if (!subChainIterator.hasNext()) {
subChainIterator = subChainSelector.iterator();
if (!subChainIterator.hasNext()) {
// subChainSelector is completely empty
return noUpcomingSelection();
}
}
SubChain subChain = subChainIterator.next();
if (!valueIterator.hasNext()) {
valueIterator = valueSelector.iterator();
if (!valueIterator.hasNext()) {
// valueSelector is completely empty
return noUpcomingSelection();
}
}
Object toValue = valueIterator.next();
boolean reversing = selectReversingMoveToo && workingRandom.nextBoolean();
return reversing
? new SubChainReversingChangeMove<>(subChain, valueSelector.getVariableDescriptor(),
inverseVariableSupply, toValue)
: new SubChainChangeMove<>(subChain, valueSelector.getVariableDescriptor(), inverseVariableSupply,
toValue);
| 153
| 296
| 449
|
<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/heuristic/selector/move/generic/chained/SubChainChangeMoveSelectorFactory.java
|
SubChainChangeMoveSelectorFactory
|
buildBaseMoveSelector
|
class SubChainChangeMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, SubChainChangeMoveSelectorConfig> {
public SubChainChangeMoveSelectorFactory(SubChainChangeMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
}
|
EntityDescriptor<Solution_> entityDescriptor = deduceEntityDescriptor(configPolicy, config.getEntityClass());
SubChainSelectorConfig subChainSelectorConfig =
Objects.requireNonNullElseGet(config.getSubChainSelectorConfig(), SubChainSelectorConfig::new);
ValueSelectorConfig valueSelectorConfig =
Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
SubChainSelector<Solution_> subChainSelector =
SubChainSelectorFactory.<Solution_> create(subChainSelectorConfig)
.buildSubChainSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder);
ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder);
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
return new SubChainChangeMoveSelector<>(subChainSelector,
(EntityIndependentValueSelector<Solution_>) valueSelector, randomSelection,
Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true));
| 127
| 373
| 500
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/chained/SubChainReversingChangeMove.java
|
SubChainReversingChangeMove
|
equals
|
class SubChainReversingChangeMove<Solution_> extends AbstractMove<Solution_> {
protected final SubChain subChain;
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final Object toPlanningValue;
protected final Object oldTrailingLastEntity;
protected final Object newTrailingEntity;
public SubChainReversingChangeMove(SubChain subChain, GenuineVariableDescriptor<Solution_> variableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply, Object toPlanningValue) {
this.subChain = subChain;
this.variableDescriptor = variableDescriptor;
this.toPlanningValue = toPlanningValue;
oldTrailingLastEntity = inverseVariableSupply.getInverseSingleton(subChain.getLastEntity());
newTrailingEntity = toPlanningValue == null ? null
: inverseVariableSupply.getInverseSingleton(toPlanningValue);
}
public SubChainReversingChangeMove(SubChain subChain, GenuineVariableDescriptor<Solution_> variableDescriptor,
Object toPlanningValue, Object oldTrailingLastEntity, Object newTrailingEntity) {
this.subChain = subChain;
this.variableDescriptor = variableDescriptor;
this.toPlanningValue = toPlanningValue;
this.oldTrailingLastEntity = oldTrailingLastEntity;
this.newTrailingEntity = newTrailingEntity;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public SubChain getSubChain() {
return subChain;
}
public Object getToPlanningValue() {
return toPlanningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
if (subChain.getEntityList().contains(toPlanningValue)) {
return false;
}
Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity());
return !Objects.equals(oldFirstValue, toPlanningValue);
}
@Override
public SubChainReversingChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity());
boolean unmovedReverse = toPlanningValue == oldFirstValue;
if (!unmovedReverse) {
return new SubChainReversingChangeMove<>(subChain.reverse(), variableDescriptor, oldFirstValue,
newTrailingEntity, oldTrailingLastEntity);
} else {
return new SubChainReversingChangeMove<>(subChain.reverse(), variableDescriptor, oldFirstValue,
oldTrailingLastEntity, newTrailingEntity);
}
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
Object firstEntity = subChain.getFirstEntity();
Object lastEntity = subChain.getLastEntity();
Object oldFirstValue = variableDescriptor.getValue(firstEntity);
boolean unmovedReverse = toPlanningValue == oldFirstValue;
// Close the old chain
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
if (!unmovedReverse) {
if (oldTrailingLastEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingLastEntity, oldFirstValue);
}
}
Object lastEntityValue = variableDescriptor.getValue(lastEntity);
// Change the entity
innerScoreDirector.changeVariableFacade(variableDescriptor, lastEntity, toPlanningValue);
// Reverse the chain
reverseChain(innerScoreDirector, lastEntity, lastEntityValue, firstEntity);
// Reroute the new chain
if (!unmovedReverse) {
if (newTrailingEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, firstEntity);
}
} else {
if (oldTrailingLastEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingLastEntity, firstEntity);
}
}
}
private void reverseChain(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, Object previous,
Object toEntity) {
while (entity != toEntity) {
Object value = variableDescriptor.getValue(previous);
scoreDirector.changeVariableFacade(variableDescriptor, previous, entity);
entity = previous;
previous = value;
}
}
@Override
public SubChainReversingChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SubChainReversingChangeMove<>(subChain.rebase(destinationScoreDirector),
variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(toPlanningValue),
destinationScoreDirector.lookUpWorkingObject(oldTrailingLastEntity),
destinationScoreDirector.lookUpWorkingObject(newTrailingEntity));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return subChain.getEntityList();
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toPlanningValue);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(subChain, variableDescriptor.getVariableName(), toPlanningValue);
}
@Override
public String toString() {
Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity());
return subChain.toDottedString() + " {" + oldFirstValue + " -reversing-> " + toPlanningValue + "}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final SubChainReversingChangeMove<?> other = (SubChainReversingChangeMove<?>) o;
return Objects.equals(subChain, other.subChain) &&
Objects.equals(variableDescriptor.getVariableName(), other.variableDescriptor.getVariableName()) &&
Objects.equals(toPlanningValue, other.toPlanningValue);
| 1,579
| 136
| 1,715
|
<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/heuristic/selector/move/generic/chained/SubChainReversingSwapMove.java
|
SubChainReversingSwapMove
|
doMoveOnGenuineVariables
|
class SubChainReversingSwapMove<Solution_> extends AbstractMove<Solution_> {
private final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final SubChain leftSubChain;
protected final Object leftTrailingLastEntity;
protected final SubChain rightSubChain;
protected final Object rightTrailingLastEntity;
public SubChainReversingSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply,
SubChain leftSubChain, SubChain rightSubChain) {
this.variableDescriptor = variableDescriptor;
this.leftSubChain = leftSubChain;
leftTrailingLastEntity = inverseVariableSupply.getInverseSingleton(leftSubChain.getLastEntity());
this.rightSubChain = rightSubChain;
rightTrailingLastEntity = inverseVariableSupply.getInverseSingleton(rightSubChain.getLastEntity());
}
public SubChainReversingSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
SubChain leftSubChain, Object leftTrailingLastEntity,
SubChain rightSubChain, Object rightTrailingLastEntity) {
this.variableDescriptor = variableDescriptor;
this.leftSubChain = leftSubChain;
this.rightSubChain = rightSubChain;
this.leftTrailingLastEntity = leftTrailingLastEntity;
this.rightTrailingLastEntity = rightTrailingLastEntity;
}
public SubChain getLeftSubChain() {
return leftSubChain;
}
public SubChain getRightSubChain() {
return rightSubChain;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
// Because leftFirstEntity and rightFirstEntity are unequal, chained guarantees their values are unequal too.
return !SubChainSwapMove.containsAnyOf(rightSubChain, leftSubChain);
}
@Override
public SubChainReversingSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new SubChainReversingSwapMove<>(variableDescriptor,
rightSubChain.reverse(), leftTrailingLastEntity,
leftSubChain.reverse(), rightTrailingLastEntity);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
private void reverseChain(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, Object previous,
Object toEntity) {
while (entity != toEntity) {
Object value = variableDescriptor.getValue(previous);
scoreDirector.changeVariableFacade(variableDescriptor, previous, entity);
entity = previous;
previous = value;
}
}
@Override
public SubChainReversingSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SubChainReversingSwapMove<>(variableDescriptor,
leftSubChain.rebase(destinationScoreDirector),
destinationScoreDirector.lookUpWorkingObject(leftTrailingLastEntity),
rightSubChain.rebase(destinationScoreDirector),
destinationScoreDirector.lookUpWorkingObject(rightTrailingLastEntity));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return CollectionUtils.concat(leftSubChain.getEntityList(), rightSubChain.getEntityList());
}
@Override
public Collection<? extends Object> getPlanningValues() {
List<Object> values = new ArrayList<>(2);
values.add(variableDescriptor.getValue(leftSubChain.getFirstEntity()));
values.add(variableDescriptor.getValue(rightSubChain.getFirstEntity()));
return values;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final SubChainReversingSwapMove<?> other = (SubChainReversingSwapMove<?>) o;
return Objects.equals(variableDescriptor, other.variableDescriptor) &&
Objects.equals(leftSubChain, other.leftSubChain) &&
Objects.equals(rightSubChain, other.rightSubChain);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, leftSubChain, rightSubChain);
}
@Override
public String toString() {
Object oldLeftValue = variableDescriptor.getValue(leftSubChain.getFirstEntity());
Object oldRightValue = variableDescriptor.getValue(rightSubChain.getFirstEntity());
return leftSubChain.toDottedString() + " {" + oldLeftValue + "} <-reversing-> "
+ rightSubChain.toDottedString() + " {" + oldRightValue + "}";
}
}
|
Object leftFirstEntity = leftSubChain.getFirstEntity();
Object leftFirstValue = variableDescriptor.getValue(leftFirstEntity);
Object leftLastEntity = leftSubChain.getLastEntity();
Object rightFirstEntity = rightSubChain.getFirstEntity();
Object rightFirstValue = variableDescriptor.getValue(rightFirstEntity);
Object rightLastEntity = rightSubChain.getLastEntity();
Object leftLastEntityValue = variableDescriptor.getValue(leftLastEntity);
Object rightLastEntityValue = variableDescriptor.getValue(rightLastEntity);
// Change the entities
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
if (leftLastEntity != rightFirstValue) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftLastEntity, rightFirstValue);
}
if (rightLastEntity != leftFirstValue) {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightLastEntity, leftFirstValue);
}
// Reverse the chains
reverseChain(innerScoreDirector, leftLastEntity, leftLastEntityValue, leftFirstEntity);
reverseChain(innerScoreDirector, rightLastEntity, rightLastEntityValue, rightFirstEntity);
// Reroute the new chains
if (leftTrailingLastEntity != null) {
if (leftTrailingLastEntity != rightFirstEntity) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftTrailingLastEntity, rightFirstEntity);
} else {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftLastEntity, rightFirstEntity);
}
}
if (rightTrailingLastEntity != null) {
if (rightTrailingLastEntity != leftFirstEntity) {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightTrailingLastEntity, leftFirstEntity);
} else {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightLastEntity, leftFirstEntity);
}
}
| 1,340
| 490
| 1,830
|
<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/heuristic/selector/move/generic/chained/SubChainSwapMove.java
|
SubChainSwapMove
|
doMoveOnGenuineVariables
|
class SubChainSwapMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final SubChain leftSubChain;
protected final Object leftTrailingLastEntity;
protected final SubChain rightSubChain;
protected final Object rightTrailingLastEntity;
public SubChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply,
SubChain leftSubChain, SubChain rightSubChain) {
this.variableDescriptor = variableDescriptor;
this.leftSubChain = leftSubChain;
leftTrailingLastEntity = inverseVariableSupply.getInverseSingleton(leftSubChain.getLastEntity());
this.rightSubChain = rightSubChain;
rightTrailingLastEntity = inverseVariableSupply.getInverseSingleton(rightSubChain.getLastEntity());
}
public SubChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
SubChain leftSubChain, Object leftTrailingLastEntity, SubChain rightSubChain,
Object rightTrailingLastEntity) {
this.variableDescriptor = variableDescriptor;
this.leftSubChain = leftSubChain;
this.rightSubChain = rightSubChain;
this.leftTrailingLastEntity = leftTrailingLastEntity;
this.rightTrailingLastEntity = rightTrailingLastEntity;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public SubChain getLeftSubChain() {
return leftSubChain;
}
public SubChain getRightSubChain() {
return rightSubChain;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return !containsAnyOf(rightSubChain, leftSubChain);
}
static boolean containsAnyOf(SubChain rightSubChain, SubChain leftSubChain) {
int leftSubChainSize = leftSubChain.getSize();
if (leftSubChainSize == 0) {
return false;
} else if (leftSubChainSize == 1) { // No optimization possible.
return rightSubChain.getEntityList().contains(leftSubChain.getFirstEntity());
}
/*
* In order to find an entity in another subchain, we need to do contains() on a List.
* List.contains() is O(n), the performance gets worse with increasing size.
* Subchains here can easily have hundreds, thousands of elements.
* As Set.contains() is O(1), independent of set size, copying the list outperforms the lookup by a lot.
* Therefore this code converts the List lookup to HashSet lookup, in situations with repeat lookup.
*/
Set<Object> rightSubChainEntityFastLookupSet = new HashSet<>(rightSubChain.getEntityList());
for (Object leftEntity : leftSubChain.getEntityList()) {
if (rightSubChainEntityFastLookupSet.contains(leftEntity)) {
return true;
}
}
return false;
}
@Override
public SubChainSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new SubChainSwapMove<>(variableDescriptor,
rightSubChain, leftTrailingLastEntity,
leftSubChain, rightTrailingLastEntity);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public SubChainSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SubChainSwapMove<>(variableDescriptor,
leftSubChain.rebase(destinationScoreDirector),
destinationScoreDirector.lookUpWorkingObject(leftTrailingLastEntity),
rightSubChain.rebase(destinationScoreDirector),
destinationScoreDirector.lookUpWorkingObject(rightTrailingLastEntity));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return CollectionUtils.concat(leftSubChain.getEntityList(), rightSubChain.getEntityList());
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Arrays.asList(
variableDescriptor.getValue(leftSubChain.getFirstEntity()),
variableDescriptor.getValue(rightSubChain.getFirstEntity()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final SubChainSwapMove<?> other = (SubChainSwapMove<?>) o;
return Objects.equals(variableDescriptor, other.variableDescriptor) &&
Objects.equals(leftSubChain, other.leftSubChain) &&
Objects.equals(rightSubChain, other.rightSubChain);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, leftSubChain, rightSubChain);
}
@Override
public String toString() {
Object oldLeftValue = variableDescriptor.getValue(leftSubChain.getFirstEntity());
Object oldRightValue = variableDescriptor.getValue(rightSubChain.getFirstEntity());
return leftSubChain.toDottedString() + " {" + oldLeftValue + "} <-> "
+ rightSubChain.toDottedString() + " {" + oldRightValue + "}";
}
}
|
Object leftFirstEntity = leftSubChain.getFirstEntity();
Object leftFirstValue = variableDescriptor.getValue(leftFirstEntity);
Object leftLastEntity = leftSubChain.getLastEntity();
Object rightFirstEntity = rightSubChain.getFirstEntity();
Object rightFirstValue = variableDescriptor.getValue(rightFirstEntity);
Object rightLastEntity = rightSubChain.getLastEntity();
// Change the entities
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
if (leftLastEntity != rightFirstValue) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftFirstEntity, rightFirstValue);
}
if (rightLastEntity != leftFirstValue) {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightFirstEntity, leftFirstValue);
}
// Reroute the new chains
if (leftTrailingLastEntity != null) {
if (leftTrailingLastEntity != rightFirstEntity) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftTrailingLastEntity, rightLastEntity);
} else {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftFirstEntity, rightLastEntity);
}
}
if (rightTrailingLastEntity != null) {
if (rightTrailingLastEntity != leftFirstEntity) {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightTrailingLastEntity, leftLastEntity);
} else {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightFirstEntity, leftLastEntity);
}
}
| 1,480
| 402
| 1,882
|
<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/heuristic/selector/move/generic/list/ListAssignMove.java
|
ListAssignMove
|
equals
|
class ListAssignMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object planningValue;
private final Object destinationEntity;
private final int destinationIndex;
public ListAssignMove(
ListVariableDescriptor<Solution_> variableDescriptor,
Object planningValue,
Object destinationEntity, int destinationIndex) {
this.variableDescriptor = variableDescriptor;
this.planningValue = planningValue;
this.destinationEntity = destinationEntity;
this.destinationIndex = destinationIndex;
}
public Object getDestinationEntity() {
return destinationEntity;
}
public int getDestinationIndex() {
return destinationIndex;
}
public Object getMovedValue() {
return planningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
@Override
public ListUnassignMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new ListUnassignMove<>(variableDescriptor, destinationEntity, destinationIndex);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
// Add planningValue to destinationEntity's list variable (at destinationIndex).
innerScoreDirector.beforeListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex);
innerScoreDirector.beforeListVariableElementAssigned(variableDescriptor, planningValue);
variableDescriptor.addElement(destinationEntity, destinationIndex, planningValue);
innerScoreDirector.afterListVariableElementAssigned(variableDescriptor, planningValue);
innerScoreDirector.afterListVariableChanged(variableDescriptor, destinationEntity, destinationIndex,
destinationIndex + 1);
}
@Override
public ListAssignMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ListAssignMove<>(
variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(planningValue),
destinationScoreDirector.lookUpWorkingObject(destinationEntity),
destinationIndex);
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, planningValue, destinationEntity, destinationIndex);
}
@Override
public String toString() {
return String.format("%s {null -> %s[%d]}",
getMovedValue(), destinationEntity, destinationIndex);
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListAssignMove<?> other = (ListAssignMove<?>) o;
return destinationIndex == other.destinationIndex
&& Objects.equals(variableDescriptor, other.variableDescriptor)
&& Objects.equals(planningValue, other.planningValue)
&& Objects.equals(destinationEntity, other.destinationEntity);
| 787
| 132
| 919
|
<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/heuristic/selector/move/generic/list/ListChangeMoveSelectorFactory.java
|
ListChangeMoveSelectorFactory
|
buildUnfoldedMoveSelectorConfig
|
class ListChangeMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, ListChangeMoveSelectorConfig> {
public ListChangeMoveSelectorFactory(ListChangeMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
checkUnfolded("valueSelectorConfig", config.getValueSelectorConfig());
checkUnfolded("destinationSelectorConfig", config.getDestinationSelectorConfig());
checkUnfolded("destinationEntitySelectorConfig", config.getDestinationSelectorConfig().getEntitySelectorConfig());
checkUnfolded("destinationValueSelectorConfig", config.getDestinationSelectorConfig().getValueSelectorConfig());
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
EntityDescriptor<Solution_> entityDescriptor = EntitySelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig().getEntitySelectorConfig())
.extractEntityDescriptor(configPolicy);
ValueSelector<Solution_> sourceValueSelector = ValueSelectorFactory
.<Solution_> create(config.getValueSelectorConfig())
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder);
if (!(sourceValueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The listChangeMoveSelector (" + config
+ ") for a list variable needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + sourceValueSelector + ")."
+ " Check your valueSelectorConfig.");
}
DestinationSelector<Solution_> destinationSelector = DestinationSelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig())
.buildDestinationSelector(configPolicy, minimumCacheType, randomSelection);
return new ListChangeMoveSelector<>(
(EntityIndependentValueSelector<Solution_>) sourceValueSelector,
destinationSelector,
randomSelection);
}
@Override
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {<FILL_FUNCTION_BODY>}
public static ListChangeMoveSelectorConfig buildChildMoveSelectorConfig(
ListVariableDescriptor<?> variableDescriptor,
ValueSelectorConfig inheritedValueSelectorConfig,
DestinationSelectorConfig inheritedDestinationSelectorConfig) {
ValueSelectorConfig childValueSelectorConfig = new ValueSelectorConfig(inheritedValueSelectorConfig);
if (childValueSelectorConfig.getMimicSelectorRef() == null) {
childValueSelectorConfig.setVariableName(variableDescriptor.getVariableName());
}
return new ListChangeMoveSelectorConfig()
.withValueSelectorConfig(childValueSelectorConfig)
.withDestinationSelectorConfig(new DestinationSelectorConfig(inheritedDestinationSelectorConfig)
.withEntitySelectorConfig(
Optional.ofNullable(inheritedDestinationSelectorConfig)
.map(DestinationSelectorConfig::getEntitySelectorConfig)
.map(EntitySelectorConfig::new) // use copy constructor if inherited not null
.orElseGet(EntitySelectorConfig::new) // otherwise create new instance
// override entity class (destination entity selector is never replaying)
.withEntityClass(variableDescriptor.getEntityDescriptor().getEntityClass()))
.withValueSelectorConfig(
Optional.ofNullable(inheritedDestinationSelectorConfig)
.map(DestinationSelectorConfig::getValueSelectorConfig)
.map(ValueSelectorConfig::new) // use copy constructor if inherited not null
.orElseGet(ValueSelectorConfig::new) // otherwise create new instance
// override variable name (destination value selector is never replaying)
.withVariableName(variableDescriptor.getVariableName())));
}
}
|
Collection<EntityDescriptor<Solution_>> entityDescriptors;
EntityDescriptor<Solution_> onlyEntityDescriptor = config.getDestinationSelectorConfig() == null ? null
: config.getDestinationSelectorConfig().getEntitySelectorConfig() == null ? null
: EntitySelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig().getEntitySelectorConfig())
.extractEntityDescriptor(configPolicy);
if (onlyEntityDescriptor != null) {
entityDescriptors = Collections.singletonList(onlyEntityDescriptor);
} else {
entityDescriptors = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors();
}
if (entityDescriptors.size() > 1) {
throw new IllegalArgumentException("The listChangeMoveSelector (" + config
+ ") cannot unfold when there are multiple entities (" + entityDescriptors + ")."
+ " Please use one listChangeMoveSelector per each planning list variable.");
}
EntityDescriptor<Solution_> entityDescriptor = entityDescriptors.iterator().next();
List<ListVariableDescriptor<Solution_>> variableDescriptorList = new ArrayList<>();
GenuineVariableDescriptor<Solution_> onlyVariableDescriptor = config.getValueSelectorConfig() == null ? null
: ValueSelectorFactory.<Solution_> create(config.getValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
GenuineVariableDescriptor<Solution_> onlyDestinationVariableDescriptor =
config.getDestinationSelectorConfig() == null ? null
: config.getDestinationSelectorConfig().getValueSelectorConfig() == null ? null
: ValueSelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig().getValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
if (onlyVariableDescriptor != null && onlyDestinationVariableDescriptor != null) {
if (!onlyVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The listChangeMoveSelector (" + config
+ ") is configured to use a planning variable (" + onlyVariableDescriptor
+ "), which is not a planning list variable."
+ " Either fix your annotations and use a @" + PlanningListVariable.class.getSimpleName()
+ " on the variable to make it work with listChangeMoveSelector"
+ " or use a changeMoveSelector instead.");
}
if (!onlyDestinationVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The destinationSelector (" + config.getDestinationSelectorConfig()
+ ") is configured to use a planning variable (" + onlyDestinationVariableDescriptor
+ "), which is not a planning list variable.");
}
if (onlyVariableDescriptor != onlyDestinationVariableDescriptor) {
throw new IllegalArgumentException("The listChangeMoveSelector's valueSelector ("
+ config.getValueSelectorConfig()
+ ") and destinationSelector's valueSelector ("
+ config.getDestinationSelectorConfig().getValueSelectorConfig()
+ ") must be configured for the same planning variable.");
}
if (onlyEntityDescriptor != null) {
// No need for unfolding or deducing
return null;
}
variableDescriptorList.add((ListVariableDescriptor<Solution_>) onlyVariableDescriptor);
} else {
variableDescriptorList.addAll(
entityDescriptor.getGenuineVariableDescriptorList().stream()
.filter(GenuineVariableDescriptor::isListVariable)
.map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor))
.collect(Collectors.toList()));
}
if (variableDescriptorList.isEmpty()) {
throw new IllegalArgumentException("The listChangeMoveSelector (" + config
+ ") cannot unfold because there are no planning list variables.");
}
if (variableDescriptorList.size() > 1) {
throw new IllegalArgumentException("The listChangeMoveSelector (" + config
+ ") cannot unfold because there are multiple planning list variables.");
}
ListChangeMoveSelectorConfig listChangeMoveSelectorConfig = buildChildMoveSelectorConfig(
variableDescriptorList.get(0),
config.getValueSelectorConfig(),
config.getDestinationSelectorConfig());
listChangeMoveSelectorConfig.inheritFolded(config);
return listChangeMoveSelectorConfig;
| 935
| 1,020
| 1,955
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/ListSwapMove.java
|
ListSwapMove
|
doMoveOnGenuineVariables
|
class ListSwapMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object leftEntity;
private final int leftIndex;
private final Object rightEntity;
private final int rightIndex;
/**
* Create a move that swaps a list variable element at {@code leftEntity.listVariable[leftIndex]} with
* {@code rightEntity.listVariable[rightIndex]}.
*
* <h4>ListSwapMove anatomy</h4>
*
* <pre>
* {@code
* / rightEntity
* right element \ | / rightIndex
* | | |
* A {Ann[0]} <-> Y {Bob[1]}
* | | |
* left element / | \ leftIndex
* \ leftEntity
* }
* </pre>
*
* <h4>Example</h4>
*
* <pre>
* {@code
* GIVEN
* Ann.tasks = [A, B, C]
* Bob.tasks = [X, Y]
*
* WHEN
* ListSwapMove: A {Ann[0]} <-> Y {Bob[1]}
*
* THEN
* Ann.tasks = [Y, B, C]
* Bob.tasks = [X, A]
* }
* </pre>
*
* @param variableDescriptor descriptor of a list variable, for example {@code Employee.taskList}
* @param leftEntity together with {@code leftIndex} identifies the left element to be moved
* @param leftIndex together with {@code leftEntity} identifies the left element to be moved
* @param rightEntity together with {@code rightIndex} identifies the right element to be moved
* @param rightIndex together with {@code rightEntity} identifies the right element to be moved
*/
public ListSwapMove(
ListVariableDescriptor<Solution_> variableDescriptor,
Object leftEntity, int leftIndex,
Object rightEntity, int rightIndex) {
this.variableDescriptor = variableDescriptor;
this.leftEntity = leftEntity;
this.leftIndex = leftIndex;
this.rightEntity = rightEntity;
this.rightIndex = rightIndex;
}
public Object getLeftEntity() {
return leftEntity;
}
public int getLeftIndex() {
return leftIndex;
}
public Object getRightEntity() {
return rightEntity;
}
public int getRightIndex() {
return rightIndex;
}
public Object getLeftValue() {
return variableDescriptor.getElement(leftEntity, leftIndex);
}
public Object getRightValue() {
return variableDescriptor.getElement(rightEntity, rightIndex);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
// TODO maybe do not generate such moves
// Do not use Object#equals on user-provided domain objects. Relying on user's implementation of Object#equals
// opens the opportunity to shoot themselves in the foot if different entities can be equal.
return !(rightEntity == leftEntity && leftIndex == rightIndex);
}
@Override
public ListSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new ListSwapMove<>(variableDescriptor, rightEntity, rightIndex, leftEntity, leftIndex);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public ListSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ListSwapMove<>(
variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(leftEntity), leftIndex,
destinationScoreDirector.lookUpWorkingObject(rightEntity), rightIndex);
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<Object> getPlanningEntities() {
// Use LinkedHashSet for predictable iteration order.
Set<Object> entities = new LinkedHashSet<>(2);
entities.add(leftEntity);
entities.add(rightEntity);
return entities;
}
@Override
public Collection<Object> getPlanningValues() {
return Arrays.asList(getLeftValue(), getRightValue());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListSwapMove<?> other = (ListSwapMove<?>) o;
return leftIndex == other.leftIndex && rightIndex == other.rightIndex
&& Objects.equals(variableDescriptor, other.variableDescriptor)
&& Objects.equals(leftEntity, other.leftEntity)
&& Objects.equals(rightEntity, other.rightEntity);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, leftEntity, leftIndex, rightEntity, rightIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d]} <-> %s {%s[%d]}",
getLeftValue(), leftEntity, leftIndex,
getRightValue(), rightEntity, rightIndex);
}
}
|
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
Object leftElement = variableDescriptor.getElement(leftEntity, leftIndex);
Object rightElement = variableDescriptor.getElement(rightEntity, rightIndex);
if (leftEntity == rightEntity) {
int fromIndex = Math.min(leftIndex, rightIndex);
int toIndex = Math.max(leftIndex, rightIndex) + 1;
innerScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex);
variableDescriptor.setElement(leftEntity, leftIndex, rightElement);
variableDescriptor.setElement(rightEntity, rightIndex, leftElement);
innerScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex);
} else {
innerScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, leftIndex, leftIndex + 1);
innerScoreDirector.beforeListVariableChanged(variableDescriptor, rightEntity, rightIndex, rightIndex + 1);
variableDescriptor.setElement(leftEntity, leftIndex, rightElement);
variableDescriptor.setElement(rightEntity, rightIndex, leftElement);
innerScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, leftIndex, leftIndex + 1);
innerScoreDirector.afterListVariableChanged(variableDescriptor, rightEntity, rightIndex, rightIndex + 1);
}
| 1,475
| 346
| 1,821
|
<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/heuristic/selector/move/generic/list/ListSwapMoveSelector.java
|
ListSwapMoveSelector
|
solvingStarted
|
class ListSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
private final EntityIndependentValueSelector<Solution_> leftValueSelector;
private final EntityIndependentValueSelector<Solution_> rightValueSelector;
private final boolean randomSelection;
private SingletonInverseVariableSupply inverseVariableSupply;
private IndexVariableSupply indexVariableSupply;
public ListSwapMoveSelector(
EntityIndependentValueSelector<Solution_> leftValueSelector,
EntityIndependentValueSelector<Solution_> rightValueSelector,
boolean randomSelection) {
// TODO require not same
this.leftValueSelector = leftValueSelector;
this.rightValueSelector = rightValueSelector;
this.randomSelection = randomSelection;
phaseLifecycleSupport.addEventListener(leftValueSelector);
if (leftValueSelector != rightValueSelector) {
phaseLifecycleSupport.addEventListener(rightValueSelector);
}
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {<FILL_FUNCTION_BODY>}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
inverseVariableSupply = null;
indexVariableSupply = null;
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (randomSelection) {
return new RandomListSwapIterator<>(
inverseVariableSupply,
indexVariableSupply,
leftValueSelector,
rightValueSelector);
} else {
return new OriginalListSwapIterator<>(
inverseVariableSupply,
indexVariableSupply,
leftValueSelector,
rightValueSelector);
}
}
@Override
public boolean isCountable() {
return leftValueSelector.isCountable() && rightValueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || leftValueSelector.isNeverEnding() || rightValueSelector.isNeverEnding();
}
@Override
public long getSize() {
return leftValueSelector.getSize() * rightValueSelector.getSize();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + leftValueSelector + ", " + rightValueSelector + ")";
}
}
|
super.solvingStarted(solverScope);
ListVariableDescriptor<Solution_> listVariableDescriptor =
(ListVariableDescriptor<Solution_>) leftValueSelector.getVariableDescriptor();
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
inverseVariableSupply = supplyManager.demand(new SingletonListInverseVariableDemand<>(listVariableDescriptor));
indexVariableSupply = supplyManager.demand(new IndexVariableDemand<>(listVariableDescriptor));
| 611
| 124
| 735
|
<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/heuristic/selector/move/generic/list/ListSwapMoveSelectorFactory.java
|
ListSwapMoveSelectorFactory
|
buildUnfoldedMoveSelectorConfig
|
class ListSwapMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, ListSwapMoveSelectorConfig> {
public ListSwapMoveSelectorFactory(ListSwapMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
ValueSelectorConfig valueSelectorConfig =
Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
ValueSelectorConfig secondaryValueSelectorConfig =
Objects.requireNonNullElse(config.getSecondaryValueSelectorConfig(), valueSelectorConfig);
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
EntityDescriptor<Solution_> entityDescriptor = getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
EntityIndependentValueSelector<Solution_> leftValueSelector = buildEntityIndependentValueSelector(configPolicy,
entityDescriptor, valueSelectorConfig, minimumCacheType, selectionOrder);
EntityIndependentValueSelector<Solution_> rightValueSelector = buildEntityIndependentValueSelector(configPolicy,
entityDescriptor, secondaryValueSelectorConfig, minimumCacheType, selectionOrder);
GenuineVariableDescriptor<Solution_> variableDescriptor = leftValueSelector.getVariableDescriptor();
// This may be redundant but emphasizes that the ListSwapMove is not designed to swap elements
// on multiple list variables, unlike the SwapMove, which swaps all (basic) variables between left and right entities.
if (variableDescriptor != rightValueSelector.getVariableDescriptor()) {
throw new IllegalStateException("Impossible state: the leftValueSelector (" + leftValueSelector
+ ") and the rightValueSelector (" + rightValueSelector
+ ") have different variable descriptors. This should have failed fast during config unfolding.");
}
return new ListSwapMoveSelector<>(
leftValueSelector,
rightValueSelector,
randomSelection);
}
private EntityIndependentValueSelector<Solution_> buildEntityIndependentValueSelector(
HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor,
ValueSelectorConfig valueSelectorConfig,
SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder) {
ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder);
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The listSwapMoveSelector (" + config
+ ") for a list variable needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your valueSelectorConfig.");
}
return (EntityIndependentValueSelector<Solution_>) valueSelector;
}
@Override
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {<FILL_FUNCTION_BODY>}
protected MoveSelectorConfig<?>
buildUnfoldedMoveSelectorConfig(List<ListVariableDescriptor<Solution_>> variableDescriptorList) {
List<MoveSelectorConfig> moveSelectorConfigList = new ArrayList<>(variableDescriptorList.size());
for (ListVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
// No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded()
ListSwapMoveSelectorConfig childMoveSelectorConfig = new ListSwapMoveSelectorConfig();
ValueSelectorConfig childValueSelectorConfig = new ValueSelectorConfig(config.getValueSelectorConfig());
if (childValueSelectorConfig.getMimicSelectorRef() == null) {
childValueSelectorConfig.setVariableName(variableDescriptor.getVariableName());
}
childMoveSelectorConfig.setValueSelectorConfig(childValueSelectorConfig);
if (config.getSecondaryValueSelectorConfig() != null) {
ValueSelectorConfig childSecondaryValueSelectorConfig =
new ValueSelectorConfig(config.getSecondaryValueSelectorConfig());
if (childSecondaryValueSelectorConfig.getMimicSelectorRef() == null) {
childSecondaryValueSelectorConfig.setVariableName(variableDescriptor.getVariableName());
}
childMoveSelectorConfig.setSecondaryValueSelectorConfig(childSecondaryValueSelectorConfig);
}
moveSelectorConfigList.add(childMoveSelectorConfig);
}
MoveSelectorConfig<?> unfoldedMoveSelectorConfig;
if (moveSelectorConfigList.size() == 1) {
unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0);
} else {
unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList);
}
unfoldedMoveSelectorConfig.inheritFolded(config);
return unfoldedMoveSelectorConfig;
}
}
|
EntityDescriptor<Solution_> entityDescriptor = getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
GenuineVariableDescriptor<Solution_> onlyVariableDescriptor = config.getValueSelectorConfig() == null ? null
: ValueSelectorFactory.<Solution_> create(config.getValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
if (config.getSecondaryValueSelectorConfig() != null) {
GenuineVariableDescriptor<Solution_> onlySecondaryVariableDescriptor =
ValueSelectorFactory.<Solution_> create(config.getSecondaryValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
if (onlyVariableDescriptor != onlySecondaryVariableDescriptor) {
throw new IllegalArgumentException("The valueSelector (" + config.getValueSelectorConfig()
+ ")'s variableName ("
+ (onlyVariableDescriptor == null ? null : onlyVariableDescriptor.getVariableName())
+ ") and secondaryValueSelectorConfig (" + config.getSecondaryValueSelectorConfig()
+ ")'s variableName ("
+ (onlySecondaryVariableDescriptor == null ? null : onlySecondaryVariableDescriptor.getVariableName())
+ ") must be the same planning list variable.");
}
}
if (onlyVariableDescriptor != null) {
if (!onlyVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The listSwapMoveSelector (" + config
+ ") is configured to use a planning variable (" + onlyVariableDescriptor
+ "), which is not a planning list variable."
+ " Either fix your annotations and use a @" + PlanningListVariable.class.getSimpleName()
+ " on the variable to make it work with listSwapMoveSelector"
+ " or use a swapMoveSelector instead.");
}
// No need for unfolding or deducing
return null;
}
List<ListVariableDescriptor<Solution_>> variableDescriptorList =
entityDescriptor.getGenuineVariableDescriptorList().stream()
.filter(GenuineVariableDescriptor::isListVariable)
.map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor))
.collect(Collectors.toList());
if (variableDescriptorList.isEmpty()) {
throw new IllegalArgumentException("The listSwapMoveSelector (" + config
+ ") cannot unfold because there are no planning list variables for the only entity (" + entityDescriptor
+ ") or no planning list variables at all.");
}
return buildUnfoldedMoveSelectorConfig(variableDescriptorList);
| 1,223
| 602
| 1,825
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/ListUnassignMove.java
|
ListUnassignMove
|
doMoveOnGenuineVariables
|
class ListUnassignMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object sourceEntity;
private final int sourceIndex;
public ListUnassignMove(
ListVariableDescriptor<Solution_> variableDescriptor,
Object sourceEntity, int sourceIndex) {
this.variableDescriptor = variableDescriptor;
this.sourceEntity = sourceEntity;
this.sourceIndex = sourceIndex;
}
private Object getMovedValue() {
return variableDescriptor.getElement(sourceEntity, sourceIndex);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
@Override
public AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
// The unassign move only serves as an undo move of the assign move. It is never being undone.
throw new UnsupportedOperationException("Undoing an unassign move is unsupported.");
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListUnassignMove<?> other = (ListUnassignMove<?>) o;
return sourceIndex == other.sourceIndex
&& Objects.equals(variableDescriptor, other.variableDescriptor)
&& Objects.equals(sourceEntity, other.sourceEntity);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, sourceEntity, sourceIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d] -> null}",
getMovedValue(), sourceEntity, sourceIndex);
}
}
|
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
List<Object> listVariable = variableDescriptor.getListVariable(sourceEntity);
Object element = listVariable.get(sourceIndex);
// Remove an element from sourceEntity's list variable (at sourceIndex).
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + 1);
innerScoreDirector.beforeListVariableElementUnassigned(variableDescriptor, element);
listVariable.remove(sourceIndex);
innerScoreDirector.afterListVariableElementUnassigned(variableDescriptor, element);
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex);
| 606
| 187
| 793
|
<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/heuristic/selector/move/generic/list/OriginalListChangeIterator.java
|
OriginalListChangeIterator
|
createUpcomingSelection
|
class OriginalListChangeIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final SingletonInverseVariableSupply inverseVariableSupply;
private final IndexVariableSupply indexVariableSupply;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final Iterator<Object> valueIterator;
private final DestinationSelector<Solution_> destinationSelector;
private Iterator<ElementRef> destinationIterator;
private Object upcomingSourceEntity;
private Integer upcomingSourceIndex;
private Object upcomingValue;
public OriginalListChangeIterator(
SingletonInverseVariableSupply inverseVariableSupply,
IndexVariableSupply indexVariableSupply,
EntityIndependentValueSelector<Solution_> valueSelector,
DestinationSelector<Solution_> destinationSelector) {
this.inverseVariableSupply = inverseVariableSupply;
this.indexVariableSupply = indexVariableSupply;
this.listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor();
this.valueIterator = valueSelector.iterator();
this.destinationSelector = destinationSelector;
this.destinationIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
while (!destinationIterator.hasNext()) {
if (!valueIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingValue = valueIterator.next();
upcomingSourceEntity = inverseVariableSupply.getInverseSingleton(upcomingValue);
upcomingSourceIndex = indexVariableSupply.getIndex(upcomingValue);
destinationIterator = destinationSelector.iterator();
}
ElementRef destination = destinationIterator.next();
if (upcomingSourceEntity == null && upcomingSourceIndex == null) {
return new ListAssignMove<>(
listVariableDescriptor,
upcomingValue,
destination.getEntity(),
destination.getIndex());
}
// No need to generate ListUnassignMove because they are only used as undo moves.
return new ListChangeMove<>(
listVariableDescriptor,
upcomingSourceEntity,
upcomingSourceIndex,
destination.getEntity(),
destination.getIndex());
| 325
| 233
| 558
|
<methods>public non-sealed void <init>() ,public boolean hasNext() ,public Move<Solution_> next() ,public java.lang.String toString() <variables>protected boolean hasUpcomingSelection,protected boolean upcomingCreated,protected Move<Solution_> upcomingSelection
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/RandomListChangeIterator.java
|
RandomListChangeIterator
|
createUpcomingSelection
|
class RandomListChangeIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final SingletonInverseVariableSupply inverseVariableSupply;
private final IndexVariableSupply indexVariableSupply;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final Iterator<Object> valueIterator;
private final Iterator<ElementRef> destinationIterator;
public RandomListChangeIterator(
SingletonInverseVariableSupply inverseVariableSupply,
IndexVariableSupply indexVariableSupply,
EntityIndependentValueSelector<Solution_> valueSelector,
DestinationSelector<Solution_> destinationSelector) {
this.inverseVariableSupply = inverseVariableSupply;
this.indexVariableSupply = indexVariableSupply;
this.listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor();
this.valueIterator = valueSelector.iterator();
this.destinationIterator = destinationSelector.iterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
if (!valueIterator.hasNext() || !destinationIterator.hasNext()) {
return noUpcomingSelection();
}
Object upcomingValue = valueIterator.next();
ElementRef destination = destinationIterator.next();
return new ListChangeMove<>(
listVariableDescriptor,
inverseVariableSupply.getInverseSingleton(upcomingValue),
indexVariableSupply.getIndex(upcomingValue),
destination.getEntity(),
destination.getIndex());
| 275
| 118
| 393
|
<methods>public non-sealed void <init>() ,public boolean hasNext() ,public Move<Solution_> next() ,public java.lang.String toString() <variables>protected boolean hasUpcomingSelection,protected boolean upcomingCreated,protected Move<Solution_> upcomingSelection
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/RandomSubListChangeMoveIterator.java
|
RandomSubListChangeMoveIterator
|
createUpcomingSelection
|
class RandomSubListChangeMoveIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final Iterator<SubList> subListIterator;
private final Iterator<ElementRef> destinationIterator;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final Random workingRandom;
private final boolean selectReversingMoveToo;
RandomSubListChangeMoveIterator(
SubListSelector<Solution_> subListSelector,
DestinationSelector<Solution_> destinationSelector,
Random workingRandom,
boolean selectReversingMoveToo) {
this.subListIterator = subListSelector.iterator();
this.destinationIterator = destinationSelector.iterator();
this.listVariableDescriptor = subListSelector.getVariableDescriptor();
this.workingRandom = workingRandom;
this.selectReversingMoveToo = selectReversingMoveToo;
}
@Override
protected Move<Solution_> createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
if (!subListIterator.hasNext() || !destinationIterator.hasNext()) {
return noUpcomingSelection();
}
SubList subList = subListIterator.next();
ElementRef destination = destinationIterator.next();
boolean reversing = selectReversingMoveToo && workingRandom.nextBoolean();
return new SubListChangeMove<>(
listVariableDescriptor,
subList,
destination.getEntity(),
destination.getIndex(),
reversing);
| 256
| 121
| 377
|
<methods>public non-sealed void <init>() ,public boolean hasNext() ,public Move<Solution_> next() ,public java.lang.String toString() <variables>protected boolean hasUpcomingSelection,protected boolean upcomingCreated,protected Move<Solution_> upcomingSelection
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/RandomSubListChangeMoveSelector.java
|
RandomSubListChangeMoveSelector
|
toString
|
class RandomSubListChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
private final SubListSelector<Solution_> subListSelector;
private final DestinationSelector<Solution_> destinationSelector;
private final boolean selectReversingMoveToo;
public RandomSubListChangeMoveSelector(
SubListSelector<Solution_> subListSelector,
DestinationSelector<Solution_> destinationSelector,
boolean selectReversingMoveToo) {
this.subListSelector = subListSelector;
this.destinationSelector = destinationSelector;
this.selectReversingMoveToo = selectReversingMoveToo;
phaseLifecycleSupport.addEventListener(subListSelector);
phaseLifecycleSupport.addEventListener(destinationSelector);
}
@Override
public Iterator<Move<Solution_>> iterator() {
return new RandomSubListChangeMoveIterator<>(
subListSelector,
destinationSelector,
workingRandom,
selectReversingMoveToo);
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return true;
}
@Override
public long getSize() {
long subListCount = subListSelector.getSize();
long destinationCount = destinationSelector.getSize();
return subListCount * destinationCount * (selectReversingMoveToo ? 2 : 1);
}
boolean isSelectReversingMoveToo() {
return selectReversingMoveToo;
}
SubListSelector<Solution_> getSubListSelector() {
return subListSelector;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + "(" + subListSelector + ", " + destinationSelector + ")";
| 452
| 29
| 481
|
<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/heuristic/selector/move/generic/list/RandomSubListSwapMoveSelector.java
|
RandomSubListSwapMoveSelector
|
iterator
|
class RandomSubListSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
private final SubListSelector<Solution_> leftSubListSelector;
private final SubListSelector<Solution_> rightSubListSelector;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final boolean selectReversingMoveToo;
public RandomSubListSwapMoveSelector(
SubListSelector<Solution_> leftSubListSelector,
SubListSelector<Solution_> rightSubListSelector,
boolean selectReversingMoveToo) {
this.leftSubListSelector = leftSubListSelector;
this.rightSubListSelector = rightSubListSelector;
this.listVariableDescriptor = leftSubListSelector.getVariableDescriptor();
if (leftSubListSelector.getVariableDescriptor() != rightSubListSelector.getVariableDescriptor()) {
throw new IllegalStateException("The selector (" + this
+ ") has a leftSubListSelector's variableDescriptor ("
+ leftSubListSelector.getVariableDescriptor()
+ ") which is not equal to the rightSubListSelector's variableDescriptor ("
+ rightSubListSelector.getVariableDescriptor() + ").");
}
this.selectReversingMoveToo = selectReversingMoveToo;
phaseLifecycleSupport.addEventListener(leftSubListSelector);
phaseLifecycleSupport.addEventListener(rightSubListSelector);
}
@Override
public Iterator<Move<Solution_>> iterator() {<FILL_FUNCTION_BODY>}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return true;
}
@Override
public long getSize() {
long leftSubListCount = leftSubListSelector.getSize();
long rightSubListCount = rightSubListSelector.getSize();
return leftSubListCount * rightSubListCount * (selectReversingMoveToo ? 2 : 1);
}
boolean isSelectReversingMoveToo() {
return selectReversingMoveToo;
}
SubListSelector<Solution_> getLeftSubListSelector() {
return leftSubListSelector;
}
SubListSelector<Solution_> getRightSubListSelector() {
return rightSubListSelector;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + leftSubListSelector + ", " + rightSubListSelector + ")";
}
}
|
return new AbstractRandomSwapIterator<>(leftSubListSelector, rightSubListSelector) {
@Override
protected Move<Solution_> newSwapSelection(SubList leftSubSelection, SubList rightSubSelection) {
boolean reversing = selectReversingMoveToo && workingRandom.nextBoolean();
return new SubListSwapMove<>(listVariableDescriptor, leftSubSelection, rightSubSelection, reversing);
}
};
| 634
| 108
| 742
|
<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/heuristic/selector/move/generic/list/SubListChangeMoveSelectorFactory.java
|
SubListChangeMoveSelectorFactory
|
buildUnfoldedMoveSelectorConfig
|
class SubListChangeMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, SubListChangeMoveSelectorConfig> {
public SubListChangeMoveSelectorFactory(SubListChangeMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
checkUnfolded("subListSelectorConfig", config.getSubListSelectorConfig());
checkUnfolded("destinationSelectorConfig", config.getDestinationSelectorConfig());
if (!randomSelection) {
throw new IllegalArgumentException("The subListChangeMoveSelector (" + config
+ ") only supports random selection order.");
}
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
EntitySelector<Solution_> entitySelector = EntitySelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig().getEntitySelectorConfig())
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
SubListSelector<Solution_> subListSelector = SubListSelectorFactory
.<Solution_> create(config.getSubListSelectorConfig())
.buildSubListSelector(configPolicy, entitySelector, minimumCacheType, selectionOrder);
DestinationSelector<Solution_> destinationSelector = DestinationSelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig())
.buildDestinationSelector(configPolicy, minimumCacheType, randomSelection);
boolean selectReversingMoveToo = Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true);
return new RandomSubListChangeMoveSelector<>(subListSelector, destinationSelector, selectReversingMoveToo);
}
@Override
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {<FILL_FUNCTION_BODY>}
private SubListChangeMoveSelectorConfig buildChildMoveSelectorConfig(ListVariableDescriptor<?> variableDescriptor) {
SubListChangeMoveSelectorConfig subListChangeMoveSelectorConfig = config.copyConfig()
.withSubListSelectorConfig(new SubListSelectorConfig(config.getSubListSelectorConfig())
.withValueSelectorConfig(Optional.ofNullable(config.getSubListSelectorConfig())
.map(SubListSelectorConfig::getValueSelectorConfig)
.map(ValueSelectorConfig::new) // use copy constructor if inherited not null
.orElseGet(ValueSelectorConfig::new)))
.withDestinationSelectorConfig(new DestinationSelectorConfig(config.getDestinationSelectorConfig())
.withEntitySelectorConfig(
Optional.ofNullable(config.getDestinationSelectorConfig())
.map(DestinationSelectorConfig::getEntitySelectorConfig)
.map(EntitySelectorConfig::new) // use copy constructor if inherited not null
.orElseGet(EntitySelectorConfig::new) // otherwise create new instance
// override entity class (destination entity selector is never replaying)
.withEntityClass(variableDescriptor.getEntityDescriptor().getEntityClass()))
.withValueSelectorConfig(
Optional.ofNullable(config.getDestinationSelectorConfig())
.map(DestinationSelectorConfig::getValueSelectorConfig)
.map(ValueSelectorConfig::new) // use copy constructor if inherited not null
.orElseGet(ValueSelectorConfig::new) // otherwise create new instance
// override variable name (destination value selector is never replaying)
.withVariableName(variableDescriptor.getVariableName())));
SubListSelectorConfig subListSelectorConfig = subListChangeMoveSelectorConfig.getSubListSelectorConfig();
SubListConfigUtil.transferDeprecatedMinimumSubListSize(
subListChangeMoveSelectorConfig,
SubListChangeMoveSelectorConfig::getMinimumSubListSize,
"subListSelector",
subListSelectorConfig);
SubListConfigUtil.transferDeprecatedMaximumSubListSize(
subListChangeMoveSelectorConfig,
SubListChangeMoveSelectorConfig::getMaximumSubListSize,
"subListSelector",
subListSelectorConfig);
if (subListSelectorConfig.getMimicSelectorRef() == null) {
subListSelectorConfig.getValueSelectorConfig().setVariableName(variableDescriptor.getVariableName());
}
return subListChangeMoveSelectorConfig;
}
}
|
Collection<EntityDescriptor<Solution_>> entityDescriptors;
EntityDescriptor<Solution_> onlyEntityDescriptor = config.getDestinationSelectorConfig() == null ? null
: config.getDestinationSelectorConfig().getEntitySelectorConfig() == null ? null
: EntitySelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig().getEntitySelectorConfig())
.extractEntityDescriptor(configPolicy);
if (onlyEntityDescriptor != null) {
entityDescriptors = Collections.singletonList(onlyEntityDescriptor);
} else {
entityDescriptors = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors();
}
if (entityDescriptors.size() > 1) {
throw new IllegalArgumentException("The subListChangeMoveSelector (" + config
+ ") cannot unfold when there are multiple entities (" + entityDescriptors + ")."
+ " Please use one subListChangeMoveSelector per each planning list variable.");
}
EntityDescriptor<Solution_> entityDescriptor = entityDescriptors.iterator().next();
List<ListVariableDescriptor<Solution_>> variableDescriptorList = new ArrayList<>();
GenuineVariableDescriptor<Solution_> onlySubListVariableDescriptor =
config.getSubListSelectorConfig() == null ? null
: config.getSubListSelectorConfig().getValueSelectorConfig() == null ? null
: ValueSelectorFactory
.<Solution_> create(config.getSubListSelectorConfig().getValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
GenuineVariableDescriptor<Solution_> onlyDestinationVariableDescriptor =
config.getDestinationSelectorConfig() == null ? null
: config.getDestinationSelectorConfig().getValueSelectorConfig() == null ? null
: ValueSelectorFactory
.<Solution_> create(config.getDestinationSelectorConfig().getValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
if (onlySubListVariableDescriptor != null && onlyDestinationVariableDescriptor != null) {
if (!onlySubListVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The subListChangeMoveSelector (" + config
+ ") is configured to use a planning variable (" + onlySubListVariableDescriptor
+ "), which is not a planning list variable.");
}
if (!onlyDestinationVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The subListChangeMoveSelector (" + config
+ ") is configured to use a planning variable (" + onlyDestinationVariableDescriptor
+ "), which is not a planning list variable.");
}
if (onlySubListVariableDescriptor != onlyDestinationVariableDescriptor) {
throw new IllegalArgumentException("The subListSelector's valueSelector ("
+ config.getSubListSelectorConfig().getValueSelectorConfig()
+ ") and destinationSelector's valueSelector ("
+ config.getDestinationSelectorConfig().getValueSelectorConfig()
+ ") must be configured for the same planning variable.");
}
if (onlyEntityDescriptor != null) {
// No need for unfolding or deducing
return null;
}
variableDescriptorList.add((ListVariableDescriptor<Solution_>) onlySubListVariableDescriptor);
} else {
variableDescriptorList.addAll(
entityDescriptor.getGenuineVariableDescriptorList().stream()
.filter(GenuineVariableDescriptor::isListVariable)
.map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor))
.collect(Collectors.toList()));
}
if (variableDescriptorList.isEmpty()) {
throw new IllegalArgumentException("The subListChangeMoveSelector (" + config
+ ") cannot unfold because there are no planning list variables.");
}
if (variableDescriptorList.size() > 1) {
throw new IllegalArgumentException("The subListChangeMoveSelector (" + config
+ ") cannot unfold because there are multiple planning list variables.");
}
return buildChildMoveSelectorConfig(variableDescriptorList.get(0));
| 1,071
| 962
| 2,033
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/kopt/EntityOrderInfo.java
|
EntityOrderInfo
|
withNewNode
|
class EntityOrderInfo {
final Object[] entities;
final int[] offsets;
final Map<Object, Integer> entityToEntityIndex;
public <Node_> EntityOrderInfo(Node_[] pickedValues, SingletonInverseVariableSupply inverseVariableSupply,
ListVariableDescriptor<?> listVariableDescriptor) {
entityToEntityIndex = new IdentityHashMap<>();
for (int i = 1; i < pickedValues.length && pickedValues[i] != null; i++) {
entityToEntityIndex.computeIfAbsent(inverseVariableSupply.getInverseSingleton(pickedValues[i]),
entity -> entityToEntityIndex.size());
}
entities = new Object[entityToEntityIndex.size()];
offsets = new int[entities.length];
for (Map.Entry<Object, Integer> entry : entityToEntityIndex.entrySet()) {
entities[entry.getValue()] = entry.getKey();
}
for (int i = 1; i < offsets.length; i++) {
offsets[i] = offsets[i - 1] + listVariableDescriptor.getListSize(entities[i - 1]);
}
}
public EntityOrderInfo(Object[] entities, Map<Object, Integer> entityToEntityIndex, int[] offsets) {
this.entities = entities;
this.entityToEntityIndex = entityToEntityIndex;
this.offsets = offsets;
}
public <Node_> EntityOrderInfo withNewNode(Node_ node, ListVariableDescriptor<?> listVariableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
public <Node_> Node_ successor(Node_ object, ListVariableDescriptor<?> listVariableDescriptor,
IndexVariableSupply indexVariableSupply, SingletonInverseVariableSupply inverseVariableSupply) {
Object entity = inverseVariableSupply.getInverseSingleton(object);
int indexInEntityList = indexVariableSupply.getIndex(object);
List<Object> listVariable = listVariableDescriptor.getListVariable(entity);
if (indexInEntityList == listVariable.size() - 1) {
int nextEntityIndex = (entityToEntityIndex.get(entity) + 1) % entities.length;
return (Node_) listVariableDescriptor.getListVariable(entities[nextEntityIndex]).get(0);
} else {
return (Node_) listVariable.get(indexInEntityList + 1);
}
}
@SuppressWarnings("unchecked")
public <Node_> Node_ predecessor(Node_ object, ListVariableDescriptor<?> listVariableDescriptor,
IndexVariableSupply indexVariableSupply, SingletonInverseVariableSupply inverseVariableSupply) {
Object entity = inverseVariableSupply.getInverseSingleton(object);
int indexInEntityList = indexVariableSupply.getIndex(object);
List<Object> listVariable = listVariableDescriptor.getListVariable(entity);
if (indexInEntityList == 0) {
// add entities.length to ensure modulo result is positive
int previousEntityIndex = (entityToEntityIndex.get(entity) - 1 + entities.length) % entities.length;
listVariable = listVariableDescriptor.getListVariable(entities[previousEntityIndex]);
return (Node_) listVariable.get(listVariable.size() - 1);
} else {
return (Node_) listVariable.get(indexInEntityList - 1);
}
}
public <Node_> boolean between(Node_ start, Node_ middle, Node_ end, IndexVariableSupply indexVariableSupply,
SingletonInverseVariableSupply inverseVariableSupply) {
int startEntityIndex = entityToEntityIndex.get(inverseVariableSupply.getInverseSingleton(start));
int middleEntityIndex = entityToEntityIndex.get(inverseVariableSupply.getInverseSingleton(middle));
int endEntityIndex = entityToEntityIndex.get(inverseVariableSupply.getInverseSingleton(end));
int startIndex = indexVariableSupply.getIndex(start) + offsets[startEntityIndex];
int middleIndex = indexVariableSupply.getIndex(middle) + offsets[middleEntityIndex];
int endIndex = indexVariableSupply.getIndex(end) + offsets[endEntityIndex];
if (startIndex <= endIndex) {
// test middleIndex in [startIndex, endIndex]
return startIndex <= middleIndex && middleIndex <= endIndex;
} else {
// test middleIndex in [0, endIndex] or middleIndex in [startIndex, listSize)
return middleIndex >= startIndex || middleIndex <= endIndex;
}
}
}
|
Object entity = inverseVariableSupply.getInverseSingleton(node);
if (entityToEntityIndex.containsKey(entity)) {
return this;
} else {
Object[] newEntities = Arrays.copyOf(entities, entities.length + 1);
Map<Object, Integer> newEntityToEntityIndex = new IdentityHashMap<>(entityToEntityIndex);
int[] newOffsets = Arrays.copyOf(offsets, offsets.length + 1);
newEntities[entities.length] = entity;
newEntityToEntityIndex.put(entity, entities.length);
newOffsets[entities.length] =
offsets[entities.length - 1] + listVariableDescriptor.getListSize(entities[entities.length - 1]);
return new EntityOrderInfo(newEntities, newEntityToEntityIndex, newOffsets);
}
| 1,177
| 221
| 1,398
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/kopt/KOptCycle.java
|
KOptCycle
|
toString
|
class KOptCycle {
/**
* The total number of k-cycles in the permutation. This is one more than the
* maximal value in {@link KOptCycle#indexToCycleIdentifier}.
*/
public final int cycleCount;
/**
* Maps an index in the removed endpoints to the cycle it belongs to
* after the new edges are added. Ranges from 0 to {@link #cycleCount} - 1.
*/
public final int[] indexToCycleIdentifier;
public KOptCycle(int cycleCount, int[] indexToCycleIdentifier) {
this.cycleCount = cycleCount;
this.indexToCycleIdentifier = indexToCycleIdentifier;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String arrayString = IntStream.of(indexToCycleIdentifier)
.sequential()
.skip(1)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", ", "[", "]"));
return "KOptCycleInfo(" +
"cycleCount=" + cycleCount +
", indexToCycleIdentifier=" + arrayString +
')';
| 204
| 103
| 307
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveSelector.java
|
KOptListMoveSelector
|
getSize
|
class KOptListMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final EntityIndependentValueSelector<Solution_> originSelector;
private final EntityIndependentValueSelector<Solution_> valueSelector;
private final int minK;
private final int maxK;
private final int[] pickedKDistribution;
private SingletonInverseVariableSupply inverseVariableSupply;
private IndexVariableSupply indexVariableSupply;
public KOptListMoveSelector(
ListVariableDescriptor<Solution_> listVariableDescriptor,
EntityIndependentValueSelector<Solution_> originSelector,
EntityIndependentValueSelector<Solution_> valueSelector,
int minK,
int maxK,
int[] pickedKDistribution) {
this.listVariableDescriptor = listVariableDescriptor;
this.originSelector = originSelector;
this.valueSelector = valueSelector;
this.minK = minK;
this.maxK = maxK;
this.pickedKDistribution = pickedKDistribution;
phaseLifecycleSupport.addEventListener(originSelector);
phaseLifecycleSupport.addEventListener(valueSelector);
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
inverseVariableSupply = supplyManager.demand(new SingletonListInverseVariableDemand<>(listVariableDescriptor));
indexVariableSupply = supplyManager.demand(new IndexVariableDemand<>(listVariableDescriptor));
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
inverseVariableSupply = null;
indexVariableSupply = null;
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Move<Solution_>> iterator() {
return new KOptListMoveIterator<>(workingRandom, listVariableDescriptor, inverseVariableSupply, indexVariableSupply,
originSelector, valueSelector, minK, maxK, pickedKDistribution);
}
@Override
public boolean isCountable() {
return false;
}
@Override
public boolean isNeverEnding() {
return true;
}
}
|
long total = 0;
long valueSelectorSize = valueSelector.getSize();
for (int i = minK; i < Math.min(valueSelectorSize, maxK); i++) {
if (valueSelectorSize > i) { // need more than k nodes in order to perform a k-opt
long kOptMoveTypes = KOptUtils.getPureKOptMoveTypes(i);
// A tour with n nodes have n - 1 edges
// And we chose k of them to remove in a k-opt
final long edgeChoices;
if (valueSelectorSize <= Integer.MAX_VALUE) {
edgeChoices = CombinatoricsUtils.binomialCoefficient((int) (valueSelectorSize - 1), i);
} else {
edgeChoices = Long.MAX_VALUE;
}
total += kOptMoveTypes * edgeChoices;
}
}
return total;
| 628
| 225
| 853
|
<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/heuristic/selector/move/generic/list/kopt/KOptListMoveSelectorFactory.java
|
KOptListMoveSelectorFactory
|
buildBaseMoveSelector
|
class KOptListMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, KOptListMoveSelectorConfig> {
private static final int DEFAULT_MINIMUM_K = 2;
private static final int DEFAULT_MAXIMUM_K = 2;
public KOptListMoveSelectorFactory(KOptListMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {<FILL_FUNCTION_BODY>}
private EntityIndependentValueSelector<Solution_> buildEntityIndependentValueSelector(
HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor,
ValueSelectorConfig valueSelectorConfig,
SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder) {
ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder);
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The kOptListMoveSelector (" + config
+ ") for a list variable needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your valueSelectorConfig.");
}
return (EntityIndependentValueSelector<Solution_>) valueSelector;
}
}
|
ValueSelectorConfig originSelectorConfig =
Objects.requireNonNullElseGet(config.getOriginSelectorConfig(), ValueSelectorConfig::new);
ValueSelectorConfig valueSelectorConfig =
Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
EntityDescriptor<Solution_> entityDescriptor = getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
EntityIndependentValueSelector<Solution_> originSelector =
buildEntityIndependentValueSelector(configPolicy, entityDescriptor, originSelectorConfig, minimumCacheType,
SelectionOrder.fromRandomSelectionBoolean(randomSelection));
EntityIndependentValueSelector<Solution_> valueSelector =
buildEntityIndependentValueSelector(configPolicy, entityDescriptor, valueSelectorConfig, minimumCacheType,
SelectionOrder.fromRandomSelectionBoolean(randomSelection));
// TODO support coexistence of list and basic variables https://issues.redhat.com/browse/PLANNER-2755
GenuineVariableDescriptor<Solution_> variableDescriptor = getTheOnlyVariableDescriptor(entityDescriptor);
if (!variableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The kOptListMoveSelector (" + config
+ ") can only be used when the domain model has a list variable."
+ " Check your @" + PlanningEntity.class.getSimpleName()
+ " and make sure it has a @" + PlanningListVariable.class.getSimpleName() + ".");
}
int minimumK = Objects.requireNonNullElse(config.getMinimumK(), DEFAULT_MINIMUM_K);
if (minimumK < 2) {
throw new IllegalArgumentException("minimumK (" + minimumK + ") must be at least 2.");
}
int maximumK = Objects.requireNonNullElse(config.getMaximumK(), DEFAULT_MAXIMUM_K);
if (maximumK < minimumK) {
throw new IllegalArgumentException("maximumK (" + maximumK + ") must be at least minimumK (" + minimumK + ").");
}
int[] pickedKDistribution = new int[maximumK - minimumK + 1];
// Each prior k is 8 times more likely to be picked than the subsequent k
int total = 1;
for (int i = minimumK; i < maximumK; i++) {
total *= 8;
}
for (int i = 0; i < pickedKDistribution.length - 1; i++) {
int remainder = total / 8;
pickedKDistribution[i] = total - remainder;
total = remainder;
}
pickedKDistribution[pickedKDistribution.length - 1] = total;
return new KOptListMoveSelector<>(((ListVariableDescriptor<Solution_>) variableDescriptor),
originSelector, valueSelector, minimumK, maximumK, pickedKDistribution);
| 395
| 692
| 1,087
|
<methods>public void <init>(org.optaplanner.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig) ,public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType, org.optaplanner.core.config.heuristic.selector.common.SelectionOrder) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/FromSolutionPropertyValueSelector.java
|
FromSolutionPropertyValueSelector
|
iterator
|
class FromSolutionPropertyValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
private final EntityIndependentValueRangeDescriptor<Solution_> valueRangeDescriptor;
private final SelectionCacheType minimumCacheType;
private final boolean randomSelection;
private final boolean valueRangeMightContainEntity;
private ValueRange<Object> cachedValueRange = null;
private Long cachedEntityListRevision = null;
private boolean cachedEntityListIsDirty = false;
public FromSolutionPropertyValueSelector(EntityIndependentValueRangeDescriptor<Solution_> valueRangeDescriptor,
SelectionCacheType minimumCacheType, boolean randomSelection) {
this.valueRangeDescriptor = valueRangeDescriptor;
this.minimumCacheType = minimumCacheType;
this.randomSelection = randomSelection;
valueRangeMightContainEntity = valueRangeDescriptor.mightContainEntity();
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return valueRangeDescriptor.getVariableDescriptor();
}
@Override
public SelectionCacheType getCacheType() {
SelectionCacheType intrinsicCacheType = valueRangeMightContainEntity
? SelectionCacheType.STEP
: SelectionCacheType.PHASE;
return (intrinsicCacheType.compareTo(minimumCacheType) > 0)
? intrinsicCacheType
: minimumCacheType;
}
// ************************************************************************
// Cache lifecycle methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector();
cachedValueRange = (ValueRange<Object>) valueRangeDescriptor.extractValueRange(scoreDirector.getWorkingSolution());
if (valueRangeMightContainEntity) {
cachedEntityListRevision = scoreDirector.getWorkingEntityListRevision();
cachedEntityListIsDirty = false;
}
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
if (valueRangeMightContainEntity) {
InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector();
if (scoreDirector.isWorkingEntityListDirty(cachedEntityListRevision)) {
if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) {
cachedEntityListIsDirty = true;
} else {
cachedValueRange = (ValueRange<Object>) valueRangeDescriptor
.extractValueRange(scoreDirector.getWorkingSolution());
cachedEntityListRevision = scoreDirector.getWorkingEntityListRevision();
}
}
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
cachedValueRange = null;
if (valueRangeMightContainEntity) {
cachedEntityListRevision = null;
cachedEntityListIsDirty = false;
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return valueRangeDescriptor.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || !isCountable();
}
@Override
public long getSize(Object entity) {
return getSize();
}
@Override
public long getSize() {
return ((CountableValueRange<?>) cachedValueRange).getSize();
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Object> endingIterator(Object entity) {
return endingIterator();
}
public Iterator<Object> endingIterator() {
return ((CountableValueRange<Object>) cachedValueRange).createOriginalIterator();
}
private void checkCachedEntityListIsDirty() {
if (cachedEntityListIsDirty) {
throw new IllegalStateException("The selector (" + this + ") with minimumCacheType (" + minimumCacheType
+ ")'s workingEntityList became dirty between steps but is still used afterwards.");
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
FromSolutionPropertyValueSelector<?> that = (FromSolutionPropertyValueSelector<?>) other;
return randomSelection == that.randomSelection &&
Objects.equals(valueRangeDescriptor, that.valueRangeDescriptor) && minimumCacheType == that.minimumCacheType;
}
@Override
public int hashCode() {
return Objects.hash(valueRangeDescriptor, minimumCacheType, randomSelection);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + getVariableDescriptor().getVariableName() + ")";
}
}
|
checkCachedEntityListIsDirty();
if (randomSelection) {
return cachedValueRange.createRandomIterator(workingRandom);
}
if (cachedValueRange instanceof CountableValueRange) {
return ((CountableValueRange<Object>) cachedValueRange).createOriginalIterator();
}
throw new IllegalStateException("Value range's class (" + cachedValueRange.getClass().getCanonicalName() + ") " +
"does not implement " + CountableValueRange.class + ", " +
"yet selectionOrder is not " + SelectionOrder.RANDOM + ".\n" +
"Maybe switch selectors' selectionOrder to " + SelectionOrder.RANDOM + "?\n" +
"Maybe switch selectors' cacheType to " + SelectionCacheType.JUST_IN_TIME + "?");
| 1,350
| 204
| 1,554
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/chained/SubChain.java
|
SubChain
|
equals
|
class SubChain {
private final List<Object> entityList;
public SubChain(List<Object> entityList) {
this.entityList = entityList;
}
public List<Object> getEntityList() {
return entityList;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public Object getFirstEntity() {
if (entityList.isEmpty()) {
return null;
}
return entityList.get(0);
}
public Object getLastEntity() {
if (entityList.isEmpty()) {
return null;
}
return entityList.get(entityList.size() - 1);
}
public int getSize() {
return entityList.size();
}
public SubChain reverse() {
return new SubChain(CollectionUtils.copy(entityList, true));
}
public SubChain subChain(int fromIndex, int toIndex) {
return new SubChain(entityList.subList(fromIndex, toIndex));
}
public SubChain rebase(ScoreDirector<?> destinationScoreDirector) {
return new SubChain(AbstractMove.rebaseList(entityList, destinationScoreDirector));
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return entityList.hashCode();
}
@Override
public String toString() {
return entityList.toString();
}
public String toDottedString() {
return "[" + getFirstEntity() + ".." + getLastEntity() + "]";
}
}
|
if (this == o) {
return true;
} else if (o instanceof SubChain) {
SubChain other = (SubChain) o;
return entityList.equals(other.entityList);
} else {
return false;
}
| 428
| 67
| 495
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/chained/SubChainSelectorFactory.java
|
SubChainSelectorFactory
|
buildSubChainSelector
|
class SubChainSelectorFactory<Solution_> {
/**
* Defaults to 1, even if it partially duplicates {@link ChangeMoveSelectorConfig},
* because otherwise the default would not include
* swapping a pillar of size 1 with another pillar of size 2 or greater.
*/
private static final int DEFAULT_MINIMUM_SUB_CHAIN_SIZE = 1;
private static final int DEFAULT_MAXIMUM_SUB_CHAIN_SIZE = Integer.MAX_VALUE;
public static <Solution_> SubChainSelectorFactory<Solution_> create(SubChainSelectorConfig subChainSelectorConfig) {
return new SubChainSelectorFactory<>(subChainSelectorConfig);
}
private final SubChainSelectorConfig config;
public SubChainSelectorFactory(SubChainSelectorConfig subChainSelectorConfig) {
this.config = subChainSelectorConfig;
}
/**
* @param configPolicy never null
* @param entityDescriptor never null
* @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}),
* then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching
* and less would be pointless.
* @param inheritedSelectionOrder never null
* @return never null
*/
public SubChainSelector<Solution_> buildSubChainSelector(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder) {<FILL_FUNCTION_BODY>}
}
|
if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) {
throw new IllegalArgumentException("The subChainSelectorConfig (" + config
+ ")'s minimumCacheType (" + minimumCacheType
+ ") must not be higher than " + SelectionCacheType.STEP
+ " because the chains change every step.");
}
ValueSelectorConfig valueSelectorConfig =
Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
// ValueSelector uses SelectionOrder.ORIGINAL because a SubChainSelector STEP caches the values
ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, SelectionOrder.ORIGINAL);
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The subChainSelectorConfig (" + config
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
return new DefaultSubChainSelector<>((EntityIndependentValueSelector<Solution_>) valueSelector,
inheritedSelectionOrder.toRandomSelectionBoolean(),
Objects.requireNonNullElse(config.getMinimumSubChainSize(), DEFAULT_MINIMUM_SUB_CHAIN_SIZE),
Objects.requireNonNullElse(config.getMaximumSubChainSize(), DEFAULT_MAXIMUM_SUB_CHAIN_SIZE));
| 400
| 392
| 792
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/EntityDependentSortingValueSelector.java
|
EntityDependentSortingValueSelector
|
iterator
|
class EntityDependentSortingValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ValueSelector<Solution_> {
private final ValueSelector<Solution_> childValueSelector;
private final SelectionCacheType cacheType;
private final SelectionSorter<Solution_, Object> sorter;
protected ScoreDirector<Solution_> scoreDirector = null;
public EntityDependentSortingValueSelector(ValueSelector<Solution_> childValueSelector,
SelectionCacheType cacheType, SelectionSorter<Solution_, Object> sorter) {
this.childValueSelector = childValueSelector;
this.cacheType = cacheType;
this.sorter = sorter;
if (childValueSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childValueSelector (" + childValueSelector
+ ") with neverEnding (" + childValueSelector.isNeverEnding() + ").");
}
if (cacheType != SelectionCacheType.STEP) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(childValueSelector);
}
public ValueSelector<Solution_> getChildValueSelector() {
return childValueSelector;
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
scoreDirector = phaseScope.getScoreDirector();
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
scoreDirector = null;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childValueSelector.getVariableDescriptor();
}
@Override
public long getSize(Object entity) {
return childValueSelector.getSize(entity);
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator(Object entity) {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Object> endingIterator(Object entity) {
return iterator(entity);
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
EntityDependentSortingValueSelector<?> that = (EntityDependentSortingValueSelector<?>) other;
return Objects.equals(childValueSelector, that.childValueSelector) && cacheType == that.cacheType
&& Objects.equals(sorter, that.sorter);
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector, cacheType, sorter);
}
@Override
public String toString() {
return "Sorting(" + childValueSelector + ")";
}
}
|
long childSize = childValueSelector.getSize(entity);
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The selector (" + this
+ ") has a childValueSelector (" + childValueSelector
+ ") with childSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
List<Object> cachedValueList = new ArrayList<>((int) childSize);
childValueSelector.iterator(entity).forEachRemaining(cachedValueList::add);
logger.trace(" Created cachedValueList: size ({}), valueSelector ({}).",
cachedValueList.size(), this);
sorter.sort(scoreDirector, cachedValueList);
logger.trace(" Sorted cachedValueList: size ({}), valueSelector ({}).",
cachedValueList.size(), this);
return cachedValueList.iterator();
| 860
| 217
| 1,077
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/EntityIndependentInitializedValueSelector.java
|
EntityIndependentInitializedValueSelector
|
determineBailOutSize
|
class EntityIndependentInitializedValueSelector<Solution_>
extends InitializedValueSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
public EntityIndependentInitializedValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector) {
super(childValueSelector);
}
@Override
public long getSize() {
return ((EntityIndependentValueSelector<Solution_>) childValueSelector).getSize();
}
@Override
public Iterator<Object> iterator() {
return new JustInTimeInitializedValueIterator(
((EntityIndependentValueSelector<Solution_>) childValueSelector).iterator(), determineBailOutSize());
}
protected long determineBailOutSize() {<FILL_FUNCTION_BODY>}
}
|
if (!bailOutEnabled) {
return -1L;
}
return ((EntityIndependentValueSelector<Solution_>) childValueSelector).getSize() * 10L;
| 204
| 51
| 255
|
<methods>public static ValueSelector<Solution_> create(ValueSelector<Solution_>) ,public Iterator<java.lang.Object> endingIterator(java.lang.Object) ,public boolean equals(java.lang.Object) ,public long getSize(java.lang.Object) ,public GenuineVariableDescriptor<Solution_> getVariableDescriptor() ,public int hashCode() ,public boolean isCountable() ,public boolean isNeverEnding() ,public Iterator<java.lang.Object> iterator(java.lang.Object) ,public java.lang.String toString() <variables>final non-sealed boolean bailOutEnabled,final non-sealed ValueSelector<Solution_> childValueSelector,private final non-sealed GenuineVariableDescriptor<Solution_> variableDescriptor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/FilteringValueSelector.java
|
JustInTimeFilteringValueIterator
|
createUpcomingSelection
|
class JustInTimeFilteringValueIterator extends UpcomingSelectionIterator<Object> {
private final Iterator<Object> childValueIterator;
private final long bailOutSize;
public JustInTimeFilteringValueIterator(Iterator<Object> childValueIterator, long bailOutSize) {
this.childValueIterator = childValueIterator;
this.bailOutSize = bailOutSize;
}
@Override
protected Object createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
Object next;
long attemptsBeforeBailOut = bailOutSize;
do {
if (!childValueIterator.hasNext()) {
return noUpcomingSelection();
}
if (bailOutEnabled) {
// if childValueIterator is neverEnding and nothing is accepted, bail out of the infinite loop
if (attemptsBeforeBailOut <= 0L) {
logger.warn("Bailing out of neverEnding selector ({}) to avoid infinite loop.",
FilteringValueSelector.this);
return noUpcomingSelection();
}
attemptsBeforeBailOut--;
}
next = childValueIterator.next();
} while (!selectionFilter.accept(scoreDirector, next));
return next;
| 129
| 183
| 312
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/InitializedValueSelector.java
|
JustInTimeInitializedValueIterator
|
createUpcomingSelection
|
class JustInTimeInitializedValueIterator extends UpcomingSelectionIterator<Object> {
private final Iterator<Object> childValueIterator;
private final long bailOutSize;
public JustInTimeInitializedValueIterator(Object entity, Iterator<Object> childValueIterator) {
this(childValueIterator, determineBailOutSize(entity));
}
public JustInTimeInitializedValueIterator(Iterator<Object> childValueIterator, long bailOutSize) {
this.childValueIterator = childValueIterator;
this.bailOutSize = bailOutSize;
}
@Override
protected Object createUpcomingSelection() {<FILL_FUNCTION_BODY>}
}
|
Object next;
long attemptsBeforeBailOut = bailOutSize;
do {
if (!childValueIterator.hasNext()) {
return noUpcomingSelection();
}
if (bailOutEnabled) {
// if childValueIterator is neverEnding and nothing is accepted, bail out of the infinite loop
if (attemptsBeforeBailOut <= 0L) {
logger.warn("Bailing out of neverEnding selector ({}) to avoid infinite loop.",
InitializedValueSelector.this);
return noUpcomingSelection();
}
attemptsBeforeBailOut--;
}
next = childValueIterator.next();
} while (!accept(next));
return next;
| 173
| 176
| 349
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/MovableChainedTrailingValueFilter.java
|
MovableChainedTrailingValueFilter
|
accept
|
class MovableChainedTrailingValueFilter<Solution_> implements SelectionFilter<Solution_, Object> {
private final GenuineVariableDescriptor<Solution_> variableDescriptor;
public MovableChainedTrailingValueFilter(GenuineVariableDescriptor<Solution_> variableDescriptor) {
this.variableDescriptor = variableDescriptor;
}
@Override
public boolean accept(ScoreDirector<Solution_> scoreDirector, Object value) {<FILL_FUNCTION_BODY>}
private SingletonInverseVariableSupply retrieveSingletonInverseVariableSupply(ScoreDirector<Solution_> scoreDirector) {
// TODO Performance loss because the supply is retrieved for every accept
// A SelectionFilter should be optionally made aware of lifecycle events, so it can cache the supply
SupplyManager supplyManager = ((InnerScoreDirector<Solution_, ?>) scoreDirector).getSupplyManager();
return supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor));
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MovableChainedTrailingValueFilter<?> that = (MovableChainedTrailingValueFilter<?>) other;
return Objects.equals(variableDescriptor, that.variableDescriptor);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor);
}
}
|
if (value == null) {
return true;
}
SingletonInverseVariableSupply supply = retrieveSingletonInverseVariableSupply(scoreDirector);
Object trailingEntity = supply.getInverseSingleton(value);
EntityDescriptor<Solution_> entityDescriptor = variableDescriptor.getEntityDescriptor();
if (trailingEntity == null || !entityDescriptor.matchesEntity(trailingEntity)) {
return true;
}
return entityDescriptor.getEffectiveMovableEntitySelectionFilter().accept(scoreDirector, trailingEntity);
| 379
| 137
| 516
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/ProbabilityValueSelector.java
|
ProbabilityValueSelector
|
iterator
|
class ProbabilityValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntityIndependentValueSelector<Solution_>, SelectionCacheLifecycleListener<Solution_> {
private final EntityIndependentValueSelector<Solution_> childValueSelector;
private final SelectionCacheType cacheType;
private final SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory;
protected NavigableMap<Double, Object> cachedEntityMap = null;
protected double probabilityWeightTotal = -1.0;
public ProbabilityValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector,
SelectionCacheType cacheType,
SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory) {
this.childValueSelector = childValueSelector;
this.cacheType = cacheType;
this.probabilityWeightFactory = probabilityWeightFactory;
if (childValueSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childValueSelector (" + childValueSelector
+ ") with neverEnding (" + childValueSelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childValueSelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
cachedEntityMap = new TreeMap<>();
ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector();
double probabilityWeightOffset = 0L;
// TODO Fail-faster if a non FromSolutionPropertyValueSelector is used
for (Object value : childValueSelector) {
double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(scoreDirector, value);
cachedEntityMap.put(probabilityWeightOffset, value);
probabilityWeightOffset += probabilityWeight;
}
probabilityWeightTotal = probabilityWeightOffset;
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
probabilityWeightTotal = -1.0;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childValueSelector.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public long getSize(Object entity) {
return getSize();
}
@Override
public long getSize() {
return cachedEntityMap.size();
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Object> endingIterator(Object entity) {
return childValueSelector.endingIterator(entity);
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ProbabilityValueSelector<?> that = (ProbabilityValueSelector<?>) other;
return Objects.equals(childValueSelector, that.childValueSelector) && cacheType == that.cacheType
&& Objects.equals(probabilityWeightFactory, that.probabilityWeightFactory);
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector, cacheType, probabilityWeightFactory);
}
@Override
public String toString() {
return "Probability(" + childValueSelector + ")";
}
}
|
return new Iterator<Object>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public Object next() {
double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
Map.Entry<Double, Object> entry = cachedEntityMap.floorEntry(randomOffset);
// entry is never null because randomOffset < probabilityWeightTotal
return entry.getValue();
}
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
};
| 1,046
| 147
| 1,193
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/ReinitializeVariableValueSelector.java
|
ReinitializeVariableValueSelector
|
equals
|
class ReinitializeVariableValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ValueSelector<Solution_> {
private final ValueSelector<Solution_> childValueSelector;
public ReinitializeVariableValueSelector(ValueSelector<Solution_> childValueSelector) {
this.childValueSelector = childValueSelector;
phaseLifecycleSupport.addEventListener(childValueSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childValueSelector.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return childValueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childValueSelector.isNeverEnding();
}
@Override
public long getSize(Object entity) {
if (isReinitializable(entity)) {
return childValueSelector.getSize(entity);
}
return 0L;
}
@Override
public Iterator<Object> iterator(Object entity) {
if (isReinitializable(entity)) {
return childValueSelector.iterator(entity);
}
return Collections.emptyIterator();
}
@Override
public Iterator<Object> endingIterator(Object entity) {
if (isReinitializable(entity)) {
return childValueSelector.endingIterator(entity);
}
return Collections.emptyIterator();
}
private boolean isReinitializable(Object entity) {
return childValueSelector.getVariableDescriptor().isReinitializable(entity);
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(childValueSelector);
}
@Override
public String toString() {
return "Reinitialize(" + childValueSelector + ")";
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ReinitializeVariableValueSelector<?> that = (ReinitializeVariableValueSelector<?>) other;
return Objects.equals(childValueSelector, that.childValueSelector);
| 516
| 83
| 599
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/SelectedCountLimitValueSelector.java
|
SelectedCountLimitValueSelector
|
getSize
|
class SelectedCountLimitValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
private final ValueSelector<Solution_> childValueSelector;
private final long selectedCountLimit;
/**
* Unlike most of the other {@link ValueSelector} decorations,
* this one works for an entity dependent {@link ValueSelector} too.
*
* @param childValueSelector never null, if any of the {@link EntityIndependentValueSelector} specific methods
* are going to be used, this parameter must also implement that interface
* @param selectedCountLimit at least 0
*/
public SelectedCountLimitValueSelector(ValueSelector<Solution_> childValueSelector, long selectedCountLimit) {
this.childValueSelector = childValueSelector;
this.selectedCountLimit = selectedCountLimit;
if (selectedCountLimit < 0L) {
throw new IllegalArgumentException("The selector (" + this
+ ") has a negative selectedCountLimit (" + selectedCountLimit + ").");
}
phaseLifecycleSupport.addEventListener(childValueSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childValueSelector.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public long getSize(Object entity) {
long childSize = childValueSelector.getSize(entity);
return Math.min(selectedCountLimit, childSize);
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Object> iterator(Object entity) {
return new SelectedCountLimitValueIterator(childValueSelector.iterator(entity));
}
@Override
public Iterator<Object> iterator() {
return new SelectedCountLimitValueIterator(((EntityIndependentValueSelector<Solution_>) childValueSelector).iterator());
}
@Override
public Iterator<Object> endingIterator(Object entity) {
return new SelectedCountLimitValueIterator(childValueSelector.endingIterator(entity));
}
private class SelectedCountLimitValueIterator extends SelectionIterator<Object> {
private final Iterator<Object> childValueIterator;
private long selectedSize;
public SelectedCountLimitValueIterator(Iterator<Object> childValueIterator) {
this.childValueIterator = childValueIterator;
selectedSize = 0L;
}
@Override
public boolean hasNext() {
return selectedSize < selectedCountLimit && childValueIterator.hasNext();
}
@Override
public Object next() {
if (selectedSize >= selectedCountLimit) {
throw new NoSuchElementException();
}
selectedSize++;
return childValueIterator.next();
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
SelectedCountLimitValueSelector<?> that = (SelectedCountLimitValueSelector<?>) other;
return selectedCountLimit == that.selectedCountLimit && Objects.equals(childValueSelector, that.childValueSelector);
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector, selectedCountLimit);
}
@Override
public String toString() {
return "SelectedCountLimit(" + childValueSelector + ")";
}
}
|
if (!(childValueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("To use the method getSize(), the moveSelector (" + this
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + childValueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
long childSize = ((EntityIndependentValueSelector<Solution_>) childValueSelector).getSize();
return Math.min(selectedCountLimit, childSize);
| 936
| 143
| 1,079
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/ShufflingValueSelector.java
|
ShufflingValueSelector
|
iterator
|
class ShufflingValueSelector<Solution_>
extends AbstractCachingValueSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
public ShufflingValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector,
SelectionCacheType cacheType) {
super(childValueSelector, cacheType);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Shuffling(" + childValueSelector + ")";
}
}
|
Collections.shuffle(cachedValueList, workingRandom);
logger.trace(" Shuffled cachedValueList with size ({}) in valueSelector({}).",
cachedValueList.size(), this);
return cachedValueList.iterator();
| 224
| 62
| 286
|
<methods>public void <init>(EntityIndependentValueSelector<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType) ,public void constructCache(SolverScope<Solution_>) ,public void disposeCache(SolverScope<Solution_>) ,public Iterator<java.lang.Object> endingIterator(java.lang.Object) ,public Iterator<java.lang.Object> endingIterator() ,public boolean equals(java.lang.Object) ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,public ValueSelector<Solution_> getChildValueSelector() ,public long getSize(java.lang.Object) ,public long getSize() ,public GenuineVariableDescriptor<Solution_> getVariableDescriptor() ,public int hashCode() ,public boolean isCountable() <variables>protected final non-sealed org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType cacheType,protected List<java.lang.Object> cachedValueList,protected final non-sealed EntityIndependentValueSelector<Solution_> childValueSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/decorator/SortingValueSelector.java
|
SortingValueSelector
|
equals
|
class SortingValueSelector<Solution_>
extends AbstractCachingValueSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
protected final SelectionSorter<Solution_, Object> sorter;
public SortingValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType,
SelectionSorter<Solution_, Object> sorter) {
super(childValueSelector, cacheType);
this.sorter = sorter;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
super.constructCache(solverScope);
sorter.sort(solverScope.getScoreDirector(), cachedValueList);
logger.trace(" Sorted cachedValueList: size ({}), valueSelector ({}).",
cachedValueList.size(), this);
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {
return cachedValueList.iterator();
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sorter);
}
@Override
public String toString() {
return "Sorting(" + childValueSelector + ")";
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
if (!super.equals(other))
return false;
SortingValueSelector<?> that = (SortingValueSelector<?>) other;
return Objects.equals(sorter, that.sorter);
| 413
| 92
| 505
|
<methods>public void <init>(EntityIndependentValueSelector<Solution_>, org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType) ,public void constructCache(SolverScope<Solution_>) ,public void disposeCache(SolverScope<Solution_>) ,public Iterator<java.lang.Object> endingIterator(java.lang.Object) ,public Iterator<java.lang.Object> endingIterator() ,public boolean equals(java.lang.Object) ,public org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType getCacheType() ,public ValueSelector<Solution_> getChildValueSelector() ,public long getSize(java.lang.Object) ,public long getSize() ,public GenuineVariableDescriptor<Solution_> getVariableDescriptor() ,public int hashCode() ,public boolean isCountable() <variables>protected final non-sealed org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType cacheType,protected List<java.lang.Object> cachedValueList,protected final non-sealed EntityIndependentValueSelector<Solution_> childValueSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/mimic/MimicRecordingValueSelector.java
|
RecordingValueIterator
|
equals
|
class RecordingValueIterator extends SelectionIterator<Object> {
private final Iterator<Object> childValueIterator;
public RecordingValueIterator(Iterator<Object> childValueIterator) {
this.childValueIterator = childValueIterator;
}
@Override
public boolean hasNext() {
boolean hasNext = childValueIterator.hasNext();
for (MimicReplayingValueSelector<Solution_> replayingValueSelector : replayingValueSelectorList) {
replayingValueSelector.recordedHasNext(hasNext);
}
return hasNext;
}
@Override
public Object next() {
Object next = childValueIterator.next();
for (MimicReplayingValueSelector<Solution_> replayingValueSelector : replayingValueSelectorList) {
replayingValueSelector.recordedNext(next);
}
return next;
}
}
@Override
public Iterator<Object> endingIterator(Object entity) {
// No recording, because the endingIterator() is used for determining size
return childValueSelector.endingIterator(entity);
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MimicRecordingValueSelector<?> that = (MimicRecordingValueSelector<?>) other;
/*
* Using list size in order to prevent recursion in equals/hashcode.
* Since the replaying selector will always point back to this instance,
* we only need to know if the lists are the same
* in order to be able to tell if two instances are equal.
*/
return Objects.equals(childValueSelector, that.childValueSelector)
&& Objects.equals(replayingValueSelectorList.size(), that.replayingValueSelectorList.size());
| 306
| 184
| 490
|
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/nearby/ListValueNearbyDistanceMatrixDemand.java
|
ListValueNearbyDistanceMatrixDemand
|
supplyNearbyDistanceMatrix
|
class ListValueNearbyDistanceMatrixDemand<Solution_, Origin_, Destination_>
extends
AbstractNearbyDistanceMatrixDemand<Origin_, Destination_, EntityIndependentValueSelector<Solution_>, MimicReplayingValueSelector<Solution_>> {
private final ToIntFunction<Origin_> destinationSizeFunction;
public ListValueNearbyDistanceMatrixDemand(
NearbyDistanceMeter<Origin_, Destination_> meter,
NearbyRandom random,
EntityIndependentValueSelector<Solution_> childValueSelector,
MimicReplayingValueSelector<Solution_> replayingOriginValueSelector,
ToIntFunction<Origin_> destinationSizeFunction) {
super(meter, random, childValueSelector, replayingOriginValueSelector);
this.destinationSizeFunction = destinationSizeFunction;
}
@Override
protected NearbyDistanceMatrix<Origin_, Destination_> supplyNearbyDistanceMatrix() {<FILL_FUNCTION_BODY>}
}
|
final long childSize = childSelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The childSize (" + childSize + ") is higher than Integer.MAX_VALUE.");
}
long originSize = replayingSelector.getSize();
if (originSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The originValueSelector (" + replayingSelector
+ ") has a valueSize (" + originSize
+ ") which is higher than Integer.MAX_VALUE.");
}
// Destinations: values extracted from a value selector.
// List variables use entity independent value selectors, so we can pass null to get and ending iterator.
Function<Origin_, Iterator<Destination_>> destinationIteratorProvider =
origin -> (Iterator<Destination_>) childSelector.endingIterator(null);
NearbyDistanceMatrix<Origin_, Destination_> nearbyDistanceMatrix =
new NearbyDistanceMatrix<>(meter, (int) originSize, destinationIteratorProvider, destinationSizeFunction);
// Origins: values extracted from a value selector.
// Replaying selector's ending iterator uses the recording selector's ending iterator. So, again, null is OK here.
replayingSelector.endingIterator(null)
.forEachRemaining(origin -> nearbyDistanceMatrix.addAllDestinations((Origin_) origin));
return nearbyDistanceMatrix;
| 250
| 338
| 588
|
<methods>public final NearbyDistanceMatrix<Origin_,Destination_> createExternalizedSupply(org.optaplanner.core.impl.domain.variable.supply.SupplyManager) ,public final boolean equals(java.lang.Object) ,public final int hashCode() <variables>protected final non-sealed EntityIndependentValueSelector<Solution_> childSelector,protected final non-sealed NearbyDistanceMeter<Origin_,Destination_> meter,protected final non-sealed org.optaplanner.core.impl.heuristic.selector.common.nearby.NearbyRandom random,protected final non-sealed MimicReplayingValueSelector<Solution_> replayingSelector
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/nearby/NearEntityNearbyValueSelector.java
|
NearEntityNearbyValueSelector
|
computeDestinationSize
|
class NearEntityNearbyValueSelector<Solution_>
extends AbstractNearbyValueSelector<Solution_, ValueSelector<Solution_>, EntitySelector<Solution_>> {
private final boolean discardNearbyIndexZero;
public NearEntityNearbyValueSelector(ValueSelector<Solution_> childValueSelector,
EntitySelector<Solution_> originEntitySelector, NearbyDistanceMeter<?, ?> nearbyDistanceMeter,
NearbyRandom nearbyRandom, boolean randomSelection) {
super(childValueSelector, originEntitySelector, nearbyDistanceMeter, nearbyRandom, randomSelection);
this.discardNearbyIndexZero = childValueSelector.getVariableDescriptor().getVariablePropertyType().isAssignableFrom(
originEntitySelector.getEntityDescriptor().getEntityClass());
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childSelector.getVariableDescriptor();
}
@Override
protected EntitySelector<Solution_> castReplayingSelector(Object uncastReplayingSelector) {
if (!(uncastReplayingSelector instanceof MimicReplayingEntitySelector)) {
// In order to select a nearby value, we must first have something to be near by.
throw new IllegalStateException("Impossible state: Nearby value selector (" + this +
") did not receive a replaying entity selector (" + uncastReplayingSelector + ").");
}
return (EntitySelector<Solution_>) uncastReplayingSelector;
}
@Override
protected AbstractNearbyDistanceMatrixDemand<?, ?, ?, ?> createDemand() {
return new ValueNearbyDistanceMatrixDemand<>(
nearbyDistanceMeter,
nearbyRandom,
childSelector,
replayingSelector,
this::computeDestinationSize);
}
private int computeDestinationSize(Object origin) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return childSelector.isCountable();
}
@Override
public long getSize(Object entity) {
return childSelector.getSize(entity) - (discardNearbyIndexZero ? 1 : 0);
}
@Override
public Iterator<Object> iterator(Object entity) {
Iterator<Object> replayingOriginEntityIterator = replayingSelector.iterator();
if (!randomSelection) {
return new OriginalNearbyValueIterator(nearbyDistanceMatrix, replayingOriginEntityIterator,
childSelector.getSize(entity), discardNearbyIndexZero);
} else {
return new RandomNearbyIterator(nearbyDistanceMatrix, nearbyRandom, workingRandom,
replayingOriginEntityIterator, childSelector.getSize(entity), discardNearbyIndexZero);
}
}
@Override
public Iterator<Object> endingIterator(Object entity) {
// TODO It should probably use nearby order
// It must include the origin entity too
return childSelector.endingIterator(entity);
}
}
|
long childSize = childSelector.getSize(origin);
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The childValueSelector (" + childSelector
+ ") has a valueSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
int destinationSize = (int) childSize;
if (randomSelection) {
// Reduce RAM memory usage by reducing destinationSize if nearbyRandom will never select a higher value
int overallSizeMaximum = nearbyRandom.getOverallSizeMaximum();
if (discardNearbyIndexZero && overallSizeMaximum < Integer.MAX_VALUE) {
overallSizeMaximum++;
}
if (destinationSize > overallSizeMaximum) {
destinationSize = overallSizeMaximum;
}
}
return destinationSize;
| 775
| 206
| 981
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/nearby/NearValueNearbyValueSelector.java
|
NearValueNearbyValueSelector
|
iterator
|
class NearValueNearbyValueSelector<Solution_>
extends
AbstractNearbyValueSelector<Solution_, EntityIndependentValueSelector<Solution_>, MimicReplayingValueSelector<Solution_>>
implements EntityIndependentValueSelector<Solution_> {
public NearValueNearbyValueSelector(
EntityIndependentValueSelector<Solution_> childValueSelector,
EntityIndependentValueSelector<Solution_> originValueSelector,
NearbyDistanceMeter<?, ?> nearbyDistanceMeter,
NearbyRandom nearbyRandom, boolean randomSelection) {
super(childValueSelector, originValueSelector, nearbyDistanceMeter, nearbyRandom, randomSelection);
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childSelector.getVariableDescriptor();
}
@Override
protected MimicReplayingValueSelector<Solution_> castReplayingSelector(Object uncastReplayingSelector) {
if (!(uncastReplayingSelector instanceof MimicReplayingValueSelector)) {
// In order to select a nearby value, we must first have something to be near by.
throw new IllegalStateException("Impossible state: Nearby value selector (" + this +
") did not receive a replaying value selector (" + uncastReplayingSelector + ").");
}
return (MimicReplayingValueSelector<Solution_>) uncastReplayingSelector;
}
@Override
protected AbstractNearbyDistanceMatrixDemand<?, ?, ?, ?> createDemand() {
return new ListValueNearbyDistanceMatrixDemand<>(
nearbyDistanceMeter,
nearbyRandom,
childSelector,
replayingSelector,
this::computeDestinationSize);
}
private int computeDestinationSize(Object origin) {
long childSize = childSelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The childValueSelector (" + childSelector
+ ") has a valueSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
int destinationSize = (int) childSize;
if (randomSelection) {
// Reduce RAM memory usage by reducing destinationSize if nearbyRandom will never select a higher value
int overallSizeMaximum = nearbyRandom.getOverallSizeMaximum();
if (destinationSize > overallSizeMaximum) {
destinationSize = overallSizeMaximum;
}
}
return destinationSize;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return childSelector.isCountable();
}
@Override
public long getSize(Object entity) {
return getSize();
}
@Override
public long getSize() {
return childSelector.getSize();
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {<FILL_FUNCTION_BODY>}
@Override
public Iterator<Object> endingIterator(Object entity) {
// TODO It should probably use nearby order
// It must include the origin entity too
return childSelector.endingIterator(entity);
}
}
|
Iterator<Object> replayingOriginValueIterator = replayingSelector.iterator();
if (!randomSelection) {
return new OriginalNearbyValueIterator(nearbyDistanceMatrix, replayingOriginValueIterator,
childSelector.getSize(), false);
} else {
return new RandomNearbyIterator(nearbyDistanceMatrix, nearbyRandom, workingRandom,
replayingOriginValueIterator, childSelector.getSize(), false);
}
| 836
| 111
| 947
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/nearby/OriginalNearbyValueIterator.java
|
OriginalNearbyValueIterator
|
selectOrigin
|
class OriginalNearbyValueIterator extends SelectionIterator<Object> {
private final NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix;
private final Iterator<Object> replayingIterator;
private final long childSize;
private boolean originSelected = false;
private boolean originIsNotEmpty;
private Object origin;
private int nextNearbyIndex;
public OriginalNearbyValueIterator(NearbyDistanceMatrix<Object, Object> nearbyDistanceMatrix,
Iterator<Object> replayingIterator, long childSize, boolean discardNearbyIndexZero) {
this.nearbyDistanceMatrix = nearbyDistanceMatrix;
this.replayingIterator = replayingIterator;
this.childSize = childSize;
this.nextNearbyIndex = discardNearbyIndexZero ? 1 : 0;
}
private void selectOrigin() {<FILL_FUNCTION_BODY>}
@Override
public boolean hasNext() {
selectOrigin();
return originIsNotEmpty && nextNearbyIndex < childSize;
}
@Override
public Object next() {
selectOrigin();
Object next = nearbyDistanceMatrix.getDestination(origin, nextNearbyIndex);
nextNearbyIndex++;
return next;
}
}
|
if (originSelected) {
return;
}
/*
* The origin iterator is guaranteed to be a replaying iterator.
* Therefore next() will point to whatever that the related recording iterator was pointing to at the time
* when its next() was called.
* As a result, origin here will be constant unless next() on the original recording iterator is called
* first.
*/
originIsNotEmpty = replayingIterator.hasNext();
origin = replayingIterator.next();
originSelected = true;
| 324
| 135
| 459
|
<methods>public non-sealed void <init>() ,public void remove() <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-core-impl/src/main/java/org/optaplanner/core/impl/heuristic/selector/value/nearby/ValueNearbyDistanceMatrixDemand.java
|
ValueNearbyDistanceMatrixDemand
|
supplyNearbyDistanceMatrix
|
class ValueNearbyDistanceMatrixDemand<Solution_, Origin_, Destination_>
extends AbstractNearbyDistanceMatrixDemand<Origin_, Destination_, ValueSelector<Solution_>, EntitySelector<Solution_>> {
private final ToIntFunction<Origin_> destinationSizeFunction;
public ValueNearbyDistanceMatrixDemand(NearbyDistanceMeter<Origin_, Destination_> meter, NearbyRandom random,
ValueSelector<Solution_> childSelector, EntitySelector<Solution_> replayingOriginEntitySelector,
ToIntFunction<Origin_> destinationSizeFunction) {
super(meter, random, childSelector, replayingOriginEntitySelector);
this.destinationSizeFunction = destinationSizeFunction;
}
@Override
protected NearbyDistanceMatrix<Origin_, Destination_> supplyNearbyDistanceMatrix() {<FILL_FUNCTION_BODY>}
}
|
long originSize = replayingSelector.getSize();
if (originSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The originEntitySelector (" + replayingSelector
+ ") has an entitySize (" + originSize
+ ") which is higher than Integer.MAX_VALUE.");
}
// Destinations: values extracted a value selector.
Function<Origin_, Iterator<Destination_>> destinationIteratorProvider =
origin -> (Iterator<Destination_>) childSelector.endingIterator(origin);
NearbyDistanceMatrix<Origin_, Destination_> nearbyDistanceMatrix =
new NearbyDistanceMatrix<>(meter, (int) originSize, destinationIteratorProvider, destinationSizeFunction);
// Origins: entities extracted from an entity selector.
replayingSelector.endingIterator()
.forEachRemaining(origin -> nearbyDistanceMatrix.addAllDestinations((Origin_) origin));
return nearbyDistanceMatrix;
| 221
| 223
| 444
|
<methods>public final NearbyDistanceMatrix<Origin_,Destination_> createExternalizedSupply(org.optaplanner.core.impl.domain.variable.supply.SupplyManager) ,public final boolean equals(java.lang.Object) ,public final int hashCode() <variables>protected final non-sealed ValueSelector<Solution_> childSelector,protected final non-sealed NearbyDistanceMeter<Origin_,Destination_> meter,protected final non-sealed org.optaplanner.core.impl.heuristic.selector.common.nearby.NearbyRandom random,protected final non-sealed EntitySelector<Solution_> replayingSelector
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.