index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainChangeMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained;
import java.util.Collections;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class SubChainChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final SubChainSelector<Solution_> subChainSelector;
protected final EntityIndependentValueSelector<Solution_> valueSelector;
protected final boolean randomSelection;
protected final boolean selectReversingMoveToo;
protected SingletonInverseVariableSupply inverseVariableSupply = null;
public SubChainChangeMoveSelector(SubChainSelector<Solution_> subChainSelector,
EntityIndependentValueSelector<Solution_> valueSelector, boolean randomSelection,
boolean selectReversingMoveToo) {
this.subChainSelector = subChainSelector;
this.valueSelector = valueSelector;
this.randomSelection = randomSelection;
this.selectReversingMoveToo = selectReversingMoveToo;
if (subChainSelector.getVariableDescriptor() != valueSelector.getVariableDescriptor()) {
throw new IllegalStateException("The selector (" + this
+ ") has a subChainSelector (" + subChainSelector
+ ") with variableDescriptor (" + subChainSelector.getVariableDescriptor()
+ ") which is not the same as the valueSelector (" + valueSelector
+ ")'s variableDescriptor(" + valueSelector.getVariableDescriptor() + ").");
}
if (!randomSelection) {
if (subChainSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a subChainSelector (" + subChainSelector
+ ") with neverEnding (" + subChainSelector.isNeverEnding() + ").");
}
if (valueSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a valueSelector (" + valueSelector
+ ") with neverEnding (" + valueSelector.isNeverEnding() + ").");
}
}
phaseLifecycleSupport.addEventListener(subChainSelector);
phaseLifecycleSupport.addEventListener(valueSelector);
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
inverseVariableSupply =
supplyManager.demand(new SingletonInverseVariableDemand<>(valueSelector.getVariableDescriptor()));
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
inverseVariableSupply = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return subChainSelector.isCountable() && valueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection;
}
@Override
public long getSize() {
return subChainSelector.getSize() * valueSelector.getSize();
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return new OriginalSubChainChangeMoveIterator();
} else {
return new RandomSubChainChangeMoveIterator();
}
}
private class OriginalSubChainChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private final Iterator<SubChain> subChainIterator;
private Iterator<Object> valueIterator = null;
private SubChain upcomingSubChain;
private Move<Solution_> nextReversingSelection = null;
private OriginalSubChainChangeMoveIterator() {
subChainIterator = subChainSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
if (selectReversingMoveToo && nextReversingSelection != null) {
Move<Solution_> upcomingSelection = nextReversingSelection;
nextReversingSelection = null;
return upcomingSelection;
}
if (!valueIterator.hasNext()) {
if (!subChainIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingSubChain = subChainIterator.next();
valueIterator = valueSelector.iterator();
if (!valueIterator.hasNext()) {
// valueSelector is completely empty
return noUpcomingSelection();
}
}
Object toValue = valueIterator.next();
Move<Solution_> upcomingSelection = new SubChainChangeMove<>(upcomingSubChain,
valueSelector.getVariableDescriptor(), inverseVariableSupply, toValue);
if (selectReversingMoveToo) {
nextReversingSelection = new SubChainReversingChangeMove<>(upcomingSubChain,
valueSelector.getVariableDescriptor(), inverseVariableSupply, toValue);
}
return upcomingSelection;
}
}
private 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() {
// 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);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + subChainSelector + ", " + valueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainChangeMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.chained.SubChainSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelectorFactory;
public 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) {
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));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainReversingChangeMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public 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) {
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);
}
@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 + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainReversingSwapMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.util.CollectionUtils;
/**
* This {@link Move} is not cacheable.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public 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) {
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);
}
}
}
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 + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainSwapMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.util.CollectionUtils;
/**
* This {@link Move} is not cacheable.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public 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) {
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);
}
}
}
@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 + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/TailChainSwapMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.anchor.AnchorVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* Also known as a 2-opt move.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class TailChainSwapMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final Object leftEntity;
protected final Object leftValue;
protected final Object leftAnchor;
protected final Object rightEntity; // Sometimes null
protected final Object rightValue;
protected final Object rightAnchor;
protected final boolean sameAnchor;
protected final Object leftNextEntity;
protected final Object rightNextEntity;
protected final boolean reverseAnchorSide;
protected final Object lastEntityInChain;
protected final Object entityAfterAnchor;
public TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply, AnchorVariableSupply anchorVariableSupply,
Object leftEntity, Object rightValue) {
this.variableDescriptor = variableDescriptor;
this.leftEntity = leftEntity;
leftValue = variableDescriptor.getValue(leftEntity);
leftAnchor = anchorVariableSupply.getAnchor(leftEntity);
rightEntity = inverseVariableSupply.getInverseSingleton(rightValue);
this.rightValue = rightValue;
rightAnchor = variableDescriptor.isValuePotentialAnchor(rightValue) ? rightValue
: anchorVariableSupply.getAnchor(rightValue);
sameAnchor = leftAnchor == rightAnchor;
if (!sameAnchor) {
leftNextEntity = null;
rightNextEntity = null;
reverseAnchorSide = false;
lastEntityInChain = null;
entityAfterAnchor = null;
} else {
leftNextEntity = inverseVariableSupply.getInverseSingleton(leftEntity);
rightNextEntity = rightEntity == null ? null : inverseVariableSupply.getInverseSingleton(rightEntity);
Object lastEntityInChainOrLeftEntity = findLastEntityInChainOrLeftEntity(inverseVariableSupply);
reverseAnchorSide = lastEntityInChainOrLeftEntity != leftEntity;
if (reverseAnchorSide) {
lastEntityInChain = lastEntityInChainOrLeftEntity;
entityAfterAnchor = inverseVariableSupply.getInverseSingleton(leftAnchor);
} else {
lastEntityInChain = null;
entityAfterAnchor = null;
}
}
}
// TODO Workaround until https://issues.redhat.com/browse/PLANNER-1250 is fixed
protected TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
Object leftEntity, Object leftValue, Object leftAnchor,
Object rightEntity, Object rightValue, Object rightAnchor) {
this.variableDescriptor = variableDescriptor;
this.leftEntity = leftEntity;
this.leftValue = leftValue;
this.leftAnchor = leftAnchor;
this.rightEntity = rightEntity;
this.rightValue = rightValue;
this.rightAnchor = rightAnchor;
this.sameAnchor = false;
this.leftNextEntity = null;
this.rightNextEntity = null;
this.reverseAnchorSide = false;
this.lastEntityInChain = null;
this.entityAfterAnchor = null;
}
// TODO Workaround until https://issues.redhat.com/browse/PLANNER-1250 is fixed
protected TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
Object leftEntity, Object leftValue, Object leftAnchor,
Object rightEntity, Object rightValue, Object rightAnchor,
Object leftNextEntity, Object rightNextEntity) {
this.variableDescriptor = variableDescriptor;
this.leftEntity = leftEntity;
this.leftValue = leftValue;
this.leftAnchor = leftAnchor;
this.rightEntity = rightEntity;
this.rightValue = rightValue;
this.rightAnchor = rightAnchor;
this.sameAnchor = true;
this.leftNextEntity = leftNextEntity;
this.rightNextEntity = rightNextEntity;
this.reverseAnchorSide = false;
this.lastEntityInChain = null;
this.entityAfterAnchor = null;
}
// TODO Workaround until https://issues.redhat.com/browse/PLANNER-1250 is fixed
protected TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor,
Object leftEntity, Object leftValue, Object leftAnchor,
Object rightEntity, Object rightValue, Object rightAnchor,
Object leftNextEntity, Object rightNextEntity, Object lastEntityInChain, Object entityAfterAnchor) {
this.variableDescriptor = variableDescriptor;
this.leftEntity = leftEntity;
this.leftValue = leftValue;
this.leftAnchor = leftAnchor;
this.rightEntity = rightEntity;
this.rightValue = rightValue;
this.rightAnchor = rightAnchor;
this.sameAnchor = true;
this.leftNextEntity = leftNextEntity;
this.rightNextEntity = rightNextEntity;
this.reverseAnchorSide = true;
this.lastEntityInChain = lastEntityInChain;
this.entityAfterAnchor = entityAfterAnchor;
}
private Object findLastEntityInChainOrLeftEntity(SingletonInverseVariableSupply inverseVariableSupply) {
Object entity = rightValue;
while (entity != leftEntity) {
Object nextEntity = inverseVariableSupply.getInverseSingleton(entity);
if (nextEntity == null) {
return entity;
}
entity = nextEntity;
}
return leftEntity;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public Object getLeftEntity() {
return leftEntity;
}
public Object getRightValue() {
return rightValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
if (Objects.equals(leftValue, rightValue)
|| Objects.equals(leftEntity, rightValue) || Objects.equals(rightEntity, leftValue)) {
return false;
}
if (rightEntity == null) {
// TODO Currently unsupported because we fail to create a valid undoMove... even though doMove supports it
if (leftAnchor == rightAnchor) {
return false;
}
}
if (!variableDescriptor.isValueRangeEntityIndependent()) {
ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
Solution_ workingSolution = scoreDirector.getWorkingSolution();
if (rightEntity != null) {
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 true;
}
@Override
public TailChainSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
if (!sameAnchor) {
return new TailChainSwapMove<>(variableDescriptor,
leftEntity, rightValue, rightAnchor,
rightEntity, leftValue, leftAnchor);
} else {
if (rightEntity == null) {
// TODO Currently unsupported because we fail to create a valid undoMove... even though doMove supports it
// https://issues.redhat.com/browse/PLANNER-1250
throw new IllegalStateException("Impossible state, because isMoveDoable() should not return true.");
}
if (!reverseAnchorSide) {
return new TailChainSwapMove<>(variableDescriptor,
rightEntity, rightNextEntity, leftAnchor,
leftEntity, rightValue, rightAnchor,
leftNextEntity, leftValue);
} else {
return new TailChainSwapMove<>(variableDescriptor,
rightEntity, rightNextEntity, leftAnchor,
leftEntity, rightValue, rightAnchor,
leftNextEntity, leftValue, entityAfterAnchor, lastEntityInChain);
}
}
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
if (!sameAnchor) {
// Change the left entity
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
// Change the right entity
if (rightEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftValue);
}
} else {
if (!reverseAnchorSide) {
// Reverses loop on the side that doesn't include the anchor, because rightValue is earlier than leftEntity
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
reverseChain(innerScoreDirector, leftValue, leftEntity, rightEntity);
if (leftNextEntity != null) {
innerScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity);
}
} else {
// Reverses loop on the side that does include the anchor, because rightValue is later than leftEntity
// Change the head of the chain
reverseChain(innerScoreDirector, leftValue, leftEntity, entityAfterAnchor);
// Change leftEntity
innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
// Change the tail of the chain
reverseChain(innerScoreDirector, lastEntityInChain, leftAnchor, rightEntity);
innerScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity);
}
}
}
protected void reverseChain(InnerScoreDirector scoreDirector, Object fromValue, Object fromEntity, Object toEntity) {
Object entity = fromValue;
Object newValue = fromEntity;
while (newValue != toEntity) {
Object oldValue = variableDescriptor.getValue(entity);
scoreDirector.changeVariableFacade(variableDescriptor, entity, newValue);
newValue = entity;
entity = oldValue;
}
}
@Override
public TailChainSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
if (!sameAnchor) {
return new TailChainSwapMove<>(variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(leftEntity),
destinationScoreDirector.lookUpWorkingObject(leftValue),
destinationScoreDirector.lookUpWorkingObject(leftAnchor),
destinationScoreDirector.lookUpWorkingObject(rightEntity),
destinationScoreDirector.lookUpWorkingObject(rightValue),
destinationScoreDirector.lookUpWorkingObject(rightAnchor));
} else {
if (!reverseAnchorSide) {
return new TailChainSwapMove<>(variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(leftEntity),
destinationScoreDirector.lookUpWorkingObject(leftValue),
destinationScoreDirector.lookUpWorkingObject(leftAnchor),
destinationScoreDirector.lookUpWorkingObject(rightEntity),
destinationScoreDirector.lookUpWorkingObject(rightValue),
destinationScoreDirector.lookUpWorkingObject(rightAnchor),
destinationScoreDirector.lookUpWorkingObject(leftNextEntity),
destinationScoreDirector.lookUpWorkingObject(rightNextEntity));
} else {
return new TailChainSwapMove<>(variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(leftEntity),
destinationScoreDirector.lookUpWorkingObject(leftValue),
destinationScoreDirector.lookUpWorkingObject(leftAnchor),
destinationScoreDirector.lookUpWorkingObject(rightEntity),
destinationScoreDirector.lookUpWorkingObject(rightValue),
destinationScoreDirector.lookUpWorkingObject(rightAnchor),
destinationScoreDirector.lookUpWorkingObject(leftNextEntity),
destinationScoreDirector.lookUpWorkingObject(rightNextEntity),
destinationScoreDirector.lookUpWorkingObject(lastEntityInChain),
destinationScoreDirector.lookUpWorkingObject(entityAfterAnchor));
}
}
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
if (rightEntity == null) {
return Collections.singleton(leftEntity);
}
return Arrays.asList(leftEntity, rightEntity);
}
@Override
public Collection<? extends Object> getPlanningValues() {
Object leftValue = variableDescriptor.getValue(leftEntity);
return Arrays.asList(leftValue, rightValue);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TailChainSwapMove<?> other = (TailChainSwapMove<?>) o;
return Objects.equals(leftEntity, other.leftEntity) &&
Objects.equals(rightValue, other.rightValue);
}
@Override
public int hashCode() {
return Objects.hash(leftEntity, rightValue);
}
@Override
public String toString() {
return leftEntity + " {" + leftValue + "} <-tailChainSwap-> " + rightEntity + " {" + rightValue + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListAssignMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Objects;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractSimplifiedMove;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
public final class ListAssignMove<Solution_> extends AbstractSimplifiedMove<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
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var variableDescriptorAwareScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
// Add planningValue to destinationEntity's list variable (at destinationIndex).
variableDescriptorAwareScoreDirector.beforeListVariableElementAssigned(variableDescriptor, planningValue);
variableDescriptorAwareScoreDirector.beforeListVariableChanged(variableDescriptor, destinationEntity, destinationIndex,
destinationIndex);
variableDescriptor.addElement(destinationEntity, destinationIndex, planningValue);
variableDescriptorAwareScoreDirector.afterListVariableChanged(variableDescriptor, destinationEntity, destinationIndex,
destinationIndex + 1);
variableDescriptorAwareScoreDirector.afterListVariableElementAssigned(variableDescriptor, planningValue);
}
@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) {
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);
}
@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);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListChangeMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* Moves an element of a {@link PlanningListVariable list variable}. The moved element is identified
* by an entity instance and a position in that entity's list variable. The element is inserted at the given index
* in the given destination entity's list variable.
* <p>
* An undo move is simply created by flipping the source and destination entity+index.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ListChangeMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object sourceEntity;
private final int sourceIndex;
private final Object destinationEntity;
private final int destinationIndex;
private Object planningValue;
/**
* The move removes a planning value element from {@code sourceEntity.listVariable[sourceIndex]}
* and inserts the planning value at {@code destinationEntity.listVariable[destinationIndex]}.
*
* <h4>ListChangeMove anatomy</h4>
*
* <pre>
* {@code
* / destinationEntity
* | / destinationIndex
* | |
* A {Ann[0]}->{Bob[2]}
* | | |
* planning value / | \ sourceIndex
* \ sourceEntity
* }
* </pre>
*
* <h4>Example 1 - source and destination entities are different</h4>
*
* <pre>
* {@code
* GIVEN
* Ann.tasks = [A, B, C]
* Bob.tasks = [X, Y]
*
* WHEN
* ListChangeMove: A {Ann[0]->Bob[2]}
*
* THEN
* Ann.tasks = [B, C]
* Bob.tasks = [X, Y, A]
* }
* </pre>
*
* <h4>Example 2 - source and destination is the same entity</h4>
*
* <pre>
* {@code
* GIVEN
* Ann.tasks = [A, B, C]
*
* WHEN
* ListChangeMove: A {Ann[0]->Ann[2]}
*
* THEN
* Ann.tasks = [B, C, A]
* }
* </pre>
*
* @param variableDescriptor descriptor of a list variable, for example {@code Employee.taskList}
* @param sourceEntity planning entity instance from which a planning value will be removed, for example "Ann"
* @param sourceIndex index in sourceEntity's list variable from which a planning value will be removed
* @param destinationEntity planning entity instance to which a planning value will be moved, for example "Bob"
* @param destinationIndex index in destinationEntity's list variable where the moved planning value will be inserted
*/
public ListChangeMove(ListVariableDescriptor<Solution_> variableDescriptor,
Object sourceEntity, int sourceIndex,
Object destinationEntity, int destinationIndex) {
this.variableDescriptor = variableDescriptor;
this.sourceEntity = sourceEntity;
this.sourceIndex = sourceIndex;
this.destinationEntity = destinationEntity;
this.destinationIndex = destinationIndex;
}
public Object getSourceEntity() {
return sourceEntity;
}
public int getSourceIndex() {
return sourceIndex;
}
public Object getDestinationEntity() {
return destinationEntity;
}
public int getDestinationIndex() {
return destinationIndex;
}
public Object getMovedValue() {
if (planningValue == null) {
planningValue = variableDescriptor.getElement(sourceEntity, sourceIndex);
}
return planningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
// TODO maybe remove this because no such move should be generated
// 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 destinationEntity != sourceEntity
|| (destinationIndex != sourceIndex && destinationIndex != variableDescriptor.getListSize(sourceEntity));
}
@Override
public ListChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new ListChangeMove<>(variableDescriptor, destinationEntity, destinationIndex, sourceEntity, sourceIndex);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
if (sourceEntity == destinationEntity) {
int fromIndex = Math.min(sourceIndex, destinationIndex);
int toIndex = Math.max(sourceIndex, destinationIndex) + 1;
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex);
Object element = variableDescriptor.removeElement(sourceEntity, sourceIndex);
variableDescriptor.addElement(destinationEntity, destinationIndex, element);
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex);
planningValue = element;
} else {
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + 1);
Object element = variableDescriptor.removeElement(sourceEntity, sourceIndex);
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex);
innerScoreDirector.beforeListVariableChanged(variableDescriptor,
destinationEntity, destinationIndex, destinationIndex);
variableDescriptor.addElement(destinationEntity, destinationIndex, element);
innerScoreDirector.afterListVariableChanged(variableDescriptor,
destinationEntity, destinationIndex, destinationIndex + 1);
planningValue = element;
}
}
@Override
public ListChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ListChangeMove<>(
variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(sourceEntity), sourceIndex,
destinationScoreDirector.lookUpWorkingObject(destinationEntity), destinationIndex);
}
// ************************************************************************
// 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(sourceEntity);
entities.add(destinationEntity);
return entities;
}
@Override
public Collection<Object> getPlanningValues() {
return Collections.singleton(planningValue);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListChangeMove<?> other = (ListChangeMove<?>) o;
return sourceIndex == other.sourceIndex && destinationIndex == other.destinationIndex
&& Objects.equals(variableDescriptor, other.variableDescriptor)
&& Objects.equals(sourceEntity, other.sourceEntity)
&& Objects.equals(destinationEntity, other.destinationEntity);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, sourceEntity, sourceIndex, destinationEntity, destinationIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d] -> %s[%d]}",
getMovedValue(), sourceEntity, sourceIndex, destinationEntity, destinationIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListChangeMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
import ai.timefold.solver.core.impl.heuristic.selector.list.UnassignedLocation;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class ListChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
private final EntityIndependentValueSelector<Solution_> sourceValueSelector;
private EntityIndependentValueSelector<Solution_> movableSourceValueSelector;
private final DestinationSelector<Solution_> destinationSelector;
private final boolean randomSelection;
private ListVariableStateSupply<Solution_> listVariableStateSupply;
public ListChangeMoveSelector(
EntityIndependentValueSelector<Solution_> sourceValueSelector,
DestinationSelector<Solution_> destinationSelector,
boolean randomSelection) {
this.sourceValueSelector = sourceValueSelector;
this.destinationSelector = destinationSelector;
this.randomSelection = randomSelection;
phaseLifecycleSupport.addEventListener(sourceValueSelector);
phaseLifecycleSupport.addEventListener(destinationSelector);
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
var listVariableDescriptor = (ListVariableDescriptor<Solution_>) sourceValueSelector.getVariableDescriptor();
var supplyManager = solverScope.getScoreDirector().getSupplyManager();
listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand());
movableSourceValueSelector =
filterPinnedListPlanningVariableValuesWithIndex(sourceValueSelector, listVariableStateSupply);
}
public static <Solution_> EntityIndependentValueSelector<Solution_> filterPinnedListPlanningVariableValuesWithIndex(
EntityIndependentValueSelector<Solution_> sourceValueSelector,
ListVariableStateSupply<Solution_> listVariableStateSupply) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
var supportsPinning = listVariableDescriptor.supportsPinning();
if (!supportsPinning) {
// Don't incur the overhead of filtering values if there is no pinning support.
return sourceValueSelector;
}
return (EntityIndependentValueSelector<Solution_>) FilteringValueSelector.of(sourceValueSelector,
(scoreDirector, selection) -> {
var elementLocation = listVariableStateSupply.getLocationInList(selection);
if (elementLocation instanceof UnassignedLocation) {
return true;
}
var elementDestination = (LocationInList) elementLocation;
var entity = elementDestination.entity();
return !listVariableDescriptor.isElementPinned(scoreDirector, entity, elementDestination.index());
});
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
listVariableStateSupply = null;
movableSourceValueSelector = null;
}
@Override
public long getSize() {
return movableSourceValueSelector.getSize() * destinationSelector.getSize();
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (randomSelection) {
return new RandomListChangeIterator<>(
listVariableStateSupply,
movableSourceValueSelector,
destinationSelector);
} else {
return new OriginalListChangeIterator<>(
listVariableStateSupply,
movableSourceValueSelector,
destinationSelector);
}
}
@Override
public boolean isCountable() {
return movableSourceValueSelector.isCountable() && destinationSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || movableSourceValueSelector.isNeverEnding() || destinationSelector.isNeverEnding();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + sourceValueSelector + ", " + destinationSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListChangeMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public 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) {
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(VariableDescriptor::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;
}
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())));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListSwapMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* Swaps two elements of a {@link PlanningListVariable list variable}.
* Each element is identified by an entity instance and an index in that entity's list variable.
* The swap move has two sides called left and right. The element at {@code leftIndex} in {@code leftEntity}'s list variable
* is replaced by the element at {@code rightIndex} in {@code rightEntity}'s list variable and vice versa.
* Left and right entity can be the same instance.
* <p>
* An undo move is created by flipping the left and right-hand entity and index.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public 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) {
// 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) {
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);
}
}
@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);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListSwapMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class ListSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
private final EntityIndependentValueSelector<Solution_> leftValueSelector;
private final EntityIndependentValueSelector<Solution_> rightValueSelector;
private final boolean randomSelection;
private ListVariableStateSupply<Solution_> listVariableStateSupply;
private EntityIndependentValueSelector<Solution_> movableLeftValueSelector;
private EntityIndependentValueSelector<Solution_> movableRightValueSelector;
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) {
super.solvingStarted(solverScope);
var listVariableDescriptor = (ListVariableDescriptor<Solution_>) leftValueSelector.getVariableDescriptor();
var supplyManager = solverScope.getScoreDirector().getSupplyManager();
listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand());
movableLeftValueSelector = filterPinnedListPlanningVariableValuesWithIndex(leftValueSelector, listVariableStateSupply);
movableRightValueSelector =
filterPinnedListPlanningVariableValuesWithIndex(rightValueSelector, listVariableStateSupply);
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
listVariableStateSupply = null;
movableLeftValueSelector = null;
movableRightValueSelector = null;
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (randomSelection) {
return new RandomListSwapIterator<>(listVariableStateSupply, movableLeftValueSelector, movableRightValueSelector);
} else {
return new OriginalListSwapIterator<>(listVariableStateSupply, movableLeftValueSelector, movableRightValueSelector);
}
}
@Override
public boolean isCountable() {
return movableLeftValueSelector.isCountable() && movableRightValueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || movableLeftValueSelector.isNeverEnding() || movableRightValueSelector.isNeverEnding();
}
@Override
public long getSize() {
return movableLeftValueSelector.getSize() * movableRightValueSelector.getSize();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + leftValueSelector + ", " + rightValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListSwapMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public 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) {
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(VariableDescriptor::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);
}
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;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListUnassignMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Objects;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractSimplifiedMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
public class ListUnassignMove<Solution_> extends AbstractSimplifiedMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object sourceEntity;
private final int sourceIndex;
private Object movedValue;
public ListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex) {
this.variableDescriptor = variableDescriptor;
this.sourceEntity = sourceEntity;
this.sourceIndex = sourceIndex;
}
public Object getSourceEntity() {
return sourceEntity;
}
public int getSourceIndex() {
return sourceIndex;
}
public Object getMovedValue() {
if (movedValue == null) {
movedValue = variableDescriptor.getElement(sourceEntity, sourceIndex);
}
return movedValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
var listVariable = variableDescriptor.getValue(sourceEntity);
Object element = listVariable.get(sourceIndex);
// Remove an element from sourceEntity's list variable (at sourceIndex).
innerScoreDirector.beforeListVariableElementUnassigned(variableDescriptor, element);
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + 1);
movedValue = listVariable.remove(sourceIndex);
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex);
innerScoreDirector.afterListVariableElementUnassigned(variableDescriptor, element);
}
@Override
public Move<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ListUnassignMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(sourceEntity),
sourceIndex);
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public boolean equals(Object o) {
if (o instanceof ListUnassignMove<?> other) {
return sourceIndex == other.sourceIndex
&& Objects.equals(variableDescriptor, other.variableDescriptor)
&& Objects.equals(sourceEntity, other.sourceEntity);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, sourceEntity, sourceIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d] -> null}",
getMovedValue(), sourceEntity, sourceIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/OriginalListChangeIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Collections;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
/**
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class OriginalListChangeIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final ListVariableStateSupply<Solution_> listVariableStateSupply;
private final Iterator<Object> valueIterator;
private final DestinationSelector<Solution_> destinationSelector;
private Iterator<ElementLocation> destinationIterator;
private Object upcomingValue;
public OriginalListChangeIterator(ListVariableStateSupply<Solution_> listVariableStateSupply,
EntityIndependentValueSelector<Solution_> valueSelector, DestinationSelector<Solution_> destinationSelector) {
this.listVariableStateSupply = listVariableStateSupply;
this.valueIterator = valueSelector.iterator();
this.destinationSelector = destinationSelector;
this.destinationIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
while (!destinationIterator.hasNext()) {
if (!valueIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingValue = valueIterator.next();
destinationIterator = destinationSelector.iterator();
}
var move = buildChangeMove(listVariableStateSupply, upcomingValue, destinationIterator);
if (move == null) {
return noUpcomingSelection();
} else {
return move;
}
}
static <Solution_> Move<Solution_> buildChangeMove(ListVariableStateSupply<Solution_> listVariableStateSupply,
Object upcomingLeftValue, Iterator<ElementLocation> destinationIterator) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
var upcomingDestination = findUnpinnedDestination(destinationIterator, listVariableDescriptor);
if (upcomingDestination == null) {
return null;
}
var upcomingSource = listVariableStateSupply.getLocationInList(upcomingLeftValue);
if (upcomingSource instanceof LocationInList sourceElement) {
if (upcomingDestination instanceof LocationInList destinationElement) {
return new ListChangeMove<>(listVariableDescriptor, sourceElement.entity(), sourceElement.index(),
destinationElement.entity(), destinationElement.index());
} else {
return new ListUnassignMove<>(listVariableDescriptor, sourceElement.entity(), sourceElement.index());
}
} else {
if (upcomingDestination instanceof LocationInList destinationElement) {
return new ListAssignMove<>(listVariableDescriptor, upcomingLeftValue, destinationElement.entity(),
destinationElement.index());
} else {
// Only used in construction heuristics to give the CH an option to leave the element unassigned.
return NoChangeMove.getInstance();
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/OriginalListSwapIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Collections;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.heuristic.move.CompositeMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
import ai.timefold.solver.core.impl.heuristic.selector.list.UnassignedLocation;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
/**
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class OriginalListSwapIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final ListVariableStateSupply<Solution_> listVariableStateSupply;
private final Iterator<Object> leftValueIterator;
private final EntityIndependentValueSelector<Solution_> rightValueSelector;
private Iterator<Object> rightValueIterator;
private Object upcomingLeftValue;
public OriginalListSwapIterator(ListVariableStateSupply<Solution_> listVariableStateSupply,
EntityIndependentValueSelector<Solution_> leftValueSelector,
EntityIndependentValueSelector<Solution_> rightValueSelector) {
this.listVariableStateSupply = listVariableStateSupply;
this.leftValueIterator = leftValueSelector.iterator();
this.rightValueSelector = rightValueSelector;
this.rightValueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
while (!rightValueIterator.hasNext()) {
if (!leftValueIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingLeftValue = leftValueIterator.next();
rightValueIterator = rightValueSelector.iterator();
}
var upcomingRightValue = rightValueIterator.next();
return buildSwapMove(listVariableStateSupply, upcomingLeftValue, upcomingRightValue);
}
static <Solution_> Move<Solution_> buildSwapMove(ListVariableStateSupply<Solution_> listVariableStateSupply,
Object upcomingLeftValue, Object upcomingRightValue) {
if (upcomingLeftValue == upcomingRightValue) {
return NoChangeMove.getInstance();
}
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
var upcomingLeft = listVariableStateSupply.getLocationInList(upcomingLeftValue);
var upcomingRight = listVariableStateSupply.getLocationInList(upcomingRightValue);
var leftUnassigned = upcomingLeft instanceof UnassignedLocation;
var rightUnassigned = upcomingRight instanceof UnassignedLocation;
if (leftUnassigned && rightUnassigned) { // No need to swap two unassigned elements.
return NoChangeMove.getInstance();
} else if (leftUnassigned) { // Unassign right, put left where right used to be.
var rightDestination = (LocationInList) upcomingRight;
var unassignMove =
new ListUnassignMove<>(listVariableDescriptor, rightDestination.entity(), rightDestination.index());
var assignMove = new ListAssignMove<>(listVariableDescriptor, upcomingLeftValue, rightDestination.entity(),
rightDestination.index());
return CompositeMove.buildMove(unassignMove, assignMove);
} else if (rightUnassigned) { // Unassign left, put right where left used to be.
var leftDestination = (LocationInList) upcomingLeft;
var unassignMove =
new ListUnassignMove<>(listVariableDescriptor, leftDestination.entity(), leftDestination.index());
var assignMove = new ListAssignMove<>(listVariableDescriptor, upcomingRightValue, leftDestination.entity(),
leftDestination.index());
return CompositeMove.buildMove(unassignMove, assignMove);
} else {
var leftDestination = (LocationInList) upcomingLeft;
var rightDestination = (LocationInList) upcomingRight;
return new ListSwapMove<>(listVariableDescriptor, leftDestination.entity(), leftDestination.index(),
rightDestination.entity(), rightDestination.index());
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomListChangeIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class RandomListChangeIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final ListVariableStateSupply<Solution_> listVariableStateSupply;
private final Iterator<Object> valueIterator;
private final Iterator<ElementLocation> destinationIterator;
public RandomListChangeIterator(ListVariableStateSupply<Solution_> listVariableStateSupply,
EntityIndependentValueSelector<Solution_> valueSelector, DestinationSelector<Solution_> destinationSelector) {
this.listVariableStateSupply = listVariableStateSupply;
this.valueIterator = valueSelector.iterator();
this.destinationIterator = destinationSelector.iterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
if (!valueIterator.hasNext() || !destinationIterator.hasNext()) {
return noUpcomingSelection();
}
var upcomingValue = valueIterator.next();
var move = OriginalListChangeIterator.buildChangeMove(listVariableStateSupply, upcomingValue,
destinationIterator);
if (move == null) {
return noUpcomingSelection();
} else {
return move;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomListSwapIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.OriginalListSwapIterator.buildSwapMove;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class RandomListSwapIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final ListVariableStateSupply<Solution_> listVariableStateSupply;
private final Iterator<Object> leftValueIterator;
private final Iterator<Object> rightValueIterator;
public RandomListSwapIterator(ListVariableStateSupply<Solution_> listVariableStateSupply,
EntityIndependentValueSelector<Solution_> leftValueSelector,
EntityIndependentValueSelector<Solution_> rightValueSelector) {
this.listVariableStateSupply = listVariableStateSupply;
this.leftValueIterator = leftValueSelector.iterator();
this.rightValueIterator = rightValueSelector.iterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
if (!leftValueIterator.hasNext() || !rightValueIterator.hasNext()) {
return noUpcomingSelection();
}
var upcomingLeftValue = leftValueIterator.next();
var upcomingRightValue = rightValueIterator.next();
return buildSwapMove(listVariableStateSupply, upcomingLeftValue, upcomingRightValue);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomSubListChangeMoveIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Iterator;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector;
class RandomSubListChangeMoveIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final Iterator<SubList> subListIterator;
private final Iterator<ElementLocation> 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() {
if (!subListIterator.hasNext() || !destinationIterator.hasNext()) {
return noUpcomingSelection();
}
var subList = subListIterator.next();
var destination = findUnpinnedDestination(destinationIterator, listVariableDescriptor);
if (destination == null) {
return noUpcomingSelection();
} else if (destination instanceof LocationInList destinationElement) {
var reversing = selectReversingMoveToo && workingRandom.nextBoolean();
return new SubListChangeMove<>(listVariableDescriptor, subList, destinationElement.entity(),
destinationElement.index(), reversing);
} else {
// TODO add SubListAssignMove
return new SubListUnassignMove<>(listVariableDescriptor, subList);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListChangeMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.util.CollectionUtils;
/**
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SubListChangeMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object sourceEntity;
private final int sourceIndex;
private final int length;
private final Object destinationEntity;
private final int destinationIndex;
private final boolean reversing;
private Collection<Object> planningValues;
public SubListChangeMove(ListVariableDescriptor<Solution_> variableDescriptor, SubList subList, Object destinationEntity,
int destinationIndex, boolean reversing) {
this(variableDescriptor, subList.entity(), subList.fromIndex(), subList.length(), destinationEntity,
destinationIndex, reversing);
}
public SubListChangeMove(
ListVariableDescriptor<Solution_> variableDescriptor,
Object sourceEntity, int sourceIndex, int length,
Object destinationEntity, int destinationIndex, boolean reversing) {
this.variableDescriptor = variableDescriptor;
this.sourceEntity = sourceEntity;
this.sourceIndex = sourceIndex;
this.length = length;
this.destinationEntity = destinationEntity;
this.destinationIndex = destinationIndex;
this.reversing = reversing;
}
public Object getSourceEntity() {
return sourceEntity;
}
public int getFromIndex() {
return sourceIndex;
}
public int getSubListSize() {
return length;
}
public int getToIndex() {
return sourceIndex + length;
}
public boolean isReversing() {
return reversing;
}
public Object getDestinationEntity() {
return destinationEntity;
}
public int getDestinationIndex() {
return destinationIndex;
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
if (destinationEntity != sourceEntity) {
return true;
} else if (destinationIndex == sourceIndex) {
return false;
} else {
return destinationIndex + length <= variableDescriptor.getListSize(destinationEntity);
}
}
@Override
protected AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new SubListChangeMove<>(variableDescriptor, destinationEntity, destinationIndex, length, sourceEntity,
sourceIndex, reversing);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
List<Object> sourceList = variableDescriptor.getValue(sourceEntity);
List<Object> subList = sourceList.subList(sourceIndex, sourceIndex + length);
planningValues = CollectionUtils.copy(subList, reversing);
if (sourceEntity == destinationEntity) {
int fromIndex = Math.min(sourceIndex, destinationIndex);
int toIndex = Math.max(sourceIndex, destinationIndex) + length;
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex);
subList.clear();
variableDescriptor.getValue(destinationEntity).addAll(destinationIndex, planningValues);
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex);
} else {
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + length);
subList.clear();
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex);
innerScoreDirector.beforeListVariableChanged(variableDescriptor, destinationEntity, destinationIndex,
destinationIndex);
variableDescriptor.getValue(destinationEntity).addAll(destinationIndex, planningValues);
innerScoreDirector.afterListVariableChanged(variableDescriptor, destinationEntity, destinationIndex,
destinationIndex + length);
}
}
@Override
public SubListChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SubListChangeMove<>(
variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(sourceEntity), sourceIndex, length,
destinationScoreDirector.lookUpWorkingObject(destinationEntity), destinationIndex,
reversing);
}
// ************************************************************************
// 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(sourceEntity);
entities.add(destinationEntity);
return entities;
}
@Override
public Collection<Object> getPlanningValues() {
return planningValues;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubListChangeMove<?> other = (SubListChangeMove<?>) o;
return sourceIndex == other.sourceIndex && length == other.length
&& destinationIndex == other.destinationIndex && reversing == other.reversing
&& variableDescriptor.equals(other.variableDescriptor)
&& sourceEntity.equals(other.sourceEntity)
&& destinationEntity.equals(other.destinationEntity);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, sourceEntity, sourceIndex, length, destinationEntity, destinationIndex,
reversing);
}
@Override
public String toString() {
return String.format("|%d| {%s[%d..%d] -%s> %s[%d]}",
length, sourceEntity, sourceIndex, getToIndex(),
reversing ? "reversing-" : "", destinationEntity, destinationIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListChangeMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public 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) {
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(VariableDescriptor::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));
}
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;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListSwapMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.util.CollectionUtils;
/**
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SubListSwapMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final SubList leftSubList;
private final SubList rightSubList;
private final boolean reversing;
private final int rightFromIndex;
private final int leftToIndex;
private List<Object> leftPlanningValueList;
private List<Object> rightPlanningValueList;
public SubListSwapMove(ListVariableDescriptor<Solution_> variableDescriptor,
Object leftEntity, int leftFromIndex, int leftToIndex,
Object rightEntity, int rightFromIndex, int rightToIndex,
boolean reversing) {
this(variableDescriptor,
new SubList(leftEntity, leftFromIndex, leftToIndex - leftFromIndex),
new SubList(rightEntity, rightFromIndex, rightToIndex - rightFromIndex),
reversing);
}
public SubListSwapMove(ListVariableDescriptor<Solution_> variableDescriptor,
SubList leftSubList,
SubList rightSubList,
boolean reversing) {
this.variableDescriptor = variableDescriptor;
if (leftSubList.entity() == rightSubList.entity() && leftSubList.fromIndex() > rightSubList.fromIndex()) {
this.leftSubList = rightSubList;
this.rightSubList = leftSubList;
} else {
this.leftSubList = leftSubList;
this.rightSubList = rightSubList;
}
this.reversing = reversing;
rightFromIndex = this.rightSubList.fromIndex();
leftToIndex = this.leftSubList.getToIndex();
}
public SubList getLeftSubList() {
return leftSubList;
}
public SubList getRightSubList() {
return rightSubList;
}
public boolean isReversing() {
return reversing;
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
// If both subLists are on the same entity, then they must not overlap.
return leftSubList.entity() != rightSubList.entity() || rightFromIndex >= leftToIndex;
}
@Override
protected AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
if (leftSubList.entity() == rightSubList.entity()) {
return new SubListSwapMove<>(variableDescriptor,
new SubList(leftSubList.entity(), leftSubList.fromIndex(), rightSubList.length()),
new SubList(rightSubList.entity(),
rightSubList.fromIndex() - leftSubList.length() + rightSubList.length(),
leftSubList.length()),
reversing);
}
return new SubListSwapMove<>(variableDescriptor,
new SubList(rightSubList.entity(), rightSubList.fromIndex(), leftSubList.length()),
new SubList(leftSubList.entity(), leftSubList.fromIndex(), rightSubList.length()),
reversing);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
Object leftEntity = leftSubList.entity();
Object rightEntity = rightSubList.entity();
int leftSubListLength = leftSubList.length();
int rightSubListLength = rightSubList.length();
int leftFromIndex = leftSubList.fromIndex();
List<Object> leftList = variableDescriptor.getValue(leftEntity);
List<Object> rightList = variableDescriptor.getValue(rightEntity);
List<Object> leftSubListView = subList(leftSubList);
List<Object> rightSubListView = subList(rightSubList);
leftPlanningValueList = CollectionUtils.copy(leftSubListView, reversing);
rightPlanningValueList = CollectionUtils.copy(rightSubListView, reversing);
if (leftEntity == rightEntity) {
int fromIndex = Math.min(leftFromIndex, rightFromIndex);
int toIndex = leftFromIndex > rightFromIndex
? leftFromIndex + leftSubListLength
: rightFromIndex + rightSubListLength;
int leftSubListDestinationIndex = rightFromIndex + rightSubListLength - leftSubListLength;
innerScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex);
rightSubListView.clear();
subList(leftSubList).clear();
leftList.addAll(leftFromIndex, rightPlanningValueList);
rightList.addAll(leftSubListDestinationIndex, leftPlanningValueList);
innerScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex);
} else {
innerScoreDirector.beforeListVariableChanged(variableDescriptor,
leftEntity, leftFromIndex, leftFromIndex + leftSubListLength);
innerScoreDirector.beforeListVariableChanged(variableDescriptor,
rightEntity, rightFromIndex, rightFromIndex + rightSubListLength);
rightSubListView.clear();
leftSubListView.clear();
leftList.addAll(leftFromIndex, rightPlanningValueList);
rightList.addAll(rightFromIndex, leftPlanningValueList);
innerScoreDirector.afterListVariableChanged(variableDescriptor,
leftEntity, leftFromIndex, leftFromIndex + rightSubListLength);
innerScoreDirector.afterListVariableChanged(variableDescriptor,
rightEntity, rightFromIndex, rightFromIndex + leftSubListLength);
}
}
@Override
public SubListSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SubListSwapMove<>(
variableDescriptor,
leftSubList.rebase(destinationScoreDirector),
rightSubList.rebase(destinationScoreDirector),
reversing);
}
// ************************************************************************
// 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(leftSubList.entity());
entities.add(rightSubList.entity());
return entities;
}
@Override
public Collection<Object> getPlanningValues() {
return CollectionUtils.concat(leftPlanningValueList, rightPlanningValueList);
}
private List<Object> subList(SubList subList) {
return variableDescriptor.getValue(subList.entity()).subList(subList.fromIndex(), subList.getToIndex());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubListSwapMove<?> other = (SubListSwapMove<?>) o;
return reversing == other.reversing && rightFromIndex == other.rightFromIndex && leftToIndex == other.leftToIndex
&& variableDescriptor.equals(other.variableDescriptor)
&& leftSubList.equals(other.leftSubList)
&& rightSubList.equals(other.rightSubList);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, leftSubList, rightSubList, reversing, rightFromIndex, leftToIndex);
}
@Override
public String toString() {
return "{" + leftSubList + "} <-" + (reversing ? "reversing-" : "") + "> {" + rightSubList + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListSwapMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class SubListSwapMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, SubListSwapMoveSelectorConfig> {
public SubListSwapMoveSelectorFactory(SubListSwapMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
if (!randomSelection) {
throw new IllegalArgumentException("The subListSwapMoveSelector (" + config
+ ") only supports random selection order.");
}
SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
EntitySelector<Solution_> entitySelector = EntitySelectorFactory
.<Solution_> create(new EntitySelectorConfig())
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
SubListSelectorConfig subListSelectorConfig =
Objects.requireNonNullElseGet(config.getSubListSelectorConfig(), SubListSelectorConfig::new);
SubListSelectorConfig secondarySubListSelectorConfig =
Objects.requireNonNullElse(config.getSecondarySubListSelectorConfig(), subListSelectorConfig);
// minimum -> subListSelector
SubListConfigUtil.transferDeprecatedMinimumSubListSize(
config,
SubListSwapMoveSelectorConfig::getMinimumSubListSize,
"subListSelector", subListSelectorConfig);
// maximum -> subListSelector
SubListConfigUtil.transferDeprecatedMaximumSubListSize(
config,
SubListSwapMoveSelectorConfig::getMaximumSubListSize,
"subListSelector", subListSelectorConfig);
if (subListSelectorConfig != secondarySubListSelectorConfig) {
// minimum -> secondarySubListSelector
SubListConfigUtil.transferDeprecatedMinimumSubListSize(
config,
SubListSwapMoveSelectorConfig::getMinimumSubListSize,
"secondarySubListSelector", secondarySubListSelectorConfig);
// maximum -> secondarySubListSelector
SubListConfigUtil.transferDeprecatedMaximumSubListSize(
config,
SubListSwapMoveSelectorConfig::getMaximumSubListSize,
"secondarySubListSelector", secondarySubListSelectorConfig);
}
SubListSelector<Solution_> leftSubListSelector = SubListSelectorFactory
.<Solution_> create(subListSelectorConfig)
.buildSubListSelector(configPolicy, entitySelector, minimumCacheType, selectionOrder);
SubListSelector<Solution_> rightSubListSelector = SubListSelectorFactory
.<Solution_> create(secondarySubListSelectorConfig)
.buildSubListSelector(configPolicy, entitySelector, minimumCacheType, selectionOrder);
boolean selectReversingMoveToo = Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true);
return new RandomSubListSwapMoveSelector<>(leftSubListSelector, rightSubListSelector, selectReversingMoveToo);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListUnassignMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractSimplifiedMove;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
/**
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SubListUnassignMove<Solution_> extends AbstractSimplifiedMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object sourceEntity;
private final int sourceIndex;
private final int length;
private Collection<Object> planningValues;
public SubListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, SubList subList) {
this(variableDescriptor, subList.entity(), subList.fromIndex(), subList.length());
}
private SubListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex,
int length) {
this.variableDescriptor = variableDescriptor;
this.sourceEntity = sourceEntity;
this.sourceIndex = sourceIndex;
this.length = length;
}
public Object getSourceEntity() {
return sourceEntity;
}
public int getFromIndex() {
return sourceIndex;
}
public int getSubListSize() {
return length;
}
public int getToIndex() {
return sourceIndex + length;
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
var sourceList = variableDescriptor.getValue(sourceEntity);
var subList = sourceList.subList(sourceIndex, sourceIndex + length);
for (var element : subList) {
innerScoreDirector.beforeListVariableElementUnassigned(variableDescriptor, element);
innerScoreDirector.afterListVariableElementUnassigned(variableDescriptor, element);
}
innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + length);
subList.clear();
innerScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex);
}
@Override
public SubListUnassignMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new SubListUnassignMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(sourceEntity),
sourceIndex, length);
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<Object> getPlanningEntities() {
// Use LinkedHashSet for predictable iteration order.
var entities = new LinkedHashSet<>(2);
entities.add(sourceEntity);
return entities;
}
@Override
public Collection<Object> getPlanningValues() {
return planningValues;
}
@Override
public boolean equals(Object o) {
if (o instanceof SubListUnassignMove<?> other) {
return sourceIndex == other.sourceIndex && length == other.length
&& variableDescriptor.equals(other.variableDescriptor)
&& sourceEntity.equals(other.sourceEntity);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, sourceEntity, sourceIndex, length);
}
@Override
public String toString() {
return String.format("|%d| {%s[%d..%d] -> null}",
length, sourceEntity, sourceIndex, getToIndex());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/EntityOrderInfo.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
record EntityOrderInfo(Object[] entities, Map<Object, Integer> entityToEntityIndex, int[] offsets) {
public static <Node_> EntityOrderInfo of(Node_[] pickedValues, ListVariableStateSupply<?> listVariableStateSupply) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
var entityToEntityIndex = new IdentityHashMap<Object, Integer>();
for (int i = 1; i < pickedValues.length && pickedValues[i] != null; i++) {
var value = pickedValues[i];
var entity = listVariableStateSupply.getInverseSingleton(value);
if (!listVariableDescriptor.getEntityDescriptor().isMovable(null, entity)) {
throw new IllegalStateException("Impossible state: immovable entity (%s) picked through value (%s)."
.formatted(entity, value));
}
entityToEntityIndex.computeIfAbsent(entity, __ -> entityToEntityIndex.size());
}
var entities = new Object[entityToEntityIndex.size()];
var offsets = new int[entities.length];
for (var entityAndIndex : entityToEntityIndex.entrySet()) {
entities[entityAndIndex.getValue()] = entityAndIndex.getKey();
}
for (int i = 1; i < offsets.length; i++) {
offsets[i] = offsets[i - 1] + listVariableDescriptor.getListSize(entities[i - 1]);
}
return new EntityOrderInfo(entities, entityToEntityIndex, offsets);
}
public <Node_> EntityOrderInfo withNewNode(Node_ node, ListVariableStateSupply<?> listVariableStateSupply) {
Object entity = listVariableStateSupply.getInverseSingleton(node);
if (entityToEntityIndex.containsKey(entity)) {
return this;
} else {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
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);
}
}
@SuppressWarnings("unchecked")
public <Node_> Node_ successor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
var elementLocation = (LocationInList) listVariableStateSupply.getLocationInList(object);
var entity = elementLocation.entity();
var indexInEntityList = elementLocation.index();
var listVariable = listVariableDescriptor.getValue(entity);
if (indexInEntityList == listVariable.size() - 1) {
var nextEntityIndex = (entityToEntityIndex.get(entity) + 1) % entities.length;
var nextEntity = entities[nextEntityIndex];
var firstUnpinnedIndexInList = listVariableDescriptor.getFirstUnpinnedIndex(nextEntity);
return (Node_) listVariableDescriptor.getElement(nextEntity, firstUnpinnedIndexInList);
} else {
return (Node_) listVariable.get(indexInEntityList + 1);
}
}
@SuppressWarnings("unchecked")
public <Node_> Node_ predecessor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
var elementLocation = (LocationInList) listVariableStateSupply.getLocationInList(object);
var entity = elementLocation.entity();
var indexInEntityList = elementLocation.index();
var firstUnpinnedIndexInList = listVariableDescriptor.getFirstUnpinnedIndex(entity);
if (indexInEntityList == firstUnpinnedIndexInList) {
// add entities.length to ensure modulo result is positive
int previousEntityIndex = (entityToEntityIndex.get(entity) - 1 + entities.length) % entities.length;
var listVariable = listVariableDescriptor.getValue(entities[previousEntityIndex]);
return (Node_) listVariable.get(listVariable.size() - 1);
} else {
return (Node_) listVariableDescriptor.getElement(entity, indexInEntityList - 1);
}
}
public <Node_> boolean between(Node_ start, Node_ middle, Node_ end, ListVariableStateSupply<?> listVariableStateSupply) {
var startElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(start);
var middleElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(middle);
var endElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(end);
int startEntityIndex = entityToEntityIndex.get(startElementLocation.entity());
int middleEntityIndex = entityToEntityIndex.get(middleElementLocation.entity());
int endEntityIndex = entityToEntityIndex.get(endElementLocation.entity());
int startIndex = startElementLocation.index() + offsets[startEntityIndex];
int middleIndex = middleElementLocation.index() + offsets[middleEntityIndex];
int endIndex = endElementLocation.index() + 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;
}
}
@Override
public boolean equals(Object o) {
return o instanceof EntityOrderInfo that
&& Arrays.equals(entities, that.entities)
&& Objects.equals(entityToEntityIndex, that.entityToEntityIndex)
&& Arrays.equals(offsets, that.offsets);
}
@Override
public int hashCode() {
int result = Objects.hash(entityToEntityIndex);
result = 31 * result + Arrays.hashCode(entities);
result = 31 * result + Arrays.hashCode(offsets);
return result;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/FlipSublistAction.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.Collections;
import java.util.List;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
/**
* Flips a sublist of a list variable, (the same thing as a {@link TwoOptListMove}, but no shift to restore the original
* origin).
* For instance, given [0, 1, 2, 3, 4], fromIndexInclusive = 1, toIndexExclusive = 3,
* the list after the move would be [0, 3, 2, 1, 4].
* If toIndexExclusive is before fromIndexInclusive,
* the flip is performed on the combined sublists [fromIndexInclusive, size) and [0, toIndexExclusive).
* For instance, given [0, 1, 2, 3, 4, 5, 6], fromIndexInclusive = 5, toIndexExclusive = 2,
* the list after the move would be [6, 5, 2, 3, 4, 1, 0] (and not [0, 6, 5, 2, 3, 4, 1]).
*/
record FlipSublistAction(ListVariableDescriptor<?> variableDescriptor, int fromIndexInclusive, int toIndexExclusive) {
FlipSublistAction createUndoMove() {
return new FlipSublistAction(variableDescriptor, fromIndexInclusive, toIndexExclusive);
}
public KOptAffectedElements getAffectedElements() {
if (fromIndexInclusive < toIndexExclusive) {
return KOptAffectedElements.forMiddleRange(fromIndexInclusive, toIndexExclusive);
} else {
return KOptAffectedElements.forWrappedRange(fromIndexInclusive, toIndexExclusive);
}
}
void doMoveOnGenuineVariables(MultipleDelegateList<?> combinedList) {
// MultipleDelegateList uses subLists starting from entityFirstUnpinnedIndex,
// so we should use 0 as the start of the list (as we are flipping the entire
// combinedList of sub-lists instead of a particular entity list).
flipSublist(combinedList, 0, fromIndexInclusive, toIndexExclusive);
}
public FlipSublistAction rebase() {
return new FlipSublistAction(variableDescriptor, fromIndexInclusive, toIndexExclusive);
}
public static <T> void flipSublist(List<T> originalList, int entityFirstUnpinnedIndex, int fromIndexInclusive,
int toIndexExclusive) {
if (fromIndexInclusive < toIndexExclusive) {
Collections.reverse(originalList.subList(fromIndexInclusive, toIndexExclusive));
} else {
var firstHalfReversedPath = originalList.subList(fromIndexInclusive, originalList.size());
var secondHalfReversedPath = originalList.subList(entityFirstUnpinnedIndex, toIndexExclusive);
// Reverse the combined list firstHalfReversedPath + secondHalfReversedPath
// For instance, (1, 2, 3)(4, 5, 6, 7, 8, 9) becomes
// (9, 8, 7)(6, 5, 4, 3, 2, 1)
var totalLength = firstHalfReversedPath.size() + secondHalfReversedPath.size();
for (var i = 0; (i < totalLength >> 1); i++) {
if (i < firstHalfReversedPath.size()) {
if (i < secondHalfReversedPath.size()) {
// firstHalfIndex = i
var secondHalfIndex = secondHalfReversedPath.size() - i - 1;
var savedFirstItem = firstHalfReversedPath.get(i);
firstHalfReversedPath.set(i, secondHalfReversedPath.get(secondHalfIndex));
secondHalfReversedPath.set(secondHalfIndex, savedFirstItem);
} else {
// firstIndex = i
var secondIndex = firstHalfReversedPath.size() - i + secondHalfReversedPath.size() - 1;
var savedFirstItem = firstHalfReversedPath.get(i);
firstHalfReversedPath.set(i, firstHalfReversedPath.get(secondIndex));
firstHalfReversedPath.set(secondIndex, savedFirstItem);
}
} else {
var firstIndex = i - firstHalfReversedPath.size();
var secondIndex = secondHalfReversedPath.size() - i - 1;
var savedFirstItem = secondHalfReversedPath.get(firstIndex);
secondHalfReversedPath.set(firstIndex, secondHalfReversedPath.get(secondIndex));
secondHalfReversedPath.set(secondIndex, savedFirstItem);
}
}
}
}
@Override
public String toString() {
return "FlipSublistAction(from=" + fromIndexInclusive + ", to=" + toIndexExclusive + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptDescriptor.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.IntStream;
import ai.timefold.solver.core.api.function.TriPredicate;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.index.IndexVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
/**
*
* @param k the number of edges being added
* @param removedEdges sequence of 2k nodes that forms the sequence of edges being removed
* @param removedEdgeIndexToTourOrder node visit order when the tour is traveled in the successor direction.
* This forms a 2k-cycle representing the permutation performed by the K-opt move.
* @param inverseRemovedEdgeIndexToTourOrder node visit order when the tour is traveled in the predecessor direction.
* It is the inverse of {@link KOptDescriptor#removedEdgeIndexToTourOrder}
* (i.e. {@link KOptDescriptor#removedEdgeIndexToTourOrder}[inverseRemovedEdgeIndexToTourOrder[i]] == i
* @param addedEdgeToOtherEndpoint maps the index of a removed edge endpoint to its corresponding added edge other endpoint.
* For instance, if the removed edges are (a, b), (c, d), (e, f) and the added edges are (a, d), (c, f), (e, b), then
* <br />
* removedEdges = [null, a, b, c, d, e, f] <br />
* addedEdgeToOtherEndpoint = [null, 4, 5, 6, 1, 2, 3] <br />
* <br />
* For any valid removedEdges index, (removedEdges[index], removedEdges[addedEdgeToOtherEndpoint[index]])
* is an edge added by this K-Opt move.
* @param <Node_>
*/
record KOptDescriptor<Node_>(int k, Node_[] removedEdges, int[] removedEdgeIndexToTourOrder,
int[] inverseRemovedEdgeIndexToTourOrder, int[] addedEdgeToOtherEndpoint) {
static <Node_> int[] computeInEdgesForSequentialMove(Node_[] removedEdges) {
var out = new int[removedEdges.length];
var k = (removedEdges.length - 1) >> 1;
out[1] = removedEdges.length - 1;
out[removedEdges.length - 1] = 1;
for (var i = 1; i < k; i++) {
out[2 * i + 1] = 2 * i;
out[2 * i] = 2 * i + 1;
}
return out;
}
/**
* Create a sequential {@link KOptDescriptor} from the given removed edges.
*
* @param removedEdges The edges removed from the tour. The added edges will
* be formed from opposite endpoints for consecutive edges.
* @param endpointToSuccessorFunction A {@link Function} that maps an endpoint to its successor
* @param betweenPredicate A {@link TriPredicate} that return true if and only if its middle
* argument is between its first and last argument when the tour is
* taken in the successor direction.
*/
KOptDescriptor(
Node_[] removedEdges,
Function<Node_, Node_> endpointToSuccessorFunction,
TriPredicate<Node_, Node_, Node_> betweenPredicate) {
this(removedEdges, computeInEdgesForSequentialMove(removedEdges), endpointToSuccessorFunction, betweenPredicate);
}
/**
* Create as sequential or non-sequential {@link KOptDescriptor} from the given removed
* and added edges.
*
* @param removedEdges The edges removed from the tour.
* @param addedEdgeToOtherEndpoint The edges added to the tour.
* @param endpointToSuccessorFunction A {@link Function} that maps an endpoint to its successor
* @param betweenPredicate A {@link TriPredicate} that return true if and only if its middle
* argument is between its first and last argument when the tour is
* taken in the successor direction.
*/
KOptDescriptor(
Node_[] removedEdges,
int[] addedEdgeToOtherEndpoint,
Function<Node_, Node_> endpointToSuccessorFunction,
TriPredicate<Node_, Node_, Node_> betweenPredicate) {
this((removedEdges.length - 1) >> 1, removedEdges, new int[removedEdges.length], new int[removedEdges.length],
addedEdgeToOtherEndpoint);
// Compute the permutation as described in FindPermutation
// (Section 5.3 "Determination of the feasibility of a move",
// An Effective Implementation of K-opt Moves for the Lin-Kernighan TSP Heuristic)
for (int i = 1, j = 1; j <= k; i += 2, j++) {
removedEdgeIndexToTourOrder[j] =
(endpointToSuccessorFunction.apply(removedEdges[i]) == removedEdges[i + 1]) ? i : i + 1;
}
Comparator<Integer> comparator = (pa, pb) -> pa.equals(pb) ? 0
: (betweenPredicate.test(removedEdges[removedEdgeIndexToTourOrder[1]], removedEdges[pa], removedEdges[pb]) ? -1
: 1);
var wrappedRemovedEdgeIndexToTourOrder = IntStream.of(removedEdgeIndexToTourOrder).boxed()
.toArray(Integer[]::new);
Arrays.sort(wrappedRemovedEdgeIndexToTourOrder, 2, k + 1, comparator);
for (var i = 0; i < removedEdgeIndexToTourOrder.length; i++) {
removedEdgeIndexToTourOrder[i] = wrappedRemovedEdgeIndexToTourOrder[i];
}
for (int i, j = 2 * k; j >= 2; j -= 2) {
removedEdgeIndexToTourOrder[j - 1] = i = removedEdgeIndexToTourOrder[j / 2];
removedEdgeIndexToTourOrder[j] = ((i & 1) == 1) ? i + 1 : i - 1;
}
for (var i = 1; i <= 2 * k; i++) {
inverseRemovedEdgeIndexToTourOrder[removedEdgeIndexToTourOrder[i]] = i;
}
}
// ****************************************************
// Complex Methods
// ****************************************************
/**
* This return a {@link KOptListMove} that corresponds to this {@link KOptDescriptor}. <br />
* <br />
* It implements the algorithm described in the paper
* <a href="https://dl.acm.org/doi/pdf/10.1145/300515.300516">"Transforming Cabbage into Turnip: Polynomial
* Algorithm for Sorting Signed Permutations by Reversals"</a> which is used in the paper
* <a href="http://webhotel4.ruc.dk/~keld/research/LKH/KoptReport.pdf">"An Effective Implementation of K-opt Moves
* for the Lin-Kernighan TSP Heuristic"</a> (Section 5.4 "Execution of a feasible move") to perform a K-opt move
* by performing the minimal number of list reversals to transform the current route into the new route after the
* K-opt. We use it here to calculate the {@link FlipSublistAction} list for the {@link KOptListMove} that is
* described by this {@link KOptDescriptor}.<br />
* <br />
* The algorithm goal is to convert a signed permutation (p_1, p_2, ..., p_(2k)) into the identify permutation
* (+1, +2, +3, ..., +(2k - 1), +2k). It can be summarized as:
*
* <ul>
* <li>
* As long as there are oriented pairs, perform the reversal that corresponds to the oriented pair with the
* maximal score (described in {@link #countOrientedPairsForReversal}).
* </li>
* <li>
* If there are no oriented pairs, Find the pair (p_i, p_j) for which |p_j – p_i| = 1, j >= i + 3,
* and i is minimal. Then reverse the segment (p_(i+1) ... p_(j-1). This corresponds to a
* hurdle cutting operation. Normally, this is not enough to guarantee the number of reversals
* is optimal, but since each hurdle corresponds to a unique cycle, the number of hurdles in
* the list at any point is at most 1 (and thus, hurdle cutting is the optimal move). (A hurdle
* is an subsequence [i, p_j, p_(j+1)..., p_(j+k-1) i+k] that can be sorted so
* [i, p_j, p_(j+1)..., p_(j+k-1), i+k] are all consecutive integers, which does not contain a subsequence
* with the previous property ([4, 7, 6, 5, 8] is a hurdle, since the subsequence [7, 6, 5] does not
* contain all the items between 7 and 5 [8, 1, 2, 3, 4]). This create enough enough oriented pairs
* to completely sort the permutation.
* </li>
* <li>
* When there are no oriented pairs and no hurdles, the algorithm is completed.
* </li>
* </ul>
*/
public <Solution_> KOptListMove<Solution_> getKOptListMove(ListVariableStateSupply<Solution_> listVariableStateSupply) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
if (!isFeasible()) {
// A KOptListMove move with an empty flip move list is not feasible, since if executed, it's a no-op.
return new KOptListMove<>(listVariableDescriptor, this, new MultipleDelegateList<>(), List.of(), 0, new int[] {});
}
var combinedList = computeCombinedList(listVariableDescriptor, listVariableStateSupply);
IndexVariableSupply indexVariableSupply =
node -> combinedList.getIndexOfValue(listVariableStateSupply, node);
var entityListSize = combinedList.size();
List<FlipSublistAction> out = new ArrayList<>();
var originalToCurrentIndexList = new int[entityListSize];
for (var index = 0; index < entityListSize; index++) {
originalToCurrentIndexList[index] = index;
}
var isMoveNotDone = true;
var bestOrientedPairFirstEndpoint = -1;
var bestOrientedPairSecondEndpoint = -1;
// Copy removedEdgeIndexToTourOrder and inverseRemovedEdgeIndexToTourOrder
// to avoid mutating the original arrays
// since this function mutates the arrays into the sorted signed permutation (+1, +2, ...).
var currentRemovedEdgeIndexToTourOrder =
Arrays.copyOf(removedEdgeIndexToTourOrder, removedEdgeIndexToTourOrder.length);
var currentInverseRemovedEdgeIndexToTourOrder =
Arrays.copyOf(inverseRemovedEdgeIndexToTourOrder, inverseRemovedEdgeIndexToTourOrder.length);
FindNextReversal: while (isMoveNotDone) {
var maximumOrientedPairCountAfterReversal = -1;
for (var firstEndpoint = 1; firstEndpoint <= 2 * k - 2; firstEndpoint++) {
var firstEndpointCurrentTourIndex = currentRemovedEdgeIndexToTourOrder[firstEndpoint];
var nextEndpointTourIndex = addedEdgeToOtherEndpoint[firstEndpointCurrentTourIndex];
var secondEndpoint = currentInverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex];
if (secondEndpoint >= firstEndpoint + 2 && (firstEndpoint & 1) == (secondEndpoint & 1)) {
var orientedPairCountAfterReversal = ((firstEndpoint & 1) == 1)
? countOrientedPairsForReversal(currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
firstEndpoint + 1,
secondEndpoint)
: countOrientedPairsForReversal(currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
firstEndpoint,
secondEndpoint - 1);
if (orientedPairCountAfterReversal > maximumOrientedPairCountAfterReversal) {
maximumOrientedPairCountAfterReversal = orientedPairCountAfterReversal;
bestOrientedPairFirstEndpoint = firstEndpoint;
bestOrientedPairSecondEndpoint = secondEndpoint;
}
}
}
if (maximumOrientedPairCountAfterReversal >= 0) {
if ((bestOrientedPairFirstEndpoint & 1) == 1) {
out.add(getListReversalMoveForEdgePair(listVariableDescriptor, indexVariableSupply,
originalToCurrentIndexList,
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint + 1]],
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint]],
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint]],
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint + 1]]));
reversePermutationPart(currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
bestOrientedPairFirstEndpoint + 1,
bestOrientedPairSecondEndpoint);
} else {
out.add(getListReversalMoveForEdgePair(listVariableDescriptor, indexVariableSupply,
originalToCurrentIndexList,
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint - 1]],
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint]],
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint]],
removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint - 1]]));
reversePermutationPart(currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
bestOrientedPairFirstEndpoint,
bestOrientedPairSecondEndpoint - 1);
}
continue;
}
// There are no oriented pairs; check for a hurdle
for (var firstEndpoint = 1; firstEndpoint <= 2 * k - 1; firstEndpoint += 2) {
var firstEndpointCurrentTourIndex = currentRemovedEdgeIndexToTourOrder[firstEndpoint];
var nextEndpointTourIndex = addedEdgeToOtherEndpoint[firstEndpointCurrentTourIndex];
var secondEndpoint = currentInverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex];
if (secondEndpoint >= firstEndpoint + 2) {
out.add(getListReversalMoveForEdgePair(listVariableDescriptor, indexVariableSupply,
originalToCurrentIndexList,
removedEdges[currentRemovedEdgeIndexToTourOrder[firstEndpoint]],
removedEdges[currentRemovedEdgeIndexToTourOrder[firstEndpoint + 1]],
removedEdges[currentRemovedEdgeIndexToTourOrder[secondEndpoint]],
removedEdges[currentRemovedEdgeIndexToTourOrder[secondEndpoint - 1]]));
reversePermutationPart(currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
firstEndpoint + 1, secondEndpoint - 1);
continue FindNextReversal;
}
}
isMoveNotDone = false;
}
var startElementShift = -indexOf(originalToCurrentIndexList, 0);
var newEndIndices = new int[combinedList.delegates.length];
var totalOffset = 0;
for (var i = 0; i < newEndIndices.length; i++) {
var listSize = combinedList.delegateSizes[i];
newEndIndices[i] = totalOffset + listSize - 1;
totalOffset += listSize;
}
newEndIndices = IntStream.of(newEndIndices)
.map(index -> indexOf(originalToCurrentIndexList, index))
.sorted()
.toArray();
newEndIndices[newEndIndices.length - 1] = originalToCurrentIndexList.length - 1;
return new KOptListMove<>(listVariableDescriptor, this, combinedList, out, startElementShift, newEndIndices);
}
/**
* Return true if and only if performing the K-opt move described by this {@link KOptDescriptor} will result in a
* single cycle.
*
* @param minK
* @param maxK
* @return true if and only if performing the K-opt move described by this {@link KOptDescriptor} will result in a
* single cycle, false otherwise.
*/
public boolean isFeasible(int minK, int maxK) {
if (k < minK || k > maxK) {
throw new IllegalStateException("Impossible state: The k-opt move k-value (%d) is not in the range [%d, %d]."
.formatted(k, minK, maxK));
}
return isFeasible();
}
private boolean isFeasible() {
var count = 0;
var currentEndpoint = 2 * k;
// This loop calculate the length of the cycle that the endpoint at removedEdges[2k] is connected
// to by iterating the loop in reverse. We know that the successor of removedEdges[2k] is 0, which
// give us our terminating condition.
while (currentEndpoint != 0) {
count++;
var currentEndpointTourIndex = removedEdgeIndexToTourOrder[currentEndpoint];
var nextEndpointTourIndex = addedEdgeToOtherEndpoint[currentEndpointTourIndex];
currentEndpoint = inverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex] ^ 1;
}
return (count == k);
}
/**
* Reverse an array between two indices and update its inverse array to point at the new locations.
*
* @param startInclusive Reverse the array starting at and including this index.
* @param endExclusive Reverse the array ending at and excluding this index.
*/
private void reversePermutationPart(int[] currentRemovedEdgeIndexToTourOrder,
int[] currentInverseRemovedEdgeIndexToTourOrder,
int startInclusive, int endExclusive) {
while (startInclusive < endExclusive) {
var savedFirstElement = currentRemovedEdgeIndexToTourOrder[startInclusive];
currentRemovedEdgeIndexToTourOrder[startInclusive] = currentRemovedEdgeIndexToTourOrder[endExclusive];
currentInverseRemovedEdgeIndexToTourOrder[currentRemovedEdgeIndexToTourOrder[endExclusive]] = startInclusive;
currentRemovedEdgeIndexToTourOrder[endExclusive] = savedFirstElement;
currentInverseRemovedEdgeIndexToTourOrder[savedFirstElement] = endExclusive;
startInclusive++;
endExclusive--;
}
}
/**
* Calculate the "score" of performing a flip on a signed permutation p.<br>
* <br>
* Let p = (p_1 ..., p_n) be a signed permutation. An oriented pair (p_i, p_j) is a pair
* of adjacent integers, that is |p_i| - |p_j| = ±1, with opposite signs. For example,
* the signed permutation <br />
* (+1 -2 -5 +4 +3) <br />
* contains three oriented pairs: (+1, -2), (-2, +3), and (-5, +4).
* Oriented pairs are useful as they indicate reversals that cause adjacent integers to be
* consecutive in the resulting permutation. For example, the oriented pair (-2, +3) induces
* the reversal <br>
* (+1 -2 -5 +4 +3) -> (+1 -4 +5 +2 +3) <br>
* creating a permutation where +3 is consecutive to +2. <br />
* <br />
* In general, the reversal induced by and oriented pair (p_i, p_j) is <br />
* p(i, j-1), if p_i + p_j = +1, and <br />
* p(i+1, j), if p_i + p_j = -1 <br />
* Such a reversal is called an oriented reversal. <br />
*
* The score of an oriented reversal is defined as the number of oriented pairs
* in the resulting permutation. <br />
* <br />
* This function perform the reversal indicated by the oriented pair, count the
* number of oriented pairs in the new permutation, undo the reversal and return
* the score.
*
* @param left The left endpoint of the flip
* @param right the right endpoint of the flip
* @return The score of the performing the signed reversal
*/
private int countOrientedPairsForReversal(int[] currentRemovedEdgeIndexToTourOrder,
int[] currentInverseRemovedEdgeIndexToTourOrder, int left, int right) {
int count = 0, i, j;
reversePermutationPart(
currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
left, right);
for (i = 1; i <= 2 * k - 2; i++) {
var currentTourIndex = currentRemovedEdgeIndexToTourOrder[i];
var otherEndpointTourIndex = addedEdgeToOtherEndpoint[currentTourIndex];
j = currentInverseRemovedEdgeIndexToTourOrder[otherEndpointTourIndex];
if (j >= i + 2 && (i & 1) == (j & 1)) {
count++;
}
}
reversePermutationPart(
currentRemovedEdgeIndexToTourOrder,
currentInverseRemovedEdgeIndexToTourOrder,
left, right);
return count;
}
/**
* Get a {@link FlipSublistAction} that reverses the sublist that consists of the path
* between the start and end of the given edges.
*
* @param listVariableDescriptor
* @param indexVariableSupply
* @param originalToCurrentIndexList
* @param firstEdgeStart
* @param firstEdgeEnd
* @param secondEdgeStart
* @param secondEdgeEnd
* @return
*/
@SuppressWarnings("unchecked")
private static <Node_> FlipSublistAction getListReversalMoveForEdgePair(
ListVariableDescriptor<?> listVariableDescriptor,
IndexVariableSupply indexVariableSupply,
int[] originalToCurrentIndexList,
Node_ firstEdgeStart,
Node_ firstEdgeEnd,
Node_ secondEdgeStart,
Node_ secondEdgeEnd) {
var originalFirstEdgeStartIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(firstEdgeStart));
var originalFirstEdgeEndIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(firstEdgeEnd));
var originalSecondEdgeStartIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(secondEdgeStart));
var originalSecondEdgeEndIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(secondEdgeEnd));
var firstEndpoint = ((originalFirstEdgeStartIndex + 1) % originalToCurrentIndexList.length) == originalFirstEdgeEndIndex
? originalFirstEdgeEndIndex
: originalFirstEdgeStartIndex;
var secondEndpoint =
((originalSecondEdgeStartIndex + 1) % originalToCurrentIndexList.length) == originalSecondEdgeEndIndex
? originalSecondEdgeEndIndex
: originalSecondEdgeStartIndex;
KOptUtils.flipSubarray(originalToCurrentIndexList, firstEndpoint, secondEndpoint);
return new FlipSublistAction(listVariableDescriptor, firstEndpoint, secondEndpoint);
}
@SuppressWarnings("unchecked")
private MultipleDelegateList<Node_> computeCombinedList(ListVariableDescriptor<?> listVariableDescriptor,
SingletonInverseVariableSupply inverseVariableSupply) {
var entityToEntityIndex = new IdentityHashMap<Object, Integer>();
for (var i = 1; i < removedEdges.length; i++) {
entityToEntityIndex.computeIfAbsent(inverseVariableSupply.getInverseSingleton(removedEdges[i]),
entity -> entityToEntityIndex.size());
}
var entities = new Object[entityToEntityIndex.size()];
List<Node_>[] entityLists = new List[entities.length];
for (var entry : entityToEntityIndex.entrySet()) {
int index = entry.getValue();
Object entity = entry.getKey();
entities[index] = entity;
entityLists[index] = (List<Node_>) listVariableDescriptor.getUnpinnedSubList(entity);
}
return new MultipleDelegateList<>(entities, entityLists);
}
private static int indexOf(int[] search, int query) {
for (var i = 0; i < search.length; i++) {
if (search[i] == query) {
return i;
}
}
return -1;
}
@Override
public boolean equals(Object o) {
return o instanceof KOptDescriptor<?> that
&& k == that.k
&& Arrays.equals(removedEdges, that.removedEdges)
&& Arrays.equals(removedEdgeIndexToTourOrder, that.removedEdgeIndexToTourOrder)
&& Arrays.equals(inverseRemovedEdgeIndexToTourOrder, that.inverseRemovedEdgeIndexToTourOrder)
&& Arrays.equals(addedEdgeToOtherEndpoint, that.addedEdgeToOtherEndpoint);
}
@Override
public int hashCode() {
int result = Objects.hash(k);
result = 31 * result + Arrays.hashCode(removedEdges);
result = 31 * result + Arrays.hashCode(removedEdgeIndexToTourOrder);
result = 31 * result + Arrays.hashCode(inverseRemovedEdgeIndexToTourOrder);
result = 31 * result + Arrays.hashCode(addedEdgeToOtherEndpoint);
return result;
}
public String toString() {
return k + "-opt(removed=" + KOptUtils.getRemovedEdgeList(this) + "\n, added=" + KOptUtils.getAddedEdgeList(this) + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class KOptListMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final KOptDescriptor<?> descriptor;
private final List<FlipSublistAction> equivalent2Opts;
private final KOptAffectedElements affectedElementsInfo;
private final int postShiftAmount;
private final int[] newEndIndices;
private final Object[] originalEntities;
KOptListMove(ListVariableDescriptor<Solution_> listVariableDescriptor,
KOptDescriptor<?> descriptor,
MultipleDelegateList<?> combinedList,
List<FlipSublistAction> equivalent2Opts,
int postShiftAmount,
int[] newEndIndices) {
this.listVariableDescriptor = listVariableDescriptor;
this.descriptor = descriptor;
this.equivalent2Opts = equivalent2Opts;
this.postShiftAmount = postShiftAmount;
this.newEndIndices = newEndIndices;
if (equivalent2Opts.isEmpty()) {
affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, 0);
} else if (postShiftAmount != 0) {
affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, combinedList.size());
} else {
var currentAffectedElements = equivalent2Opts.get(0).getAffectedElements();
for (var i = 1; i < equivalent2Opts.size(); i++) {
currentAffectedElements = currentAffectedElements.merge(equivalent2Opts.get(i).getAffectedElements());
}
affectedElementsInfo = currentAffectedElements;
}
originalEntities = combinedList.delegateEntities;
}
private KOptListMove(ListVariableDescriptor<Solution_> listVariableDescriptor,
KOptDescriptor<?> descriptor,
List<FlipSublistAction> equivalent2Opts,
int postShiftAmount,
int[] newEndIndices,
Object[] originalEntities) {
this.listVariableDescriptor = listVariableDescriptor;
this.descriptor = descriptor;
this.equivalent2Opts = equivalent2Opts;
this.postShiftAmount = postShiftAmount;
this.newEndIndices = newEndIndices;
if (equivalent2Opts.isEmpty()) {
affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, 0);
} else if (postShiftAmount != 0) {
affectedElementsInfo = KOptAffectedElements.forMiddleRange(0,
computeCombinedList(listVariableDescriptor, originalEntities).size());
} else {
var currentAffectedElements = equivalent2Opts.get(0).getAffectedElements();
for (var i = 1; i < equivalent2Opts.size(); i++) {
currentAffectedElements = currentAffectedElements.merge(equivalent2Opts.get(i).getAffectedElements());
}
affectedElementsInfo = currentAffectedElements;
}
this.originalEntities = originalEntities;
}
KOptDescriptor<?> getDescriptor() {
return descriptor;
}
@Override
protected AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
if (equivalent2Opts.isEmpty()) {
return this;
} else {
List<FlipSublistAction> inverse2Opts = new ArrayList<>(equivalent2Opts.size());
for (var i = equivalent2Opts.size() - 1; i >= 0; i--) {
inverse2Opts.add(equivalent2Opts.get(i).createUndoMove());
}
var combinedList = computeCombinedList(listVariableDescriptor, originalEntities);
var originalEndIndices = new int[newEndIndices.length];
for (var i = 0; i < originalEndIndices.length - 1; i++) {
originalEndIndices[i] = combinedList.offsets[i + 1] - 1;
}
originalEndIndices[originalEndIndices.length - 1] = combinedList.size() - 1;
return new UndoKOptListMove<>(listVariableDescriptor, descriptor, inverse2Opts, -postShiftAmount,
originalEndIndices, originalEntities);
}
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
var combinedList = computeCombinedList(listVariableDescriptor, originalEntities);
combinedList.actOnAffectedElements(listVariableDescriptor,
originalEntities,
(entity, start, end) -> innerScoreDirector.beforeListVariableChanged(listVariableDescriptor, entity,
start,
end));
// subLists will get corrupted by ConcurrentModifications, so do the operations
// on a clone
var combinedListCopy = combinedList.copy();
for (var move : equivalent2Opts) {
move.doMoveOnGenuineVariables(combinedListCopy);
}
combinedListCopy.moveElementsOfDelegates(newEndIndices);
Collections.rotate(combinedListCopy, postShiftAmount);
combinedList.applyChangesFromCopy(combinedListCopy);
combinedList.actOnAffectedElements(listVariableDescriptor,
originalEntities,
(entity, start, end) -> innerScoreDirector.afterListVariableChanged(listVariableDescriptor, entity,
start,
end));
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return !equivalent2Opts.isEmpty();
}
@Override
public KOptListMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
var rebasedEquivalent2Opts = new ArrayList<FlipSublistAction>(equivalent2Opts.size());
var innerScoreDirector = (InnerScoreDirector<?, ?>) destinationScoreDirector;
var newEntities = new Object[originalEntities.length];
for (var i = 0; i < newEntities.length; i++) {
newEntities[i] = innerScoreDirector.lookUpWorkingObject(originalEntities[i]);
}
for (var twoOpt : equivalent2Opts) {
rebasedEquivalent2Opts.add(twoOpt.rebase());
}
return new KOptListMove<>(listVariableDescriptor, descriptor, rebasedEquivalent2Opts, postShiftAmount, newEndIndices,
newEntities);
}
@Override
public String getSimpleMoveTypeDescription() {
return descriptor.k() + "-opt(" + listVariableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<?> getPlanningEntities() {
return List.of(originalEntities);
}
@Override
public Collection<?> getPlanningValues() {
var out = new ArrayList<>();
var combinedList = computeCombinedList(listVariableDescriptor, originalEntities);
if (affectedElementsInfo.wrappedStartIndex() != -1) {
out.addAll(combinedList.subList(affectedElementsInfo.wrappedStartIndex(), combinedList.size()));
out.addAll(combinedList.subList(0, affectedElementsInfo.wrappedEndIndex()));
}
for (var affectedRange : affectedElementsInfo.affectedMiddleRangeList()) {
out.addAll(combinedList.subList(affectedRange.startInclusive(), affectedRange.endExclusive()));
}
return out;
}
public String toString() {
return descriptor.toString();
}
private static <Solution_> MultipleDelegateList<?>
computeCombinedList(ListVariableDescriptor<Solution_> listVariableDescriptor, Object[] entities) {
@SuppressWarnings("unchecked")
List<Object>[] delegates = new List[entities.length];
for (var i = 0; i < entities.length; i++) {
delegates[i] = listVariableDescriptor.getUnpinnedSubList(entities[i]);
}
return new MultipleDelegateList<>(entities, delegates);
}
/**
* A K-Opt move that does the list rotation before performing the flips instead of after, allowing
* it to act as the undo move of a K-Opt move that does the rotation after the flips.
*
* @param <Solution_>
*/
private static final class UndoKOptListMove<Solution_, Node_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final KOptDescriptor<Node_> descriptor;
private final List<FlipSublistAction> equivalent2Opts;
private final int preShiftAmount;
private final int[] newEndIndices;
private final Object[] originalEntities;
public UndoKOptListMove(ListVariableDescriptor<Solution_> listVariableDescriptor,
KOptDescriptor<Node_> descriptor,
List<FlipSublistAction> equivalent2Opts,
int preShiftAmount,
int[] newEndIndices,
Object[] originalEntities) {
this.listVariableDescriptor = listVariableDescriptor;
this.descriptor = descriptor;
this.equivalent2Opts = equivalent2Opts;
this.preShiftAmount = preShiftAmount;
this.newEndIndices = newEndIndices;
this.originalEntities = originalEntities;
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
@Override
protected AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
throw new UnsupportedOperationException();
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
var combinedList = computeCombinedList(listVariableDescriptor, originalEntities);
combinedList.actOnAffectedElements(
listVariableDescriptor,
originalEntities,
(entity, start, end) -> innerScoreDirector.beforeListVariableChanged(listVariableDescriptor, entity,
start,
end));
// subLists will get corrupted by ConcurrentModifications, so do the operations
// on a clone
var combinedListCopy = combinedList.copy();
Collections.rotate(combinedListCopy, preShiftAmount);
combinedListCopy.moveElementsOfDelegates(newEndIndices);
for (var move : equivalent2Opts) {
move.doMoveOnGenuineVariables(combinedListCopy);
}
combinedList.applyChangesFromCopy(combinedListCopy);
combinedList.actOnAffectedElements(listVariableDescriptor,
originalEntities,
(entity, start, end) -> innerScoreDirector.afterListVariableChanged(listVariableDescriptor, entity,
start,
end));
}
public String toString() {
return "Undo" + descriptor.toString();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
final class KOptListMoveIterator<Solution_, Node_> extends UpcomingSelectionIterator<Move<Solution_>> {
private final Random workingRandom;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final ListVariableStateSupply<Solution_> listVariableStateSupply;
private final EntityIndependentValueSelector<Node_> originSelector;
private final EntityIndependentValueSelector<Node_> valueSelector;
private final int minK;
private final int[] pickedKDistribution;
private final int pickedKDistributionSum;
private final int maxCyclesPatchedInInfeasibleMove;
public KOptListMoveIterator(Random workingRandom, ListVariableDescriptor<Solution_> listVariableDescriptor,
ListVariableStateSupply<Solution_> listVariableStateSupply, EntityIndependentValueSelector<Node_> originSelector,
EntityIndependentValueSelector<Node_> valueSelector, int minK, int maxK, int[] pickedKDistribution) {
this.workingRandom = workingRandom;
this.listVariableDescriptor = listVariableDescriptor;
this.listVariableStateSupply = listVariableStateSupply;
this.originSelector = originSelector;
this.valueSelector = valueSelector;
this.minK = minK;
this.pickedKDistribution = pickedKDistribution;
var tmpPickedKDistributionSum = 0;
for (var relativeDistributionAmount : pickedKDistribution) {
tmpPickedKDistributionSum += relativeDistributionAmount;
}
this.pickedKDistributionSum = tmpPickedKDistributionSum;
this.maxCyclesPatchedInInfeasibleMove = maxK;
}
@Override
protected Move<Solution_> createUpcomingSelection() {
var locationInDistribution = workingRandom.nextInt(pickedKDistributionSum);
var indexInDistribution = 0;
while (locationInDistribution >= pickedKDistribution[indexInDistribution]) {
locationInDistribution -= pickedKDistribution[indexInDistribution];
indexInDistribution++;
}
var k = minK + indexInDistribution;
if (k == 2) {
return pickTwoOptMove();
}
var descriptor = pickKOptMove(k);
if (descriptor == null) {
// Was unable to find a K-Opt move
return NoChangeMove.getInstance();
}
return descriptor.getKOptListMove(listVariableStateSupply);
}
private Move<Solution_> pickTwoOptMove() {
@SuppressWarnings("unchecked")
var originIterator = (Iterator<Node_>) originSelector.iterator();
if (!originIterator.hasNext()) {
return NoChangeMove.getInstance();
}
@SuppressWarnings("unchecked")
var valueIterator = (Iterator<Node_>) valueSelector.iterator();
if (!valueIterator.hasNext()) {
return NoChangeMove.getInstance();
}
Object firstValue = originIterator.next();
Object secondValue = valueIterator.next();
var firstElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(firstValue);
var secondElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(secondValue);
return new TwoOptListMove<>(listVariableDescriptor, firstElementLocation.entity(), secondElementLocation.entity(),
firstElementLocation.index(), secondElementLocation.index());
}
@SuppressWarnings("unchecked")
private Iterator<Node_> getValuesOnSelectedEntitiesIterator(Node_[] pickedValues) {
var entityOrderInfo = EntityOrderInfo.of(pickedValues, listVariableStateSupply);
return (Iterator<Node_>) workingRandom.ints(0, entityOrderInfo.entities().length)
.mapToObj(index -> {
var entity = entityOrderInfo.entities()[index];
return listVariableDescriptor.getRandomUnpinnedElement(entity, workingRandom);
})
.iterator();
}
@SuppressWarnings("unchecked")
private KOptDescriptor<Node_> pickKOptMove(int k) {
// The code in the paper used 1-index arrays
var pickedValues = (Node_[]) new Object[2 * k + 1];
var originIterator = (Iterator<Node_>) originSelector.iterator();
pickedValues[1] = originIterator.next();
if (pickedValues[1] == null) {
return null;
}
var remainingAttempts = 20;
while (remainingAttempts > 0
&& listVariableDescriptor
.getUnpinnedSubListSize(listVariableStateSupply.getInverseSingleton(pickedValues[1])) < 2) {
do {
if (!originIterator.hasNext()) {
return null;
}
pickedValues[1] = originIterator.next();
remainingAttempts--;
} while ((pickedValues[1] == null));
}
if (remainingAttempts == 0) {
// could not find a value in a list with more than 1 element
return null;
}
var entityOrderInfo = EntityOrderInfo.of(pickedValues, listVariableStateSupply);
pickedValues[2] = workingRandom.nextBoolean() ? getNodeSuccessor(entityOrderInfo, pickedValues[1])
: getNodePredecessor(entityOrderInfo, pickedValues[1]);
if (isNodeEndpointOfList(pickedValues[1]) || isNodeEndpointOfList(pickedValues[2])) {
return pickKOptMoveRec(getValuesOnSelectedEntitiesIterator(pickedValues), entityOrderInfo, pickedValues, 2, k,
false);
} else {
return pickKOptMoveRec((Iterator<Node_>) valueSelector.iterator(), entityOrderInfo, pickedValues, 2, k, true);
}
}
private KOptDescriptor<Node_> pickKOptMoveRec(Iterator<Node_> valueIterator,
EntityOrderInfo entityOrderInfo,
Node_[] pickedValues,
int pickedSoFar,
int k,
boolean canSelectNewEntities) {
var previousRemovedEdgeEndpoint = pickedValues[2 * pickedSoFar - 2];
Node_ nextRemovedEdgePoint, nextRemovedEdgeOppositePoint;
var remainingAttempts = (k - pickedSoFar + 3) * 2;
while (remainingAttempts > 0) {
nextRemovedEdgePoint = valueIterator.next();
var newEntityOrderInfo =
entityOrderInfo.withNewNode(nextRemovedEdgePoint, listVariableStateSupply);
while (nextRemovedEdgePoint == getNodePredecessor(newEntityOrderInfo, previousRemovedEdgeEndpoint) ||
nextRemovedEdgePoint == getNodeSuccessor(newEntityOrderInfo, previousRemovedEdgeEndpoint) ||
isEdgeAlreadyAdded(pickedValues, previousRemovedEdgeEndpoint, nextRemovedEdgePoint, pickedSoFar - 2) ||
(isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint,
getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint),
pickedSoFar - 2)
&& isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint,
getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint),
pickedSoFar - 2))) {
if (remainingAttempts == 0) {
return null;
}
nextRemovedEdgePoint = valueIterator.next();
newEntityOrderInfo =
entityOrderInfo.withNewNode(nextRemovedEdgePoint, listVariableStateSupply);
remainingAttempts--;
}
remainingAttempts--;
pickedValues[2 * pickedSoFar - 1] = nextRemovedEdgePoint;
if (isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint,
getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint),
pickedSoFar - 2)) {
nextRemovedEdgeOppositePoint = getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint);
} else if (isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint,
getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint),
pickedSoFar - 2)) {
nextRemovedEdgeOppositePoint = getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint);
} else {
nextRemovedEdgeOppositePoint =
workingRandom.nextBoolean() ? getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint)
: getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint);
}
pickedValues[2 * pickedSoFar] = nextRemovedEdgeOppositePoint;
if (canSelectNewEntities && isNodeEndpointOfList(nextRemovedEdgePoint)
|| isNodeEndpointOfList(nextRemovedEdgeOppositePoint)) {
valueIterator = getValuesOnSelectedEntitiesIterator(pickedValues);
canSelectNewEntities = false;
}
if (pickedSoFar < k) {
var descriptor = pickKOptMoveRec(valueIterator, newEntityOrderInfo, pickedValues,
pickedSoFar + 1, k, canSelectNewEntities);
if (descriptor != null && descriptor.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) {
return descriptor;
}
} else {
var descriptor = new KOptDescriptor<Node_>(pickedValues,
KOptUtils.getMultiEntitySuccessorFunction(pickedValues,
listVariableStateSupply),
KOptUtils.getMultiEntityBetweenPredicate(pickedValues,
listVariableStateSupply));
if (descriptor.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) {
return descriptor;
} else {
descriptor = patchCycles(
descriptor,
newEntityOrderInfo, pickedValues,
pickedSoFar);
if (descriptor.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) {
return descriptor;
}
}
}
}
return null;
}
KOptDescriptor<Node_> patchCycles(KOptDescriptor<Node_> descriptor, EntityOrderInfo entityOrderInfo,
Node_[] oldRemovedEdges, int k) {
Node_ s1, s2;
var removedEdgeIndexToTourOrder = descriptor.removedEdgeIndexToTourOrder();
var valueIterator = getValuesOnSelectedEntitiesIterator(oldRemovedEdges);
var cycleInfo = KOptUtils.getCyclesForPermutation(descriptor);
var cycleCount = cycleInfo.cycleCount();
var cycle = cycleInfo.indexToCycleIdentifier();
// If cycleCount != 1,
// we are changing an infeasible k-opt move that results in cycleCount cycles
// into a (k+cycleCount) move.
// If the k+cycleCount > maxK, we should ignore generating the move
// Note: maxCyclesPatchedInInfeasibleMove = maxK
if (cycleCount == 1 || k + cycleCount > maxCyclesPatchedInInfeasibleMove) {
return descriptor;
}
var currentCycle =
getShortestCycleIdentifier(entityOrderInfo, oldRemovedEdges, cycle, removedEdgeIndexToTourOrder, cycleCount, k);
for (var i = 0; i < k; i++) {
if (cycle[removedEdgeIndexToTourOrder[2 * i]] == currentCycle) {
var sStart = oldRemovedEdges[removedEdgeIndexToTourOrder[2 * i]];
var sStop = oldRemovedEdges[removedEdgeIndexToTourOrder[2 * i + 1]];
var attemptRemaining = k;
for (s1 = sStart; s1 != sStop; s1 = s2) {
attemptRemaining--;
if (attemptRemaining == 0) {
break;
}
var removedEdges = Arrays.copyOf(oldRemovedEdges, oldRemovedEdges.length + 2);
removedEdges[2 * k + 1] = s1;
s2 = getNodeSuccessor(entityOrderInfo, s1);
removedEdges[2 * k + 2] = s2;
var addedEdgeToOtherEndpoint =
Arrays.copyOf(KOptDescriptor.computeInEdgesForSequentialMove(oldRemovedEdges),
removedEdges.length + 2 + (2 * cycleCount));
for (var newEdge = removedEdges.length; newEdge < addedEdgeToOtherEndpoint.length - 2; newEdge++) {
addedEdgeToOtherEndpoint[newEdge] = newEdge + 2;
}
addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint.length - 1] = addedEdgeToOtherEndpoint.length - 3;
addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint.length - 2] = addedEdgeToOtherEndpoint.length - 4;
var newMove = patchCyclesRec(valueIterator, descriptor, entityOrderInfo, removedEdges,
addedEdgeToOtherEndpoint, cycle, currentCycle,
k, 2, cycleCount);
if (newMove.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) {
return newMove;
}
}
}
}
return descriptor;
}
KOptDescriptor<Node_> patchCyclesRec(Iterator<Node_> valueIterator,
KOptDescriptor<Node_> originalMove, EntityOrderInfo entityOrderInfo,
Node_[] oldRemovedEdges, int[] addedEdgeToOtherEndpoint, int[] cycle, int currentCycle,
int k, int patchedCycleCount, int cycleCount) {
Node_ s1, s2, s3, s4;
int NewCycle, i;
var cycleSaved = new Integer[1 + 2 * k];
var removedEdges = Arrays.copyOf(oldRemovedEdges, oldRemovedEdges.length + 2);
s1 = removedEdges[2 * k + 1];
s2 = removedEdges[i = 2 * (k + patchedCycleCount) - 2];
addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint[i] = i + 1] = i;
for (i = 1; i <= 2 * k; i++) {
cycleSaved[i] = cycle[i];
}
s3 = valueIterator.next();
var remainingAttempts = cycleCount * 2;
while (s3 == getNodePredecessor(entityOrderInfo, s2) || s3 == getNodeSuccessor(entityOrderInfo, s2)
|| ((NewCycle = findCycleIdentifierForNode(entityOrderInfo, s3, removedEdges,
originalMove.removedEdgeIndexToTourOrder(),
cycle)) == currentCycle)
||
(isEdgeAlreadyDeleted(removedEdges, s3, getNodePredecessor(entityOrderInfo, s3), k)
&& isEdgeAlreadyDeleted(removedEdges, s3, getNodeSuccessor(entityOrderInfo, s3), k))) {
if (remainingAttempts == 0) {
return originalMove;
}
s3 = valueIterator.next();
remainingAttempts--;
}
removedEdges[2 * (k + patchedCycleCount) - 1] = s3;
if (isEdgeAlreadyDeleted(removedEdges, s3, getNodePredecessor(entityOrderInfo, s3), k)) {
s4 = getNodeSuccessor(entityOrderInfo, s3);
} else if (isEdgeAlreadyDeleted(removedEdges, s3, getNodeSuccessor(entityOrderInfo, s3), k)) {
s4 = getNodePredecessor(entityOrderInfo, s3);
} else {
s4 = workingRandom.nextBoolean() ? getNodeSuccessor(entityOrderInfo, s3) : getNodePredecessor(entityOrderInfo, s3);
}
removedEdges[2 * (k + patchedCycleCount)] = s4;
if (cycleCount > 2) {
for (i = 1; i <= 2 * k; i++) {
if (cycle[i] == NewCycle) {
cycle[i] = currentCycle;
}
}
var recursiveCall =
patchCyclesRec(valueIterator, originalMove, entityOrderInfo, removedEdges, addedEdgeToOtherEndpoint, cycle,
currentCycle,
k, patchedCycleCount + 1, cycleCount - 1);
if (recursiveCall.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) {
return recursiveCall;
}
for (i = 1; i <= 2 * k; i++) {
cycle[i] = cycleSaved[i];
}
} else if (s4 != s1) {
addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint[2 * k + 1] = 2 * (k + patchedCycleCount)] =
2 * k + 1;
return new KOptDescriptor<>(removedEdges, addedEdgeToOtherEndpoint,
KOptUtils.getMultiEntitySuccessorFunction(removedEdges, listVariableStateSupply),
KOptUtils.getMultiEntityBetweenPredicate(removedEdges, listVariableStateSupply));
}
return originalMove;
}
int findCycleIdentifierForNode(EntityOrderInfo entityOrderInfo, Node_ value, Node_[] pickedValues, int[] permutation,
int[] indexToCycle) {
for (var i = 1; i < pickedValues.length; i++) {
if (isMiddleNodeBetween(entityOrderInfo, pickedValues[permutation[i - 1]], value, pickedValues[permutation[i]])) {
return indexToCycle[permutation[i]];
}
}
throw new IllegalStateException("Cannot find cycle the " + value + " belongs to");
}
int getShortestCycleIdentifier(EntityOrderInfo entityOrderInfo, Object[] removeEdgeEndpoints, int[] endpointIndexToCycle,
int[] removeEdgeEndpointIndexToTourOrder, int cycleCount, int k) {
int i;
var minCycleIdentifier = 0;
var minSize = Integer.MAX_VALUE;
var size = new int[cycleCount + 1];
for (i = 1; i <= cycleCount; i++) {
size[i] = 0;
}
removeEdgeEndpointIndexToTourOrder[0] = removeEdgeEndpointIndexToTourOrder[2 * k];
for (i = 0; i < 2 * k; i += 2) {
size[endpointIndexToCycle[removeEdgeEndpointIndexToTourOrder[i]]] +=
getSegmentSize(entityOrderInfo, removeEdgeEndpoints[removeEdgeEndpointIndexToTourOrder[i]],
removeEdgeEndpoints[removeEdgeEndpointIndexToTourOrder[i + 1]]);
}
for (i = 1; i <= cycleCount; i++) {
if (size[i] < minSize) {
minSize = size[i];
minCycleIdentifier = i - 1;
}
}
return minCycleIdentifier;
}
private int getSegmentSize(EntityOrderInfo entityOrderInfo, Object from, Object to) {
var entityToEntityIndex = entityOrderInfo.entityToEntityIndex();
var startElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(from);
var endElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(to);
int startEntityIndex = entityToEntityIndex.get(startElementLocation.entity());
int endEntityIndex = entityToEntityIndex.get(endElementLocation.entity());
var offsets = entityOrderInfo.offsets();
var startIndex = offsets[startEntityIndex] + startElementLocation.index();
var endIndex = offsets[endEntityIndex] + endElementLocation.index();
if (startIndex <= endIndex) {
return endIndex - startIndex;
} else {
var entities = entityOrderInfo.entities();
var totalRouteSize =
offsets[offsets.length - 1] + listVariableDescriptor.getListSize(entities[entities.length - 1]);
return totalRouteSize - startIndex + endIndex;
}
}
private boolean isEdgeAlreadyAdded(Object[] pickedValues, Object ta, Object tb, int k) {
var i = 2 * k;
while ((i -= 2) > 0) {
if ((ta == pickedValues[i] && tb == pickedValues[i + 1]) ||
(ta == pickedValues[i + 1] && tb == pickedValues[i])) {
return true;
}
}
return false;
}
private boolean isEdgeAlreadyDeleted(Object[] pickedValues, Object ta, Object tb, int k) {
var i = 2 * k + 2;
while ((i -= 2) > 0) {
if ((ta == pickedValues[i - 1] && tb == pickedValues[i]) ||
(ta == pickedValues[i] && tb == pickedValues[i - 1])) {
return true;
}
}
return false;
}
private boolean isNodeEndpointOfList(Object node) {
var elementLocation = (LocationInList) listVariableStateSupply.getLocationInList(node);
var index = elementLocation.index();
var firstUnpinnedIndex = listVariableDescriptor.getFirstUnpinnedIndex(elementLocation.entity());
if (index == firstUnpinnedIndex) {
return true;
}
var size = listVariableDescriptor.getListSize(elementLocation.entity());
return index == size - 1;
}
private Node_ getNodeSuccessor(EntityOrderInfo entityOrderInfo, Node_ node) {
return entityOrderInfo.successor(node, listVariableStateSupply);
}
private Node_ getNodePredecessor(EntityOrderInfo entityOrderInfo, Node_ node) {
return entityOrderInfo.predecessor(node, listVariableStateSupply);
}
private boolean isMiddleNodeBetween(EntityOrderInfo entityOrderInfo, Node_ start, Node_ middle, Node_ end) {
return entityOrderInfo.between(start, middle, end, listVariableStateSupply);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import org.apache.commons.math3.util.CombinatoricsUtils;
final 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 ListVariableStateSupply<Solution_> listVariableStateSupply;
private EntityIndependentValueSelector<Solution_> effectiveOriginSelector;
private EntityIndependentValueSelector<Solution_> effectiveValueSelector;
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);
var supplyManager = solverScope.getScoreDirector().getSupplyManager();
listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand());
effectiveOriginSelector = createEffectiveValueSelector(originSelector, listVariableStateSupply);
effectiveValueSelector = createEffectiveValueSelector(valueSelector, listVariableStateSupply);
}
private EntityIndependentValueSelector<Solution_> createEffectiveValueSelector(
EntityIndependentValueSelector<Solution_> entityIndependentValueSelector,
ListVariableStateSupply<Solution_> listVariableStateSupply) {
var filteredValueSelector =
filterPinnedListPlanningVariableValuesWithIndex(entityIndependentValueSelector, listVariableStateSupply);
return filterNotAssignedValues(filteredValueSelector, listVariableStateSupply);
}
private EntityIndependentValueSelector<Solution_> filterNotAssignedValues(
EntityIndependentValueSelector<Solution_> entityIndependentValueSelector,
ListVariableStateSupply<Solution_> listVariableStateSupply) {
if (!listVariableDescriptor.allowsUnassignedValues()) {
return entityIndependentValueSelector;
}
// We need to filter out unassigned vars.
return (EntityIndependentValueSelector<Solution_>) FilteringValueSelector.of(entityIndependentValueSelector,
(scoreDirector, selection) -> {
if (listVariableStateSupply.getUnassignedCount() == 0) {
return true;
}
return listVariableStateSupply.isAssigned(selection);
});
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
listVariableStateSupply = null;
effectiveOriginSelector = null;
effectiveValueSelector = null;
}
@Override
public long getSize() {
long total = 0;
long valueSelectorSize = effectiveValueSelector.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;
}
@Override
public Iterator<Move<Solution_>> iterator() {
return new KOptListMoveIterator<>(workingRandom, listVariableDescriptor, listVariableStateSupply,
effectiveOriginSelector,
effectiveValueSelector, minK, maxK, pickedKDistribution);
}
@Override
public boolean isCountable() {
return false;
}
@Override
public boolean isNeverEnding() {
return true;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public final 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) {
var originSelectorConfig = Objects.requireNonNullElseGet(config.getOriginSelectorConfig(), ValueSelectorConfig::new);
var valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new);
var entityDescriptor = getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
var originSelector = buildEntityIndependentValueSelector(configPolicy, entityDescriptor, originSelectorConfig,
minimumCacheType, selectionOrder);
var valueSelector = buildEntityIndependentValueSelector(configPolicy, entityDescriptor, valueSelectorConfig,
minimumCacheType, selectionOrder);
// TODO support coexistence of list and basic variables https://issues.redhat.com/browse/PLANNER-2755
var variableDescriptor = getTheOnlyVariableDescriptor(entityDescriptor);
if (!variableDescriptor.isListVariable()) {
throw new IllegalArgumentException("""
The kOptListMoveSelector (%s) can only be used when the domain model has a list variable.
Check your @%s and make sure it has a @%s."""
.formatted(config, PlanningEntity.class.getSimpleName(), PlanningListVariable.class.getSimpleName()));
}
int minimumK = Objects.requireNonNullElse(config.getMinimumK(), DEFAULT_MINIMUM_K);
if (minimumK < 2) {
throw new IllegalArgumentException("minimumK (%d) must be at least 2."
.formatted(minimumK));
}
int maximumK = Objects.requireNonNullElse(config.getMaximumK(), DEFAULT_MAXIMUM_K);
if (maximumK < minimumK) {
throw new IllegalArgumentException("maximumK (%d) must be at least minimumK (%d)."
.formatted(maximumK, minimumK));
}
var pickedKDistribution = new int[maximumK - minimumK + 1];
// Each prior k is 8 times more likely to be picked than the subsequent k
var total = 1;
for (var i = minimumK; i < maximumK; i++) {
total *= 8;
}
for (var 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);
}
private EntityIndependentValueSelector<Solution_> buildEntityIndependentValueSelector(
HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor,
ValueSelectorConfig valueSelectorConfig,
SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder) {
var valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder);
if (valueSelector instanceof EntityIndependentValueSelector<Solution_> entityIndependentValueSelector) {
return entityIndependentValueSelector;
}
throw new IllegalArgumentException("""
The kOptListMoveSelector (%s) for a list variable needs to be based on an %s (%s).
Check your valueSelectorConfig."""
.formatted(config, EntityIndependentValueSelector.class.getSimpleName(), valueSelector));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/MultipleDelegateList.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import java.util.RandomAccess;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.function.TriConsumer;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
/**
* A list that delegates get and set operations to multiple delegates.
* Add and removal operations are not supported.
*
* @param <T>
*/
final class MultipleDelegateList<T> implements List<T>, RandomAccess {
final Object[] delegateEntities;
final List<T>[] delegates;
final int[] delegateSizes;
final int[] offsets;
final int totalSize;
@SafeVarargs
public MultipleDelegateList(Object[] delegateEntities, List<T>... delegates) {
this.delegates = delegates;
this.delegateEntities = delegateEntities;
this.delegateSizes = new int[delegates.length];
this.offsets = new int[delegates.length];
var sizeSoFar = 0;
for (var i = 0; i < delegates.length; i++) {
delegateSizes[i] = delegates[i].size();
offsets[i] = sizeSoFar;
sizeSoFar += delegateSizes[i];
}
this.totalSize = sizeSoFar;
}
@SafeVarargs
MultipleDelegateList(List<T>... delegates) {
this(new Object[delegates.length], delegates);
}
@SuppressWarnings("unchecked")
public MultipleDelegateList<T> copy() {
List<T>[] delegateClones = new List[delegates.length];
for (var i = 0; i < delegates.length; i++) {
delegateClones[i] = new ArrayList<>(delegates[i]);
}
return new MultipleDelegateList<>(delegateEntities, delegateClones);
}
@SuppressWarnings("unchecked")
public void applyChangesFromCopy(MultipleDelegateList<?> copy) {
for (var i = 0; i < delegates.length; i++) {
delegates[i].clear();
delegates[i].addAll((List<T>) copy.delegates[i]);
}
}
public int getIndexOfValue(ListVariableStateSupply<?> listVariableStateSupply, Object value) {
var elementLocation = listVariableStateSupply.getLocationInList(value);
if (elementLocation instanceof LocationInList elementLocationInList) {
var entity = elementLocationInList.entity();
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
for (var i = 0; i < delegateEntities.length; i++) {
if (delegateEntities[i] == entity) {
var firstUnpinnedIndex = listVariableDescriptor.getFirstUnpinnedIndex(delegateEntities[i]);
return offsets[i] + (elementLocationInList.index() - firstUnpinnedIndex);
}
}
}
// Unassigned or not found.
throw new IllegalArgumentException("Value (" + value + ") is not contained in any entity list");
}
public void actOnAffectedElements(ListVariableDescriptor<?> listVariableDescriptor, Object[] originalEntities,
TriConsumer<Object, Integer, Integer> action) {
for (Object originalEntity : originalEntities) {
action.accept(originalEntity,
listVariableDescriptor.getFirstUnpinnedIndex(originalEntity),
listVariableDescriptor.getListSize(originalEntity));
}
}
public void moveElementsOfDelegates(int[] newDelegateEndIndices) {
List<T>[] newDelegateData = new List[delegates.length];
var start = 0;
for (var i = 0; i < newDelegateData.length; i++) {
newDelegateData[i] = List.copyOf(subList(start, newDelegateEndIndices[i] + 1));
start = newDelegateEndIndices[i] + 1;
}
for (var i = 0; i < delegates.length; i++) {
delegates[i].clear();
delegates[i].addAll(newDelegateData[i]);
}
var sizeSoFar = 0;
for (var i = 0; i < delegates.length; i++) {
delegateSizes[i] = delegates[i].size();
offsets[i] = sizeSoFar;
sizeSoFar += delegateSizes[i];
}
}
@Override
public int size() {
return totalSize;
}
@Override
public boolean isEmpty() {
return totalSize == 0;
}
@Override
public boolean contains(Object o) {
for (var delegate : delegates) {
if (delegate.contains(o)) {
return true;
}
}
return false;
}
@Override
public Iterator<T> iterator() {
return Stream.of(delegates).flatMap(Collection::stream).iterator();
}
@Override
public Object[] toArray() {
return Stream.of(delegates).flatMap(Collection::stream).toArray();
}
@Override
@SuppressWarnings("unchecked")
public <T1> T1[] toArray(T1[] t1s) {
var out = Stream.of(delegates).flatMap(Collection::stream).toArray(size -> {
if (size <= t1s.length) {
return t1s;
} else {
return (T1[]) Array.newInstance(t1s.getClass().getComponentType(), size);
}
});
if (out.length > totalSize) {
out[totalSize] = null;
}
return out;
}
@Override
public boolean containsAll(Collection<?> collection) {
return collection.stream().allMatch(this::contains);
}
private int getDelegateIndex(int actualIndex) {
var delegateIndex = 0;
while (delegateSizes[delegateIndex] <= actualIndex) {
actualIndex -= delegateSizes[delegateIndex];
delegateIndex++;
}
return delegateIndex;
}
@Override
public T get(int i) {
if (i < 0 || i >= totalSize) {
throw new IndexOutOfBoundsException("Index (" + i + ") out of bounds for a list of size (" + totalSize + ")");
}
var delegateIndex = getDelegateIndex(i);
return delegates[delegateIndex].get(i - offsets[delegateIndex]);
}
@Override
public T set(int i, T t) {
if (i < 0 || i >= totalSize) {
throw new IndexOutOfBoundsException("Index (" + i + ") out of bounds for a list of size (" + totalSize + ")");
}
var delegateIndex = getDelegateIndex(i);
return delegates[delegateIndex].set(i - offsets[delegateIndex], t);
}
@Override
public int indexOf(Object o) {
if (delegates.length == 0) {
return -1;
}
var delegateIndex = 0;
var objectIndex = -1;
var offset = 0;
while (delegateIndex < delegates.length && (objectIndex = delegates[delegateIndex].indexOf(o)) == -1) {
// We do the indexOf in the while condition so offset is not updated
// for the list that contains the element
// (ex: [1, 2, 3].indexOf(2) should return 1, not 4)
offset += delegateSizes[delegateIndex];
delegateIndex++;
}
if (objectIndex == -1) {
return -1;
}
return offset + objectIndex;
}
@Override
public int lastIndexOf(Object o) {
if (delegates.length == 0) {
return -1;
}
var delegateIndex = delegates.length - 1;
var objectIndex = -1;
var offset = 0;
while (delegateIndex >= 0 && objectIndex == -1) {
// We update index here so offset is updated with the containing
// list size (since totalSize is subtracted from it)
// (ex: [1, 2, 3].lastIndexOf(2) should return 1, not 4)
objectIndex = delegates[delegateIndex].lastIndexOf(o);
offset += delegateSizes[delegateIndex];
delegateIndex--;
}
if (objectIndex == -1) {
return -1;
}
return (totalSize - offset) + objectIndex;
}
@Override
public ListIterator<T> listIterator() {
return new MultipleDelegateListIterator<>(this, 0);
}
@Override
public ListIterator<T> listIterator(int i) {
return new MultipleDelegateListIterator<>(this, i);
}
@Override
public MultipleDelegateList<T> subList(int startInclusive, int endExclusive) {
if (startInclusive < 0) {
throw new IndexOutOfBoundsException("Sublist start index (" + startInclusive + ") out of range");
}
if (endExclusive > totalSize) {
throw new IndexOutOfBoundsException("Sublist end index (" + endExclusive + ") out of range");
}
var startDelegateIndex = 0;
var endDelegateIndex = 0;
while (startInclusive >= delegateSizes[startDelegateIndex]) {
startInclusive -= delegateSizes[startDelegateIndex];
startDelegateIndex++;
}
while (endExclusive > delegateSizes[endDelegateIndex]) {
endExclusive -= delegateSizes[endDelegateIndex];
endDelegateIndex++;
}
@SuppressWarnings("unchecked")
List<T>[] out = new List[endDelegateIndex - startDelegateIndex + 1];
if (out.length == 0) {
return new MultipleDelegateList<>(delegateEntities);
}
if (startDelegateIndex == endDelegateIndex) {
out[0] = delegates[startDelegateIndex].subList(startInclusive, endExclusive);
} else {
out[0] = delegates[startDelegateIndex].subList(startInclusive, delegateSizes[startDelegateIndex]);
out[out.length - 1] = delegates[endDelegateIndex].subList(0, endExclusive);
System.arraycopy(delegates, startDelegateIndex + 1, out, 1, out.length - 2);
}
return new MultipleDelegateList<>(delegateEntities, out);
}
@Override
public boolean add(T t) {
throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list");
}
@Override
public void add(int i, T t) {
throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list");
}
@Override
public T remove(int i) {
throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list");
}
@Override
public boolean addAll(Collection<? extends T> collection) {
throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list");
}
@Override
public boolean addAll(int i, Collection<? extends T> collection) {
throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list");
}
@Override
public boolean removeAll(Collection<?> collection) {
throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list");
}
@Override
public boolean retainAll(Collection<?> collection) {
throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list");
}
@Override
public void clear() {
throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list");
}
@Override
public String toString() {
return Arrays.toString(delegates);
}
@Override
public boolean equals(Object o) {
if (o instanceof List other) {
if (other.size() != totalSize) {
return false;
}
for (var i = 0; i < totalSize; i++) {
if (!Objects.equals(other.get(i), get(i))) {
return false;
}
}
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
return Arrays.hashCode(delegates);
}
private static final class MultipleDelegateListIterator<T> implements ListIterator<T> {
final MultipleDelegateList<T> parent;
int currentIndex;
public MultipleDelegateListIterator(MultipleDelegateList<T> parent, int currentIndex) {
this.parent = parent;
this.currentIndex = currentIndex;
}
@Override
public boolean hasNext() {
return currentIndex < parent.totalSize;
}
@Override
public T next() {
var out = parent.get(currentIndex);
currentIndex++;
return out;
}
@Override
public boolean hasPrevious() {
return currentIndex > 0;
}
@Override
public T previous() {
currentIndex--;
return parent.get(currentIndex);
}
@Override
public int nextIndex() {
return currentIndex + 1;
}
@Override
public int previousIndex() {
return currentIndex - 1;
}
@Override
public void set(T t) {
parent.set(currentIndex, t);
}
@Override
public void add(T t) {
throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list");
}
@Override
public void remove() {
throw new UnsupportedOperationException("Cannot remove elements to a multiple delegate list");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/TwoOptListMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.util.CollectionUtils;
/**
* A 2-opt move for list variables, which takes two edges and swap their endpoints.
* For instance, let [A, B, E, D, C, F, G, H] be the route assigned to an entity.
* Select (B, E) and (C, F) as the edges to swap.
* Then the resulting route after this operation would be [A, B, C, D, E, F, G, H].
* The edge (B, E) became (B, C), and the edge (C, F) became (E, F)
* (the first edge end point became the second edge start point and vice versa).
* It is used to fix crossings; for instance, it can change:
*
* <pre>{@code
* ... -> A B <- ...
* ....... x .......
* ... <- C D -> ...
* }</pre>
*
* to
*
* <pre>{@code
* ... -> A -> B -> ...
* ... <- C <- D <- ...
* }</pre>
*
* Note the sub-path D...B was reversed.
* The 2-opt works by reversing the path between the two edges being removed.
* <p>
* When the edges are assigned to different entities,
* it results in a tail swap.
* For instance, let r1 = [A, B, C, D], and r2 = [E, F, G, H].
* Doing a 2-opt on (B, C) + (F, G) will result in r1 = [A, B, G, H] and r2 = [E, F, C, D].
*
* @param <Solution_>
*/
public final class TwoOptListMove<Solution_> extends AbstractMove<Solution_> {
private final ListVariableDescriptor<Solution_> variableDescriptor;
private final Object firstEntity;
private final Object secondEntity;
private final int firstEdgeEndpoint;
private final int secondEdgeEndpoint;
private final int shift;
private final int entityFirstUnpinnedIndex;
public TwoOptListMove(ListVariableDescriptor<Solution_> variableDescriptor,
Object firstEntity, Object secondEntity,
int firstEdgeEndpoint,
int secondEdgeEndpoint) {
this.variableDescriptor = variableDescriptor;
this.firstEntity = firstEntity;
this.secondEntity = secondEntity;
this.firstEdgeEndpoint = firstEdgeEndpoint;
this.secondEdgeEndpoint = secondEdgeEndpoint;
if (firstEntity == secondEntity) {
entityFirstUnpinnedIndex = variableDescriptor.getFirstUnpinnedIndex(firstEntity);
if (firstEdgeEndpoint == 0) {
shift = -secondEdgeEndpoint;
} else if (secondEdgeEndpoint < firstEdgeEndpoint) {
int listSize = variableDescriptor.getListSize(firstEntity);
int flippedSectionSize = listSize - firstEdgeEndpoint + secondEdgeEndpoint;
int firstElementIndexInFlipped = listSize - firstEdgeEndpoint;
int firstElementMirroredIndex = flippedSectionSize - firstElementIndexInFlipped;
shift = -(firstEdgeEndpoint + firstElementMirroredIndex - 1);
} else {
shift = 0;
}
} else {
// This is a tail swap move, so entityFirstUnpinnedIndex is unused as no
// flipping will be done
entityFirstUnpinnedIndex = 0;
shift = 0;
}
}
private TwoOptListMove(ListVariableDescriptor<Solution_> variableDescriptor,
Object firstEntity, Object secondEntity,
int firstEdgeEndpoint,
int secondEdgeEndpoint,
int entityFirstUnpinnedIndex,
int shift) {
this.variableDescriptor = variableDescriptor;
this.firstEntity = firstEntity;
this.secondEntity = secondEntity;
this.firstEdgeEndpoint = firstEdgeEndpoint;
this.secondEdgeEndpoint = secondEdgeEndpoint;
this.entityFirstUnpinnedIndex = entityFirstUnpinnedIndex;
this.shift = shift;
}
@Override
protected TwoOptListMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
return new TwoOptListMove<>(variableDescriptor,
firstEntity,
secondEntity,
firstEdgeEndpoint,
secondEdgeEndpoint,
entityFirstUnpinnedIndex,
-shift);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
if (firstEntity == secondEntity) {
doSublistReversal(scoreDirector);
} else {
doTailSwap(scoreDirector);
}
}
private void doTailSwap(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
List<Object> firstListVariable = variableDescriptor.getValue(firstEntity);
List<Object> secondListVariable = variableDescriptor.getValue(secondEntity);
int firstOriginalSize = firstListVariable.size();
int secondOriginalSize = secondListVariable.size();
innerScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity,
firstEdgeEndpoint,
firstOriginalSize);
innerScoreDirector.beforeListVariableChanged(variableDescriptor, secondEntity,
secondEdgeEndpoint,
secondOriginalSize);
List<Object> firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstOriginalSize);
List<Object> secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondOriginalSize);
int tailSizeDifference = secondListVariableTail.size() - firstListVariableTail.size();
List<Object> firstListVariableTailCopy = new ArrayList<>(firstListVariableTail);
firstListVariableTail.clear();
firstListVariable.addAll(secondListVariableTail);
secondListVariableTail.clear();
secondListVariable.addAll(firstListVariableTailCopy);
innerScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity,
firstEdgeEndpoint,
firstOriginalSize + tailSizeDifference);
innerScoreDirector.afterListVariableChanged(variableDescriptor, secondEntity,
secondEdgeEndpoint,
secondOriginalSize - tailSizeDifference);
}
private void doSublistReversal(ScoreDirector<Solution_> scoreDirector) {
InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
List<Object> listVariable = variableDescriptor.getValue(firstEntity);
if (firstEdgeEndpoint < secondEdgeEndpoint) {
if (firstEdgeEndpoint > 0) {
innerScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity,
firstEdgeEndpoint,
secondEdgeEndpoint);
} else {
innerScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity,
entityFirstUnpinnedIndex,
listVariable.size());
}
if (firstEdgeEndpoint == 0 && shift > 0) {
if (entityFirstUnpinnedIndex == 0) {
Collections.rotate(listVariable, shift);
} else {
Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()),
shift);
}
}
FlipSublistAction.flipSublist(listVariable, entityFirstUnpinnedIndex, firstEdgeEndpoint, secondEdgeEndpoint);
if (firstEdgeEndpoint == 0 && shift < 0) {
if (entityFirstUnpinnedIndex == 0) {
Collections.rotate(listVariable, shift);
} else {
Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()),
shift);
}
}
if (firstEdgeEndpoint > 0) {
innerScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity,
firstEdgeEndpoint,
secondEdgeEndpoint);
} else {
innerScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity,
entityFirstUnpinnedIndex,
listVariable.size());
}
} else {
innerScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity,
entityFirstUnpinnedIndex,
listVariable.size());
if (shift > 0) {
if (entityFirstUnpinnedIndex == 0) {
Collections.rotate(listVariable, shift);
} else {
Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()),
shift);
}
}
FlipSublistAction.flipSublist(listVariable, entityFirstUnpinnedIndex, firstEdgeEndpoint, secondEdgeEndpoint);
if (shift < 0) {
if (entityFirstUnpinnedIndex == 0) {
Collections.rotate(listVariable, shift);
} else {
Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()),
shift);
}
}
innerScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity,
entityFirstUnpinnedIndex,
listVariable.size());
}
}
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
if (firstEntity == secondEntity) {
if (shift != 0) {
// A shift will rotate the entire list, changing the visiting order
return true;
}
int chainLength = Math.abs(secondEdgeEndpoint - firstEdgeEndpoint);
// The chain flipped by a K-Opt only changes if there are at least 2 values
// in the chain
return chainLength >= 2;
}
// This is a tail-swap move otherwise, which always changes at least one element
// (the element where the tail begins for each entity)
return true;
}
@Override
public TwoOptListMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new TwoOptListMove<>(variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(firstEntity),
destinationScoreDirector.lookUpWorkingObject(secondEntity),
firstEdgeEndpoint,
secondEdgeEndpoint,
entityFirstUnpinnedIndex,
shift);
}
@Override
public String getSimpleMoveTypeDescription() {
return "2-Opt(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<?> getPlanningEntities() {
if (firstEntity == secondEntity) {
return Collections.singleton(firstEntity);
}
return Set.of(firstEntity, secondEntity);
}
@Override
public Collection<?> getPlanningValues() {
if (firstEntity == secondEntity) {
List<Object> listVariable = variableDescriptor.getValue(firstEntity);
if (firstEdgeEndpoint < secondEdgeEndpoint) {
return new ArrayList<>(listVariable.subList(firstEdgeEndpoint, secondEdgeEndpoint));
} else {
List<Object> firstHalfReversedPath = listVariable.subList(firstEdgeEndpoint, listVariable.size());
List<Object> secondHalfReversedPath = listVariable.subList(entityFirstUnpinnedIndex, secondEdgeEndpoint);
return CollectionUtils.concat(firstHalfReversedPath, secondHalfReversedPath);
}
} else {
List<Object> firstListVariable = variableDescriptor.getValue(firstEntity);
List<Object> secondListVariable = variableDescriptor.getValue(secondEntity);
List<Object> firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstListVariable.size());
List<Object> secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondListVariable.size());
List<Object> out = new ArrayList<>(firstListVariableTail.size() + secondListVariableTail.size());
out.addAll(firstListVariableTail);
out.addAll(secondListVariableTail);
return out;
}
}
public Object getFirstEntity() {
return firstEntity;
}
public Object getSecondEntity() {
return secondEntity;
}
public Object getFirstEdgeEndpoint() {
return firstEdgeEndpoint;
}
public Object getSecondEdgeEndpoint() {
return secondEdgeEndpoint;
}
@Override
public String toString() {
return "2-Opt(firstEntity=" +
firstEntity +
", secondEntity=" + secondEntity +
", firstEndpointIndex=" + firstEdgeEndpoint +
", secondEndpointIndex=" + secondEdgeEndpoint +
")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/EntityIndependentValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value;
import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector;
/**
* @see FromSolutionPropertyValueSelector
*/
public interface EntityIndependentValueSelector<Solution_> extends ValueSelector<Solution_>,
IterableSelector<Solution_, Object> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/FromEntityPropertyValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
/**
* This is the common {@link ValueSelector} implementation.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class FromEntityPropertyValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ValueSelector<Solution_> {
private final ValueRangeDescriptor<Solution_> valueRangeDescriptor;
private final boolean randomSelection;
private Solution_ workingSolution;
public FromEntityPropertyValueSelector(ValueRangeDescriptor<Solution_> valueRangeDescriptor, boolean randomSelection) {
this.valueRangeDescriptor = valueRangeDescriptor;
this.randomSelection = randomSelection;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return valueRangeDescriptor.getVariableDescriptor();
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
// type cast in order to avoid SolverLifeCycleListener and all its children needing to be generified
workingSolution = phaseScope.getWorkingSolution();
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
workingSolution = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return valueRangeDescriptor.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || !isCountable();
}
@Override
public long getSize(Object entity) {
return valueRangeDescriptor.extractValueRangeSize(workingSolution, entity);
}
@Override
public Iterator<Object> iterator(Object entity) {
ValueRange<Object> valueRange = (ValueRange<Object>) valueRangeDescriptor.extractValueRange(workingSolution, entity);
if (!randomSelection) {
return ((CountableValueRange<Object>) valueRange).createOriginalIterator();
} else {
return valueRange.createRandomIterator(workingRandom);
}
}
@Override
public Iterator<Object> endingIterator(Object entity) {
ValueRange<Object> valueRange = (ValueRange<Object>) valueRangeDescriptor.extractValueRange(workingSolution, entity);
return ((CountableValueRange<Object>) valueRange).createOriginalIterator();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FromEntityPropertyValueSelector<?> that = (FromEntityPropertyValueSelector<?>) o;
return randomSelection == that.randomSelection && Objects.equals(valueRangeDescriptor, that.valueRangeDescriptor);
}
@Override
public int hashCode() {
return Objects.hash(valueRangeDescriptor, randomSelection);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + getVariableDescriptor().getVariableName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/FromSolutionPropertyValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.EntityIndependentValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* This is the common {@link ValueSelector} implementation.
*/
public final 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() {
checkCachedEntityListIsDirty();
if (randomSelection) {
return cachedValueRange.createRandomIterator(workingRandom);
}
if (cachedValueRange instanceof CountableValueRange range) {
return range.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 + "?");
}
@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() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/ValueSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.value;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.EntityIndependentValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.WeightFactorySelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.AssignedListValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.CachingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.DowncastingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.EntityDependentSortingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.InitializedValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.ProbabilityValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.ReinitializeVariableValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.SelectedCountLimitValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.ShufflingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.SortingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.UnassignedListValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.mimic.MimicRecordingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.mimic.MimicReplayingValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.mimic.ValueMimicRecorder;
import ai.timefold.solver.core.impl.solver.ClassInstanceCache;
public class ValueSelectorFactory<Solution_>
extends AbstractSelectorFactory<Solution_, ValueSelectorConfig> {
public static <Solution_> ValueSelectorFactory<Solution_> create(ValueSelectorConfig valueSelectorConfig) {
return new ValueSelectorFactory<>(valueSelectorConfig);
}
public ValueSelectorFactory(ValueSelectorConfig valueSelectorConfig) {
super(valueSelectorConfig);
}
public GenuineVariableDescriptor<Solution_> extractVariableDescriptor(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor) {
String variableName = config.getVariableName();
if (variableName != null) {
return getVariableDescriptorForName(downcastEntityDescriptor(configPolicy, entityDescriptor), variableName);
} else if (config.getMimicSelectorRef() != null) {
return configPolicy.getValueMimicRecorder(config.getMimicSelectorRef()).getVariableDescriptor();
} else {
return null;
}
}
/**
* @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 ValueSelector<Solution_> buildValueSelector(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder) {
return buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder,
configPolicy.isReinitializeVariableFilterEnabled(), ListValueFilteringType.NONE);
}
public ValueSelector<Solution_> buildValueSelector(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder, boolean applyReinitializeVariableFiltering,
ListValueFilteringType listValueFilteringType) {
GenuineVariableDescriptor<Solution_> variableDescriptor = deduceGenuineVariableDescriptor(
downcastEntityDescriptor(configPolicy, entityDescriptor), config.getVariableName());
if (config.getMimicSelectorRef() != null) {
ValueSelector<Solution_> valueSelector = buildMimicReplaying(configPolicy);
valueSelector =
applyReinitializeVariableFiltering(applyReinitializeVariableFiltering, variableDescriptor, valueSelector);
valueSelector = applyDowncasting(valueSelector);
return valueSelector;
}
SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(config.getCacheType(), minimumCacheType);
SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(config.getSelectionOrder(), inheritedSelectionOrder);
if (config.getNearbySelectionConfig() != null) {
config.getNearbySelectionConfig().validateNearby(resolvedCacheType, resolvedSelectionOrder);
}
validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder);
validateSorting(resolvedSelectionOrder);
validateProbability(resolvedSelectionOrder);
validateSelectedLimit(minimumCacheType);
// baseValueSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely
ValueSelector<Solution_> valueSelector =
buildBaseValueSelector(variableDescriptor, SelectionCacheType.max(minimumCacheType, resolvedCacheType),
determineBaseRandomSelection(variableDescriptor, resolvedCacheType, resolvedSelectionOrder));
if (config.getNearbySelectionConfig() != null) {
// TODO Static filtering (such as movableEntitySelectionFilter) should affect nearbySelection too
valueSelector = applyNearbySelection(configPolicy, entityDescriptor, minimumCacheType,
resolvedSelectionOrder, valueSelector);
}
ClassInstanceCache instanceCache = configPolicy.getClassInstanceCache();
valueSelector = applyFiltering(valueSelector, instanceCache);
valueSelector = applyInitializedChainedValueFilter(configPolicy, variableDescriptor, valueSelector);
valueSelector = applySorting(resolvedCacheType, resolvedSelectionOrder, valueSelector, instanceCache);
valueSelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, valueSelector, instanceCache);
valueSelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, valueSelector);
valueSelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, valueSelector);
valueSelector = applySelectedLimit(valueSelector);
valueSelector = applyListValueFiltering(configPolicy, listValueFilteringType, variableDescriptor, valueSelector);
valueSelector = applyMimicRecording(configPolicy, valueSelector);
valueSelector =
applyReinitializeVariableFiltering(applyReinitializeVariableFiltering, variableDescriptor, valueSelector);
valueSelector = applyDowncasting(valueSelector);
return valueSelector;
}
protected ValueSelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy) {
if (config.getId() != null
|| config.getVariableName() != null
|| config.getCacheType() != null
|| config.getSelectionOrder() != null
|| config.getNearbySelectionConfig() != null
|| config.getFilterClass() != null
|| config.getSorterManner() != null
|| config.getSorterComparatorClass() != null
|| config.getSorterWeightFactoryClass() != null
|| config.getSorterOrder() != null
|| config.getSorterClass() != null
|| config.getProbabilityWeightFactoryClass() != null
|| config.getSelectedCountLimit() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with mimicSelectorRef (" + config.getMimicSelectorRef()
+ ") has another property that is not null.");
}
ValueMimicRecorder<Solution_> valueMimicRecorder = configPolicy.getValueMimicRecorder(config.getMimicSelectorRef());
if (valueMimicRecorder == null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has a mimicSelectorRef (" + config.getMimicSelectorRef()
+ ") for which no valueSelector with that id exists (in its solver phase).");
}
return new MimicReplayingValueSelector<>(valueMimicRecorder);
}
protected EntityDescriptor<Solution_> downcastEntityDescriptor(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor) {
if (config.getDowncastEntityClass() != null) {
Class<?> parentEntityClass = entityDescriptor.getEntityClass();
if (!parentEntityClass.isAssignableFrom(config.getDowncastEntityClass())) {
throw new IllegalStateException("The downcastEntityClass (" + config.getDowncastEntityClass()
+ ") is not a subclass of the parentEntityClass (" + parentEntityClass
+ ") configured by the " + EntitySelector.class.getSimpleName() + ".");
}
SolutionDescriptor<Solution_> solutionDescriptor = configPolicy.getSolutionDescriptor();
entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(config.getDowncastEntityClass());
if (entityDescriptor == null) {
throw new IllegalArgumentException("The selectorConfig (" + config
+ ") has an downcastEntityClass (" + config.getDowncastEntityClass()
+ ") that is not a known planning entity.\n"
+ "Check your solver configuration. If that class (" + config.getDowncastEntityClass().getSimpleName()
+ ") is not in the entityClassSet (" + solutionDescriptor.getEntityClassSet()
+ "), check your @" + PlanningSolution.class.getSimpleName()
+ " implementation's annotated methods too.");
}
}
return entityDescriptor;
}
protected boolean determineBaseRandomSelection(GenuineVariableDescriptor<Solution_> variableDescriptor,
SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) {
switch (resolvedSelectionOrder) {
case ORIGINAL:
return false;
case SORTED:
case SHUFFLED:
case PROBABILISTIC:
// baseValueSelector and lower should be ORIGINAL if they are going to get cached completely
return false;
case RANDOM:
// Predict if caching will occur
return resolvedCacheType.isNotCached()
|| (isBaseInherentlyCached(variableDescriptor) && !hasFiltering(variableDescriptor));
default:
throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder
+ ") is not implemented.");
}
}
protected boolean isBaseInherentlyCached(GenuineVariableDescriptor<Solution_> variableDescriptor) {
return variableDescriptor.isValueRangeEntityIndependent();
}
private ValueSelector<Solution_> buildBaseValueSelector(GenuineVariableDescriptor<Solution_> variableDescriptor,
SelectionCacheType minimumCacheType, boolean randomSelection) {
ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
// TODO minimumCacheType SOLVER is only a problem if the valueRange includes entities or custom weird cloning
if (minimumCacheType == SelectionCacheType.SOLVER) {
// TODO Solver cached entities are not compatible with ConstraintStreams and IncrementalScoreDirector
// because between phases the entities get cloned
throw new IllegalArgumentException("The minimumCacheType (" + minimumCacheType
+ ") is not yet supported. Please use " + SelectionCacheType.PHASE + " instead.");
}
if (valueRangeDescriptor.isEntityIndependent()) {
return new FromSolutionPropertyValueSelector<>(
(EntityIndependentValueRangeDescriptor<Solution_>) valueRangeDescriptor, minimumCacheType,
randomSelection);
} else {
// TODO Do not allow PHASE cache on FromEntityPropertyValueSelector, except if the moveSelector is PHASE cached too.
return new FromEntityPropertyValueSelector<>(valueRangeDescriptor, randomSelection);
}
}
private boolean hasFiltering(GenuineVariableDescriptor<Solution_> variableDescriptor) {
return config.getFilterClass() != null ||
(variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.hasMovableChainedTrailingValueFilter());
}
protected ValueSelector<Solution_> applyFiltering(ValueSelector<Solution_> valueSelector,
ClassInstanceCache instanceCache) {
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
if (hasFiltering(variableDescriptor)) {
List<SelectionFilter<Solution_, Object>> filterList = new ArrayList<>(config.getFilterClass() == null ? 1 : 2);
if (config.getFilterClass() != null) {
filterList.add(instanceCache.newInstance(config, "filterClass", config.getFilterClass()));
}
// Filter out pinned entities
if (variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.hasMovableChainedTrailingValueFilter()) {
filterList.add(basicVariableDescriptor.getMovableChainedTrailingValueFilter());
}
valueSelector = FilteringValueSelector.of(valueSelector, SelectionFilter.compose(filterList));
}
return valueSelector;
}
protected ValueSelector<Solution_> applyInitializedChainedValueFilter(HeuristicConfigPolicy<Solution_> configPolicy,
GenuineVariableDescriptor<Solution_> variableDescriptor, ValueSelector<Solution_> valueSelector) {
boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.isChained();
if (configPolicy.isInitializedChainedValueFilterEnabled() && isChained) {
valueSelector = InitializedValueSelector.create(valueSelector);
}
return valueSelector;
}
protected void validateSorting(SelectionOrder resolvedSelectionOrder) {
if ((config.getSorterManner() != null || config.getSorterComparatorClass() != null
|| config.getSorterWeightFactoryClass() != null
|| config.getSorterOrder() != null || config.getSorterClass() != null)
&& resolvedSelectionOrder != SelectionOrder.SORTED) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with sorterManner (" + config.getSorterManner()
+ ") and sorterComparatorClass (" + config.getSorterComparatorClass()
+ ") and sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass()
+ ") and sorterOrder (" + config.getSorterOrder()
+ ") and sorterClass (" + config.getSorterClass()
+ ") has a resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") that is not " + SelectionOrder.SORTED + ".");
}
if (config.getSorterManner() != null && config.getSorterComparatorClass() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has both a sorterManner (" + config.getSorterManner()
+ ") and a sorterComparatorClass (" + config.getSorterComparatorClass() + ").");
}
if (config.getSorterManner() != null && config.getSorterWeightFactoryClass() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has both a sorterManner (" + config.getSorterManner()
+ ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ").");
}
if (config.getSorterManner() != null && config.getSorterClass() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has both a sorterManner (" + config.getSorterManner()
+ ") and a sorterClass (" + config.getSorterClass() + ").");
}
if (config.getSorterManner() != null && config.getSorterOrder() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with sorterManner (" + config.getSorterManner()
+ ") has a non-null sorterOrder (" + config.getSorterOrder() + ").");
}
if (config.getSorterComparatorClass() != null && config.getSorterWeightFactoryClass() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has both a sorterComparatorClass (" + config.getSorterComparatorClass()
+ ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ").");
}
if (config.getSorterComparatorClass() != null && config.getSorterClass() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has both a sorterComparatorClass (" + config.getSorterComparatorClass()
+ ") and a sorterClass (" + config.getSorterClass() + ").");
}
if (config.getSorterWeightFactoryClass() != null && config.getSorterClass() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has both a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass()
+ ") and a sorterClass (" + config.getSorterClass() + ").");
}
if (config.getSorterClass() != null && config.getSorterOrder() != null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with sorterClass (" + config.getSorterClass()
+ ") has a non-null sorterOrder (" + config.getSorterOrder() + ").");
}
}
protected ValueSelector<Solution_> applySorting(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder,
ValueSelector<Solution_> valueSelector, ClassInstanceCache instanceCache) {
if (resolvedSelectionOrder == SelectionOrder.SORTED) {
SelectionSorter<Solution_, Object> sorter;
if (config.getSorterManner() != null) {
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
if (!ValueSelectorConfig.hasSorter(config.getSorterManner(), variableDescriptor)) {
return valueSelector;
}
sorter = ValueSelectorConfig.determineSorter(config.getSorterManner(), variableDescriptor);
} else if (config.getSorterComparatorClass() != null) {
Comparator<Object> sorterComparator =
instanceCache.newInstance(config, "sorterComparatorClass", config.getSorterComparatorClass());
sorter = new ComparatorSelectionSorter<>(sorterComparator,
SelectionSorterOrder.resolve(config.getSorterOrder()));
} else if (config.getSorterWeightFactoryClass() != null) {
SelectionSorterWeightFactory<Solution_, Object> sorterWeightFactory =
instanceCache.newInstance(config, "sorterWeightFactoryClass", config.getSorterWeightFactoryClass());
sorter = new WeightFactorySelectionSorter<>(sorterWeightFactory,
SelectionSorterOrder.resolve(config.getSorterOrder()));
} else if (config.getSorterClass() != null) {
sorter = instanceCache.newInstance(config, "sorterClass", config.getSorterClass());
} else {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs a sorterManner (" + config.getSorterManner()
+ ") or a sorterComparatorClass (" + config.getSorterComparatorClass()
+ ") or a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass()
+ ") or a sorterClass (" + config.getSorterClass() + ").");
}
if (!valueSelector.getVariableDescriptor().isValueRangeEntityIndependent()
&& resolvedCacheType == SelectionCacheType.STEP) {
valueSelector = new EntityDependentSortingValueSelector<>(valueSelector, resolvedCacheType, sorter);
} else {
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with resolvedCacheType (" + resolvedCacheType
+ ") and resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
valueSelector = new SortingValueSelector<>((EntityIndependentValueSelector<Solution_>) valueSelector,
resolvedCacheType, sorter);
}
}
return valueSelector;
}
protected void validateProbability(SelectionOrder resolvedSelectionOrder) {
if (config.getProbabilityWeightFactoryClass() != null
&& resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass()
+ ") has a resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") that is not " + SelectionOrder.PROBABILISTIC + ".");
}
}
protected ValueSelector<Solution_> applyProbability(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector, ClassInstanceCache instanceCache) {
if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) {
if (config.getProbabilityWeightFactoryClass() == null) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs a probabilityWeightFactoryClass ("
+ config.getProbabilityWeightFactoryClass() + ").");
}
SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory = instanceCache.newInstance(config,
"probabilityWeightFactoryClass", config.getProbabilityWeightFactoryClass());
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with resolvedCacheType (" + resolvedCacheType
+ ") and resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
valueSelector = new ProbabilityValueSelector<>((EntityIndependentValueSelector<Solution_>) valueSelector,
resolvedCacheType, probabilityWeightFactory);
}
return valueSelector;
}
private ValueSelector<Solution_> applyShuffling(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector) {
if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) {
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with resolvedCacheType (" + resolvedCacheType
+ ") and resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
valueSelector = new ShufflingValueSelector<>((EntityIndependentValueSelector<Solution_>) valueSelector,
resolvedCacheType);
}
return valueSelector;
}
private ValueSelector<Solution_> applyCaching(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector) {
if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(valueSelector.getCacheType()) > 0) {
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with resolvedCacheType (" + resolvedCacheType
+ ") and resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
valueSelector = new CachingValueSelector<>((EntityIndependentValueSelector<Solution_>) valueSelector,
resolvedCacheType, resolvedSelectionOrder.toRandomSelectionBoolean());
}
return valueSelector;
}
private void validateSelectedLimit(SelectionCacheType minimumCacheType) {
if (config.getSelectedCountLimit() != null && minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with selectedCountLimit (" + config.getSelectedCountLimit()
+ ") has a minimumCacheType (" + minimumCacheType
+ ") that is higher than " + SelectionCacheType.JUST_IN_TIME + ".");
}
}
private ValueSelector<Solution_> applySelectedLimit(ValueSelector<Solution_> valueSelector) {
if (config.getSelectedCountLimit() != null) {
valueSelector = new SelectedCountLimitValueSelector<>(valueSelector, config.getSelectedCountLimit());
}
return valueSelector;
}
private ValueSelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType,
SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector) {
return TimefoldSolverEnterpriseService
.loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION)
.applyNearbySelection(config, configPolicy, entityDescriptor, minimumCacheType, resolvedSelectionOrder,
valueSelector);
}
private ValueSelector<Solution_> applyMimicRecording(HeuristicConfigPolicy<Solution_> configPolicy,
ValueSelector<Solution_> valueSelector) {
if (config.getId() != null) {
if (config.getId().isEmpty()) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") has an empty id (" + config.getId() + ").");
}
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with id (" + config.getId()
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
MimicRecordingValueSelector<Solution_> mimicRecordingValueSelector = new MimicRecordingValueSelector<>(
(EntityIndependentValueSelector<Solution_>) valueSelector);
configPolicy.addValueMimicRecorder(config.getId(), mimicRecordingValueSelector);
valueSelector = mimicRecordingValueSelector;
}
return valueSelector;
}
ValueSelector<Solution_> applyListValueFiltering(HeuristicConfigPolicy<?> configPolicy,
ListValueFilteringType listValueFilteringType,
GenuineVariableDescriptor<Solution_> variableDescriptor, ValueSelector<Solution_> valueSelector) {
if (variableDescriptor.isListVariable() && configPolicy.isUnassignedValuesAllowed()
&& listValueFilteringType != ListValueFilteringType.NONE) {
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The valueSelectorConfig (" + config
+ ") with id (" + config.getId()
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
valueSelector = listValueFilteringType == ListValueFilteringType.ACCEPT_ASSIGNED
? new AssignedListValueSelector<>(((EntityIndependentValueSelector<Solution_>) valueSelector))
: new UnassignedListValueSelector<>(((EntityIndependentValueSelector<Solution_>) valueSelector));
}
return valueSelector;
}
private ValueSelector<Solution_> applyReinitializeVariableFiltering(boolean applyReinitializeVariableFiltering,
GenuineVariableDescriptor<Solution_> variableDescriptor, ValueSelector<Solution_> valueSelector) {
if (applyReinitializeVariableFiltering && !variableDescriptor.isListVariable()) {
valueSelector = new ReinitializeVariableValueSelector<>(valueSelector);
}
return valueSelector;
}
private ValueSelector<Solution_> applyDowncasting(ValueSelector<Solution_> valueSelector) {
if (config.getDowncastEntityClass() != null) {
valueSelector = new DowncastingValueSelector<>(valueSelector, config.getDowncastEntityClass());
}
return valueSelector;
}
public enum ListValueFilteringType {
NONE,
ACCEPT_ASSIGNED,
ACCEPT_UNASSIGNED,
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/chained/DefaultSubChainSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.chained;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge;
import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* This is the common {@link SubChainSelector} implementation.
*/
public class DefaultSubChainSelector<Solution_> extends AbstractSelector<Solution_>
implements SubChainSelector<Solution_>, SelectionCacheLifecycleListener<Solution_> {
protected static final SelectionCacheType CACHE_TYPE = SelectionCacheType.STEP;
protected final EntityIndependentValueSelector<Solution_> valueSelector;
protected final boolean randomSelection;
protected SingletonInverseVariableSupply inverseVariableSupply;
// The sub selection here is a sequence. For example from ABCDE, it can select BCD, but not ACD.
protected final int minimumSubChainSize;
protected final int maximumSubChainSize;
protected List<SubChain> anchorTrailingChainList = null;
public DefaultSubChainSelector(EntityIndependentValueSelector<Solution_> valueSelector, boolean randomSelection,
int minimumSubChainSize, int maximumSubChainSize) {
this.valueSelector = valueSelector;
this.randomSelection = randomSelection;
boolean isChained =
valueSelector.getVariableDescriptor() instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.isChained();
if (!isChained) {
throw new IllegalArgumentException(
"The selector (%s)'s valueSelector (%s) must have a chained variableDescriptor chained (%s)."
.formatted(this, valueSelector, isChained));
}
if (valueSelector.isNeverEnding()) {
throw new IllegalStateException(
"The selector (%s) has a valueSelector (%s) with neverEnding (%s)."
.formatted(this, valueSelector, valueSelector.isNeverEnding()));
}
phaseLifecycleSupport.addEventListener(valueSelector);
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(CACHE_TYPE, this));
this.minimumSubChainSize = minimumSubChainSize;
this.maximumSubChainSize = maximumSubChainSize;
if (minimumSubChainSize < 1) {
throw new IllegalStateException("The selector (%s)'s minimumSubChainSize (%d) must be at least 1."
.formatted(this, minimumSubChainSize));
}
if (minimumSubChainSize > maximumSubChainSize) {
throw new IllegalStateException("The minimumSubChainSize (%d) must be less than maximumSubChainSize (%d)."
.formatted(minimumSubChainSize, maximumSubChainSize));
}
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return valueSelector.getVariableDescriptor();
}
@Override
public SelectionCacheType getCacheType() {
return CACHE_TYPE;
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor));
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
inverseVariableSupply = null;
}
// ************************************************************************
// Cache lifecycle methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
long valueSize = valueSelector.getSize();
// Fail-fast when anchorTrailingChainList.size() could ever be too big
if (valueSize > Integer.MAX_VALUE) {
throw new IllegalStateException(
"The selector (%s) has a valueSelector (%s) with valueSize (%d) which is higher than Integer.MAX_VALUE."
.formatted(this, valueSelector, valueSize));
}
List<Object> anchorList = new ArrayList<>();
for (Object value : valueSelector) {
if (variableDescriptor.isValuePotentialAnchor(value)) {
anchorList.add(value);
}
}
int anchorListSize = Math.max(anchorList.size(), 1);
anchorTrailingChainList = new ArrayList<>(anchorListSize);
int anchorChainInitialCapacity = ((int) valueSize / anchorListSize) + 1;
for (Object anchor : anchorList) {
List<Object> anchorChain = new ArrayList<>(anchorChainInitialCapacity);
Object trailingEntity = inverseVariableSupply.getInverseSingleton(anchor);
while (trailingEntity != null) {
anchorChain.add(trailingEntity);
trailingEntity = inverseVariableSupply.getInverseSingleton(trailingEntity);
}
if (anchorChain.size() >= minimumSubChainSize) {
anchorTrailingChainList.add(new SubChain(anchorChain));
}
}
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
anchorTrailingChainList = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return randomSelection;
}
@Override
public long getSize() {
long selectionSize = 0L;
for (SubChain anchorTrailingChain : anchorTrailingChainList) {
selectionSize += calculateSubChainSelectionSize(anchorTrailingChain);
}
return selectionSize;
}
protected long calculateSubChainSelectionSize(SubChain anchorTrailingChain) {
long anchorTrailingChainSize = anchorTrailingChain.getSize();
long n = anchorTrailingChainSize - minimumSubChainSize + 1L;
long m = (maximumSubChainSize >= anchorTrailingChainSize)
? 0L
: anchorTrailingChainSize - maximumSubChainSize;
return (n * (n + 1L) / 2L) - (m * (m + 1L) / 2L);
}
@Override
public Iterator<SubChain> iterator() {
if (!randomSelection) {
return new OriginalSubChainIterator(anchorTrailingChainList.listIterator());
} else {
return new RandomSubChainIterator();
}
}
@Override
public ListIterator<SubChain> listIterator() {
if (!randomSelection) {
return new OriginalSubChainIterator(anchorTrailingChainList.listIterator());
} else {
throw new IllegalStateException("The selector (%s) does not support a ListIterator with randomSelection (%s)."
.formatted(this, randomSelection));
}
}
@Override
public ListIterator<SubChain> listIterator(int index) {
if (!randomSelection) {
// TODO Implement more efficient ListIterator https://issues.redhat.com/browse/PLANNER-37
OriginalSubChainIterator it = new OriginalSubChainIterator(anchorTrailingChainList.listIterator());
for (int i = 0; i < index; i++) {
it.next();
}
return it;
} else {
throw new IllegalStateException("The selector (%s) does not support a ListIterator with randomSelection (%s)."
.formatted(this, randomSelection));
}
}
private class OriginalSubChainIterator extends UpcomingSelectionIterator<SubChain>
implements ListIterator<SubChain> {
private final ListIterator<SubChain> anchorTrailingChainIterator;
private List<Object> anchorTrailingChain;
private int fromIndex; // Inclusive
private int toIndex; // Exclusive
private int nextListIteratorIndex;
public OriginalSubChainIterator(ListIterator<SubChain> anchorTrailingChainIterator) {
this.anchorTrailingChainIterator = anchorTrailingChainIterator;
fromIndex = 0;
toIndex = 1;
anchorTrailingChain = Collections.emptyList();
nextListIteratorIndex = 0;
}
@Override
protected SubChain createUpcomingSelection() {
toIndex++;
if (toIndex - fromIndex > maximumSubChainSize || toIndex > anchorTrailingChain.size()) {
fromIndex++;
toIndex = fromIndex + minimumSubChainSize;
// minimumSubChainSize <= maximumSubChainSize so (toIndex - fromIndex > maximumSubChainSize) is true
while (toIndex > anchorTrailingChain.size()) {
if (!anchorTrailingChainIterator.hasNext()) {
return noUpcomingSelection();
}
anchorTrailingChain = anchorTrailingChainIterator.next().getEntityList();
fromIndex = 0;
toIndex = fromIndex + minimumSubChainSize;
}
}
return new SubChain(anchorTrailingChain.subList(fromIndex, toIndex));
}
@Override
public SubChain next() {
nextListIteratorIndex++;
return super.next();
}
@Override
public int nextIndex() {
return nextListIteratorIndex;
}
@Override
public boolean hasPrevious() {
throw new UnsupportedOperationException();
}
@Override
public SubChain previous() {
throw new UnsupportedOperationException();
}
@Override
public int previousIndex() {
throw new UnsupportedOperationException();
}
@Override
public void set(SubChain subChain) {
throw new UnsupportedOperationException("The optional operation set() is not supported.");
}
@Override
public void add(SubChain subChain) {
throw new UnsupportedOperationException("The optional operation add() is not supported.");
}
}
private class RandomSubChainIterator extends UpcomingSelectionIterator<SubChain> {
private RandomSubChainIterator() {
if (anchorTrailingChainList.isEmpty()) {
upcomingSelection = noUpcomingSelection();
upcomingCreated = true;
}
}
@Override
protected SubChain createUpcomingSelection() {
SubChain anchorTrailingChain = selectAnchorTrailingChain();
// Every SubChain has the same probability (from this point on at least).
// A random fromIndex and random toIndex would not be fair.
long selectionSize = calculateSubChainSelectionSize(anchorTrailingChain);
// Black magic to translate selectionIndex into fromIndex and toIndex
long fromIndex = RandomUtils.nextLong(workingRandom, selectionSize);
long subChainSize = minimumSubChainSize;
long countInThatSize = anchorTrailingChain.getSize() - subChainSize + 1;
while (fromIndex >= countInThatSize) {
fromIndex -= countInThatSize;
subChainSize++;
countInThatSize--;
if (countInThatSize <= 0) {
throw new IllegalStateException("Impossible if calculateSubChainSelectionSize() works correctly.");
}
}
return anchorTrailingChain.subChain((int) fromIndex, (int) (fromIndex + subChainSize));
}
private SubChain selectAnchorTrailingChain() {
// Known issue/compromise: Every SubChain should have same probability, but doesn't.
// Instead, every anchorTrailingChain has the same probability.
int anchorTrailingChainListIndex = workingRandom.nextInt(anchorTrailingChainList.size());
return anchorTrailingChainList.get(anchorTrailingChainListIndex);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + valueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/chained/SubChainSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.value.chained;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.chained.SubChainSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public 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) {
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));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/AbstractCachingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge;
import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public abstract class AbstractCachingValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_>, ValueSelector<Solution_> {
protected final EntityIndependentValueSelector<Solution_> childValueSelector;
protected final SelectionCacheType cacheType;
protected List<Object> cachedValueList = null;
public AbstractCachingValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector,
SelectionCacheType cacheType) {
this.childValueSelector = childValueSelector;
this.cacheType = cacheType;
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));
}
public ValueSelector<Solution_> getChildValueSelector() {
return childValueSelector;
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
long childSize = childValueSelector.getSize();
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.");
}
cachedValueList = new ArrayList<>((int) childSize);
// TODO Fail-faster if a non FromSolutionPropertyValueSelector is used
childValueSelector.iterator().forEachRemaining(cachedValueList::add);
logger.trace(" Created cachedValueList: size ({}), valueSelector ({}).",
cachedValueList.size(), this);
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
cachedValueList = null;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childValueSelector.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public long getSize(Object entity) {
return getSize();
}
public long getSize() {
return cachedValueList.size();
}
@Override
public Iterator<Object> endingIterator(Object entity) {
return endingIterator();
}
public Iterator<Object> endingIterator() {
return cachedValueList.iterator();
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
AbstractCachingValueSelector<?> that = (AbstractCachingValueSelector<?>) other;
return Objects.equals(childValueSelector, that.childValueSelector) && cacheType == that.cacheType;
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector, cacheType);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/AbstractInverseEntityFilteringValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.Objects;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
/**
* Filters planning values based on their assigned status. The assigned status is determined using the inverse supply.
* If the inverse entity is not null, the value is assigned, otherwise it is unassigned.
* A subclass must implement the {@link #valueFilter(Object)} to decide whether assigned or unassigned values will be selected.
* <p>
* Does implement {@link EntityIndependentValueSelector} because the question whether a value is assigned or not does not depend
* on a specific entity.
*/
abstract class AbstractInverseEntityFilteringValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
protected final EntityIndependentValueSelector<Solution_> childValueSelector;
protected ListVariableStateSupply<Solution_> listVariableStateSupply;
protected AbstractInverseEntityFilteringValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector) {
if (childValueSelector.isNeverEnding()) {
throw new IllegalArgumentException("The selector (" + this
+ ") has a childValueSelector (" + childValueSelector
+ ") with neverEnding (" + childValueSelector.isNeverEnding() + ").\n"
+ "This is not allowed because " + AbstractInverseEntityFilteringValueSelector.class.getSimpleName()
+ " cannot decorate a never-ending child value selector.\n"
+ "This could be a result of using random selection order (which is often the default).");
}
this.childValueSelector = childValueSelector;
phaseLifecycleSupport.addEventListener(childValueSelector);
}
protected abstract boolean valueFilter(Object value);
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
ListVariableDescriptor<Solution_> variableDescriptor =
(ListVariableDescriptor<Solution_>) childValueSelector.getVariableDescriptor();
listVariableStateSupply = phaseScope.getScoreDirector().getSupplyManager()
.demand(variableDescriptor.getStateDemand());
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
listVariableStateSupply = null;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return childValueSelector.getVariableDescriptor();
}
@Override
public boolean isCountable() {
// Because !neverEnding => countable.
return true;
}
@Override
public boolean isNeverEnding() {
// Because the childValueSelector is not never-ending.
return false;
}
@Override
public long getSize(Object entity) {
return getSize();
}
@Override
public long getSize() {
return streamUnassignedValues().count();
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {
return streamUnassignedValues().iterator();
}
@Override
public Iterator<Object> endingIterator(Object entity) {
return iterator();
}
private Stream<Object> streamUnassignedValues() {
return StreamSupport.stream(childValueSelector.spliterator(), false)
// Accept either assigned or unassigned values.
.filter(this::valueFilter);
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
AbstractInverseEntityFilteringValueSelector<?> that = (AbstractInverseEntityFilteringValueSelector<?>) other;
return Objects.equals(childValueSelector, that.childValueSelector);
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/AssignedListValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementDestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
/**
* Only selects values from the child value selector that are initialized.
* This is used for {@link ElementDestinationSelector}’s child value selector during Construction Heuristic phase
* to filter out values which cannot be used to build a destination {@link LocationInList}.
*/
public final class AssignedListValueSelector<Solution_> extends AbstractInverseEntityFilteringValueSelector<Solution_> {
public AssignedListValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector) {
super(childValueSelector);
}
@Override
protected boolean valueFilter(Object value) {
if (listVariableStateSupply.getUnassignedCount() == 0) {
return true; // Avoid hash lookup.
}
return listVariableStateSupply.isAssigned(value);
}
@Override
public String toString() {
return "Assigned(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/CachingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.CachingEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.CachingMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
/**
* A {@link ValueSelector} that caches the result of its child {@link ValueSelector}.
* <p>
* Keep this code in sync with {@link CachingEntitySelector} and {@link CachingMoveSelector}.
*/
public final class CachingValueSelector<Solution_>
extends AbstractCachingValueSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
protected final boolean randomSelection;
public CachingValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector,
SelectionCacheType cacheType, boolean randomSelection) {
super(childValueSelector, cacheType);
this.randomSelection = randomSelection;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public Iterator<Object> iterator(Object entity) {
return iterator();
}
@Override
public Iterator<Object> iterator() {
if (!randomSelection) {
return cachedValueList.iterator();
} else {
return new CachedListRandomIterator<>(cachedValueList, workingRandom);
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
if (!super.equals(other))
return false;
CachingValueSelector<?> that = (CachingValueSelector<?>) other;
return randomSelection == that.randomSelection;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), randomSelection);
}
@Override
public String toString() {
return "Caching(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/EntityDependentSortingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
public final 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) {
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();
}
@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 + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/EntityIndependentFilteringValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
public final class EntityIndependentFilteringValueSelector<Solution_>
extends FilteringValueSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
EntityIndependentFilteringValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector,
SelectionFilter<Solution_, Object> filter) {
super(childValueSelector, filter);
}
@Override
public long getSize() {
return ((EntityIndependentValueSelector<Solution_>) childValueSelector).getSize();
}
@Override
public Iterator<Object> iterator() {
return new JustInTimeFilteringValueIterator(((EntityIndependentValueSelector<Solution_>) childValueSelector).iterator(),
determineBailOutSize());
}
private long determineBailOutSize() {
if (!bailOutEnabled) {
return -1L;
}
return ((EntityIndependentValueSelector<Solution_>) childValueSelector).getSize() * 10L;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/EntityIndependentInitializedValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
public final 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() {
if (!bailOutEnabled) {
return -1L;
}
return ((EntityIndependentValueSelector<Solution_>) childValueSelector).getSize() * 10L;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/FilteringValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
public class FilteringValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ValueSelector<Solution_> {
public static <Solution_> ValueSelector<Solution_> of(ValueSelector<Solution_> valueSelector,
SelectionFilter<Solution_, Object> filter) {
if (valueSelector instanceof EntityIndependentFilteringValueSelector<Solution_> filteringValueSelector) {
return new EntityIndependentFilteringValueSelector<>(
(EntityIndependentValueSelector<Solution_>) filteringValueSelector.childValueSelector,
SelectionFilter.compose(filteringValueSelector.selectionFilter, filter));
} else if (valueSelector instanceof FilteringValueSelector<Solution_> filteringValueSelector) {
return new FilteringValueSelector<>(filteringValueSelector.childValueSelector,
SelectionFilter.compose(filteringValueSelector.selectionFilter, filter));
} else if (valueSelector instanceof EntityIndependentValueSelector<Solution_> entityIndependentValueSelector) {
return new EntityIndependentFilteringValueSelector<>(entityIndependentValueSelector, filter);
} else {
return new FilteringValueSelector<>(valueSelector, filter);
}
}
protected final ValueSelector<Solution_> childValueSelector;
final SelectionFilter<Solution_, Object> selectionFilter;
protected final boolean bailOutEnabled;
private ScoreDirector<Solution_> scoreDirector = null;
protected FilteringValueSelector(ValueSelector<Solution_> childValueSelector, SelectionFilter<Solution_, Object> filter) {
this.childValueSelector = Objects.requireNonNull(childValueSelector);
this.selectionFilter = Objects.requireNonNull(filter);
bailOutEnabled = childValueSelector.isNeverEnding();
phaseLifecycleSupport.addEventListener(childValueSelector);
}
// ************************************************************************
// 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 boolean isCountable() {
return childValueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childValueSelector.isNeverEnding();
}
@Override
public long getSize(Object entity) {
return childValueSelector.getSize(entity);
}
@Override
public Iterator<Object> iterator(Object entity) {
return new JustInTimeFilteringValueIterator(childValueSelector.iterator(entity),
determineBailOutSize(entity));
}
protected 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() {
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.debug("Bailing out of neverEnding selector ({}) to avoid infinite loop.",
FilteringValueSelector.this);
return noUpcomingSelection();
}
attemptsBeforeBailOut--;
}
next = childValueIterator.next();
} while (!selectionFilter.accept(scoreDirector, next));
return next;
}
}
@Override
public Iterator<Object> endingIterator(Object entity) {
return new JustInTimeFilteringValueIterator(childValueSelector.endingIterator(entity),
determineBailOutSize(entity));
}
protected long determineBailOutSize(Object entity) {
if (!bailOutEnabled) {
return -1L;
}
return childValueSelector.getSize(entity) * 10L;
}
@Override
public boolean equals(Object o) {
return o instanceof FilteringValueSelector<?> that
&& Objects.equals(childValueSelector, that.childValueSelector)
&& Objects.equals(selectionFilter, that.selectionFilter);
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector, selectionFilter);
}
@Override
public String toString() {
return "Filtering(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/InitializedValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
/**
* Prevents creating chains without an anchor.
* <p>
* Filters out every value that is a planning entity for which the {@link PlanningVariable}
* (on which this {@link ValueSelector} applies to) is uninitialized.
* <p>
* Mainly used for chained planning variables, but supports other planning variables too.
*/
public class InitializedValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ValueSelector<Solution_> {
public static <Solution_> ValueSelector<Solution_> create(ValueSelector<Solution_> valueSelector) {
if (valueSelector instanceof EntityIndependentValueSelector) {
return new EntityIndependentInitializedValueSelector<>((EntityIndependentValueSelector<Solution_>) valueSelector);
} else {
return new InitializedValueSelector<>(valueSelector);
}
}
private final GenuineVariableDescriptor<Solution_> variableDescriptor;
final ValueSelector<Solution_> childValueSelector;
final boolean bailOutEnabled;
InitializedValueSelector(ValueSelector<Solution_> childValueSelector) {
this.variableDescriptor = childValueSelector.getVariableDescriptor();
this.childValueSelector = childValueSelector;
bailOutEnabled = childValueSelector.isNeverEnding();
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) {
// TODO use cached results
return childValueSelector.getSize(entity);
}
@Override
public Iterator<Object> iterator(Object entity) {
return new JustInTimeInitializedValueIterator(entity, childValueSelector.iterator(entity));
}
@Override
public Iterator<Object> endingIterator(Object entity) {
return new JustInTimeInitializedValueIterator(entity, childValueSelector.endingIterator(entity));
}
protected 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() {
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.debug("Bailing out of neverEnding selector ({}) to avoid infinite loop.",
InitializedValueSelector.this);
return noUpcomingSelection();
}
attemptsBeforeBailOut--;
}
next = childValueIterator.next();
} while (!accept(next));
return next;
}
}
protected long determineBailOutSize(Object entity) {
if (!bailOutEnabled) {
return -1L;
}
return childValueSelector.getSize(entity) * 10L;
}
protected boolean accept(Object value) {
return value == null
|| !variableDescriptor.getEntityDescriptor().getEntityClass().isAssignableFrom(value.getClass())
|| variableDescriptor.isInitialized(value);
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
InitializedValueSelector<?> that = (InitializedValueSelector<?>) other;
return Objects.equals(variableDescriptor, that.variableDescriptor)
&& Objects.equals(childValueSelector, that.childValueSelector);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, childValueSelector);
}
@Override
public String toString() {
return "Initialized(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/MovableChainedTrailingValueFilter.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final 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) {
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);
}
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);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/ProbabilityValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.TreeMap;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge;
import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public final 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() {
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.");
}
};
}
@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 + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/ReinitializeVariableValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Collections;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
/**
* Prevents reassigning of already initialized variables during Construction Heuristics and Exhaustive Search.
* <p>
* Returns no values for an entity's variable if the variable is not reinitializable.
* <p>
* Does not implement {@link EntityIndependentValueSelector} because if used like that,
* it shouldn't be added during configuration in the first place.
*/
public final 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) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ReinitializeVariableValueSelector<?> that = (ReinitializeVariableValueSelector<?>) other;
return Objects.equals(childValueSelector, that.childValueSelector);
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector);
}
@Override
public String toString() {
return "Reinitialize(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/SelectedCountLimitValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
public final 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() {
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);
}
@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 + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/ShufflingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Collections;
import java.util.Iterator;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
public final 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() {
Collections.shuffle(cachedValueList, workingRandom);
logger.trace(" Shuffled cachedValueList with size ({}) in valueSelector({}).",
cachedValueList.size(), this);
return cachedValueList.iterator();
}
@Override
public String toString() {
return "Shuffling(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/SortingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import java.util.Iterator;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public final 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) {
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);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sorter);
}
@Override
public String toString() {
return "Sorting(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/UnassignedListValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.decorator;
import ai.timefold.solver.core.impl.constructionheuristic.placer.QueuedValuePlacer;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
/**
* Only selects values from the child value selector that are uninitialized.
* This used for {@link QueuedValuePlacer}’s recording value selector during Construction Heuristic phase
* to prevent reinitializing values.
*/
public final class UnassignedListValueSelector<Solution_> extends AbstractInverseEntityFilteringValueSelector<Solution_> {
public UnassignedListValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector) {
super(childValueSelector);
}
@Override
protected boolean valueFilter(Object value) {
if (listVariableStateSupply.getUnassignedCount() == 0) {
return false; // Avoid hash lookup.
}
return !listVariableStateSupply.isAssigned(value);
}
@Override
public String toString() {
return "Unassigned(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/mimic/MimicRecordingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.mimic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
public class MimicRecordingValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ValueMimicRecorder<Solution_>, EntityIndependentValueSelector<Solution_> {
protected final EntityIndependentValueSelector<Solution_> childValueSelector;
protected final List<MimicReplayingValueSelector<Solution_>> replayingValueSelectorList;
public MimicRecordingValueSelector(EntityIndependentValueSelector<Solution_> childValueSelector) {
this.childValueSelector = childValueSelector;
phaseLifecycleSupport.addEventListener(childValueSelector);
replayingValueSelectorList = new ArrayList<>();
}
@Override
public void addMimicReplayingValueSelector(MimicReplayingValueSelector<Solution_> replayingValueSelector) {
replayingValueSelectorList.add(replayingValueSelector);
}
// ************************************************************************
// 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) {
return childValueSelector.getSize(entity);
}
@Override
public long getSize() {
return childValueSelector.getSize();
}
@Override
public Iterator<Object> iterator(Object entity) {
return new RecordingValueIterator(childValueSelector.iterator(entity));
}
@Override
public Iterator<Object> iterator() {
return new RecordingValueIterator(childValueSelector.iterator());
}
private 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) {
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());
}
@Override
public int hashCode() {
return Objects.hash(childValueSelector, replayingValueSelectorList.size());
}
@Override
public String toString() {
return "Recording(" + childValueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/mimic/MimicReplayingValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.value.mimic;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
public class MimicReplayingValueSelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntityIndependentValueSelector<Solution_> {
protected final ValueMimicRecorder<Solution_> valueMimicRecorder;
protected boolean hasRecordingCreated;
protected boolean hasRecording;
protected boolean recordingCreated;
protected Object recording;
protected boolean recordingAlreadyReturned;
public MimicReplayingValueSelector(ValueMimicRecorder<Solution_> valueMimicRecorder) {
this.valueMimicRecorder = valueMimicRecorder;
// No PhaseLifecycleSupport because the MimicRecordingValueSelector is hooked up elsewhere too
valueMimicRecorder.addMimicReplayingValueSelector(this);
// Precondition for iterator(Object)'s current implementation
if (!valueMimicRecorder.getVariableDescriptor().isValueRangeEntityIndependent()) {
throw new IllegalArgumentException(
"The current implementation support only an entityIndependent variable ("
+ valueMimicRecorder.getVariableDescriptor() + ").");
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
// Doing this in phaseStarted instead of stepStarted due to QueuedValuePlacer compatibility
hasRecordingCreated = false;
recordingCreated = false;
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
// Doing this in phaseEnded instead of stepEnded due to QueuedValuePlacer compatibility
hasRecordingCreated = false;
hasRecording = false;
recordingCreated = false;
recording = null;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return valueMimicRecorder.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return valueMimicRecorder.isCountable();
}
@Override
public boolean isNeverEnding() {
return valueMimicRecorder.isNeverEnding();
}
@Override
public long getSize(Object entity) {
return valueMimicRecorder.getSize(entity);
}
@Override
public long getSize() {
return valueMimicRecorder.getSize();
}
@Override
public Iterator<Object> iterator(Object entity) {
// Ignores the entity, but the constructor of this class guarantees that the valueRange is entity independent
return new ReplayingValueIterator();
}
@Override
public Iterator<Object> iterator() {
return new ReplayingValueIterator();
}
public void recordedHasNext(boolean hasNext) {
hasRecordingCreated = true;
hasRecording = hasNext;
recordingCreated = false;
recording = null;
recordingAlreadyReturned = false;
}
public void recordedNext(Object next) {
hasRecordingCreated = true;
hasRecording = true;
recordingCreated = true;
recording = next;
recordingAlreadyReturned = false;
}
private class ReplayingValueIterator extends SelectionIterator<Object> {
private ReplayingValueIterator() {
// 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 recordingValueSelector (" + valueMimicRecorder
+ ")'s hasNext() has not been called yet. ");
}
return hasRecording && !recordingAlreadyReturned;
}
@Override
public Object next() {
if (!recordingCreated) {
throw new IllegalStateException("Replay must occur after record."
+ " The recordingValueSelector (" + valueMimicRecorder
+ ")'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() {
if (hasRecordingCreated && !hasRecording) {
return "No next replay";
}
return "Next replay (" + (recordingCreated ? recording : "?") + ")";
}
}
@Override
public Iterator<Object> endingIterator(Object entity) {
// No replaying, because the endingIterator() is used for determining size
return valueMimicRecorder.endingIterator(entity);
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MimicReplayingValueSelector<?> that = (MimicReplayingValueSelector<?>) other;
return Objects.equals(valueMimicRecorder, that.valueMimicRecorder);
}
@Override
public int hashCode() {
return Objects.hash(valueMimicRecorder);
}
@Override
public String toString() {
return "Replaying(" + valueMimicRecorder + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/value/mimic/ValueMimicRecorder.java | package ai.timefold.solver.core.impl.heuristic.selector.value.mimic;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
public interface ValueMimicRecorder<Solution_> {
/**
* @param replayingValueSelector never null
*/
void addMimicReplayingValueSelector(MimicReplayingValueSelector<Solution_> replayingValueSelector);
/**
* @return As defined by {@link ValueSelector#getVariableDescriptor()}
* @see ValueSelector#getVariableDescriptor()
*/
GenuineVariableDescriptor<Solution_> getVariableDescriptor();
/**
* @return As defined by {@link ValueSelector#isCountable()}
* @see ValueSelector#isCountable()
*/
boolean isCountable();
/**
* @return As defined by {@link ValueSelector#isNeverEnding()}
* @see ValueSelector#isNeverEnding()
*/
boolean isNeverEnding();
/**
* @return As defined by {@link EntityIndependentValueSelector#getSize()}
* @see EntityIndependentValueSelector#getSize()
*/
long getSize();
/**
* @return As defined by {@link ValueSelector#getSize(Object)}
* @see ValueSelector#getSize(Object)
*/
long getSize(Object entity);
/**
* @return As defined by {@link ValueSelector#endingIterator(Object)}
* @see ValueSelector#endingIterator(Object)
*/
Iterator<Object> endingIterator(Object entity);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/DefaultLocalSearchPhase.java | package ai.timefold.solver.core.impl.localsearch;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.localsearch.decider.LocalSearchDecider;
import ai.timefold.solver.core.impl.localsearch.event.LocalSearchPhaseLifecycleListener;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
/**
* Default implementation of {@link LocalSearchPhase}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class DefaultLocalSearchPhase<Solution_> extends AbstractPhase<Solution_> implements LocalSearchPhase<Solution_>,
LocalSearchPhaseLifecycleListener<Solution_> {
protected final LocalSearchDecider<Solution_> decider;
protected final AtomicLong acceptedMoveCountPerStep = new AtomicLong(0);
protected final AtomicLong selectedMoveCountPerStep = new AtomicLong(0);
protected final Map<Tags, AtomicLong> constraintMatchTotalTagsToStepCount = new ConcurrentHashMap<>();
protected final Map<Tags, AtomicLong> constraintMatchTotalTagsToBestCount = new ConcurrentHashMap<>();
protected final Map<Tags, List<AtomicReference<Number>>> constraintMatchTotalStepScoreMap = new ConcurrentHashMap<>();
protected final Map<Tags, List<AtomicReference<Number>>> constraintMatchTotalBestScoreMap = new ConcurrentHashMap<>();
private DefaultLocalSearchPhase(Builder<Solution_> builder) {
super(builder);
decider = builder.decider;
}
@Override
public String getPhaseTypeString() {
return "Local Search";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
LocalSearchPhaseScope<Solution_> phaseScope = new LocalSearchPhaseScope<>(solverScope);
phaseStarted(phaseScope);
if (solverScope.isMetricEnabled(SolverMetric.MOVE_COUNT_PER_STEP)) {
Metrics.gauge(SolverMetric.MOVE_COUNT_PER_STEP.getMeterId() + ".accepted",
solverScope.getMonitoringTags(), acceptedMoveCountPerStep);
Metrics.gauge(SolverMetric.MOVE_COUNT_PER_STEP.getMeterId() + ".selected",
solverScope.getMonitoringTags(), selectedMoveCountPerStep);
}
while (!phaseTermination.isPhaseTerminated(phaseScope)) {
LocalSearchStepScope<Solution_> stepScope = new LocalSearchStepScope<>(phaseScope);
stepScope.setTimeGradient(phaseTermination.calculatePhaseTimeGradient(phaseScope));
stepStarted(stepScope);
decider.decideNextStep(stepScope);
if (stepScope.getStep() == null) {
if (phaseTermination.isPhaseTerminated(phaseScope)) {
logger.trace("{} Step index ({}), time spent ({}) terminated without picking a nextStep.",
logIndentation,
stepScope.getStepIndex(),
stepScope.getPhaseScope().calculateSolverTimeMillisSpentUpToNow());
} else if (stepScope.getSelectedMoveCount() == 0L) {
logger.warn("{} No doable selected move at step index ({}), time spent ({})."
+ " Terminating phase early.",
logIndentation,
stepScope.getStepIndex(),
stepScope.getPhaseScope().calculateSolverTimeMillisSpentUpToNow());
} else {
throw new IllegalStateException("The step index (" + stepScope.getStepIndex()
+ ") has accepted/selected move count (" + stepScope.getAcceptedMoveCount() + "/"
+ stepScope.getSelectedMoveCount()
+ ") but failed to pick a nextStep (" + stepScope.getStep() + ").");
}
// Although stepStarted has been called, stepEnded is not called for this step
break;
}
doStep(stepScope);
stepEnded(stepScope);
phaseScope.setLastCompletedStepScope(stepScope);
}
phaseEnded(phaseScope);
}
protected void doStep(LocalSearchStepScope<Solution_> stepScope) {
Move<Solution_> step = stepScope.getStep();
Move<Solution_> undoStep = step.doMove(stepScope.getScoreDirector());
stepScope.setUndoStep(undoStep);
predictWorkingStepScore(stepScope, step);
solver.getBestSolutionRecaller().processWorkingSolutionDuringStep(stepScope);
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
decider.solvingStarted(solverScope);
}
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
decider.phaseStarted(phaseScope);
// TODO maybe this restriction should be lifted to allow LocalSearch to initialize a solution too?
assertWorkingSolutionInitialized(phaseScope);
}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
decider.stepStarted(stepScope);
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
decider.stepEnded(stepScope);
collectMetrics(stepScope);
LocalSearchPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
if (logger.isDebugEnabled()) {
logger.debug("{} LS step ({}), time spent ({}), score ({}), {} best score ({})," +
" accepted/selected move count ({}/{}), picked move ({}).",
logIndentation,
stepScope.getStepIndex(),
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
stepScope.getScore(),
(stepScope.getBestScoreImproved() ? "new" : " "), phaseScope.getBestScore(),
stepScope.getAcceptedMoveCount(),
stepScope.getSelectedMoveCount(),
stepScope.getStepString());
}
}
private void collectMetrics(LocalSearchStepScope<Solution_> stepScope) {
LocalSearchPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
SolverScope<Solution_> solverScope = phaseScope.getSolverScope();
if (solverScope.isMetricEnabled(SolverMetric.MOVE_COUNT_PER_STEP)) {
acceptedMoveCountPerStep.set(stepScope.getAcceptedMoveCount());
selectedMoveCountPerStep.set(stepScope.getSelectedMoveCount());
}
if (solverScope.isMetricEnabled(SolverMetric.CONSTRAINT_MATCH_TOTAL_STEP_SCORE)
|| solverScope.isMetricEnabled(SolverMetric.CONSTRAINT_MATCH_TOTAL_BEST_SCORE)) {
InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector();
ScoreDefinition<?> scoreDefinition = solverScope.getScoreDefinition();
if (scoreDirector.isConstraintMatchEnabled()) {
for (ConstraintMatchTotal<?> constraintMatchTotal : scoreDirector.getConstraintMatchTotalMap()
.values()) {
Tags tags = solverScope.getMonitoringTags().and(
"constraint.package", constraintMatchTotal.getConstraintRef().packageName(),
"constraint.name", constraintMatchTotal.getConstraintRef().constraintName());
collectConstraintMatchTotalMetrics(SolverMetric.CONSTRAINT_MATCH_TOTAL_BEST_SCORE, tags,
constraintMatchTotalTagsToBestCount,
constraintMatchTotalBestScoreMap, constraintMatchTotal, scoreDefinition, solverScope);
collectConstraintMatchTotalMetrics(SolverMetric.CONSTRAINT_MATCH_TOTAL_STEP_SCORE, tags,
constraintMatchTotalTagsToStepCount,
constraintMatchTotalStepScoreMap, constraintMatchTotal, scoreDefinition, solverScope);
}
}
}
}
private void collectConstraintMatchTotalMetrics(SolverMetric metric, Tags tags, Map<Tags, AtomicLong> countMap,
Map<Tags, List<AtomicReference<Number>>> scoreMap, ConstraintMatchTotal<?> constraintMatchTotal,
ScoreDefinition<?> scoreDefinition, SolverScope<Solution_> solverScope) {
if (solverScope.isMetricEnabled(metric)) {
if (countMap.containsKey(tags)) {
countMap.get(tags).set(constraintMatchTotal.getConstraintMatchCount());
} else {
AtomicLong count = new AtomicLong(constraintMatchTotal.getConstraintMatchCount());
countMap.put(tags, count);
Metrics.gauge(metric.getMeterId() + ".count",
tags, count);
}
SolverMetric.registerScoreMetrics(metric,
tags, scoreDefinition, scoreMap, constraintMatchTotal.getScore());
}
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
decider.phaseEnded(phaseScope);
phaseScope.endingNow();
logger.info("{}Local Search phase ({}) ended: time spent ({}), best score ({}),"
+ " score calculation speed ({}/sec), step total ({}).",
logIndentation,
phaseIndex,
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
phaseScope.getBestScore(),
phaseScope.getPhaseScoreCalculationSpeed(),
phaseScope.getNextStepIndex());
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
decider.solvingEnded(solverScope);
}
@Override
public void solvingError(SolverScope<Solution_> solverScope, Exception exception) {
super.solvingError(solverScope, exception);
decider.solvingError(solverScope, exception);
}
public static class Builder<Solution_> extends AbstractPhase.Builder<Solution_> {
private final LocalSearchDecider<Solution_> decider;
public Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination,
LocalSearchDecider<Solution_> decider) {
super(phaseIndex, logIndentation, phaseTermination);
this.decider = decider;
}
@Override
public DefaultLocalSearchPhase<Solution_> build() {
return new DefaultLocalSearchPhase<>(this);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/DefaultLocalSearchPhaseFactory.java | package ai.timefold.solver.core.impl.localsearch;
import java.util.Collections;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.NearbyAutoConfigurationMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig;
import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig;
import ai.timefold.solver.core.config.localsearch.LocalSearchType;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.AcceptorType;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchPickEarlyType;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.composite.UnionMoveSelectorFactory;
import ai.timefold.solver.core.impl.localsearch.decider.LocalSearchDecider;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.Acceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AcceptorFactory;
import ai.timefold.solver.core.impl.localsearch.decider.forager.LocalSearchForager;
import ai.timefold.solver.core.impl.localsearch.decider.forager.LocalSearchForagerFactory;
import ai.timefold.solver.core.impl.phase.AbstractPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.Termination;
public class DefaultLocalSearchPhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, LocalSearchPhaseConfig> {
public DefaultLocalSearchPhaseFactory(LocalSearchPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public LocalSearchPhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) {
HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
Termination<Solution_> phaseTermination = buildPhaseTermination(phaseConfigPolicy, solverTermination);
DefaultLocalSearchPhase.Builder<Solution_> builder =
new DefaultLocalSearchPhase.Builder<>(phaseIndex, solverConfigPolicy.getLogIndentation(), phaseTermination,
buildDecider(phaseConfigPolicy, phaseTermination));
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
builder.setAssertStepScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
builder.setAssertExpectedStepScore(true);
builder.setAssertShadowVariablesAreNotStaleAfterStep(true);
}
return builder.build();
}
private LocalSearchDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy,
Termination<Solution_> termination) {
MoveSelector<Solution_> moveSelector = buildMoveSelector(configPolicy);
Acceptor<Solution_> acceptor = buildAcceptor(configPolicy);
LocalSearchForager<Solution_> forager = buildForager(configPolicy);
if (moveSelector.isNeverEnding() && !forager.supportsNeverEndingMoveSelector()) {
throw new IllegalStateException("The moveSelector (" + moveSelector
+ ") has neverEnding (" + moveSelector.isNeverEnding()
+ "), but the forager (" + forager
+ ") does not support it.\n"
+ "Maybe configure the <forager> with an <acceptedCountLimit>.");
}
Integer moveThreadCount = configPolicy.getMoveThreadCount();
EnvironmentMode environmentMode = configPolicy.getEnvironmentMode();
LocalSearchDecider<Solution_> decider;
if (moveThreadCount == null) {
decider = new LocalSearchDecider<>(configPolicy.getLogIndentation(), termination, moveSelector, acceptor, forager);
} else {
decider = TimefoldSolverEnterpriseService
.loadOrFail(TimefoldSolverEnterpriseService.Feature.MULTITHREADED_SOLVING)
.buildLocalSearch(moveThreadCount, termination, moveSelector, acceptor, forager, environmentMode,
configPolicy);
}
if (environmentMode.isNonIntrusiveFullAsserted()) {
decider.setAssertMoveScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
decider.setAssertExpectedUndoMoveScore(true);
}
return decider;
}
protected Acceptor<Solution_> buildAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
LocalSearchAcceptorConfig acceptorConfig_;
if (phaseConfig.getAcceptorConfig() != null) {
if (phaseConfig.getLocalSearchType() != null) {
throw new IllegalArgumentException("The localSearchType (" + phaseConfig.getLocalSearchType()
+ ") must not be configured if the acceptorConfig (" + phaseConfig.getAcceptorConfig()
+ ") is explicitly configured.");
}
acceptorConfig_ = phaseConfig.getAcceptorConfig();
} else {
LocalSearchType localSearchType_ =
Objects.requireNonNullElse(phaseConfig.getLocalSearchType(), LocalSearchType.LATE_ACCEPTANCE);
acceptorConfig_ = new LocalSearchAcceptorConfig();
switch (localSearchType_) {
case HILL_CLIMBING:
case VARIABLE_NEIGHBORHOOD_DESCENT:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.HILL_CLIMBING));
break;
case TABU_SEARCH:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.ENTITY_TABU));
break;
case SIMULATED_ANNEALING:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.SIMULATED_ANNEALING));
break;
case LATE_ACCEPTANCE:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.LATE_ACCEPTANCE));
break;
case GREAT_DELUGE:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.GREAT_DELUGE));
break;
default:
throw new IllegalStateException("The localSearchType (" + localSearchType_
+ ") is not implemented.");
}
}
return AcceptorFactory.<Solution_> create(acceptorConfig_)
.buildAcceptor(configPolicy);
}
protected LocalSearchForager<Solution_> buildForager(HeuristicConfigPolicy<Solution_> configPolicy) {
LocalSearchForagerConfig foragerConfig_;
if (phaseConfig.getForagerConfig() != null) {
if (phaseConfig.getLocalSearchType() != null) {
throw new IllegalArgumentException("The localSearchType (" + phaseConfig.getLocalSearchType()
+ ") must not be configured if the foragerConfig (" + phaseConfig.getForagerConfig()
+ ") is explicitly configured.");
}
foragerConfig_ = phaseConfig.getForagerConfig();
} else {
LocalSearchType localSearchType_ =
Objects.requireNonNullElse(phaseConfig.getLocalSearchType(), LocalSearchType.LATE_ACCEPTANCE);
foragerConfig_ = new LocalSearchForagerConfig();
switch (localSearchType_) {
case HILL_CLIMBING:
foragerConfig_.setAcceptedCountLimit(1);
break;
case TABU_SEARCH:
// Slow stepping algorithm
foragerConfig_.setAcceptedCountLimit(1000);
break;
case SIMULATED_ANNEALING:
case LATE_ACCEPTANCE:
case GREAT_DELUGE:
// Fast stepping algorithm
foragerConfig_.setAcceptedCountLimit(1);
break;
case VARIABLE_NEIGHBORHOOD_DESCENT:
foragerConfig_.setPickEarlyType(LocalSearchPickEarlyType.FIRST_LAST_STEP_SCORE_IMPROVING);
break;
default:
throw new IllegalStateException("The localSearchType (" + localSearchType_
+ ") is not implemented.");
}
}
return LocalSearchForagerFactory.<Solution_> create(foragerConfig_).buildForager();
}
protected MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy) {
MoveSelector<Solution_> moveSelector;
SelectionCacheType defaultCacheType = SelectionCacheType.JUST_IN_TIME;
SelectionOrder defaultSelectionOrder;
if (phaseConfig.getLocalSearchType() == LocalSearchType.VARIABLE_NEIGHBORHOOD_DESCENT) {
defaultSelectionOrder = SelectionOrder.ORIGINAL;
} else {
defaultSelectionOrder = SelectionOrder.RANDOM;
}
if (phaseConfig.getMoveSelectorConfig() == null) {
moveSelector = new UnionMoveSelectorFactory<Solution_>(determineDefaultMoveSelectorConfig(configPolicy))
.buildMoveSelector(configPolicy, defaultCacheType, defaultSelectionOrder, true);
} else {
AbstractMoveSelectorFactory<Solution_, ?> moveSelectorFactory =
MoveSelectorFactory.create(phaseConfig.getMoveSelectorConfig());
if (configPolicy.getNearbyDistanceMeterClass() != null
&& NearbyAutoConfigurationMoveSelectorConfig.class
.isAssignableFrom(phaseConfig.getMoveSelectorConfig().getClass())
&& !UnionMoveSelectorConfig.class.isAssignableFrom(phaseConfig.getMoveSelectorConfig().getClass())) {
// The move selector config is not a composite selector, but it accepts Nearby autoconfiguration.
// We create a new UnionMoveSelectorConfig with the existing selector to enable Nearby autoconfiguration.
MoveSelectorConfig moveSelectorCopy = (MoveSelectorConfig) phaseConfig.getMoveSelectorConfig().copyConfig();
UnionMoveSelectorConfig updatedConfig = new UnionMoveSelectorConfig()
.withMoveSelectors(moveSelectorCopy);
moveSelectorFactory = MoveSelectorFactory.create(updatedConfig);
}
moveSelector = moveSelectorFactory.buildMoveSelector(configPolicy, defaultCacheType, defaultSelectionOrder, true);
}
return moveSelector;
}
private UnionMoveSelectorConfig determineDefaultMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {
var solutionDescriptor = configPolicy.getSolutionDescriptor();
var basicVariableDescriptorList = solutionDescriptor.getEntityDescriptors().stream()
.flatMap(entityDescriptor -> entityDescriptor.getGenuineVariableDescriptorList().stream())
.filter(variableDescriptor -> !variableDescriptor.isListVariable())
.distinct()
.toList();
var hasChainedVariable = basicVariableDescriptorList.stream()
.filter(v -> v instanceof BasicVariableDescriptor<Solution_>)
.anyMatch(v -> ((BasicVariableDescriptor<?>) v).isChained());
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (basicVariableDescriptorList.isEmpty()) { // We only have the one list variable.
return new UnionMoveSelectorConfig()
.withMoveSelectors(new ListChangeMoveSelectorConfig(), new ListSwapMoveSelectorConfig(),
new KOptListMoveSelectorConfig());
} else if (listVariableDescriptor == null) { // We only have basic variables.
if (hasChainedVariable) {
return new UnionMoveSelectorConfig()
.withMoveSelectors(new ChangeMoveSelectorConfig(), new SwapMoveSelectorConfig(),
new TailChainSwapMoveSelectorConfig());
} else {
return new UnionMoveSelectorConfig()
.withMoveSelectors(new ChangeMoveSelectorConfig(), new SwapMoveSelectorConfig());
}
} else {
/*
* We have a mix of basic and list variables.
* The "old" move selector configs handle this situation correctly but they complain of it being deprecated.
*
* Combining essential variables with list variables in a single entity is not supported. Therefore,
* default selectors do not support enabling Nearby Selection with multiple entities.
*
* TODO Improve so that list variables get list variable selectors directly.
* TODO PLANNER-2755 Support coexistence of basic and list variables on the same entity.
*/
if (configPolicy.getNearbyDistanceMeterClass() != null) {
throw new IllegalArgumentException(
"""
The configuration contains both basic and list variables, which makes it incompatible with using a top-level nearbyDistanceMeterClass (%s).
Specify move selectors manually or remove the top-level nearbyDistanceMeterClass from your solver config."""
.formatted(configPolicy.getNearbyDistanceMeterClass()));
}
return new UnionMoveSelectorConfig()
.withMoveSelectors(new ChangeMoveSelectorConfig(), new SwapMoveSelectorConfig());
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/LocalSearchDecider.java | package ai.timefold.solver.core.impl.localsearch.decider;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.Acceptor;
import ai.timefold.solver.core.impl.localsearch.decider.forager.LocalSearchForager;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class LocalSearchDecider<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final String logIndentation;
protected final Termination<Solution_> termination;
protected final MoveSelector<Solution_> moveSelector;
protected final Acceptor<Solution_> acceptor;
protected final LocalSearchForager<Solution_> forager;
protected boolean assertMoveScoreFromScratch = false;
protected boolean assertExpectedUndoMoveScore = false;
public LocalSearchDecider(String logIndentation, Termination<Solution_> termination,
MoveSelector<Solution_> moveSelector, Acceptor<Solution_> acceptor, LocalSearchForager<Solution_> forager) {
this.logIndentation = logIndentation;
this.termination = termination;
this.moveSelector = moveSelector;
this.acceptor = acceptor;
this.forager = forager;
}
public Termination<Solution_> getTermination() {
return termination;
}
public MoveSelector<Solution_> getMoveSelector() {
return moveSelector;
}
public Acceptor<Solution_> getAcceptor() {
return acceptor;
}
public LocalSearchForager<Solution_> getForager() {
return forager;
}
public void setAssertMoveScoreFromScratch(boolean assertMoveScoreFromScratch) {
this.assertMoveScoreFromScratch = assertMoveScoreFromScratch;
}
public void setAssertExpectedUndoMoveScore(boolean assertExpectedUndoMoveScore) {
this.assertExpectedUndoMoveScore = assertExpectedUndoMoveScore;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public void solvingStarted(SolverScope<Solution_> solverScope) {
moveSelector.solvingStarted(solverScope);
acceptor.solvingStarted(solverScope);
forager.solvingStarted(solverScope);
}
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
moveSelector.phaseStarted(phaseScope);
acceptor.phaseStarted(phaseScope);
forager.phaseStarted(phaseScope);
}
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
moveSelector.stepStarted(stepScope);
acceptor.stepStarted(stepScope);
forager.stepStarted(stepScope);
}
public void decideNextStep(LocalSearchStepScope<Solution_> stepScope) {
InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector();
scoreDirector.setAllChangesWillBeUndoneBeforeStepEnds(true);
int moveIndex = 0;
for (Move<Solution_> move : moveSelector) {
LocalSearchMoveScope<Solution_> moveScope = new LocalSearchMoveScope<>(stepScope, moveIndex, move);
moveIndex++;
doMove(moveScope);
if (forager.isQuitEarly()) {
break;
}
stepScope.getPhaseScope().getSolverScope().checkYielding();
if (termination.isPhaseTerminated(stepScope.getPhaseScope())) {
break;
}
}
scoreDirector.setAllChangesWillBeUndoneBeforeStepEnds(false);
pickMove(stepScope);
}
protected <Score_ extends Score<Score_>> void doMove(LocalSearchMoveScope<Solution_> moveScope) {
InnerScoreDirector<Solution_, Score_> scoreDirector = moveScope.getScoreDirector();
if (!moveScope.getMove().isMoveDoable(scoreDirector)) {
throw new IllegalStateException("Impossible state: Local search move selector (" + moveSelector
+ ") provided a non-doable move (" + moveScope.getMove() + ").");
}
scoreDirector.doAndProcessMove(moveScope.getMove(), assertMoveScoreFromScratch, score -> {
moveScope.setScore(score);
boolean accepted = acceptor.isAccepted(moveScope);
moveScope.setAccepted(accepted);
forager.addMove(moveScope);
});
if (assertExpectedUndoMoveScore) {
scoreDirector.assertExpectedUndoMoveScore(moveScope.getMove(),
(Score_) moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore());
}
logger.trace("{} Move index ({}), score ({}), accepted ({}), move ({}).",
logIndentation,
moveScope.getMoveIndex(), moveScope.getScore(), moveScope.getAccepted(),
moveScope.getMove());
}
protected void pickMove(LocalSearchStepScope<Solution_> stepScope) {
LocalSearchMoveScope<Solution_> pickedMoveScope = forager.pickMove(stepScope);
if (pickedMoveScope != null) {
Move<Solution_> step = pickedMoveScope.getMove();
stepScope.setStep(step);
if (logger.isDebugEnabled()) {
stepScope.setStepString(step.toString());
}
stepScope.setScore(pickedMoveScope.getScore());
}
}
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
moveSelector.stepEnded(stepScope);
acceptor.stepEnded(stepScope);
forager.stepEnded(stepScope);
}
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
moveSelector.phaseEnded(phaseScope);
acceptor.phaseEnded(phaseScope);
forager.phaseEnded(phaseScope);
}
public void solvingEnded(SolverScope<Solution_> solverScope) {
moveSelector.solvingEnded(solverScope);
acceptor.solvingEnded(solverScope);
forager.solvingEnded(solverScope);
}
public void solvingError(SolverScope<Solution_> solverScope, Exception exception) {
// Overridable by a subclass.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/AcceptorFactory.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.AcceptorType;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.stepcountinghillclimbing.StepCountingHillClimbingType;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.greatdeluge.GreatDelugeAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.hillclimbing.HillClimbingAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance.LateAcceptanceAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.simulatedannealing.SimulatedAnnealingAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.stepcountinghillclimbing.StepCountingHillClimbingAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.EntityTabuAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.MoveTabuAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.ValueTabuAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.size.EntityRatioTabuSizeStrategy;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.size.FixedTabuSizeStrategy;
public class AcceptorFactory<Solution_> {
// Based on Tomas Muller's work. TODO Confirm with benchmark across our examples/datasets
private static final double DEFAULT_WATER_LEVEL_INCREMENT_RATIO = 0.00_000_005;
public static <Solution_> AcceptorFactory<Solution_> create(LocalSearchAcceptorConfig acceptorConfig) {
return new AcceptorFactory<>(acceptorConfig);
}
private final LocalSearchAcceptorConfig acceptorConfig;
public AcceptorFactory(LocalSearchAcceptorConfig acceptorConfig) {
this.acceptorConfig = acceptorConfig;
}
public Acceptor<Solution_> buildAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
List<Acceptor<Solution_>> acceptorList = Stream.of(
buildHillClimbingAcceptor(),
buildStepCountingHillClimbingAcceptor(),
buildEntityTabuAcceptor(configPolicy),
buildValueTabuAcceptor(configPolicy),
buildMoveTabuAcceptor(configPolicy),
buildUndoMoveTabuAcceptor(configPolicy),
buildSimulatedAnnealingAcceptor(configPolicy),
buildLateAcceptanceAcceptor(),
buildGreatDelugeAcceptor(configPolicy))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
if (acceptorList.size() == 1) {
return acceptorList.get(0);
} else if (acceptorList.size() > 1) {
return new CompositeAcceptor<>(acceptorList);
} else {
throw new IllegalArgumentException(
"The acceptor does not specify any acceptorType (" + acceptorConfig.getAcceptorTypeList()
+ ") or other acceptor property.\n"
+ "For a good starting values,"
+ " see the docs section \"Which optimization algorithms should I use?\".");
}
}
private Optional<HillClimbingAcceptor<Solution_>> buildHillClimbingAcceptor() {
if (acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.HILL_CLIMBING)) {
HillClimbingAcceptor<Solution_> acceptor = new HillClimbingAcceptor<>();
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<StepCountingHillClimbingAcceptor<Solution_>> buildStepCountingHillClimbingAcceptor() {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.STEP_COUNTING_HILL_CLIMBING))
|| acceptorConfig.getStepCountingHillClimbingSize() != null) {
int stepCountingHillClimbingSize_ =
Objects.requireNonNullElse(acceptorConfig.getStepCountingHillClimbingSize(), 400);
StepCountingHillClimbingType stepCountingHillClimbingType_ =
Objects.requireNonNullElse(acceptorConfig.getStepCountingHillClimbingType(),
StepCountingHillClimbingType.STEP);
StepCountingHillClimbingAcceptor<Solution_> acceptor = new StepCountingHillClimbingAcceptor<>(
stepCountingHillClimbingSize_, stepCountingHillClimbingType_);
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<EntityTabuAcceptor<Solution_>> buildEntityTabuAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.ENTITY_TABU))
|| acceptorConfig.getEntityTabuSize() != null || acceptorConfig.getEntityTabuRatio() != null
|| acceptorConfig.getFadingEntityTabuSize() != null || acceptorConfig.getFadingEntityTabuRatio() != null) {
EntityTabuAcceptor<Solution_> acceptor = new EntityTabuAcceptor<>(configPolicy.getLogIndentation());
if (acceptorConfig.getEntityTabuSize() != null) {
if (acceptorConfig.getEntityTabuRatio() != null) {
throw new IllegalArgumentException("The acceptor cannot have both acceptorConfig.getEntityTabuSize() ("
+ acceptorConfig.getEntityTabuSize() + ") and acceptorConfig.getEntityTabuRatio() ("
+ acceptorConfig.getEntityTabuRatio() + ").");
}
acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getEntityTabuSize()));
} else if (acceptorConfig.getEntityTabuRatio() != null) {
acceptor.setTabuSizeStrategy(new EntityRatioTabuSizeStrategy<>(acceptorConfig.getEntityTabuRatio()));
} else if (acceptorConfig.getFadingEntityTabuSize() == null && acceptorConfig.getFadingEntityTabuRatio() == null) {
acceptor.setTabuSizeStrategy(new EntityRatioTabuSizeStrategy<>(0.1));
}
if (acceptorConfig.getFadingEntityTabuSize() != null) {
if (acceptorConfig.getFadingEntityTabuRatio() != null) {
throw new IllegalArgumentException(
"The acceptor cannot have both acceptorConfig.getFadingEntityTabuSize() ("
+ acceptorConfig.getFadingEntityTabuSize()
+ ") and acceptorConfig.getFadingEntityTabuRatio() ("
+ acceptorConfig.getFadingEntityTabuRatio() + ").");
}
acceptor.setFadingTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getFadingEntityTabuSize()));
} else if (acceptorConfig.getFadingEntityTabuRatio() != null) {
acceptor.setFadingTabuSizeStrategy(
new EntityRatioTabuSizeStrategy<>(acceptorConfig.getFadingEntityTabuRatio()));
}
if (configPolicy.getEnvironmentMode().isNonIntrusiveFullAsserted()) {
acceptor.setAssertTabuHashCodeCorrectness(true);
}
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<ValueTabuAcceptor<Solution_>> buildValueTabuAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.VALUE_TABU))
|| acceptorConfig.getValueTabuSize() != null || acceptorConfig.getValueTabuRatio() != null
|| acceptorConfig.getFadingValueTabuSize() != null || acceptorConfig.getFadingValueTabuRatio() != null) {
ValueTabuAcceptor<Solution_> acceptor = new ValueTabuAcceptor<>(configPolicy.getLogIndentation());
if (acceptorConfig.getValueTabuSize() != null) {
if (acceptorConfig.getValueTabuRatio() != null) {
throw new IllegalArgumentException("The acceptor cannot have both acceptorConfig.getValueTabuSize() ("
+ acceptorConfig.getValueTabuSize() + ") and acceptorConfig.getValueTabuRatio() ("
+ acceptorConfig.getValueTabuRatio() + ").");
}
acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getValueTabuSize()));
} else if (acceptorConfig.getValueTabuRatio() != null) {
/*
* Although the strategy was implemented, it always threw UnsupportedOperationException.
* Therefore the strategy was removed and exception thrown here directly.
*/
throw new UnsupportedOperationException();
}
if (acceptorConfig.getFadingValueTabuSize() != null) {
if (acceptorConfig.getFadingValueTabuRatio() != null) {
throw new IllegalArgumentException("The acceptor cannot have both acceptorConfig.getFadingValueTabuSize() ("
+ acceptorConfig.getFadingValueTabuSize() + ") and acceptorConfig.getFadingValueTabuRatio() ("
+ acceptorConfig.getFadingValueTabuRatio() + ").");
}
acceptor.setFadingTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getFadingValueTabuSize()));
} else if (acceptorConfig.getFadingValueTabuRatio() != null) {
/*
* Although the strategy was implemented, it always threw UnsupportedOperationException.
* Therefore the strategy was removed and exception thrown here directly.
*/
throw new UnsupportedOperationException();
}
if (acceptorConfig.getValueTabuSize() != null) {
acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getValueTabuSize()));
}
if (acceptorConfig.getFadingValueTabuSize() != null) {
acceptor.setFadingTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getFadingValueTabuSize()));
}
if (configPolicy.getEnvironmentMode().isNonIntrusiveFullAsserted()) {
acceptor.setAssertTabuHashCodeCorrectness(true);
}
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<MoveTabuAcceptor<Solution_>> buildMoveTabuAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.MOVE_TABU))
|| acceptorConfig.getMoveTabuSize() != null || acceptorConfig.getFadingMoveTabuSize() != null) {
MoveTabuAcceptor<Solution_> acceptor = new MoveTabuAcceptor<>(configPolicy.getLogIndentation());
acceptor.setUseUndoMoveAsTabuMove(false);
if (acceptorConfig.getMoveTabuSize() != null) {
acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getMoveTabuSize()));
}
if (acceptorConfig.getFadingMoveTabuSize() != null) {
acceptor.setFadingTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getFadingMoveTabuSize()));
}
if (configPolicy.getEnvironmentMode().isNonIntrusiveFullAsserted()) {
acceptor.setAssertTabuHashCodeCorrectness(true);
}
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<MoveTabuAcceptor<Solution_>> buildUndoMoveTabuAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.UNDO_MOVE_TABU))
|| acceptorConfig.getUndoMoveTabuSize() != null || acceptorConfig.getFadingUndoMoveTabuSize() != null) {
MoveTabuAcceptor<Solution_> acceptor = new MoveTabuAcceptor<>(configPolicy.getLogIndentation());
acceptor.setUseUndoMoveAsTabuMove(true);
if (acceptorConfig.getUndoMoveTabuSize() != null) {
acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getUndoMoveTabuSize()));
}
if (acceptorConfig.getFadingUndoMoveTabuSize() != null) {
acceptor.setFadingTabuSizeStrategy(new FixedTabuSizeStrategy<>(acceptorConfig.getFadingUndoMoveTabuSize()));
}
if (configPolicy.getEnvironmentMode().isNonIntrusiveFullAsserted()) {
acceptor.setAssertTabuHashCodeCorrectness(true);
}
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<SimulatedAnnealingAcceptor<Solution_>>
buildSimulatedAnnealingAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.SIMULATED_ANNEALING))
|| acceptorConfig.getSimulatedAnnealingStartingTemperature() != null) {
SimulatedAnnealingAcceptor<Solution_> acceptor = new SimulatedAnnealingAcceptor<>();
if (acceptorConfig.getSimulatedAnnealingStartingTemperature() == null) {
// TODO Support SA without a parameter
throw new IllegalArgumentException("The acceptorType (" + AcceptorType.SIMULATED_ANNEALING
+ ") currently requires a acceptorConfig.getSimulatedAnnealingStartingTemperature() ("
+ acceptorConfig.getSimulatedAnnealingStartingTemperature() + ").");
}
acceptor.setStartingTemperature(
configPolicy.getScoreDefinition().parseScore(acceptorConfig.getSimulatedAnnealingStartingTemperature()));
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<LateAcceptanceAcceptor<Solution_>> buildLateAcceptanceAcceptor() {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.LATE_ACCEPTANCE))
|| acceptorConfig.getLateAcceptanceSize() != null) {
LateAcceptanceAcceptor<Solution_> acceptor = new LateAcceptanceAcceptor<>();
acceptor.setLateAcceptanceSize(Objects.requireNonNullElse(acceptorConfig.getLateAcceptanceSize(), 400));
return Optional.of(acceptor);
}
return Optional.empty();
}
private Optional<GreatDelugeAcceptor<Solution_>> buildGreatDelugeAcceptor(HeuristicConfigPolicy<Solution_> configPolicy) {
if ((acceptorConfig.getAcceptorTypeList() != null
&& acceptorConfig.getAcceptorTypeList().contains(AcceptorType.GREAT_DELUGE))
|| acceptorConfig.getGreatDelugeWaterLevelIncrementScore() != null
|| acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() != null) {
GreatDelugeAcceptor<Solution_> acceptor = new GreatDelugeAcceptor<>();
if (acceptorConfig.getGreatDelugeWaterLevelIncrementScore() != null) {
if (acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() != null) {
throw new IllegalArgumentException("The acceptor cannot have both a "
+ "acceptorConfig.getGreatDelugeWaterLevelIncrementScore() ("
+ acceptorConfig.getGreatDelugeWaterLevelIncrementScore()
+ ") and a acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() ("
+ acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() + ").");
}
acceptor.setWaterLevelIncrementScore(
configPolicy.getScoreDefinition().parseScore(acceptorConfig.getGreatDelugeWaterLevelIncrementScore()));
} else if (acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() != null) {
if (acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() <= 0.0) {
throw new IllegalArgumentException("The acceptorConfig.getGreatDelugeWaterLevelIncrementRatio() ("
+ acceptorConfig.getGreatDelugeWaterLevelIncrementRatio()
+ ") must be positive because the water level should increase.");
}
acceptor.setWaterLevelIncrementRatio(acceptorConfig.getGreatDelugeWaterLevelIncrementRatio());
} else {
acceptor.setWaterLevelIncrementRatio(DEFAULT_WATER_LEVEL_INCREMENT_RATIO);
}
return Optional.of(acceptor);
}
return Optional.empty();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/greatdeluge/GreatDelugeAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.greatdeluge;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class GreatDelugeAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
private Score initialWaterLevel;
private Score waterLevelIncrementScore;
private Double waterLevelIncrementRatio;
private Score startingWaterLevel = null;
private Score currentWaterLevel = null;
private Double currentWaterLevelRatio = null;
public Score getWaterLevelIncrementScore() {
return this.waterLevelIncrementScore;
}
public void setWaterLevelIncrementScore(Score waterLevelIncrementScore) {
this.waterLevelIncrementScore = waterLevelIncrementScore;
}
public Score getInitialWaterLevel() {
return this.initialWaterLevel;
}
public void setInitialWaterLevel(Score initialLevel) {
this.initialWaterLevel = initialLevel;
}
public Double getWaterLevelIncrementRatio() {
return this.waterLevelIncrementRatio;
}
public void setWaterLevelIncrementRatio(Double waterLevelIncrementRatio) {
this.waterLevelIncrementRatio = waterLevelIncrementRatio;
}
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
startingWaterLevel = initialWaterLevel != null ? initialWaterLevel : phaseScope.getBestScore();
if (waterLevelIncrementRatio != null) {
currentWaterLevelRatio = 0.0;
}
currentWaterLevel = startingWaterLevel;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
startingWaterLevel = null;
if (waterLevelIncrementRatio != null) {
currentWaterLevelRatio = null;
}
currentWaterLevel = null;
}
@Override
public boolean isAccepted(LocalSearchMoveScope moveScope) {
Score moveScore = moveScope.getScore();
if (moveScore.compareTo(currentWaterLevel) >= 0) {
return true;
}
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
if (moveScore.compareTo(lastStepScore) > 0) {
// Aspiration
return true;
}
return false;
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
if (waterLevelIncrementScore != null) {
currentWaterLevel = currentWaterLevel.add(waterLevelIncrementScore);
} else {
// Avoid numerical instability: SimpleScore.of(500).multiply(0.000_001) underflows to zero
currentWaterLevelRatio += waterLevelIncrementRatio;
currentWaterLevel = startingWaterLevel.add(
// TODO targetWaterLevel.subtract(startingWaterLevel).multiply(waterLevelIncrementRatio);
// Use startingWaterLevel.abs() to keep the number being positive.
startingWaterLevel.abs().multiply(currentWaterLevelRatio));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/hillclimbing/HillClimbingAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.hillclimbing;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
public class HillClimbingAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
Score moveScore = moveScope.getScore();
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
return moveScore.compareTo(lastStepScore) >= 0;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/lateacceptance/LateAcceptanceAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class LateAcceptanceAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected int lateAcceptanceSize = -1;
protected boolean hillClimbingEnabled = true;
protected Score[] previousScores;
protected int lateScoreIndex = -1;
public void setLateAcceptanceSize(int lateAcceptanceSize) {
this.lateAcceptanceSize = lateAcceptanceSize;
}
public void setHillClimbingEnabled(boolean hillClimbingEnabled) {
this.hillClimbingEnabled = hillClimbingEnabled;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
validate();
previousScores = new Score[lateAcceptanceSize];
Score initialScore = phaseScope.getBestScore();
for (int i = 0; i < previousScores.length; i++) {
previousScores[i] = initialScore;
}
lateScoreIndex = 0;
}
private void validate() {
if (lateAcceptanceSize <= 0) {
throw new IllegalArgumentException("The lateAcceptanceSize (" + lateAcceptanceSize
+ ") cannot be negative or zero.");
}
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
Score moveScore = moveScope.getScore();
Score lateScore = previousScores[lateScoreIndex];
if (moveScore.compareTo(lateScore) >= 0) {
return true;
}
if (hillClimbingEnabled) {
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
if (moveScore.compareTo(lastStepScore) >= 0) {
return true;
}
}
return false;
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
previousScores[lateScoreIndex] = stepScope.getScore();
lateScoreIndex = (lateScoreIndex + 1) % lateAcceptanceSize;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
previousScores = null;
lateScoreIndex = -1;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/simulatedannealing/SimulatedAnnealingAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.simulatedannealing;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
/**
* The time gradient implementation of simulated annealing.
*/
public class SimulatedAnnealingAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected Score startingTemperature;
protected int levelsLength = -1;
protected double[] startingTemperatureLevels;
// No protected Score temperature do avoid rounding errors when using Score.multiply(double)
protected double[] temperatureLevels;
protected double temperatureMinimum = 1.0E-100; // Double.MIN_NORMAL is E-308
public void setStartingTemperature(Score startingTemperature) {
this.startingTemperature = startingTemperature;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
for (double startingTemperatureLevel : startingTemperature.toLevelDoubles()) {
if (startingTemperatureLevel < 0.0) {
throw new IllegalArgumentException("The startingTemperature (" + startingTemperature
+ ") cannot have negative level (" + startingTemperatureLevel + ").");
}
}
startingTemperatureLevels = startingTemperature.toLevelDoubles();
temperatureLevels = startingTemperatureLevels;
levelsLength = startingTemperatureLevels.length;
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
startingTemperatureLevels = null;
temperatureLevels = null;
levelsLength = -1;
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
LocalSearchPhaseScope<Solution_> phaseScope = moveScope.getStepScope().getPhaseScope();
Score lastStepScore = phaseScope.getLastCompletedStepScope().getScore();
Score moveScore = moveScope.getScore();
if (moveScore.compareTo(lastStepScore) >= 0) {
return true;
}
Score moveScoreDifference = lastStepScore.subtract(moveScore);
double[] moveScoreDifferenceLevels = moveScoreDifference.toLevelDoubles();
double acceptChance = 1.0;
for (int i = 0; i < levelsLength; i++) {
double moveScoreDifferenceLevel = moveScoreDifferenceLevels[i];
double temperatureLevel = temperatureLevels[i];
double acceptChanceLevel;
if (moveScoreDifferenceLevel <= 0.0) {
// In this level, moveScore is better than the lastStepScore, so do not disrupt the acceptChance
acceptChanceLevel = 1.0;
} else {
acceptChanceLevel = Math.exp(-moveScoreDifferenceLevel / temperatureLevel);
}
acceptChance *= acceptChanceLevel;
}
if (moveScope.getWorkingRandom().nextDouble() < acceptChance) {
return true;
} else {
return false;
}
}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
// TimeGradient only refreshes at the beginning of a step, so this code is in stepStarted instead of stepEnded
double timeGradient = stepScope.getTimeGradient();
double reverseTimeGradient = 1.0 - timeGradient;
temperatureLevels = new double[levelsLength];
for (int i = 0; i < levelsLength; i++) {
temperatureLevels[i] = startingTemperatureLevels[i] * reverseTimeGradient;
if (temperatureLevels[i] < temperatureMinimum) {
temperatureLevels[i] = temperatureMinimum;
}
}
// TODO implement reheating
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/stepcountinghillclimbing/StepCountingHillClimbingAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.stepcountinghillclimbing;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.stepcountinghillclimbing.StepCountingHillClimbingType;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class StepCountingHillClimbingAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected int stepCountingHillClimbingSize = -1;
protected StepCountingHillClimbingType stepCountingHillClimbingType;
protected Score thresholdScore;
protected int count = -1;
public StepCountingHillClimbingAcceptor(int stepCountingHillClimbingSize,
StepCountingHillClimbingType stepCountingHillClimbingType) {
this.stepCountingHillClimbingSize = stepCountingHillClimbingSize;
this.stepCountingHillClimbingType = stepCountingHillClimbingType;
if (stepCountingHillClimbingSize <= 0) {
throw new IllegalArgumentException("The stepCountingHillClimbingSize (" + stepCountingHillClimbingSize
+ ") cannot be negative or zero.");
}
if (stepCountingHillClimbingType == null) {
throw new IllegalArgumentException("The stepCountingHillClimbingType (" + stepCountingHillClimbingType
+ ") cannot be null.");
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
thresholdScore = phaseScope.getBestScore();
count = 0;
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
Score lastStepScore = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore();
Score moveScore = moveScope.getScore();
if (moveScore.compareTo(lastStepScore) >= 0) {
return true;
}
return moveScore.compareTo(thresholdScore) >= 0;
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
count += determineCountIncrement(stepScope);
if (count >= stepCountingHillClimbingSize) {
thresholdScore = stepScope.getScore();
count = 0;
}
}
private int determineCountIncrement(LocalSearchStepScope<Solution_> stepScope) {
switch (stepCountingHillClimbingType) {
case SELECTED_MOVE:
long selectedMoveCount = stepScope.getSelectedMoveCount();
return selectedMoveCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) selectedMoveCount;
case ACCEPTED_MOVE:
long acceptedMoveCount = stepScope.getAcceptedMoveCount();
return acceptedMoveCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) acceptedMoveCount;
case STEP:
return 1;
case EQUAL_OR_IMPROVING_STEP:
return ((Score) stepScope.getScore()).compareTo(
stepScope.getPhaseScope().getLastCompletedStepScope().getScore()) >= 0 ? 1 : 0;
case IMPROVING_STEP:
return ((Score) stepScope.getScore()).compareTo(
stepScope.getPhaseScope().getLastCompletedStepScope().getScore()) > 0 ? 1 : 0;
default:
throw new IllegalStateException("The stepCountingHillClimbingType (" + stepCountingHillClimbingType
+ ") is not implemented.");
}
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
thresholdScore = null;
count = -1;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/tabu/AbstractTabuAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.Acceptor;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.size.TabuSizeStrategy;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
/**
* Abstract superclass for all Tabu Acceptors.
*
* @see Acceptor
*/
public abstract class AbstractTabuAcceptor<Solution_> extends AbstractAcceptor<Solution_> {
protected final String logIndentation;
protected TabuSizeStrategy<Solution_> tabuSizeStrategy = null;
protected TabuSizeStrategy<Solution_> fadingTabuSizeStrategy = null;
protected boolean aspirationEnabled = true;
protected boolean assertTabuHashCodeCorrectness = false;
protected Map<Object, Integer> tabuToStepIndexMap;
protected Deque<Object> tabuSequenceDeque;
protected int workingTabuSize = -1;
protected int workingFadingTabuSize = -1;
public AbstractTabuAcceptor(String logIndentation) {
this.logIndentation = logIndentation;
}
public void setTabuSizeStrategy(TabuSizeStrategy<Solution_> tabuSizeStrategy) {
this.tabuSizeStrategy = tabuSizeStrategy;
}
public void setFadingTabuSizeStrategy(TabuSizeStrategy<Solution_> fadingTabuSizeStrategy) {
this.fadingTabuSizeStrategy = fadingTabuSizeStrategy;
}
public void setAspirationEnabled(boolean aspirationEnabled) {
this.aspirationEnabled = aspirationEnabled;
}
public void setAssertTabuHashCodeCorrectness(boolean assertTabuHashCodeCorrectness) {
this.assertTabuHashCodeCorrectness = assertTabuHashCodeCorrectness;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
LocalSearchStepScope<Solution_> lastCompletedStepScope = phaseScope.getLastCompletedStepScope();
// Tabu sizes do not change during stepStarted(), because they must be in sync with the tabuSequenceList.size()
workingTabuSize = tabuSizeStrategy == null ? 0 : tabuSizeStrategy.determineTabuSize(lastCompletedStepScope);
workingFadingTabuSize = fadingTabuSizeStrategy == null ? 0
: fadingTabuSizeStrategy.determineTabuSize(lastCompletedStepScope);
int totalTabuListSize = workingTabuSize + workingFadingTabuSize; // is at least 1
tabuToStepIndexMap = new HashMap<>(totalTabuListSize);
tabuSequenceDeque = new ArrayDeque<>();
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
tabuToStepIndexMap = null;
tabuSequenceDeque = null;
workingTabuSize = -1;
workingFadingTabuSize = -1;
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
// Tabu sizes do not change during stepStarted(), because they must be in sync with the tabuSequenceList.size()
workingTabuSize = tabuSizeStrategy == null ? 0 : tabuSizeStrategy.determineTabuSize(stepScope);
workingFadingTabuSize = fadingTabuSizeStrategy == null ? 0 : fadingTabuSizeStrategy.determineTabuSize(stepScope);
adjustTabuList(stepScope.getStepIndex(), findNewTabu(stepScope));
}
protected void adjustTabuList(int tabuStepIndex, Collection<? extends Object> tabus) {
int totalTabuListSize = workingTabuSize + workingFadingTabuSize; // is at least 1
// Remove the oldest tabu(s)
for (Iterator<Object> it = tabuSequenceDeque.iterator(); it.hasNext();) {
Object oldTabu = it.next();
Integer oldTabuStepIndexInteger = tabuToStepIndexMap.get(oldTabu);
if (oldTabuStepIndexInteger == null) {
throw new IllegalStateException("HashCode stability violation: the hashCode() of tabu ("
+ oldTabu + ") of class (" + oldTabu.getClass()
+ ") changed during planning, since it was inserted in the tabu Map or Set.");
}
int oldTabuStepCount = tabuStepIndex - oldTabuStepIndexInteger; // at least 1
if (oldTabuStepCount < totalTabuListSize) {
break;
}
it.remove();
tabuToStepIndexMap.remove(oldTabu);
}
// Add the new tabu(s)
for (Object tabu : tabus) {
// Push tabu to the end of the line
if (tabuToStepIndexMap.containsKey(tabu)) {
tabuToStepIndexMap.remove(tabu);
tabuSequenceDeque.remove(tabu);
}
tabuToStepIndexMap.put(tabu, tabuStepIndex);
tabuSequenceDeque.add(tabu);
}
}
@Override
public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) {
int maximumTabuStepIndex = locateMaximumTabuStepIndex(moveScope);
if (maximumTabuStepIndex < 0) {
// The move isn't tabu at all
return true;
}
if (aspirationEnabled) {
// Natural comparison because shifting penalties don't apply
if (moveScope.getScore().compareTo(
moveScope.getStepScope().getPhaseScope().getBestScore()) > 0) {
logger.trace("{} Proposed move ({}) is tabu, but is accepted anyway due to aspiration.",
logIndentation,
moveScope.getMove());
return true;
}
}
int tabuStepCount = moveScope.getStepScope().getStepIndex() - maximumTabuStepIndex; // at least 1
if (tabuStepCount <= workingTabuSize) {
logger.trace("{} Proposed move ({}) is tabu and is therefore not accepted.",
logIndentation, moveScope.getMove());
return false;
}
double acceptChance = calculateFadingTabuAcceptChance(tabuStepCount - workingTabuSize);
boolean accepted = moveScope.getWorkingRandom().nextDouble() < acceptChance;
if (accepted) {
logger.trace("{} Proposed move ({}) is fading tabu with acceptChance ({}) and is accepted.",
logIndentation,
moveScope.getMove(), acceptChance);
} else {
logger.trace("{} Proposed move ({}) is fading tabu with acceptChance ({}) and is not accepted.",
logIndentation,
moveScope.getMove(), acceptChance);
}
return accepted;
}
private int locateMaximumTabuStepIndex(LocalSearchMoveScope<Solution_> moveScope) {
Collection<? extends Object> checkingTabus = findTabu(moveScope);
int maximumTabuStepIndex = -1;
for (Object checkingTabu : checkingTabus) {
Integer tabuStepIndexInteger = tabuToStepIndexMap.get(checkingTabu);
if (tabuStepIndexInteger != null) {
maximumTabuStepIndex = Math.max(tabuStepIndexInteger, maximumTabuStepIndex);
}
if (assertTabuHashCodeCorrectness) {
for (Object tabu : tabuSequenceDeque) {
// tabu and checkingTabu can be null with a planning variable which allows unassigned values
if (tabu != null && tabu.equals(checkingTabu)) {
if (tabu.hashCode() != checkingTabu.hashCode()) {
throw new IllegalStateException("HashCode/equals contract violation: tabu (" + tabu
+ ") of class (" + tabu.getClass()
+ ") and checkingTabu (" + checkingTabu
+ ") are equals() but have a different hashCode().");
}
if (tabuStepIndexInteger == null) {
throw new IllegalStateException("HashCode stability violation: the hashCode() of tabu ("
+ tabu + ") of class (" + tabu.getClass()
+ ") changed during planning, since it was inserted in the tabu Map or Set.");
}
}
}
}
}
return maximumTabuStepIndex;
}
/**
* @param fadingTabuStepCount {@code 0 < fadingTabuStepCount <= fadingTabuSize}
* @return {@code 0.0 < acceptChance < 1.0}
*/
protected double calculateFadingTabuAcceptChance(int fadingTabuStepCount) {
// The + 1's are because acceptChance should not be 0.0 or 1.0
// when (fadingTabuStepCount == 0) or (fadingTabuStepCount + 1 == workingFadingTabuSize)
return (workingFadingTabuSize - fadingTabuStepCount) / ((double) (workingFadingTabuSize + 1));
}
protected abstract Collection<? extends Object> findTabu(LocalSearchMoveScope<Solution_> moveScope);
protected abstract Collection<? extends Object> findNewTabu(LocalSearchStepScope<Solution_> stepScope);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/tabu/EntityTabuAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu;
import java.util.Collection;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class EntityTabuAcceptor<Solution_> extends AbstractTabuAcceptor<Solution_> {
public EntityTabuAcceptor(String logIndentation) {
super(logIndentation);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
protected Collection<? extends Object> findTabu(LocalSearchMoveScope<Solution_> moveScope) {
return moveScope.getMove().getPlanningEntities();
}
@Override
protected Collection<? extends Object> findNewTabu(LocalSearchStepScope<Solution_> stepScope) {
return stepScope.getStep().getPlanningEntities();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/tabu/MoveTabuAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu;
import java.util.Collection;
import java.util.Collections;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class MoveTabuAcceptor<Solution_> extends AbstractTabuAcceptor<Solution_> {
protected boolean useUndoMoveAsTabuMove = true;
public MoveTabuAcceptor(String logIndentation) {
super(logIndentation);
}
public void setUseUndoMoveAsTabuMove(boolean useUndoMoveAsTabuMove) {
this.useUndoMoveAsTabuMove = useUndoMoveAsTabuMove;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
protected Collection<? extends Object> findTabu(LocalSearchMoveScope<Solution_> moveScope) {
return Collections.singletonList(moveScope.getMove());
}
@Override
protected Collection<? extends Object> findNewTabu(LocalSearchStepScope<Solution_> stepScope) {
Move<?> tabuMove;
if (useUndoMoveAsTabuMove) {
tabuMove = stepScope.getUndoStep();
} else {
tabuMove = stepScope.getStep();
}
return Collections.singletonList(tabuMove);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/acceptor/tabu/ValueTabuAcceptor.java | package ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu;
import java.util.Collection;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class ValueTabuAcceptor<Solution_> extends AbstractTabuAcceptor<Solution_> {
public ValueTabuAcceptor(String logIndentation) {
super(logIndentation);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
protected Collection<? extends Object> findTabu(LocalSearchMoveScope<Solution_> moveScope) {
return moveScope.getMove().getPlanningValues();
}
@Override
protected Collection<? extends Object> findNewTabu(LocalSearchStepScope<Solution_> stepScope) {
return stepScope.getStep().getPlanningValues();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/forager/AcceptedLocalSearchForager.java | package ai.timefold.solver.core.impl.localsearch.decider.forager;
import java.util.List;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchPickEarlyType;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.Acceptor;
import ai.timefold.solver.core.impl.localsearch.decider.forager.finalist.FinalistPodium;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* A {@link LocalSearchForager} which forages accepted moves and ignores unaccepted moves.
*
* @see LocalSearchForager
* @see Acceptor
*/
public class AcceptedLocalSearchForager<Solution_> extends AbstractLocalSearchForager<Solution_> {
protected final FinalistPodium<Solution_> finalistPodium;
protected final LocalSearchPickEarlyType pickEarlyType;
protected final int acceptedCountLimit;
protected final boolean breakTieRandomly;
protected long selectedMoveCount;
protected long acceptedMoveCount;
protected LocalSearchMoveScope<Solution_> earlyPickedMoveScope;
public AcceptedLocalSearchForager(FinalistPodium<Solution_> finalistPodium,
LocalSearchPickEarlyType pickEarlyType, int acceptedCountLimit, boolean breakTieRandomly) {
this.finalistPodium = finalistPodium;
this.pickEarlyType = pickEarlyType;
this.acceptedCountLimit = acceptedCountLimit;
if (acceptedCountLimit < 1) {
throw new IllegalArgumentException("The acceptedCountLimit (" + acceptedCountLimit
+ ") cannot be negative or zero.");
}
this.breakTieRandomly = breakTieRandomly;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
finalistPodium.solvingStarted(solverScope);
}
@Override
public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
finalistPodium.phaseStarted(phaseScope);
}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
finalistPodium.stepStarted(stepScope);
selectedMoveCount = 0L;
acceptedMoveCount = 0L;
earlyPickedMoveScope = null;
}
@Override
public boolean supportsNeverEndingMoveSelector() {
// TODO FIXME magical value Integer.MAX_VALUE coming from ForagerConfig
return acceptedCountLimit < Integer.MAX_VALUE;
}
@Override
public void addMove(LocalSearchMoveScope<Solution_> moveScope) {
selectedMoveCount++;
if (moveScope.getAccepted()) {
acceptedMoveCount++;
checkPickEarly(moveScope);
}
finalistPodium.addMove(moveScope);
}
protected void checkPickEarly(LocalSearchMoveScope<Solution_> moveScope) {
switch (pickEarlyType) {
case NEVER:
break;
case FIRST_BEST_SCORE_IMPROVING:
Score bestScore = moveScope.getStepScope().getPhaseScope().getBestScore();
if (moveScope.getScore().compareTo(bestScore) > 0) {
earlyPickedMoveScope = moveScope;
}
break;
case FIRST_LAST_STEP_SCORE_IMPROVING:
Score lastStepScore = moveScope.getStepScope().getPhaseScope()
.getLastCompletedStepScope().getScore();
if (moveScope.getScore().compareTo(lastStepScore) > 0) {
earlyPickedMoveScope = moveScope;
}
break;
default:
throw new IllegalStateException("The pickEarlyType (" + pickEarlyType + ") is not implemented.");
}
}
@Override
public boolean isQuitEarly() {
return earlyPickedMoveScope != null || acceptedMoveCount >= acceptedCountLimit;
}
@Override
public LocalSearchMoveScope<Solution_> pickMove(LocalSearchStepScope<Solution_> stepScope) {
stepScope.setSelectedMoveCount(selectedMoveCount);
stepScope.setAcceptedMoveCount(acceptedMoveCount);
if (earlyPickedMoveScope != null) {
return earlyPickedMoveScope;
}
List<LocalSearchMoveScope<Solution_>> finalistList = finalistPodium.getFinalistList();
if (finalistList.isEmpty()) {
return null;
}
if (finalistList.size() == 1 || !breakTieRandomly) {
return finalistList.get(0);
}
int randomIndex = stepScope.getWorkingRandom().nextInt(finalistList.size());
return finalistList.get(randomIndex);
}
@Override
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
finalistPodium.stepEnded(stepScope);
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
finalistPodium.phaseEnded(phaseScope);
selectedMoveCount = 0L;
acceptedMoveCount = 0L;
earlyPickedMoveScope = null;
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
finalistPodium.solvingEnded(solverScope);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + pickEarlyType + ", " + acceptedCountLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/forager/LocalSearchForagerFactory.java | package ai.timefold.solver.core.impl.localsearch.decider.forager;
import java.util.Objects;
import ai.timefold.solver.core.config.localsearch.decider.forager.FinalistPodiumType;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchPickEarlyType;
public class LocalSearchForagerFactory<Solution_> {
public static <Solution_> LocalSearchForagerFactory<Solution_> create(LocalSearchForagerConfig foragerConfig) {
return new LocalSearchForagerFactory<>(foragerConfig);
}
private final LocalSearchForagerConfig foragerConfig;
public LocalSearchForagerFactory(LocalSearchForagerConfig foragerConfig) {
this.foragerConfig = foragerConfig;
}
public LocalSearchForager<Solution_> buildForager() {
LocalSearchPickEarlyType pickEarlyType_ =
Objects.requireNonNullElse(foragerConfig.getPickEarlyType(), LocalSearchPickEarlyType.NEVER);
int acceptedCountLimit_ = Objects.requireNonNullElse(foragerConfig.getAcceptedCountLimit(), Integer.MAX_VALUE);
FinalistPodiumType finalistPodiumType_ =
Objects.requireNonNullElse(foragerConfig.getFinalistPodiumType(), FinalistPodiumType.HIGHEST_SCORE);
// Breaking ties randomly leads to better results statistically
boolean breakTieRandomly_ = Objects.requireNonNullElse(foragerConfig.getBreakTieRandomly(), true);
return new AcceptedLocalSearchForager<>(finalistPodiumType_.buildFinalistPodium(), pickEarlyType_,
acceptedCountLimit_, breakTieRandomly_);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/forager | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/forager/finalist/HighestScoreFinalistPodium.java | package ai.timefold.solver.core.impl.localsearch.decider.forager.finalist;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
/**
* Default implementation of {@link FinalistPodium}.
*
* @see FinalistPodium
*/
public final class HighestScoreFinalistPodium<Solution_> extends AbstractFinalistPodium<Solution_> {
protected Score finalistScore;
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
finalistScore = null;
}
@Override
public void addMove(LocalSearchMoveScope<Solution_> moveScope) {
boolean accepted = moveScope.getAccepted();
if (finalistIsAccepted && !accepted) {
return;
}
if (accepted && !finalistIsAccepted) {
finalistIsAccepted = true;
finalistScore = null;
}
Score moveScore = moveScope.getScore();
int scoreComparison = doComparison(moveScore);
if (scoreComparison > 0) {
finalistScore = moveScore;
clearAndAddFinalist(moveScope);
} else if (scoreComparison == 0) {
addFinalist(moveScope);
}
}
private int doComparison(Score moveScore) {
if (finalistScore == null) {
return 1;
}
return moveScore.compareTo(finalistScore);
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
finalistScore = null;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/forager | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/decider/forager/finalist/StrategicOscillationByLevelFinalistPodium.java | package ai.timefold.solver.core.impl.localsearch.decider.forager.finalist;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
/**
* Strategic oscillation, works well with Tabu search.
*
* @see FinalistPodium
*/
public final class StrategicOscillationByLevelFinalistPodium<Solution_> extends AbstractFinalistPodium<Solution_> {
protected final boolean referenceBestScoreInsteadOfLastStepScore;
protected Score referenceScore;
protected Number[] referenceLevelNumbers;
protected Score finalistScore;
protected Number[] finalistLevelNumbers;
protected boolean finalistImprovesUponReference;
public StrategicOscillationByLevelFinalistPodium(boolean referenceBestScoreInsteadOfLastStepScore) {
this.referenceBestScoreInsteadOfLastStepScore = referenceBestScoreInsteadOfLastStepScore;
}
@Override
public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
referenceScore = referenceBestScoreInsteadOfLastStepScore
? stepScope.getPhaseScope().getBestScore()
: stepScope.getPhaseScope().getLastCompletedStepScope().getScore();
referenceLevelNumbers = referenceBestScoreInsteadOfLastStepScore
? stepScope.getPhaseScope().getBestScore().toLevelNumbers()
: stepScope.getPhaseScope().getLastCompletedStepScope().getScore().toLevelNumbers();
finalistScore = null;
finalistLevelNumbers = null;
finalistImprovesUponReference = false;
}
@Override
public void addMove(LocalSearchMoveScope<Solution_> moveScope) {
boolean accepted = moveScope.getAccepted();
if (finalistIsAccepted && !accepted) {
return;
}
if (accepted && !finalistIsAccepted) {
finalistIsAccepted = true;
finalistScore = null;
finalistLevelNumbers = null;
}
Score moveScore = moveScope.getScore();
Number[] moveLevelNumbers = moveScore.toLevelNumbers();
int comparison = doComparison(moveScore, moveLevelNumbers);
if (comparison > 0) {
finalistScore = moveScore;
finalistLevelNumbers = moveLevelNumbers;
finalistImprovesUponReference = (moveScore.compareTo(referenceScore) > 0);
clearAndAddFinalist(moveScope);
} else if (comparison == 0) {
addFinalist(moveScope);
}
}
private int doComparison(Score moveScore, Number[] moveLevelNumbers) {
if (finalistScore == null) {
return 1;
}
// If there is an improving move, do not oscillate
if (!finalistImprovesUponReference && moveScore.compareTo(referenceScore) < 0) {
for (int i = 0; i < referenceLevelNumbers.length; i++) {
boolean moveIsHigher = ((Comparable) moveLevelNumbers[i]).compareTo(referenceLevelNumbers[i]) > 0;
boolean finalistIsHigher = ((Comparable) finalistLevelNumbers[i]).compareTo(referenceLevelNumbers[i]) > 0;
if (moveIsHigher) {
if (finalistIsHigher) {
// Both are higher, take the best one but do not ignore higher levels
break;
} else {
// The move has the first level which is higher while the finalist is lower than the reference
return 1;
}
} else {
if (finalistIsHigher) {
// The finalist has the first level which is higher while the move is lower than the reference
return -1;
} else {
// Both are lower, ignore this level
}
}
}
}
return moveScore.compareTo(finalistScore);
}
@Override
public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
referenceScore = null;
referenceLevelNumbers = null;
finalistScore = null;
finalistLevelNumbers = null;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/scope/LocalSearchMoveScope.java | package ai.timefold.solver.core.impl.localsearch.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.phase.scope.AbstractMoveScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class LocalSearchMoveScope<Solution_> extends AbstractMoveScope<Solution_> {
private final LocalSearchStepScope<Solution_> stepScope;
private Boolean accepted = null;
public LocalSearchMoveScope(LocalSearchStepScope<Solution_> stepScope, int moveIndex, Move<Solution_> move) {
super(moveIndex, move);
this.stepScope = stepScope;
}
@Override
public LocalSearchStepScope<Solution_> getStepScope() {
return stepScope;
}
public Boolean getAccepted() {
return accepted;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/scope/LocalSearchPhaseScope.java | package ai.timefold.solver.core.impl.localsearch.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class LocalSearchPhaseScope<Solution_> extends AbstractPhaseScope<Solution_> {
private LocalSearchStepScope<Solution_> lastCompletedStepScope;
public LocalSearchPhaseScope(SolverScope<Solution_> solverScope) {
super(solverScope);
lastCompletedStepScope = new LocalSearchStepScope<>(this, -1);
lastCompletedStepScope.setTimeGradient(0.0);
}
@Override
public LocalSearchStepScope<Solution_> getLastCompletedStepScope() {
return lastCompletedStepScope;
}
public void setLastCompletedStepScope(LocalSearchStepScope<Solution_> lastCompletedStepScope) {
this.lastCompletedStepScope = lastCompletedStepScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/localsearch/scope/LocalSearchStepScope.java | package ai.timefold.solver.core.impl.localsearch.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class LocalSearchStepScope<Solution_> extends AbstractStepScope<Solution_> {
private final LocalSearchPhaseScope<Solution_> phaseScope;
private double timeGradient = Double.NaN;
private Move<Solution_> step = null;
private String stepString = null;
private Move<Solution_> undoStep = null;
private Long selectedMoveCount = null;
private Long acceptedMoveCount = null;
public LocalSearchStepScope(LocalSearchPhaseScope<Solution_> phaseScope) {
this(phaseScope, phaseScope.getNextStepIndex());
}
public LocalSearchStepScope(LocalSearchPhaseScope<Solution_> phaseScope, int stepIndex) {
super(stepIndex);
this.phaseScope = phaseScope;
}
@Override
public LocalSearchPhaseScope<Solution_> getPhaseScope() {
return phaseScope;
}
public double getTimeGradient() {
return timeGradient;
}
public void setTimeGradient(double timeGradient) {
this.timeGradient = timeGradient;
}
public Move<Solution_> getStep() {
return step;
}
public void setStep(Move<Solution_> step) {
this.step = step;
}
/**
* @return null if logging level is too high
*/
public String getStepString() {
return stepString;
}
public void setStepString(String stepString) {
this.stepString = stepString;
}
public Move<Solution_> getUndoStep() {
return undoStep;
}
public void setUndoStep(Move<Solution_> undoStep) {
this.undoStep = undoStep;
}
public Long getSelectedMoveCount() {
return selectedMoveCount;
}
public void setSelectedMoveCount(Long selectedMoveCount) {
this.selectedMoveCount = selectedMoveCount;
}
public Long getAcceptedMoveCount() {
return acceptedMoveCount;
}
public void setAcceptedMoveCount(Long acceptedMoveCount) {
this.acceptedMoveCount = acceptedMoveCount;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/partitionedsearch/DefaultPartitionedSearchPhaseFactory.java | package ai.timefold.solver.core.impl.partitionedsearch;
import ai.timefold.solver.core.config.partitionedsearch.PartitionedSearchPhaseConfig;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.phase.AbstractPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.Termination;
public class DefaultPartitionedSearchPhaseFactory<Solution_>
extends AbstractPhaseFactory<Solution_, PartitionedSearchPhaseConfig> {
public DefaultPartitionedSearchPhaseFactory(PartitionedSearchPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public PartitionedSearchPhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) {
return TimefoldSolverEnterpriseService
.loadOrFail(TimefoldSolverEnterpriseService.Feature.PARTITIONED_SEARCH)
.buildPartitionedSearch(phaseIndex, phaseConfig, solverConfigPolicy, solverTermination,
this::buildPhaseTermination);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/AbstractPhase.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.localsearch.DefaultLocalSearchPhase;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleSupport;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.AbstractSolver;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see DefaultLocalSearchPhase
*/
public abstract class AbstractPhase<Solution_> implements Phase<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final int phaseIndex;
protected final String logIndentation;
// Called "phaseTermination" to clearly distinguish from "solverTermination" inside AbstractSolver.
protected final Termination<Solution_> phaseTermination;
protected final boolean assertStepScoreFromScratch;
protected final boolean assertExpectedStepScore;
protected final boolean assertShadowVariablesAreNotStaleAfterStep;
/** Used for {@link #addPhaseLifecycleListener(PhaseLifecycleListener)}. */
protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport = new PhaseLifecycleSupport<>();
protected AbstractSolver<Solution_> solver;
protected AbstractPhase(Builder<Solution_> builder) {
phaseIndex = builder.phaseIndex;
logIndentation = builder.logIndentation;
phaseTermination = builder.phaseTermination;
assertStepScoreFromScratch = builder.assertStepScoreFromScratch;
assertExpectedStepScore = builder.assertExpectedStepScore;
assertShadowVariablesAreNotStaleAfterStep = builder.assertShadowVariablesAreNotStaleAfterStep;
}
public int getPhaseIndex() {
return phaseIndex;
}
public Termination<Solution_> getPhaseTermination() {
return phaseTermination;
}
public AbstractSolver<Solution_> getSolver() {
return solver;
}
public void setSolver(AbstractSolver<Solution_> solver) {
this.solver = solver;
}
public boolean isAssertStepScoreFromScratch() {
return assertStepScoreFromScratch;
}
public boolean isAssertExpectedStepScore() {
return assertExpectedStepScore;
}
public boolean isAssertShadowVariablesAreNotStaleAfterStep() {
return assertShadowVariablesAreNotStaleAfterStep;
}
public abstract String getPhaseTypeString();
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
phaseTermination.solvingStarted(solverScope);
phaseLifecycleSupport.fireSolvingStarted(solverScope);
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
phaseTermination.solvingEnded(solverScope);
phaseLifecycleSupport.fireSolvingEnded(solverScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
phaseScope.startingNow();
phaseScope.reset();
solver.phaseStarted(phaseScope);
phaseTermination.phaseStarted(phaseScope);
phaseLifecycleSupport.firePhaseStarted(phaseScope);
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
solver.phaseEnded(phaseScope);
phaseTermination.phaseEnded(phaseScope);
phaseLifecycleSupport.firePhaseEnded(phaseScope);
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
solver.stepStarted(stepScope);
phaseTermination.stepStarted(stepScope);
phaseLifecycleSupport.fireStepStarted(stepScope);
}
protected <Score_ extends Score<Score_>> void calculateWorkingStepScore(AbstractStepScope<Solution_> stepScope,
Object completedAction) {
AbstractPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
Score_ score = phaseScope.calculateScore();
stepScope.setScore(score);
if (assertStepScoreFromScratch) {
phaseScope.assertWorkingScoreFromScratch((Score_) stepScope.getScore(), completedAction);
}
if (assertShadowVariablesAreNotStaleAfterStep) {
phaseScope.assertShadowVariablesAreNotStale((Score_) stepScope.getScore(), completedAction);
}
}
protected <Score_ extends Score<Score_>> void predictWorkingStepScore(AbstractStepScope<Solution_> stepScope,
Object completedAction) {
AbstractPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
// There is no need to recalculate the score, but we still need to set it
phaseScope.getSolutionDescriptor().setScore(phaseScope.getWorkingSolution(), stepScope.getScore());
if (assertStepScoreFromScratch) {
phaseScope.assertPredictedScoreFromScratch((Score_) stepScope.getScore(), completedAction);
}
if (assertExpectedStepScore) {
phaseScope.assertExpectedWorkingScore((Score_) stepScope.getScore(), completedAction);
}
if (assertShadowVariablesAreNotStaleAfterStep) {
phaseScope.assertShadowVariablesAreNotStale((Score_) stepScope.getScore(), completedAction);
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
solver.stepEnded(stepScope);
collectMetrics(stepScope);
phaseTermination.stepEnded(stepScope);
phaseLifecycleSupport.fireStepEnded(stepScope);
}
private void collectMetrics(AbstractStepScope<Solution_> stepScope) {
SolverScope<Solution_> solverScope = stepScope.getPhaseScope().getSolverScope();
if (solverScope.isMetricEnabled(SolverMetric.STEP_SCORE) && stepScope.getScore().isSolutionInitialized()) {
SolverMetric.registerScoreMetrics(SolverMetric.STEP_SCORE,
solverScope.getMonitoringTags(),
solverScope.getScoreDefinition(),
solverScope.getStepScoreMap(),
stepScope.getScore());
}
}
@Override
public void addPhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener) {
phaseLifecycleSupport.addEventListener(phaseLifecycleListener);
}
@Override
public void removePhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener) {
phaseLifecycleSupport.removeEventListener(phaseLifecycleListener);
}
// ************************************************************************
// Assert methods
// ************************************************************************
protected void assertWorkingSolutionInitialized(AbstractPhaseScope<Solution_> phaseScope) {
if (!phaseScope.getStartingScore().isSolutionInitialized()) {
InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector();
SolutionDescriptor<Solution_> solutionDescriptor = scoreDirector.getSolutionDescriptor();
Solution_ workingSolution = scoreDirector.getWorkingSolution();
solutionDescriptor.visitAllEntities(workingSolution, entity -> {
EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(
entity.getClass());
if (!entityDescriptor.isEntityInitializedOrPinned(scoreDirector, entity)) {
String variableRef = null;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : entityDescriptor
.getGenuineVariableDescriptorList()) {
if (!variableDescriptor.isInitialized(entity)) {
variableRef = variableDescriptor.getSimpleEntityAndVariableName();
break;
}
}
throw new IllegalStateException(getPhaseTypeString() + " phase (" + phaseIndex
+ ") needs to start from an initialized solution, but the planning variable (" + variableRef
+ ") is uninitialized for the entity (" + entity + ").\n"
+ "Maybe there is no Construction Heuristic configured before this phase to initialize the solution.\n"
+ "Or maybe the getter/setters of your planning variables in your domain classes aren't implemented correctly.");
}
});
}
}
protected abstract static class Builder<Solution_> {
private final int phaseIndex;
private final String logIndentation;
private final Termination<Solution_> phaseTermination;
private boolean assertStepScoreFromScratch = false;
private boolean assertExpectedStepScore = false;
private boolean assertShadowVariablesAreNotStaleAfterStep = false;
protected Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination) {
this.phaseIndex = phaseIndex;
this.logIndentation = logIndentation;
this.phaseTermination = phaseTermination;
}
public void setAssertStepScoreFromScratch(boolean assertStepScoreFromScratch) {
this.assertStepScoreFromScratch = assertStepScoreFromScratch;
}
public void setAssertExpectedStepScore(boolean assertExpectedStepScore) {
this.assertExpectedStepScore = assertExpectedStepScore;
}
public void setAssertShadowVariablesAreNotStaleAfterStep(boolean assertShadowVariablesAreNotStaleAfterStep) {
this.assertShadowVariablesAreNotStaleAfterStep = assertShadowVariablesAreNotStaleAfterStep;
}
protected abstract AbstractPhase<Solution_> build();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/AbstractPhaseFactory.java | package ai.timefold.solver.core.impl.phase;
import java.util.Objects;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.solver.termination.PhaseToSolverTerminationBridge;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import ai.timefold.solver.core.impl.solver.termination.TerminationFactory;
public abstract class AbstractPhaseFactory<Solution_, PhaseConfig_ extends PhaseConfig<PhaseConfig_>>
implements PhaseFactory<Solution_> {
protected final PhaseConfig_ phaseConfig;
public AbstractPhaseFactory(PhaseConfig_ phaseConfig) {
this.phaseConfig = phaseConfig;
}
protected Termination<Solution_> buildPhaseTermination(HeuristicConfigPolicy<Solution_> configPolicy,
Termination<Solution_> solverTermination) {
TerminationConfig terminationConfig_ =
Objects.requireNonNullElseGet(phaseConfig.getTerminationConfig(), TerminationConfig::new);
// In case of childThread PART_THREAD, the solverTermination is actually the parent phase's phaseTermination
// with the bridge removed, so it's ok to add it again
Termination<Solution_> phaseTermination = new PhaseToSolverTerminationBridge<>(solverTermination);
return TerminationFactory.<Solution_> create(terminationConfig_).buildTermination(configPolicy, phaseTermination);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/NoChangePhase.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
/**
* A {@link NoChangePhase} is a {@link Phase} which does nothing.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Phase
* @see AbstractPhase
*/
public class NoChangePhase<Solution_> extends AbstractPhase<Solution_> {
private NoChangePhase(Builder<Solution_> builder) {
super(builder);
}
@Override
public String getPhaseTypeString() {
return "No Change";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
logger.info("{}No Change phase ({}) ended.",
logIndentation,
phaseIndex);
}
public static class Builder<Solution_> extends AbstractPhase.Builder<Solution_> {
public Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination) {
super(phaseIndex, logIndentation, phaseTermination);
}
@Override
public NoChangePhase<Solution_> build() {
return new NoChangePhase<>(this);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/NoChangePhaseFactory.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.config.phase.NoChangePhaseConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.Termination;
public class NoChangePhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, NoChangePhaseConfig> {
public NoChangePhaseFactory(NoChangePhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public NoChangePhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) {
HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
return new NoChangePhase.Builder<>(phaseIndex, solverConfigPolicy.getLogIndentation(),
buildPhaseTermination(phaseConfigPolicy, solverTermination)).build();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/PhaseFactory.java | package ai.timefold.solver.core.impl.phase;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import ai.timefold.solver.core.config.exhaustivesearch.ExhaustiveSearchPhaseConfig;
import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig;
import ai.timefold.solver.core.config.partitionedsearch.PartitionedSearchPhaseConfig;
import ai.timefold.solver.core.config.phase.NoChangePhaseConfig;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory;
import ai.timefold.solver.core.impl.exhaustivesearch.DefaultExhaustiveSearchPhaseFactory;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.localsearch.DefaultLocalSearchPhaseFactory;
import ai.timefold.solver.core.impl.partitionedsearch.DefaultPartitionedSearchPhaseFactory;
import ai.timefold.solver.core.impl.phase.custom.DefaultCustomPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.Termination;
public interface PhaseFactory<Solution_> {
static <Solution_> PhaseFactory<Solution_> create(PhaseConfig<?> phaseConfig) {
if (LocalSearchPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultLocalSearchPhaseFactory<>((LocalSearchPhaseConfig) phaseConfig);
} else if (ConstructionHeuristicPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultConstructionHeuristicPhaseFactory<>((ConstructionHeuristicPhaseConfig) phaseConfig);
} else if (PartitionedSearchPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultPartitionedSearchPhaseFactory<>((PartitionedSearchPhaseConfig) phaseConfig);
} else if (CustomPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultCustomPhaseFactory<>((CustomPhaseConfig) phaseConfig);
} else if (ExhaustiveSearchPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultExhaustiveSearchPhaseFactory<>((ExhaustiveSearchPhaseConfig) phaseConfig);
} else if (NoChangePhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new NoChangePhaseFactory<>((NoChangePhaseConfig) phaseConfig);
} else {
throw new IllegalArgumentException(String.format("Unknown %s type: (%s).",
PhaseConfig.class.getSimpleName(), phaseConfig.getClass().getName()));
}
}
static <Solution_> List<Phase<Solution_>> buildPhases(List<PhaseConfig> phaseConfigList,
HeuristicConfigPolicy<Solution_> configPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller,
Termination<Solution_> termination) {
List<Phase<Solution_>> phaseList = new ArrayList<>(phaseConfigList.size());
for (int phaseIndex = 0; phaseIndex < phaseConfigList.size(); phaseIndex++) {
PhaseConfig phaseConfig = phaseConfigList.get(phaseIndex);
if (phaseIndex > 0) {
PhaseConfig previousPhaseConfig = phaseConfigList.get(phaseIndex - 1);
if (!canTerminate(previousPhaseConfig)) {
throw new IllegalStateException("Solver configuration contains an unreachable phase. "
+ "Phase #" + phaseIndex + " (" + phaseConfig + ") follows a phase "
+ "without a configured termination (" + previousPhaseConfig + ").");
}
}
PhaseFactory<Solution_> phaseFactory = PhaseFactory.create(phaseConfig);
Phase<Solution_> phase = phaseFactory.buildPhase(phaseIndex, configPolicy, bestSolutionRecaller, termination);
phaseList.add(phase);
}
return phaseList;
}
static boolean canTerminate(PhaseConfig phaseConfig) {
if (phaseConfig instanceof ConstructionHeuristicPhaseConfig
|| phaseConfig instanceof ExhaustiveSearchPhaseConfig
|| phaseConfig instanceof CustomPhaseConfig) { // Termination guaranteed.
return true;
}
TerminationConfig terminationConfig = phaseConfig.getTerminationConfig();
return (terminationConfig != null && terminationConfig.isConfigured());
}
Phase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/CustomPhase.java | package ai.timefold.solver.core.impl.phase.custom;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
import ai.timefold.solver.core.impl.phase.Phase;
/**
* A {@link CustomPhase} is a {@link Phase} which uses {@link CustomPhaseCommand}s.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Phase
* @see AbstractPhase
* @see DefaultCustomPhase
*/
public interface CustomPhase<Solution_> extends Phase<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/CustomPhaseCommand.java | package ai.timefold.solver.core.impl.phase.custom;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.solver.ProblemFactChange;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.phase.Phase;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* Runs a custom algorithm as a {@link Phase} of the {@link Solver} that changes the planning variables.
* Do not abuse to change the problems facts,
* instead use {@link Solver#addProblemFactChange(ProblemFactChange)} for that.
* <p>
* To add custom properties, configure custom properties and add public setters for them.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@FunctionalInterface
public interface CustomPhaseCommand<Solution_> {
/**
* Changes {@link PlanningSolution working solution} of {@link ScoreDirector#getWorkingSolution()}.
* When the {@link PlanningSolution working solution} is modified, the {@link ScoreDirector} must be correctly notified
* (through {@link ScoreDirector#beforeVariableChanged(Object, String)} and
* {@link ScoreDirector#afterVariableChanged(Object, String)}),
* otherwise calculated {@link Score}s will be corrupted.
* <p>
* Don't forget to call {@link ScoreDirector#triggerVariableListeners()} after each set of changes
* (especially before every {@link InnerScoreDirector#calculateScore()} call)
* to ensure all shadow variables are updated.
*
* @param scoreDirector never null, the {@link ScoreDirector} that needs to get notified of the changes.
*/
void changeWorkingSolution(ScoreDirector<Solution_> scoreDirector);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/DefaultCustomPhase.java | package ai.timefold.solver.core.impl.phase.custom;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomStepScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
/**
* Default implementation of {@link CustomPhase}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
final class DefaultCustomPhase<Solution_> extends AbstractPhase<Solution_> implements CustomPhase<Solution_> {
private final List<CustomPhaseCommand<Solution_>> customPhaseCommandList;
private DefaultCustomPhase(Builder<Solution_> builder) {
super(builder);
customPhaseCommandList = builder.customPhaseCommandList;
}
@Override
public String getPhaseTypeString() {
return "Custom";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
CustomPhaseScope<Solution_> phaseScope = new CustomPhaseScope<>(solverScope);
phaseStarted(phaseScope);
for (CustomPhaseCommand<Solution_> customPhaseCommand : customPhaseCommandList) {
solverScope.checkYielding();
if (phaseTermination.isPhaseTerminated(phaseScope)) {
break;
}
CustomStepScope<Solution_> stepScope = new CustomStepScope<>(phaseScope);
stepStarted(stepScope);
doStep(stepScope, customPhaseCommand);
stepEnded(stepScope);
phaseScope.setLastCompletedStepScope(stepScope);
}
phaseEnded(phaseScope);
}
private void doStep(CustomStepScope<Solution_> stepScope, CustomPhaseCommand<Solution_> customPhaseCommand) {
InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector();
customPhaseCommand.changeWorkingSolution(scoreDirector);
calculateWorkingStepScore(stepScope, customPhaseCommand);
solver.getBestSolutionRecaller().processWorkingSolutionDuringStep(stepScope);
}
public void stepEnded(CustomStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
CustomPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
if (logger.isDebugEnabled()) {
logger.debug("{} Custom step ({}), time spent ({}), score ({}), {} best score ({}).",
logIndentation,
stepScope.getStepIndex(),
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
stepScope.getScore(),
stepScope.getBestScoreImproved() ? "new" : " ",
phaseScope.getBestScore());
}
}
public void phaseEnded(CustomPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
phaseScope.endingNow();
logger.info("{}Custom phase ({}) ended: time spent ({}), best score ({}),"
+ " score calculation speed ({}/sec), step total ({}).",
logIndentation,
phaseIndex,
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
phaseScope.getBestScore(),
phaseScope.getPhaseScoreCalculationSpeed(),
phaseScope.getNextStepIndex());
}
public static final class Builder<Solution_> extends AbstractPhase.Builder<Solution_> {
private final List<CustomPhaseCommand<Solution_>> customPhaseCommandList;
public Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination,
List<CustomPhaseCommand<Solution_>> customPhaseCommandList) {
super(phaseIndex, logIndentation, phaseTermination);
this.customPhaseCommandList = List.copyOf(customPhaseCommandList);
}
@Override
public DefaultCustomPhase<Solution_> build() {
return new DefaultCustomPhase<>(this);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/DefaultCustomPhaseFactory.java | package ai.timefold.solver.core.impl.phase.custom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.phase.AbstractPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.Termination;
public class DefaultCustomPhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, CustomPhaseConfig> {
public DefaultCustomPhaseFactory(CustomPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public CustomPhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) {
HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
if (ConfigUtils.isEmptyCollection(phaseConfig.getCustomPhaseCommandClassList())
&& ConfigUtils.isEmptyCollection(phaseConfig.getCustomPhaseCommandList())) {
throw new IllegalArgumentException(
"Configure at least 1 <customPhaseCommandClass> in the <customPhase> configuration.");
}
List<CustomPhaseCommand<Solution_>> customPhaseCommandList_ = new ArrayList<>(getCustomPhaseCommandListSize());
if (phaseConfig.getCustomPhaseCommandClassList() != null) {
for (Class<? extends CustomPhaseCommand> customPhaseCommandClass : phaseConfig.getCustomPhaseCommandClassList()) {
if (customPhaseCommandClass == null) {
throw new IllegalArgumentException("The customPhaseCommandClass (" + customPhaseCommandClass
+ ") cannot be null in the customPhase (" + phaseConfig + ").\n" +
"Maybe there was a typo in the class name provided in the solver config XML?");
}
customPhaseCommandList_.add(createCustomPhaseCommand(customPhaseCommandClass));
}
}
if (phaseConfig.getCustomPhaseCommandList() != null) {
customPhaseCommandList_.addAll((Collection) phaseConfig.getCustomPhaseCommandList());
}
DefaultCustomPhase.Builder<Solution_> builder =
new DefaultCustomPhase.Builder<>(phaseIndex, solverConfigPolicy.getLogIndentation(),
buildPhaseTermination(phaseConfigPolicy, solverTermination), customPhaseCommandList_);
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
builder.setAssertStepScoreFromScratch(true);
}
return builder.build();
}
private CustomPhaseCommand<Solution_>
createCustomPhaseCommand(Class<? extends CustomPhaseCommand> customPhaseCommandClass) {
CustomPhaseCommand<Solution_> customPhaseCommand = ConfigUtils.newInstance(phaseConfig,
"customPhaseCommandClass", customPhaseCommandClass);
ConfigUtils.applyCustomProperties(customPhaseCommand, "customPhaseCommandClass", phaseConfig.getCustomProperties(),
"customProperties");
return customPhaseCommand;
}
private int getCustomPhaseCommandListSize() {
return (phaseConfig.getCustomPhaseCommandClassList() == null ? 0 : phaseConfig.getCustomPhaseCommandClassList().size())
+ (phaseConfig.getCustomPhaseCommandList() == null ? 0 : phaseConfig.getCustomPhaseCommandList().size());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/NoChangeCustomPhaseCommand.java | package ai.timefold.solver.core.impl.phase.custom;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
/**
* Makes no changes.
*/
public class NoChangeCustomPhaseCommand implements CustomPhaseCommand<Object> {
@Override
public void changeWorkingSolution(ScoreDirector<Object> scoreDirector) {
// Do nothing
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/scope/CustomPhaseScope.java | package ai.timefold.solver.core.impl.phase.custom.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class CustomPhaseScope<Solution_> extends AbstractPhaseScope<Solution_> {
private CustomStepScope<Solution_> lastCompletedStepScope;
public CustomPhaseScope(SolverScope<Solution_> solverScope) {
super(solverScope);
lastCompletedStepScope = new CustomStepScope<>(this, -1);
}
@Override
public CustomStepScope<Solution_> getLastCompletedStepScope() {
return lastCompletedStepScope;
}
public void setLastCompletedStepScope(CustomStepScope<Solution_> lastCompletedStepScope) {
this.lastCompletedStepScope = lastCompletedStepScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/custom/scope/CustomStepScope.java | package ai.timefold.solver.core.impl.phase.custom.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class CustomStepScope<Solution_> extends AbstractStepScope<Solution_> {
private final CustomPhaseScope<Solution_> phaseScope;
public CustomStepScope(CustomPhaseScope<Solution_> phaseScope) {
this(phaseScope, phaseScope.getNextStepIndex());
}
public CustomStepScope(CustomPhaseScope<Solution_> phaseScope, int stepIndex) {
super(stepIndex);
this.phaseScope = phaseScope;
}
@Override
public CustomPhaseScope<Solution_> getPhaseScope() {
return phaseScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/scope/AbstractMoveScope.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractMoveScope<Solution_> {
protected final int moveIndex;
protected final Move<Solution_> move;
protected Score<?> score = null;
public AbstractMoveScope(int moveIndex, Move<Solution_> move) {
this.moveIndex = moveIndex;
this.move = move;
}
public abstract AbstractStepScope<Solution_> getStepScope();
public int getMoveIndex() {
return moveIndex;
}
public Move<Solution_> getMove() {
return move;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public int getStepIndex() {
return getStepScope().getStepIndex();
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return getStepScope().getScoreDirector();
}
public Solution_ getWorkingSolution() {
return getStepScope().getWorkingSolution();
}
public Random getWorkingRandom() {
return getStepScope().getWorkingRandom();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + getStepScope().getStepIndex() + "/" + moveIndex + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/scope/AbstractPhaseScope.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractPhaseScope<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final SolverScope<Solution_> solverScope;
protected Long startingSystemTimeMillis;
protected Long startingScoreCalculationCount;
protected Score startingScore;
protected Long endingSystemTimeMillis;
protected Long endingScoreCalculationCount;
protected long childThreadsScoreCalculationCount = 0;
protected int bestSolutionStepIndex;
public AbstractPhaseScope(SolverScope<Solution_> solverScope) {
this.solverScope = solverScope;
}
public SolverScope<Solution_> getSolverScope() {
return solverScope;
}
public Long getStartingSystemTimeMillis() {
return startingSystemTimeMillis;
}
public <Score_ extends Score<Score_>> Score_ getStartingScore() {
return (Score_) startingScore;
}
public Long getEndingSystemTimeMillis() {
return endingSystemTimeMillis;
}
public int getBestSolutionStepIndex() {
return bestSolutionStepIndex;
}
public void setBestSolutionStepIndex(int bestSolutionStepIndex) {
this.bestSolutionStepIndex = bestSolutionStepIndex;
}
public abstract AbstractStepScope<Solution_> getLastCompletedStepScope();
// ************************************************************************
// Calculated methods
// ************************************************************************
public void reset() {
bestSolutionStepIndex = -1;
// solverScope.getBestScore() is null with an uninitialized score
startingScore = solverScope.getBestScore() == null ? solverScope.calculateScore() : solverScope.getBestScore();
if (getLastCompletedStepScope().getStepIndex() < 0) {
getLastCompletedStepScope().setScore(startingScore);
}
}
public void startingNow() {
startingSystemTimeMillis = System.currentTimeMillis();
startingScoreCalculationCount = getScoreDirector().getCalculationCount();
}
public void endingNow() {
endingSystemTimeMillis = System.currentTimeMillis();
endingScoreCalculationCount = getScoreDirector().getCalculationCount();
}
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solverScope.getSolutionDescriptor();
}
public long calculateSolverTimeMillisSpentUpToNow() {
return solverScope.calculateTimeMillisSpentUpToNow();
}
public long calculatePhaseTimeMillisSpentUpToNow() {
long now = System.currentTimeMillis();
return now - startingSystemTimeMillis;
}
public long getPhaseTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
public void addChildThreadsScoreCalculationCount(long addition) {
solverScope.addChildThreadsScoreCalculationCount(addition);
childThreadsScoreCalculationCount += addition;
}
public long getPhaseScoreCalculationCount() {
return endingScoreCalculationCount - startingScoreCalculationCount + childThreadsScoreCalculationCount;
}
/**
* @return at least 0, per second
*/
public long getPhaseScoreCalculationSpeed() {
long timeMillisSpent = getPhaseTimeMillisSpent();
// Avoid divide by zero exception on a fast CPU
return getPhaseScoreCalculationCount() * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent);
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return solverScope.getScoreDirector();
}
public Solution_ getWorkingSolution() {
return solverScope.getWorkingSolution();
}
public int getWorkingEntityCount() {
return solverScope.getWorkingEntityCount();
}
public <Score_ extends Score<Score_>> Score_ calculateScore() {
return (Score_) solverScope.calculateScore();
}
public <Score_ extends Score<Score_>> void assertExpectedWorkingScore(Score_ expectedWorkingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertExpectedWorkingScore(expectedWorkingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertWorkingScoreFromScratch(Score_ workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertWorkingScoreFromScratch(workingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertPredictedScoreFromScratch(Score_ workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertPredictedScoreFromScratch(workingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertShadowVariablesAreNotStale(Score_ workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertShadowVariablesAreNotStale(workingScore, completedAction);
}
public Random getWorkingRandom() {
return getSolverScope().getWorkingRandom();
}
public boolean isBestSolutionInitialized() {
return solverScope.isBestSolutionInitialized();
}
public <Score_ extends Score<Score_>> Score_ getBestScore() {
return (Score_) solverScope.getBestScore();
}
public long getPhaseBestSolutionTimeMillis() {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
// If the termination is explicitly phase configured, previous phases must not affect it
if (bestSolutionTimeMillis < startingSystemTimeMillis) {
bestSolutionTimeMillis = startingSystemTimeMillis;
}
return bestSolutionTimeMillis;
}
public int getNextStepIndex() {
return getLastCompletedStepScope().getStepIndex() + 1;
}
@Override
public String toString() {
return getClass().getSimpleName(); // TODO add + "(" + phaseIndex + ")"
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/phase/scope/AbstractStepScope.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractStepScope<Solution_> {
protected final int stepIndex;
protected Score<?> score = null;
protected boolean bestScoreImproved = false;
// Stays null if there is no need to clone it
protected Solution_ clonedSolution = null;
public AbstractStepScope(int stepIndex) {
this.stepIndex = stepIndex;
}
public abstract AbstractPhaseScope<Solution_> getPhaseScope();
public int getStepIndex() {
return stepIndex;
}
public Score<?> getScore() {
return score;
}
public void setScore(Score<?> score) {
this.score = score;
}
public boolean getBestScoreImproved() {
return bestScoreImproved;
}
public void setBestScoreImproved(Boolean bestScoreImproved) {
this.bestScoreImproved = bestScoreImproved;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return getPhaseScope().getScoreDirector();
}
public Solution_ getWorkingSolution() {
return getPhaseScope().getWorkingSolution();
}
public Random getWorkingRandom() {
return getPhaseScope().getWorkingRandom();
}
public Solution_ createOrGetClonedSolution() {
if (clonedSolution == null) {
clonedSolution = getScoreDirector().cloneWorkingSolution();
}
return clonedSolution;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + stepIndex + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/DefaultScoreExplanation.java | package ai.timefold.solver.core.impl.score;
import static java.util.Comparator.comparing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.ScoreExplanation;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
public final class DefaultScoreExplanation<Solution_, Score_ extends Score<Score_>>
implements ScoreExplanation<Solution_, Score_> {
private static final int DEFAULT_SCORE_EXPLANATION_INDICTMENT_LIMIT = 5;
private static final int DEFAULT_SCORE_EXPLANATION_CONSTRAINT_MATCH_LIMIT = 2;
private final Solution_ solution;
private final Score_ score;
private final Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap;
private final List<ConstraintJustification> constraintJustificationList;
private final Map<Object, Indictment<Score_>> indictmentMap;
private final AtomicReference<String> summary = new AtomicReference<>(); // Will be calculated lazily.
public static <Score_ extends Score<Score_>> String explainScore(Score_ workingScore,
Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection,
Collection<Indictment<Score_>> indictmentCollection) {
return explainScore(workingScore, constraintMatchTotalCollection, indictmentCollection,
DEFAULT_SCORE_EXPLANATION_INDICTMENT_LIMIT, DEFAULT_SCORE_EXPLANATION_CONSTRAINT_MATCH_LIMIT);
}
public static <Score_ extends Score<Score_>> String explainScore(Score_ workingScore,
Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection,
Collection<Indictment<Score_>> indictmentCollection, int indictmentLimit, int constraintMatchLimit) {
var scoreExplanation = new StringBuilder((constraintMatchTotalCollection.size() + 4 + 2 * indictmentLimit) * 80);
scoreExplanation.append("""
Explanation of score (%s):
Constraint matches:
""".formatted(workingScore));
Comparator<ConstraintMatchTotal<Score_>> constraintMatchTotalComparator = comparing(ConstraintMatchTotal::getScore);
Comparator<ConstraintMatch<Score_>> constraintMatchComparator = comparing(ConstraintMatch::getScore);
constraintMatchTotalCollection.stream()
.sorted(constraintMatchTotalComparator)
.forEach(constraintMatchTotal -> {
var constraintMatchSet = constraintMatchTotal.getConstraintMatchSet();
scoreExplanation.append("""
%s: constraint (%s) has %s matches:
""".formatted(constraintMatchTotal.getScore().toShortString(),
constraintMatchTotal.getConstraintRef().constraintName(), constraintMatchSet.size()));
constraintMatchSet.stream()
.sorted(constraintMatchComparator)
.limit(constraintMatchLimit)
.forEach(constraintMatch -> scoreExplanation.append("""
%s: justified with (%s)
""".formatted(constraintMatch.getScore().toShortString(),
constraintMatch.getJustification())));
if (constraintMatchSet.size() > constraintMatchLimit) {
scoreExplanation.append("""
...
""");
}
});
var indictmentCount = indictmentCollection.size();
if (indictmentLimit < indictmentCount) {
scoreExplanation.append("""
Indictments (top %s of %s):
""".formatted(indictmentLimit, indictmentCount));
} else {
scoreExplanation.append("""
Indictments:
""");
}
Comparator<Indictment<Score_>> indictmentComparator = comparing(Indictment::getScore);
Comparator<ConstraintMatch<Score_>> constraintMatchScoreComparator = comparing(ConstraintMatch::getScore);
indictmentCollection.stream()
.sorted(indictmentComparator)
.limit(indictmentLimit)
.forEach(indictment -> {
var constraintMatchSet = indictment.getConstraintMatchSet();
scoreExplanation.append("""
%s: indicted with (%s) has %s matches:
""".formatted(indictment.getScore().toShortString(), indictment.getIndictedObject(),
constraintMatchSet.size()));
constraintMatchSet.stream()
.sorted(constraintMatchScoreComparator)
.limit(constraintMatchLimit)
.forEach(constraintMatch -> scoreExplanation.append("""
%s: constraint (%s)
""".formatted(constraintMatch.getScore().toShortString(),
constraintMatch.getConstraintRef().constraintName())));
if (constraintMatchSet.size() > constraintMatchLimit) {
scoreExplanation.append("""
...
""");
}
});
if (indictmentCount > indictmentLimit) {
scoreExplanation.append("""
...
""");
}
return scoreExplanation.toString();
}
public DefaultScoreExplanation(InnerScoreDirector<Solution_, Score_> scoreDirector) {
this(scoreDirector.getWorkingSolution(), scoreDirector.calculateScore(), scoreDirector.getConstraintMatchTotalMap(),
scoreDirector.getIndictmentMap());
}
public DefaultScoreExplanation(Solution_ solution, Score_ score,
Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap) {
this.solution = solution;
this.score = score;
this.constraintMatchTotalMap = constraintMatchTotalMap;
List<ConstraintJustification> workingConstraintJustificationList = new ArrayList<>();
for (ConstraintMatchTotal<Score_> constraintMatchTotal : constraintMatchTotalMap.values()) {
for (ConstraintMatch<Score_> constraintMatch : constraintMatchTotal.getConstraintMatchSet()) {
ConstraintJustification justification = constraintMatch.getJustification();
workingConstraintJustificationList.add(justification);
}
}
this.constraintJustificationList = workingConstraintJustificationList;
this.indictmentMap = indictmentMap;
}
@Override
public Solution_ getSolution() {
return solution;
}
@Override
public Score_ getScore() {
return score;
}
@Override
public Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() {
return constraintMatchTotalMap;
}
@Override
public List<ConstraintJustification> getJustificationList() {
return constraintJustificationList;
}
@Override
public Map<Object, Indictment<Score_>> getIndictmentMap() {
return indictmentMap;
}
@Override
public String getSummary() {
return summary.updateAndGet(currentSummary -> Objects.requireNonNullElseGet(currentSummary,
() -> explainScore(score, constraintMatchTotalMap.values(), indictmentMap.values())));
}
@Override
public String toString() {
return getSummary(); // So that this class can be used in strings directly.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/ScoreUtil.java | package ai.timefold.solver.core.impl.score;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.function.Predicate;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
public final class ScoreUtil {
public static final String INIT_LABEL = "init";
public static final String HARD_LABEL = "hard";
public static final String MEDIUM_LABEL = "medium";
public static final String SOFT_LABEL = "soft";
public static final String[] LEVEL_SUFFIXES = new String[] { HARD_LABEL, SOFT_LABEL };
public static String[] parseScoreTokens(Class<? extends Score<?>> scoreClass, String scoreString, String... levelSuffixes) {
String[] scoreTokens = new String[levelSuffixes.length + 1];
String[] suffixedScoreTokens = scoreString.split("/");
int startIndex;
if (suffixedScoreTokens.length == levelSuffixes.length + 1) {
String suffixedScoreToken = suffixedScoreTokens[0];
if (!suffixedScoreToken.endsWith(INIT_LABEL)) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") doesn't follow the correct pattern (" + buildScorePattern(false, levelSuffixes) + "):"
+ " the suffixedScoreToken (" + suffixedScoreToken
+ ") does not end with levelSuffix (" + INIT_LABEL + ").");
}
scoreTokens[0] = suffixedScoreToken.substring(0, suffixedScoreToken.length() - INIT_LABEL.length());
startIndex = 1;
} else if (suffixedScoreTokens.length == levelSuffixes.length) {
scoreTokens[0] = "0";
startIndex = 0;
} else {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") doesn't follow the correct pattern (" + buildScorePattern(false, levelSuffixes) + "):"
+ " the suffixedScoreTokens length (" + suffixedScoreTokens.length
+ ") differs from the levelSuffixes length ("
+ levelSuffixes.length + " or " + (levelSuffixes.length + 1) + ").");
}
for (int i = 0; i < levelSuffixes.length; i++) {
String suffixedScoreToken = suffixedScoreTokens[startIndex + i];
String levelSuffix = levelSuffixes[i];
if (!suffixedScoreToken.endsWith(levelSuffix)) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") doesn't follow the correct pattern (" + buildScorePattern(false, levelSuffixes) + "):"
+ " the suffixedScoreToken (" + suffixedScoreToken
+ ") does not end with levelSuffix (" + levelSuffix + ").");
}
scoreTokens[1 + i] = suffixedScoreToken.substring(0, suffixedScoreToken.length() - levelSuffix.length());
}
return scoreTokens;
}
public static int parseInitScore(Class<? extends Score<?>> scoreClass, String scoreString, String initScoreString) {
try {
return Integer.parseInt(initScoreString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName() + ") has a initScoreString ("
+ initScoreString + ") which is not a valid integer.", e);
}
}
public static int parseLevelAsInt(Class<? extends Score<?>> scoreClass, String scoreString, String levelString) {
if (levelString.equals("*")) {
return Integer.MIN_VALUE;
}
try {
return Integer.parseInt(levelString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName() + ") has a levelString (" + levelString
+ ") which is not a valid integer.", e);
}
}
public static long parseLevelAsLong(Class<? extends Score<?>> scoreClass, String scoreString, String levelString) {
if (levelString.equals("*")) {
return Long.MIN_VALUE;
}
try {
return Long.parseLong(levelString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName() + ") has a levelString (" + levelString
+ ") which is not a valid long.", e);
}
}
public static BigDecimal parseLevelAsBigDecimal(Class<? extends Score<?>> scoreClass, String scoreString,
String levelString) {
if (levelString.equals("*")) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") has a wildcard (*) as levelString (" + levelString
+ ") which is not supported for BigDecimal score values," +
" because there is no general MIN_VALUE for BigDecimal.");
}
try {
return new BigDecimal(levelString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName() + ") has a levelString (" + levelString
+ ") which is not a valid BigDecimal.", e);
}
}
public static String buildScorePattern(boolean bendable, String... levelSuffixes) {
StringBuilder scorePattern = new StringBuilder(levelSuffixes.length * 10);
boolean first = true;
for (String levelSuffix : levelSuffixes) {
if (first) {
first = false;
} else {
scorePattern.append("/");
}
if (bendable) {
scorePattern.append("[999/.../999]");
} else {
scorePattern.append("999");
}
scorePattern.append(levelSuffix);
}
return scorePattern.toString();
}
public static String getInitPrefix(int initScore) {
if (initScore == 0) {
return "";
}
return initScore + INIT_LABEL + "/";
}
public static <Score_ extends Score<Score_>> String buildShortString(Score<Score_> score, Predicate<Number> notZero,
String... levelLabels) {
int initScore = score.initScore();
StringBuilder shortString = new StringBuilder();
if (initScore != 0) {
shortString.append(initScore).append(INIT_LABEL);
}
int i = 0;
for (Number levelNumber : score.toLevelNumbers()) {
if (notZero.test(levelNumber)) {
if (shortString.length() > 0) {
shortString.append("/");
}
shortString.append(levelNumber).append(levelLabels[i]);
}
i++;
}
if (shortString.length() == 0) {
// Even for BigDecimals we use "0" over "0.0" because different levels can have different scales
return "0";
}
return shortString.toString();
}
public static String[][] parseBendableScoreTokens(Class<? extends IBendableScore<?>> scoreClass,
String scoreString) {
String[][] scoreTokens = new String[3][];
scoreTokens[0] = new String[1];
int startIndex = 0;
int initEndIndex = scoreString.indexOf(INIT_LABEL, startIndex);
if (initEndIndex >= 0) {
scoreTokens[0][0] = scoreString.substring(startIndex, initEndIndex);
startIndex = initEndIndex + INIT_LABEL.length() + "/".length();
} else {
scoreTokens[0][0] = "0";
}
for (int i = 0; i < LEVEL_SUFFIXES.length; i++) {
String levelSuffix = LEVEL_SUFFIXES[i];
int endIndex = scoreString.indexOf(levelSuffix, startIndex);
if (endIndex < 0) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") doesn't follow the correct pattern (" + buildScorePattern(true, LEVEL_SUFFIXES) + "):"
+ " the levelSuffix (" + levelSuffix
+ ") isn't in the scoreSubstring (" + scoreString.substring(startIndex) + ").");
}
String scoreSubString = scoreString.substring(startIndex, endIndex);
if (!scoreSubString.startsWith("[") || !scoreSubString.endsWith("]")) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") doesn't follow the correct pattern (" + buildScorePattern(true, LEVEL_SUFFIXES) + "):"
+ " the scoreSubString (" + scoreSubString
+ ") does not start and end with \"[\" and \"]\".");
}
if (scoreSubString.equals("[]")) {
scoreTokens[1 + i] = new String[0];
} else {
scoreTokens[1 + i] = scoreSubString.substring(1, scoreSubString.length() - 1).split("/");
}
startIndex = endIndex + levelSuffix.length() + "/".length();
}
if (startIndex != scoreString.length() + "/".length()) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + scoreClass.getSimpleName()
+ ") doesn't follow the correct pattern (" + buildScorePattern(true, LEVEL_SUFFIXES) + "):"
+ " the suffix (" + scoreString.substring(startIndex - 1) + ") is unsupported.");
}
return scoreTokens;
}
public static <Score_ extends IBendableScore<Score_>> String buildBendableShortString(IBendableScore<Score_> score,
Predicate<Number> notZero) {
int initScore = score.initScore();
StringBuilder shortString = new StringBuilder();
if (initScore != 0) {
shortString.append(initScore).append(INIT_LABEL);
}
Number[] levelNumbers = score.toLevelNumbers();
int hardLevelsSize = score.hardLevelsSize();
if (Arrays.stream(levelNumbers).limit(hardLevelsSize).anyMatch(notZero)) {
if (shortString.length() > 0) {
shortString.append("/");
}
shortString.append("[");
boolean first = true;
for (int i = 0; i < hardLevelsSize; i++) {
if (first) {
first = false;
} else {
shortString.append("/");
}
shortString.append(levelNumbers[i]);
}
shortString.append("]").append(HARD_LABEL);
}
int softLevelsSize = score.softLevelsSize();
if (Arrays.stream(levelNumbers).skip(hardLevelsSize).anyMatch(notZero)) {
if (shortString.length() > 0) {
shortString.append("/");
}
shortString.append("[");
boolean first = true;
for (int i = 0; i < softLevelsSize; i++) {
if (first) {
first = false;
} else {
shortString.append("/");
}
shortString.append(levelNumbers[hardLevelsSize + i]);
}
shortString.append("]").append(SOFT_LABEL);
}
if (shortString.length() == 0) {
// Even for BigDecimals we use "0" over "0.0" because different levels can have different scales
return "0";
}
return shortString.toString();
}
private ScoreUtil() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/BendableBigDecimalScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class BendableBigDecimalScoreDefinition extends AbstractBendableScoreDefinition<BendableBigDecimalScore> {
public BendableBigDecimalScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableBigDecimalScore> getScoreClass() {
return BendableBigDecimalScore.class;
}
@Override
public BendableBigDecimalScore getZeroScore() {
return BendableBigDecimalScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableBigDecimalScore getOneSoftestScore() {
return BendableBigDecimalScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, BigDecimal.ONE);
}
@Override
public BendableBigDecimalScore parseScore(String scoreString) {
BendableBigDecimalScore score = BendableBigDecimalScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableBigDecimalScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableBigDecimalScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
BigDecimal[] hardScores = new BigDecimal[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (BigDecimal) levelNumbers[i];
}
BigDecimal[] softScores = new BigDecimal[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (BigDecimal) levelNumbers[hardLevelsSize + i];
}
return BendableBigDecimalScore.ofUninitialized(initScore, hardScores, softScores);
}
public BendableBigDecimalScore createScore(BigDecimal... scores) {
return createScoreUninitialized(0, scores);
}
public BendableBigDecimalScore createScoreUninitialized(int initScore, BigDecimal... scores) {
int levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableBigDecimalScore.ofUninitialized(initScore,
Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public BendableBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public BendableBigDecimalScore divideBySanitizedDivisor(BendableBigDecimalScore dividend,
BendableBigDecimalScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
BigDecimal[] hardScores = new BigDecimal[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
BigDecimal[] softScores = new BigDecimal[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
BigDecimal[] levels = Stream.concat(Arrays.stream(hardScores), Arrays.stream(softScores))
.toArray(BigDecimal[]::new);
return createScoreUninitialized(divide(dividendInitScore, divisorInitScore), levels);
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/BendableLongScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import java.util.stream.LongStream;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class BendableLongScoreDefinition extends AbstractBendableScoreDefinition<BendableLongScore> {
public BendableLongScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableLongScore> getScoreClass() {
return BendableLongScore.class;
}
@Override
public BendableLongScore getZeroScore() {
return BendableLongScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableLongScore getOneSoftestScore() {
return BendableLongScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, 1L);
}
@Override
public BendableLongScore parseScore(String scoreString) {
BendableLongScore score = BendableLongScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableLongScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableLongScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableLongScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
long[] hardScores = new long[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (Long) levelNumbers[i];
}
long[] softScores = new long[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (Long) levelNumbers[hardLevelsSize + i];
}
return BendableLongScore.ofUninitialized(initScore, hardScores, softScores);
}
public BendableLongScore createScore(long... scores) {
return createScoreUninitialized(0, scores);
}
public BendableLongScore createScoreUninitialized(int initScore, long... scores) {
int levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableLongScore.ofUninitialized(initScore,
Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableLongScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
long[] hardScores = new long[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.hardScore(i)
: Long.MAX_VALUE;
}
long[] softScores = new long[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.softScore(i)
: Long.MAX_VALUE;
}
return BendableLongScore.ofUninitialized(0, hardScores, softScores);
}
@Override
public BendableLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableLongScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
long[] hardScores = new long[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_UP)
? score.hardScore(i)
: Long.MIN_VALUE;
}
long[] softScores = new long[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_UP)
? score.softScore(i)
: Long.MIN_VALUE;
}
return BendableLongScore.ofUninitialized(0, hardScores, softScores);
}
@Override
public BendableLongScore divideBySanitizedDivisor(BendableLongScore dividend, BendableLongScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
long[] hardScores = new long[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
long[] softScores = new long[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
long[] levels = LongStream.concat(Arrays.stream(hardScores), Arrays.stream(softScores)).toArray();
return createScoreUninitialized(divide(dividendInitScore, divisorInitScore), levels);
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/BendableScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import java.util.stream.IntStream;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class BendableScoreDefinition extends AbstractBendableScoreDefinition<BendableScore> {
public BendableScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableScore> getScoreClass() {
return BendableScore.class;
}
@Override
public BendableScore getZeroScore() {
return BendableScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableScore getOneSoftestScore() {
return BendableScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, 1);
}
@Override
public BendableScore parseScore(String scoreString) {
BendableScore score = BendableScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (Integer) levelNumbers[i];
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (Integer) levelNumbers[hardLevelsSize + i];
}
return BendableScore.ofUninitialized(initScore, hardScores, softScores);
}
public BendableScore createScore(int... scores) {
return createScoreUninitialized(0, scores);
}
public BendableScore createScoreUninitialized(int initScore, int... scores) {
int levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableScore.ofUninitialized(initScore,
Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, BendableScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.hardScore(i)
: Integer.MAX_VALUE;
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.softScore(i)
: Integer.MAX_VALUE;
}
return BendableScore.ofUninitialized(0, hardScores, softScores);
}
@Override
public BendableScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, BendableScore score) {
InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels();
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_UP)
? score.hardScore(i)
: Integer.MIN_VALUE;
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_UP)
? score.softScore(i)
: Integer.MIN_VALUE;
}
return BendableScore.ofUninitialized(0, hardScores, softScores);
}
@Override
public BendableScore divideBySanitizedDivisor(BendableScore dividend, BendableScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
int[] hardScores = new int[hardLevelsSize];
for (int i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
int[] softScores = new int[softLevelsSize];
for (int i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
int[] levels = IntStream.concat(Arrays.stream(hardScores), Arrays.stream(softScores)).toArray();
return createScoreUninitialized(divide(dividendInitScore, divisorInitScore), levels);
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/HardMediumSoftBigDecimalScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.math.BigDecimal;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardMediumSoftBigDecimalScoreDefinition extends AbstractScoreDefinition<HardMediumSoftBigDecimalScore> {
public HardMediumSoftBigDecimalScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftBigDecimalScore> getScoreClass() {
return HardMediumSoftBigDecimalScore.class;
}
@Override
public HardMediumSoftBigDecimalScore getZeroScore() {
return HardMediumSoftBigDecimalScore.ZERO;
}
@Override
public HardMediumSoftBigDecimalScore getOneSoftestScore() {
return HardMediumSoftBigDecimalScore.ONE_SOFT;
}
@Override
public HardMediumSoftBigDecimalScore parseScore(String scoreString) {
return HardMediumSoftBigDecimalScore.parseScore(scoreString);
}
@Override
public HardMediumSoftBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftBigDecimalScore.ofUninitialized(initScore, (BigDecimal) levelNumbers[0],
(BigDecimal) levelNumbers[1], (BigDecimal) levelNumbers[2]);
}
@Override
public HardMediumSoftBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public HardMediumSoftBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftBigDecimalScore score) {
// TODO https://issues.redhat.com/browse/PLANNER-232
throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" +
" because a BigDecimal cannot represent infinity.");
}
@Override
public HardMediumSoftBigDecimalScore divideBySanitizedDivisor(HardMediumSoftBigDecimalScore dividend,
HardMediumSoftBigDecimalScore divisor) {
int dividendInitScore = dividend.initScore();
int divisorInitScore = sanitize(divisor.initScore());
BigDecimal dividendHardScore = dividend.hardScore();
BigDecimal divisorHardScore = sanitize(divisor.hardScore());
BigDecimal dividendMediumScore = dividend.mediumScore();
BigDecimal divisorMediumScore = sanitize(divisor.mediumScore());
BigDecimal dividendSoftScore = dividend.softScore();
BigDecimal divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
divide(dividendInitScore, divisorInitScore),
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.