index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/ListIterableSelector.java | package ai.timefold.solver.core.impl.heuristic.selector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.ListIterable;
public interface ListIterableSelector<Solution_, T> extends IterableSelector<Solution_, T>, ListIterable<T> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/Selector.java | package ai.timefold.solver.core.impl.heuristic.selector;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
/**
* General interface for {@link MoveSelector}, {@link EntitySelector} and {@link ValueSelector}
* which generates {@link Move}s or parts of them.
*/
public interface Selector<Solution_> extends PhaseLifecycleListener<Solution_> {
/**
* If false, then {@link #isNeverEnding()} is true.
*
* @return true if all the {@link ValueRange}s are countable
* (for example a double value range between 1.2 and 1.4 is not countable)
*/
boolean isCountable();
/**
* Is true if {@link #isCountable()} is false
* or if this selector is in random order (for most cases).
* Is never true when this selector is in shuffled order (which is less scalable but more exact).
*
* @return true if the {@link Iterator#hasNext()} of the {@link Iterator} created by {@link Iterable#iterator()}
* never returns false (except when it's empty).
*/
boolean isNeverEnding();
/**
* Unless this selector itself caches, this returns {@link SelectionCacheType#JUST_IN_TIME},
* even if a selector child caches.
*
* @return never null
*/
SelectionCacheType getCacheType();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/ReachableValues.java | package ai.timefold.solver.core.impl.heuristic.selector.common;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.FromEntityPropertyValueRangeDescriptor;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* This class records the relationship between each planning value and all entities that include the related value
* within its value range.
*
* @see FromEntityPropertyValueRangeDescriptor
*/
@NullMarked
public final class ReachableValues {
private final Map<Object, ReachableItemValue> values;
private final @Nullable Class<?> valueClass;
private final boolean acceptsNullValue;
private @Nullable ReachableItemValue firstCachedObject;
private @Nullable ReachableItemValue secondCachedObject;
public ReachableValues(Map<Object, ReachableItemValue> values, Class<?> valueClass, boolean acceptsNullValue) {
this.values = values;
this.valueClass = valueClass;
this.acceptsNullValue = acceptsNullValue;
}
private @Nullable ReachableItemValue fetchItemValue(Object value) {
ReachableItemValue selected = null;
if (firstCachedObject != null && firstCachedObject.value == value) {
selected = firstCachedObject;
} else if (secondCachedObject != null && secondCachedObject.value == value) {
selected = secondCachedObject;
// The most recently used item is moved to the first position.
// The goal is to try to keep recently used items in the cache.
secondCachedObject = firstCachedObject;
firstCachedObject = selected;
}
if (selected == null) {
selected = values.get(value);
secondCachedObject = firstCachedObject;
firstCachedObject = selected;
}
return selected;
}
public List<Object> extractEntitiesAsList(Object value) {
var itemValue = fetchItemValue(value);
if (itemValue == null) {
return Collections.emptyList();
}
return itemValue.randomAccessEntityList;
}
public List<Object> extractValuesAsList(Object value) {
var itemValue = fetchItemValue(value);
if (itemValue == null) {
return Collections.emptyList();
}
return itemValue.randomAccessValueList;
}
public int getSize() {
return values.size();
}
public boolean isEntityReachable(@Nullable Object origin, @Nullable Object entity) {
if (entity == null) {
return true;
}
if (origin == null) {
return acceptsNullValue;
}
var originItemValue = fetchItemValue(origin);
if (originItemValue == null) {
return false;
}
return originItemValue.entityMap.containsKey(entity);
}
public boolean isValueReachable(Object origin, @Nullable Object otherValue) {
var originItemValue = fetchItemValue(Objects.requireNonNull(origin));
if (originItemValue == null) {
return false;
}
if (otherValue == null) {
return acceptsNullValue;
}
return originItemValue.valueMap.containsKey(Objects.requireNonNull(otherValue));
}
public boolean matchesValueClass(Object value) {
return valueClass != null && valueClass.isAssignableFrom(Objects.requireNonNull(value).getClass());
}
@NullMarked
public static final class ReachableItemValue {
private final Object value;
private final Map<Object, Object> entityMap;
private final Map<Object, Object> valueMap;
private final List<Object> randomAccessEntityList;
private final List<Object> randomAccessValueList;
public ReachableItemValue(Object value, int entityListSize, int valueListSize) {
this.value = value;
this.entityMap = new IdentityHashMap<>(entityListSize);
this.randomAccessEntityList = new ArrayList<>(entityListSize);
this.valueMap = ConfigUtils.isGenericTypeImmutable(value.getClass()) ? new LinkedHashMap<>(valueListSize)
: new IdentityHashMap<>(valueListSize);
this.randomAccessValueList = new ArrayList<>(valueListSize);
}
public void addEntity(Object entity) {
if (entityMap.put(entity, entity) == null) {
randomAccessEntityList.add(entity);
}
}
public void addValue(Object value) {
if (valueMap.put(value, value) == null) {
randomAccessValueList.add(value);
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/SelectionCacheLifecycleBridge.java | package ai.timefold.solver.core.impl.heuristic.selector.common;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public final class SelectionCacheLifecycleBridge<Solution_> implements PhaseLifecycleListener<Solution_> {
private final SelectionCacheType cacheType;
private final SelectionCacheLifecycleListener<Solution_> selectionCacheLifecycleListener;
private boolean isConstructed = false;
public SelectionCacheLifecycleBridge(SelectionCacheType cacheType,
SelectionCacheLifecycleListener<Solution_> selectionCacheLifecycleListener) {
this.cacheType = cacheType;
this.selectionCacheLifecycleListener = selectionCacheLifecycleListener;
if (cacheType == null) {
throw new IllegalArgumentException("The cacheType (" + cacheType
+ ") for selectionCacheLifecycleListener (" + selectionCacheLifecycleListener
+ ") should have already been resolved.");
}
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
assertNotConstructed();
if (cacheType == SelectionCacheType.SOLVER) {
selectionCacheLifecycleListener.constructCache(solverScope);
isConstructed = true;
}
}
private void assertNotConstructed() {
if (isConstructed) {
throw new IllegalStateException("Impossible state: selection cache of type (" + cacheType + ") for listener ("
+ selectionCacheLifecycleListener + ") already constructed.");
}
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
if (cacheType == SelectionCacheType.PHASE) {
assertNotConstructed();
selectionCacheLifecycleListener.constructCache(phaseScope.getSolverScope());
isConstructed = true;
}
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
if (cacheType == SelectionCacheType.STEP) {
assertNotConstructed();
selectionCacheLifecycleListener.constructCache(stepScope.getPhaseScope().getSolverScope());
isConstructed = true;
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (cacheType == SelectionCacheType.STEP) {
assertConstructed();
selectionCacheLifecycleListener.disposeCache(stepScope.getPhaseScope().getSolverScope());
isConstructed = false;
}
}
private void assertConstructed() {
if (!isConstructed) {
throw new IllegalStateException("Impossible state: selection cache of type (" + cacheType + ") for listener ("
+ selectionCacheLifecycleListener + ") already disposed of.");
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
if (cacheType != SelectionCacheType.SOLVER) {
// Dispose of step cache as well, since we aren't guaranteed that stepEnded() was called.
if (cacheType != SelectionCacheType.STEP) {
assertConstructed(); // The step cache may have already been disposed of during stepEnded().
}
selectionCacheLifecycleListener.disposeCache(phaseScope.getSolverScope());
isConstructed = false;
}
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
if (cacheType == SelectionCacheType.SOLVER) {
assertConstructed();
selectionCacheLifecycleListener.disposeCache(solverScope);
isConstructed = false;
} else {
assertNotConstructed(); // Fail fast if we have a disposal problem, which is effectively a memory leak.
}
}
@Override
public String toString() {
return "Bridge(" + selectionCacheLifecycleListener + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/SelectionCacheLifecycleListener.java | package ai.timefold.solver.core.impl.heuristic.selector.common;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public interface SelectionCacheLifecycleListener<Solution_> {
void constructCache(SolverScope<Solution_> solverScope);
void disposeCache(SolverScope<Solution_> solverScope);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/ValueRangeRecorderId.java | package ai.timefold.solver.core.impl.heuristic.selector.common;
public record ValueRangeRecorderId(String recorderId, boolean basicVariable) {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/ComparatorSelectionSorter.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import java.util.Collections;
import java.util.Comparator;
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.config.heuristic.selector.common.decorator.SelectionSorterOrder;
/**
* Sorts a selection {@link List} based on a {@link Comparator}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type
*/
public final class ComparatorSelectionSorter<Solution_, T> implements SelectionSorter<Solution_, T> {
private final Comparator<T> appliedComparator;
public ComparatorSelectionSorter(Comparator<T> comparator, SelectionSorterOrder selectionSorterOrder) {
switch (selectionSorterOrder) {
case ASCENDING:
this.appliedComparator = comparator;
break;
case DESCENDING:
this.appliedComparator = Collections.reverseOrder(comparator);
break;
default:
throw new IllegalStateException("The selectionSorterOrder (" + selectionSorterOrder
+ ") is not implemented.");
}
}
@Override
public void sort(ScoreDirector<Solution_> scoreDirector, List<T> selectionList) {
selectionList.sort(appliedComparator);
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ComparatorSelectionSorter<?, ?> that = (ComparatorSelectionSorter<?, ?>) other;
return Objects.equals(appliedComparator, that.appliedComparator);
}
@Override
public int hashCode() {
return Objects.hash(appliedComparator);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/CompositeSelectionFilter.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
/**
* Combines several {@link SelectionFilter}s into one.
* Does a logical AND over the accept status of its filters.
*
*/
record CompositeSelectionFilter<Solution_, T>(SelectionFilter<Solution_, T>[] selectionFilterArray)
implements
SelectionFilter<Solution_, T> {
static final SelectionFilter NOOP = (scoreDirector, selection) -> true;
@Override
public boolean accept(ScoreDirector<Solution_> scoreDirector, T selection) {
for (var selectionFilter : selectionFilterArray) {
if (!selectionFilter.accept(scoreDirector, selection)) {
return false;
}
}
return true;
}
@Override
public boolean equals(Object other) {
return other instanceof CompositeSelectionFilter<?, ?> otherCompositeSelectionFilter
&& Arrays.equals(selectionFilterArray, otherCompositeSelectionFilter.selectionFilterArray);
}
@Override
public int hashCode() {
return Arrays.hashCode(selectionFilterArray);
}
@Override
public String toString() {
return "CompositeSelectionFilter[" + Arrays.toString(selectionFilterArray) + ']';
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/FairSelectorProbabilityWeightFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector;
public class FairSelectorProbabilityWeightFactory<Solution_>
implements SelectionProbabilityWeightFactory<Solution_, IterableSelector> {
@Override
public double createProbabilityWeight(ScoreDirector<Solution_> scoreDirector, IterableSelector selector) {
return selector.getSize();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/SelectionFilter.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.Selector;
/**
* Decides on accepting or discarding a selection,
* which is either a {@link PlanningEntity}, a planning value, a {@link Move} or a {@link Selector}).
* For example, a pinned {@link PlanningEntity} is rejected and therefore never used in a {@link Move}.
* <p>
* A filtered selection is considered as not selected, it does not count as an unaccepted selection.
*
* <p>
* Implementations are expected to be stateless.
* The solver may choose to reuse instances.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type.
* On problems using multiple planning variables on a single entity without specifying single variable name,
* this needs to be {@link Object} as variables of both types will be tested.
*/
@FunctionalInterface
public interface SelectionFilter<Solution_, T> {
/**
* Creates a {@link SelectionFilter} which applies all the provided filters one after another.
* Once one filter in the sequence returns false, no later filers are evaluated.
*
* @param filterArray filters to apply, never null
* @return never null
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type
*/
@SafeVarargs
static <Solution_, T> SelectionFilter<Solution_, T> compose(SelectionFilter<Solution_, T>... filterArray) {
return compose(Arrays.asList(filterArray));
}
/**
* As defined by {@link #compose(SelectionFilter[])}.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static <Solution_, T> SelectionFilter<Solution_, T> compose(List<SelectionFilter<Solution_, T>> filterList) {
return switch (filterList.size()) {
case 0 -> CompositeSelectionFilter.NOOP;
case 1 -> filterList.get(0);
default -> {
var distinctFilterArray = filterList.stream()
.flatMap(filter -> {
if (filter == CompositeSelectionFilter.NOOP) {
return Stream.empty();
} else if (filter instanceof CompositeSelectionFilter<Solution_, T> compositeSelectionFilter) {
// Decompose composites if necessary; avoids needless recursion.
return Arrays.stream(compositeSelectionFilter.selectionFilterArray());
} else {
return Stream.of(filter);
}
})
.distinct()
.toArray(SelectionFilter[]::new);
yield switch (distinctFilterArray.length) {
case 0 -> CompositeSelectionFilter.NOOP;
case 1 -> distinctFilterArray[0];
default -> new CompositeSelectionFilter<>(distinctFilterArray);
};
}
};
}
/**
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} to which the selection belongs or applies to
* @param selection never null, a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector}
* @return true if the selection is accepted (for example it is movable),
* false if the selection will be discarded (for example it is pinned)
*/
boolean accept(ScoreDirector<Solution_> scoreDirector, T selection);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/SelectionProbabilityWeightFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.Selector;
/**
* Create a probabilityWeight for a selection
* (which is a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector}).
* A probabilityWeight represents the random chance that a selection will be selected.
* Some use cases benefit from focusing moves more actively on specific selections.
*
* <p>
* Implementations are expected to be stateless.
* The solver may choose to reuse instances.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type
*/
@FunctionalInterface
public interface SelectionProbabilityWeightFactory<Solution_, T> {
/**
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} to which the selection belongs or applies to
* @param selection never null, a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector}
* to create the probabilityWeight for
* @return {@code 0.0 <= returnValue <} {@link Double#POSITIVE_INFINITY}
*/
double createProbabilityWeight(ScoreDirector<Solution_> scoreDirector, T selection);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/SelectionSorter.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import java.util.List;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.Selector;
/**
* Decides the order of a {@link List} of selection
* (which is a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector}).
*
* <p>
* Implementations are expected to be stateless.
* The solver may choose to reuse instances.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type
*/
@FunctionalInterface
public interface SelectionSorter<Solution_, T> {
/**
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} to which the selections belong or apply to
* @param selectionList never null, a {@link List}
* of {@link PlanningEntity}, planningValue, {@link Move} or {@link Selector}
*/
void sort(ScoreDirector<Solution_> scoreDirector, List<T> selectionList);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/SelectionSorterWeightFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.Selector;
/**
* Creates a weight to decide the order of a collections of selections
* (a selection is a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector}).
* The selections are then sorted by their weight,
* normally ascending unless it's configured descending.
*
* <p>
* Implementations are expected to be stateless.
* The solver may choose to reuse instances.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type
*/
@FunctionalInterface
public interface SelectionSorterWeightFactory<Solution_, T> {
/**
* @param solution never null, the {@link PlanningSolution} to which the selection belongs or applies to
* @param selection never null, a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector}
* @return never null, for example a {@link Integer}, {@link Double} or a more complex {@link Comparable}
*/
Comparable createSorterWeight(Solution_ solution, T selection);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/WeightFactorySelectionSorter.java | package ai.timefold.solver.core.impl.heuristic.selector.common.decorator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.Selector;
/**
* Sorts a selection {@link List} based on a {@link SelectionSorterWeightFactory}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <T> the selection type
*/
public final class WeightFactorySelectionSorter<Solution_, T> implements SelectionSorter<Solution_, T> {
private final SelectionSorterWeightFactory<Solution_, T> selectionSorterWeightFactory;
private final Comparator<Comparable> appliedWeightComparator;
public WeightFactorySelectionSorter(SelectionSorterWeightFactory<Solution_, T> selectionSorterWeightFactory,
SelectionSorterOrder selectionSorterOrder) {
this.selectionSorterWeightFactory = selectionSorterWeightFactory;
switch (selectionSorterOrder) {
case ASCENDING:
this.appliedWeightComparator = Comparator.naturalOrder();
break;
case DESCENDING:
this.appliedWeightComparator = Collections.reverseOrder();
break;
default:
throw new IllegalStateException("The selectionSorterOrder (" + selectionSorterOrder
+ ") is not implemented.");
}
}
@Override
public void sort(ScoreDirector<Solution_> scoreDirector, List<T> selectionList) {
sort(scoreDirector.getWorkingSolution(), selectionList);
}
/**
* @param solution never null, the {@link PlanningSolution} to which the selections belong or apply to
* @param selectionList never null, a {@link List}
* of {@link PlanningEntity}, planningValue, {@link Move} or {@link Selector}
*/
public void sort(Solution_ solution, List<T> selectionList) {
SortedMap<Comparable, T> selectionMap = new TreeMap<>(appliedWeightComparator);
for (T selection : selectionList) {
Comparable difficultyWeight = selectionSorterWeightFactory.createSorterWeight(solution, selection);
T previous = selectionMap.put(difficultyWeight, selection);
if (previous != null) {
throw new IllegalStateException("The selectionList contains 2 times the same selection ("
+ previous + ") and (" + selection + ").");
}
}
selectionList.clear();
selectionList.addAll(selectionMap.values());
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
WeightFactorySelectionSorter<?, ?> that = (WeightFactorySelectionSorter<?, ?>) other;
return Objects.equals(selectionSorterWeightFactory, that.selectionSorterWeightFactory)
&& Objects.equals(appliedWeightComparator, that.appliedWeightComparator);
}
@Override
public int hashCode() {
return Objects.hash(selectionSorterWeightFactory, appliedWeightComparator);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/AbstractOriginalChangeIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Collections;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
public abstract class AbstractOriginalChangeIterator<Solution_, Move_ extends Move<Solution_>>
extends UpcomingSelectionIterator<Move_> {
private final ValueSelector<Solution_> valueSelector;
private final Iterator<Object> entityIterator;
private Iterator<Object> valueIterator;
private Object upcomingEntity;
public AbstractOriginalChangeIterator(EntitySelector<Solution_> entitySelector,
ValueSelector<Solution_> valueSelector) {
this.valueSelector = valueSelector;
entityIterator = entitySelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move_ createUpcomingSelection() {
while (!valueIterator.hasNext()) {
if (!entityIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingEntity = entityIterator.next();
valueIterator = valueSelector.iterator(upcomingEntity);
}
Object toValue = valueIterator.next();
return newChangeSelection(upcomingEntity, toValue);
}
protected abstract Move_ newChangeSelection(Object entity, Object toValue);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/AbstractOriginalSwapIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Collections;
import java.util.ListIterator;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.ListIterableSelector;
public abstract class AbstractOriginalSwapIterator<Solution_, Move_ extends Move<Solution_>, SubSelection_>
extends UpcomingSelectionIterator<Move_> {
public static <Solution_, SubSelection_> long getSize(ListIterableSelector<Solution_, SubSelection_> leftSubSelector,
ListIterableSelector<Solution_, SubSelection_> rightSubSelector) {
if (leftSubSelector != rightSubSelector) {
return leftSubSelector.getSize() * rightSubSelector.getSize();
} else {
long leftSize = leftSubSelector.getSize();
return leftSize * (leftSize - 1L) / 2L;
}
}
protected final ListIterable<SubSelection_> leftSubSelector;
protected final ListIterable<SubSelection_> rightSubSelector;
protected final boolean leftEqualsRight;
private final ListIterator<SubSelection_> leftSubSelectionIterator;
private ListIterator<SubSelection_> rightSubSelectionIterator;
private SubSelection_ leftSubSelection;
public AbstractOriginalSwapIterator(ListIterable<SubSelection_> leftSubSelector,
ListIterable<SubSelection_> rightSubSelector) {
this.leftSubSelector = leftSubSelector;
this.rightSubSelector = rightSubSelector;
leftEqualsRight = (leftSubSelector == rightSubSelector);
leftSubSelectionIterator = leftSubSelector.listIterator();
rightSubSelectionIterator = Collections.<SubSelection_> emptyList().listIterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
}
@Override
protected Move_ createUpcomingSelection() {
while (!rightSubSelectionIterator.hasNext()) {
if (!leftSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
leftSubSelection = leftSubSelectionIterator.next();
if (!leftEqualsRight) {
rightSubSelectionIterator = rightSubSelector.listIterator();
} else {
// Select A-B, A-C, B-C. Do not select B-A, C-A, C-B. Do not select A-A, B-B, C-C.
if (!leftSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
rightSubSelectionIterator = rightSubSelector.listIterator(leftSubSelectionIterator.nextIndex());
// rightEntityIterator's first hasNext() always returns true because of the nextIndex()
}
}
SubSelection_ rightSubSelection = rightSubSelectionIterator.next();
return newSwapSelection(leftSubSelection, rightSubSelection);
}
protected abstract Move_ newSwapSelection(SubSelection_ leftSubSelection, SubSelection_ rightSubSelection);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/AbstractRandomChangeIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
public abstract class AbstractRandomChangeIterator<Solution_, Move_ extends Move<Solution_>>
extends UpcomingSelectionIterator<Move_> {
private final EntitySelector<Solution_> entitySelector;
private final ValueSelector<Solution_> valueSelector;
private Iterator<Object> entityIterator;
public AbstractRandomChangeIterator(EntitySelector<Solution_> entitySelector,
ValueSelector<Solution_> valueSelector) {
this.entitySelector = entitySelector;
this.valueSelector = valueSelector;
entityIterator = entitySelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
}
@Override
protected Move_ createUpcomingSelection() {
// Ideally, this code should have read:
// Object entity = entityIterator.next();
// Iterator<Object> valueIterator = valueSelector.iterator(entity);
// Object toValue = valueIterator.next();
// But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
if (!entityIterator.hasNext()) {
entityIterator = entitySelector.iterator();
if (!entityIterator.hasNext()) {
return noUpcomingSelection();
}
}
Object entity = entityIterator.next();
Iterator<Object> valueIterator = valueSelector.iterator(entity);
int entityIteratorCreationCount = 0;
// This loop is mostly only relevant when the entityIterator or valueIterator is non-random or shuffled
while (!valueIterator.hasNext()) {
// Try the next entity
if (!entityIterator.hasNext()) {
entityIterator = entitySelector.iterator();
entityIteratorCreationCount++;
if (entityIteratorCreationCount >= 2) {
// All entity-value combinations have been tried (some even more than once)
return noUpcomingSelection();
}
}
entity = entityIterator.next();
valueIterator = valueSelector.iterator(entity);
}
Object toValue = valueIterator.next();
return newChangeSelection(entity, toValue);
}
protected abstract Move_ newChangeSelection(Object entity, Object toValue);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/AbstractRandomSwapIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.move.Move;
public abstract class AbstractRandomSwapIterator<Solution_, Move_ extends Move<Solution_>, SubSelection_>
extends UpcomingSelectionIterator<Move_> {
protected final Iterable<SubSelection_> leftSubSelector;
protected final Iterable<SubSelection_> rightSubSelector;
protected Iterator<SubSelection_> leftSubSelectionIterator;
protected Iterator<SubSelection_> rightSubSelectionIterator;
public AbstractRandomSwapIterator(Iterable<SubSelection_> leftSubSelector,
Iterable<SubSelection_> rightSubSelector) {
this.leftSubSelector = leftSubSelector;
this.rightSubSelector = rightSubSelector;
leftSubSelectionIterator = this.leftSubSelector.iterator();
rightSubSelectionIterator = this.rightSubSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
}
@Override
protected Move_ createUpcomingSelection() {
// Ideally, this code should have read:
// SubS leftSubSelection = leftSubSelectionIterator.next();
// SubS rightSubSelection = rightSubSelectionIterator.next();
// But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
if (!leftSubSelectionIterator.hasNext()) {
leftSubSelectionIterator = leftSubSelector.iterator();
if (!leftSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
}
SubSelection_ leftSubSelection = leftSubSelectionIterator.next();
if (!rightSubSelectionIterator.hasNext()) {
rightSubSelectionIterator = rightSubSelector.iterator();
if (!rightSubSelectionIterator.hasNext()) {
return noUpcomingSelection();
}
}
SubSelection_ rightSubSelection = rightSubSelectionIterator.next();
return newSwapSelection(leftSubSelection, rightSubSelection);
}
protected abstract Move_ newSwapSelection(SubSelection_ leftSubSelection, SubSelection_ rightSubSelection);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/CachedListRandomIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.heuristic.move.Move;
/**
* This {@link Iterator} does not shuffle and is never ending.
*
* @param <S> Selection type, for example a {@link Move} class, an entity class or a value class.
*/
public class CachedListRandomIterator<S> extends SelectionIterator<S> {
protected final List<S> cachedList;
protected final Random workingRandom;
protected final boolean empty;
public CachedListRandomIterator(List<S> cachedList, Random workingRandom) {
this.cachedList = cachedList;
this.workingRandom = workingRandom;
empty = cachedList.isEmpty();
}
@Override
public boolean hasNext() {
return !empty;
}
@Override
public S next() {
if (empty) {
throw new NoSuchElementException();
}
int index = workingRandom.nextInt(cachedList.size());
return cachedList.get(index);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/ListIterable.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.List;
import java.util.ListIterator;
/**
* An extension on the {@link Iterable} interface that supports {@link #listIterator()} and {@link #listIterator(int)}.
*
* @param <T> the element type
*/
public interface ListIterable<T> extends Iterable<T> {
/**
* @see List#listIterator()
* @return never null, see {@link List#listIterator()}.
*/
ListIterator<T> listIterator();
/**
* @see List#listIterator()
* @param index lower than the size of this {@link ListIterable}, see {@link List#listIterator(int)}.
* @return never null, see {@link List#listIterator(int)}.
*/
ListIterator<T> listIterator(int index);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/SelectionIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Iterator;
public abstract class SelectionIterator<S> implements Iterator<S> {
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/SelectionListIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.ListIterator;
public abstract class SelectionListIterator<S> implements ListIterator<S> {
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
@Override
public void set(Object o) {
throw new UnsupportedOperationException("The optional operation set(...) is not supported.");
}
@Override
public void add(Object o) {
throw new UnsupportedOperationException("The optional operation add(...) is not supported.");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/SingletonIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class SingletonIterator<T> implements ListIterator<T> {
private final T singleton;
private boolean hasNext;
private boolean hasPrevious;
public SingletonIterator(T singleton) {
this.singleton = singleton;
hasNext = true;
hasPrevious = true;
}
public SingletonIterator(T singleton, int index) {
this.singleton = singleton;
if (index < 0 || index > 1) {
throw new IllegalArgumentException("The index (" + index + ") is invalid.");
}
hasNext = (index == 0);
hasPrevious = !hasNext;
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (!hasNext) {
throw new NoSuchElementException();
}
hasNext = false;
hasPrevious = true;
return singleton;
}
@Override
public boolean hasPrevious() {
return hasPrevious;
}
@Override
public T previous() {
if (!hasPrevious) {
throw new NoSuchElementException();
}
hasNext = true;
hasPrevious = false;
return singleton;
}
@Override
public int nextIndex() {
return hasNext ? 0 : 1;
}
@Override
public int previousIndex() {
return hasPrevious ? 0 : -1;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(T t) {
throw new UnsupportedOperationException();
}
@Override
public void add(T t) {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/UpcomingSelectionIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
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.Selector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.MimicReplayingEntitySelector;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
/**
* IMPORTANT: The constructor of any subclass of this abstract class, should never call any of its child
* {@link Selector}'s {@link Iterator#hasNext()} or {@link Iterator#next()} methods,
* because that can cause descendant {@link Selector}s to be selected too early
* (which breaks {@link MimicReplayingEntitySelector}).
*
* @param <S> Selection type, for example a {@link Move} class, an entity class or a value class.
*/
public abstract class UpcomingSelectionIterator<S> extends SelectionIterator<S> {
protected boolean upcomingCreated = false;
protected boolean hasUpcomingSelection = true;
protected S upcomingSelection;
@Override
public boolean hasNext() {
if (!upcomingCreated) {
upcomingSelection = createUpcomingSelection();
upcomingCreated = true;
}
return hasUpcomingSelection;
}
@Override
public S next() {
if (!hasUpcomingSelection) {
throw new NoSuchElementException();
}
if (!upcomingCreated) {
upcomingSelection = createUpcomingSelection();
}
upcomingCreated = false;
return upcomingSelection;
}
protected abstract S createUpcomingSelection();
protected S noUpcomingSelection() {
hasUpcomingSelection = false;
return null;
}
@Override
public String toString() {
if (!upcomingCreated) {
return "Next upcoming (?)";
} else if (!hasUpcomingSelection) {
return "No next upcoming";
} else {
return "Next upcoming (" + upcomingSelection + ")";
}
}
/**
* Some destination iterators, such as nearby destination iterators, may return even elements which are pinned.
* This is because the nearby matrix always picks from all nearby elements, and is unaware of any pinning.
* This means that later we need to filter out the pinned elements, so that moves aren't generated for them.
*
* @param destinationIterator never null
* @param listVariableDescriptor never null
* @return null if no unpinned destination was found, at which point the iterator is exhausted.
*/
public static ElementPosition findUnpinnedDestination(Iterator<ElementPosition> destinationIterator,
ListVariableDescriptor<?> listVariableDescriptor) {
while (destinationIterator.hasNext()) {
var destination = destinationIterator.next();
if (!isPinned(destination, listVariableDescriptor)) {
return destination;
}
}
return null;
}
public static boolean isPinned(ElementPosition destination, ListVariableDescriptor<?> listVariableDescriptor) {
if (destination instanceof PositionInList positionInList) {
return listVariableDescriptor.isElementPinned(null, positionInList.entity(), positionInList.index());
} else { // Unassigned element cannot be pinned.
return false;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/UpcomingSelectionListIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.common.iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public abstract class UpcomingSelectionListIterator<S> extends UpcomingSelectionIterator<S>
implements ListIterator<S> {
private int nextListIteratorIndex = 0;
protected S previousSelection;
protected boolean previousCreated = false;
protected boolean hasPreviousSelection = false;
protected S noPreviousSelection() {
hasPreviousSelection = false;
return null;
}
protected abstract S createUpcomingSelection();
protected abstract S createPreviousSelection();
@Override
public boolean hasPrevious() {
if (!previousCreated) {
previousSelection = createPreviousSelection();
previousCreated = true;
}
return hasPreviousSelection;
}
@Override
public S next() {
S next = super.next();
nextListIteratorIndex++;
hasPreviousSelection = true;
return next;
}
@Override
public S previous() {
if (!hasPreviousSelection) {
throw new NoSuchElementException();
}
if (!previousCreated) {
previousSelection = createPreviousSelection();
}
previousCreated = false;
nextListIteratorIndex--;
hasUpcomingSelection = true;
return previousSelection;
}
@Override
public int nextIndex() {
return nextListIteratorIndex;
}
@Override
public int previousIndex() {
return nextListIteratorIndex - 1;
}
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
@Override
public void set(S o) {
throw new UnsupportedOperationException("The optional operation set(...) is not supported.");
}
@Override
public void add(S o) {
throw new UnsupportedOperationException("The optional operation add(...) is not supported.");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/common/nearby/NearbyDistanceMeter.java | package ai.timefold.solver.core.impl.heuristic.selector.common.nearby;
/**
* Implementations are expected to be stateless.
* The solver may choose to reuse instances.
*
* @param <O>
* @param <D>
*/
@FunctionalInterface
public interface NearbyDistanceMeter<O, D> {
/**
* Measures the distance from the origin to the destination.
* The distance can be in any unit, such a meters, foot, seconds or milliseconds.
* For example, vehicle routing often uses driving time in seconds.
* <p>
* Distances can be asymmetrical: the distance from an origin to a destination
* often differs from the distance from that destination to that origin.
*
* @param origin never null
* @param destination never null
* @return Preferably always {@code >= 0.0}. If origin == destination, it usually returns 0.0.
*/
double getNearbyDistance(O origin, D destination);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/EntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.ListIterableSelector;
/**
* Selects instances of 1 {@link PlanningEntity} annotated class.
* Instances created via {@link EntitySelectorFactory} are guaranteed to exclude pinned entities.
*
* @see AbstractDemandEnabledSelector
* @see FromSolutionEntitySelector
*/
public interface EntitySelector<Solution_> extends ListIterableSelector<Solution_, Object> {
/**
* @return never null
*/
EntityDescriptor<Solution_> getEntityDescriptor();
/**
* If {@link #isNeverEnding()} is true, then {@link #iterator()} will never end.
* This returns an ending {@link Iterator}, that tries to match {@link #iterator()} as much as possible,
* but returns each distinct element only once and returns every element that might possibly be selected
* and therefore it might not respect the configuration of this {@link EntitySelector} entirely.
*
* @return never null
* @see #iterator()
*/
Iterator<Object> endingIterator();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/EntitySelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.entity;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
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.common.nearby.NearbySelectionConfig;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
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.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.common.ValueRangeRecorderId;
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.decorator.CachingEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.FilteringEntityByEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.FilteringEntityByValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.FilteringEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.ProbabilityEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.SelectedCountLimitEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.ShufflingEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.SortingEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.MimicRecordingEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.MimicReplayingEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
import ai.timefold.solver.core.impl.solver.ClassInstanceCache;
public class EntitySelectorFactory<Solution_> extends AbstractSelectorFactory<Solution_, EntitySelectorConfig> {
public static <Solution_> EntitySelectorFactory<Solution_> create(EntitySelectorConfig entitySelectorConfig) {
return new EntitySelectorFactory<>(entitySelectorConfig);
}
public EntitySelectorFactory(EntitySelectorConfig entitySelectorConfig) {
super(entitySelectorConfig);
}
public EntityDescriptor<Solution_> extractEntityDescriptor(HeuristicConfigPolicy<Solution_> configPolicy) {
var entityClass = config.getEntityClass();
var mimicSelectorRef = config.getMimicSelectorRef();
if (entityClass != null) {
var solutionDescriptor = configPolicy.getSolutionDescriptor();
var entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(entityClass);
if (entityDescriptor == null) {
throw new IllegalArgumentException("""
The selectorConfig (%s) has an entityClass (%s) that is not a known planning entity.
Check your solver configuration. If that class (%s) is not in the entityClassSet (%s), \
check your @%s implementation's annotated methods too."""
.formatted(config, entityClass, entityClass.getSimpleName(),
solutionDescriptor.getEntityClassSet(), PlanningSolution.class.getSimpleName()));
}
return entityDescriptor;
} else if (mimicSelectorRef != null) {
return configPolicy.getEntityMimicRecorder(mimicSelectorRef).getEntityDescriptor();
} else {
return null;
}
}
public EntitySelector<Solution_> buildEntitySelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) {
return buildEntitySelector(configPolicy, minimumCacheType, inheritedSelectionOrder, null);
}
/**
* @param configPolicy 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
* @param valueRangeRecorderId the recorder id to be used to create a replaying selector when enabling entity value
* range
* @return never null
*/
public EntitySelector<Solution_> buildEntitySelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder,
ValueRangeRecorderId valueRangeRecorderId) {
if (config.getMimicSelectorRef() != null) {
return buildMimicReplaying(configPolicy);
}
var entityDescriptor = deduceEntityDescriptor(configPolicy, config.getEntityClass());
var resolvedCacheType = SelectionCacheType.resolve(config.getCacheType(), minimumCacheType);
var resolvedSelectionOrder = SelectionOrder.resolve(config.getSelectionOrder(), inheritedSelectionOrder);
var nearbySelectionConfig = config.getNearbySelectionConfig();
if (nearbySelectionConfig != null) {
nearbySelectionConfig.validateNearby(resolvedCacheType, resolvedSelectionOrder);
}
validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder);
validateSorting(resolvedSelectionOrder);
validateProbability(resolvedSelectionOrder);
validateSelectedLimit(minimumCacheType);
// baseEntitySelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely
var baseRandomSelection = determineBaseRandomSelection(entityDescriptor, resolvedCacheType, resolvedSelectionOrder);
var baseSelectionCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType);
var entitySelector = buildBaseEntitySelector(entityDescriptor, baseSelectionCacheType,
baseRandomSelection);
var instanceCache = configPolicy.getClassInstanceCache();
if (nearbySelectionConfig != null) {
// TODO Static filtering (such as movableEntitySelectionFilter) should affect nearbySelection
entitySelector = applyNearbySelection(configPolicy, nearbySelectionConfig, minimumCacheType,
resolvedSelectionOrder, entitySelector);
} else {
// The nearby selector will implement its own logic to filter out unreachable elements.
// Therefore, we only apply entity value range filtering if the nearby feature is not enabled;
// otherwise, we would end up applying the filtering logic twice.
// The range-filtering node for list variables will use the ReachableValues structure
// to fetch and iterate only over the values that are reachable from the current selection.
// It is expected that the size of the reachable values will be smaller than that of the filtering node
// created by the applyFiltering function.
// Therefore, we first create the range-filtering node,
// and then we apply the usual filtering node decorator.
entitySelector = applyEntityValueRangeFilteringForListVariable(configPolicy, entitySelector, valueRangeRecorderId,
minimumCacheType, inheritedSelectionOrder, baseRandomSelection);
}
entitySelector = applyFiltering(entitySelector, instanceCache);
if (nearbySelectionConfig == null) {
// The range-filtering node for basic variables will use the entity child selector
// to iterate over the values.
// The node will iterate over any available entities from the child selector.
// Creating it after the usual filter node may result in evaluating fewer entities.
entitySelector = applyEntityValueRangeFilteringForBasicVariable(configPolicy, entitySelector, valueRangeRecorderId,
baseRandomSelection);
}
entitySelector = applySorting(resolvedCacheType, resolvedSelectionOrder, entitySelector, instanceCache);
entitySelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, entitySelector, instanceCache);
entitySelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, entitySelector);
entitySelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, entitySelector);
entitySelector = applySelectedLimit(resolvedSelectionOrder, entitySelector);
entitySelector = applyMimicRecording(configPolicy, entitySelector);
return entitySelector;
}
protected EntitySelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy) {
final var anyConfigurationParameterDefined = Stream
.of(config.getId(), config.getEntityClass(), config.getCacheType(), config.getSelectionOrder(),
config.getNearbySelectionConfig(), config.getFilterClass(), config.getSorterManner(),
config.getSorterComparatorClass(), config.getSorterWeightFactoryClass(), config.getSorterOrder(),
config.getSorterClass(), config.getProbabilityWeightFactoryClass(), config.getSelectedCountLimit())
.anyMatch(Objects::nonNull);
if (anyConfigurationParameterDefined) {
throw new IllegalArgumentException(
"The entitySelectorConfig (%s) with mimicSelectorRef (%s) has another property that is not null."
.formatted(config, config.getMimicSelectorRef()));
}
return buildMimicReplaying(configPolicy, config.getMimicSelectorRef());
}
private MimicReplayingEntitySelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy,
String id) {
var entityMimicRecorder = configPolicy.getEntityMimicRecorder(id);
if (entityMimicRecorder == null) {
throw new IllegalArgumentException(
"The entitySelectorConfig (%s) has a mimicSelectorRef (%s) for which no entitySelector with that id exists (in its solver phase)."
.formatted(config, config.getMimicSelectorRef()));
}
return new MimicReplayingEntitySelector<>(entityMimicRecorder);
}
protected boolean determineBaseRandomSelection(EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) {
return switch (resolvedSelectionOrder) {
case ORIGINAL, SORTED, SHUFFLED, PROBABILISTIC ->
// baseValueSelector and lower should be ORIGINAL if they are going to get cached completely
false;
case RANDOM ->
// Predict if caching will occur
resolvedCacheType.isNotCached()
|| (isBaseInherentlyCached() && !hasFiltering(entityDescriptor));
default -> throw new IllegalStateException("The selectionOrder (%s) is not implemented."
.formatted(resolvedSelectionOrder));
};
}
protected boolean isBaseInherentlyCached() {
return true;
}
private EntitySelector<Solution_> buildBaseEntitySelector(EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType minimumCacheType, boolean randomSelection) {
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 (%s) is not supported here. Please use %s instead."
.formatted(minimumCacheType, SelectionCacheType.PHASE));
}
// FromSolutionEntitySelector has an intrinsicCacheType STEP
return new FromSolutionEntitySelector<>(entityDescriptor, minimumCacheType, randomSelection);
}
private boolean hasFiltering(EntityDescriptor<Solution_> entityDescriptor) {
return config.getFilterClass() != null || entityDescriptor.hasEffectiveMovableEntityFilter();
}
private EntitySelector<Solution_> applyEntityValueRangeFilteringForListVariable(
HeuristicConfigPolicy<Solution_> configPolicy, EntitySelector<Solution_> entitySelector,
ValueRangeRecorderId valueRangeRecorderId, SelectionCacheType minimumCacheType, SelectionOrder selectionOrder,
boolean randomSelection) {
if (valueRangeRecorderId == null || valueRangeRecorderId.recorderId() == null || valueRangeRecorderId.basicVariable()) {
return entitySelector;
}
var valueSelectorConfig = new ValueSelectorConfig()
.withMimicSelectorRef(valueRangeRecorderId.recorderId());
var replayingValueSelector = (IterableValueSelector<Solution_>) ValueSelectorFactory
.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder);
return new FilteringEntityByValueSelector<>(entitySelector, replayingValueSelector, randomSelection);
}
private EntitySelector<Solution_> applyEntityValueRangeFilteringForBasicVariable(
HeuristicConfigPolicy<Solution_> configPolicy, EntitySelector<Solution_> entitySelector,
ValueRangeRecorderId valueRangeRecorderId, boolean randomSelection) {
if (valueRangeRecorderId == null || valueRangeRecorderId.recorderId() == null
|| !valueRangeRecorderId.basicVariable()) {
return entitySelector;
}
var replayingEntitySelector = buildMimicReplaying(configPolicy, valueRangeRecorderId.recorderId());
return new FilteringEntityByEntitySelector<>(entitySelector, replayingEntitySelector, randomSelection);
}
private EntitySelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy,
NearbySelectionConfig nearbySelectionConfig, SelectionCacheType minimumCacheType,
SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) {
return TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION)
.applyNearbySelection(config, configPolicy, nearbySelectionConfig, minimumCacheType,
resolvedSelectionOrder, entitySelector);
}
private EntitySelector<Solution_> applyFiltering(EntitySelector<Solution_> entitySelector,
ClassInstanceCache instanceCache) {
var entityDescriptor = entitySelector.getEntityDescriptor();
if (hasFiltering(entityDescriptor)) {
var filterClass = config.getFilterClass();
var filterList = new ArrayList<SelectionFilter<Solution_, Object>>(filterClass == null ? 1 : 2);
if (filterClass != null) {
SelectionFilter<Solution_, Object> selectionFilter =
instanceCache.newInstance(config, "filterClass", filterClass);
filterList.add(selectionFilter);
}
// Filter out pinned entities
if (entityDescriptor.hasEffectiveMovableEntityFilter()) {
filterList.add((scoreDirector, selection) -> entityDescriptor.getEffectiveMovableEntityFilter()
.test(scoreDirector.getWorkingSolution(), selection));
}
// Do not filter out initialized entities here for CH and ES, because they can be partially initialized
// Instead, ValueSelectorConfig.applyReinitializeVariableFiltering() does that.
entitySelector = FilteringEntitySelector.of(entitySelector, SelectionFilter.compose(filterList));
}
return entitySelector;
}
protected void validateSorting(SelectionOrder resolvedSelectionOrder) {
var sorterManner = config.getSorterManner();
var sorterComparatorClass = config.getSorterComparatorClass();
var sorterWeightFactoryClass = config.getSorterWeightFactoryClass();
var sorterOrder = config.getSorterOrder();
var sorterClass = config.getSorterClass();
if ((sorterManner != null || sorterComparatorClass != null || sorterWeightFactoryClass != null || sorterOrder != null
|| sorterClass != null) && resolvedSelectionOrder != SelectionOrder.SORTED) {
throw new IllegalArgumentException("""
The entitySelectorConfig (%s) with sorterManner (%s) \
and sorterComparatorClass (%s) and sorterWeightFactoryClass (%s) and sorterOrder (%s) and sorterClass (%s) \
has a resolvedSelectionOrder (%s) that is not %s."""
.formatted(config, sorterManner, sorterComparatorClass, sorterWeightFactoryClass, sorterOrder, sorterClass,
resolvedSelectionOrder, SelectionOrder.SORTED));
}
assertNotSorterMannerAnd(config, "sorterComparatorClass", EntitySelectorConfig::getSorterComparatorClass);
assertNotSorterMannerAnd(config, "sorterWeightFactoryClass", EntitySelectorConfig::getSorterWeightFactoryClass);
assertNotSorterMannerAnd(config, "sorterClass", EntitySelectorConfig::getSorterClass);
assertNotSorterMannerAnd(config, "sorterOrder", EntitySelectorConfig::getSorterOrder);
assertNotSorterClassAnd(config, "sorterComparatorClass", EntitySelectorConfig::getSorterComparatorClass);
assertNotSorterClassAnd(config, "sorterWeightFactoryClass", EntitySelectorConfig::getSorterWeightFactoryClass);
assertNotSorterClassAnd(config, "sorterOrder", EntitySelectorConfig::getSorterOrder);
if (sorterComparatorClass != null && sorterWeightFactoryClass != null) {
throw new IllegalArgumentException(
"The entitySelectorConfig (%s) has both a sorterComparatorClass (%s) and a sorterWeightFactoryClass (%s)."
.formatted(config, sorterComparatorClass, sorterWeightFactoryClass));
}
}
private static void assertNotSorterMannerAnd(EntitySelectorConfig config, String propertyName,
Function<EntitySelectorConfig, Object> propertyAccessor) {
var sorterManner = config.getSorterManner();
var property = propertyAccessor.apply(config);
if (sorterManner != null && property != null) {
throw new IllegalArgumentException("The entitySelectorConfig (%s) has both a sorterManner (%s) and a %s (%s)."
.formatted(config, sorterManner, propertyName, property));
}
}
private static void assertNotSorterClassAnd(EntitySelectorConfig config, String propertyName,
Function<EntitySelectorConfig, Object> propertyAccessor) {
var sorterClass = config.getSorterClass();
var property = propertyAccessor.apply(config);
if (sorterClass != null && property != null) {
throw new IllegalArgumentException(
"The entitySelectorConfig (%s) with sorterClass (%s) has a non-null %s (%s)."
.formatted(config, sorterClass, propertyName, property));
}
}
protected EntitySelector<Solution_> applySorting(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector, ClassInstanceCache instanceCache) {
if (resolvedSelectionOrder == SelectionOrder.SORTED) {
SelectionSorter<Solution_, Object> sorter;
var sorterManner = config.getSorterManner();
if (sorterManner != null) {
var entityDescriptor = entitySelector.getEntityDescriptor();
if (!EntitySelectorConfig.hasSorter(sorterManner, entityDescriptor)) {
return entitySelector;
}
sorter = EntitySelectorConfig.determineSorter(sorterManner, entityDescriptor);
} 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 entitySelectorConfig (%s) with resolvedSelectionOrder (%s) needs \
a sorterManner (%s) or a sorterComparatorClass (%s) or a sorterWeightFactoryClass (%s) \
or a sorterClass (%s)."""
.formatted(config, resolvedSelectionOrder, sorterManner, config.getSorterComparatorClass(),
config.getSorterWeightFactoryClass(), config.getSorterClass()));
}
entitySelector = new SortingEntitySelector<>(entitySelector, resolvedCacheType, sorter);
}
return entitySelector;
}
protected void validateProbability(SelectionOrder resolvedSelectionOrder) {
if (config.getProbabilityWeightFactoryClass() != null
&& resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) {
throw new IllegalArgumentException("The entitySelectorConfig (" + config
+ ") with probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass()
+ ") has a resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") that is not " + SelectionOrder.PROBABILISTIC + ".");
}
}
protected EntitySelector<Solution_> applyProbability(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector, ClassInstanceCache instanceCache) {
if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) {
if (config.getProbabilityWeightFactoryClass() == null) {
throw new IllegalArgumentException("The entitySelectorConfig (" + config
+ ") with resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") needs a probabilityWeightFactoryClass ("
+ config.getProbabilityWeightFactoryClass() + ").");
}
SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory = instanceCache.newInstance(config,
"probabilityWeightFactoryClass", config.getProbabilityWeightFactoryClass());
entitySelector = new ProbabilityEntitySelector<>(entitySelector, resolvedCacheType, probabilityWeightFactory);
}
return entitySelector;
}
private EntitySelector<Solution_> applyShuffling(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) {
if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) {
entitySelector = new ShufflingEntitySelector<>(entitySelector, resolvedCacheType);
}
return entitySelector;
}
private EntitySelector<Solution_> applyCaching(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) {
if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(entitySelector.getCacheType()) > 0) {
entitySelector = new CachingEntitySelector<>(entitySelector, resolvedCacheType,
resolvedSelectionOrder.toRandomSelectionBoolean());
}
return entitySelector;
}
private void validateSelectedLimit(SelectionCacheType minimumCacheType) {
if (config.getSelectedCountLimit() != null
&& minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) {
throw new IllegalArgumentException("The entitySelectorConfig (" + config
+ ") with selectedCountLimit (" + config.getSelectedCountLimit()
+ ") has a minimumCacheType (" + minimumCacheType
+ ") that is higher than " + SelectionCacheType.JUST_IN_TIME + ".");
}
}
private EntitySelector<Solution_> applySelectedLimit(SelectionOrder resolvedSelectionOrder,
EntitySelector<Solution_> entitySelector) {
if (config.getSelectedCountLimit() != null) {
entitySelector = new SelectedCountLimitEntitySelector<>(entitySelector,
resolvedSelectionOrder.toRandomSelectionBoolean(), config.getSelectedCountLimit());
}
return entitySelector;
}
private EntitySelector<Solution_> applyMimicRecording(HeuristicConfigPolicy<Solution_> configPolicy,
EntitySelector<Solution_> entitySelector) {
var id = config.getId();
if (id != null) {
if (id.isEmpty()) {
throw new IllegalArgumentException("The entitySelectorConfig (%s) has an empty id (%s).".formatted(config, id));
}
var mimicRecordingEntitySelector = new MimicRecordingEntitySelector<>(entitySelector);
configPolicy.addEntityMimicRecorder(id, mimicRecordingEntitySelector);
entitySelector = mimicRecordingEntitySelector;
}
return entitySelector;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/FromSolutionEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator;
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 EntitySelector} implementation.
*/
public final class FromSolutionEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntitySelector<Solution_> {
private final EntityDescriptor<Solution_> entityDescriptor;
private final SelectionCacheType minimumCacheType;
private final boolean randomSelection;
private List<Object> cachedEntityList = null;
private Long cachedEntityListRevision = null;
private boolean cachedEntityListIsDirty = false;
public FromSolutionEntitySelector(EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType minimumCacheType, boolean randomSelection) {
this.entityDescriptor = entityDescriptor;
this.minimumCacheType = minimumCacheType;
this.randomSelection = randomSelection;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return entityDescriptor;
}
/**
* @return never null, at least {@link SelectionCacheType#STEP}
*/
@Override
public SelectionCacheType getCacheType() {
var intrinsicCacheType = SelectionCacheType.STEP;
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();
reloadCachedEntityList(scoreDirector);
}
private void reloadCachedEntityList(InnerScoreDirector<Solution_, ?> scoreDirector) {
cachedEntityList = entityDescriptor.extractEntities(scoreDirector.getWorkingSolution());
cachedEntityListRevision = scoreDirector.getWorkingEntityListRevision();
cachedEntityListIsDirty = false;
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
var scoreDirector = stepScope.getScoreDirector();
if (scoreDirector.isWorkingEntityListDirty(cachedEntityListRevision)) {
if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) {
cachedEntityListIsDirty = true;
} else {
reloadCachedEntityList(scoreDirector);
}
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
cachedEntityList = null;
cachedEntityListRevision = null;
cachedEntityListIsDirty = false;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public long getSize() {
return cachedEntityList.size();
}
@Override
public Iterator<Object> iterator() {
checkCachedEntityListIsDirty();
if (!randomSelection) {
return cachedEntityList.iterator();
} else {
return new CachedListRandomIterator<>(cachedEntityList, workingRandom);
}
}
@Override
public ListIterator<Object> listIterator() {
checkCachedEntityListIsDirty();
if (!randomSelection) {
return cachedEntityList.listIterator();
} else {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (" + randomSelection + ").");
}
}
@Override
public ListIterator<Object> listIterator(int index) {
checkCachedEntityListIsDirty();
if (!randomSelection) {
return cachedEntityList.listIterator(index);
} else {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (" + randomSelection + ").");
}
}
@Override
public Iterator<Object> endingIterator() {
checkCachedEntityListIsDirty();
return cachedEntityList.iterator();
}
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;
var that = (FromSolutionEntitySelector<?>) other;
return randomSelection == that.randomSelection && Objects.equals(entityDescriptor, that.entityDescriptor)
&& minimumCacheType == that.minimumCacheType;
}
@Override
public int hashCode() {
return Objects.hash(entityDescriptor, minimumCacheType, randomSelection);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entityDescriptor.getEntityClass().getSimpleName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/AbstractCachingEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.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.entity.descriptor.EntityDescriptor;
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.entity.EntitySelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public abstract class AbstractCachingEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_>, EntitySelector<Solution_> {
protected final EntitySelector<Solution_> childEntitySelector;
protected final SelectionCacheType cacheType;
protected List<Object> cachedEntityList = null;
public AbstractCachingEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType) {
this.childEntitySelector = childEntitySelector;
this.cacheType = cacheType;
if (childEntitySelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childEntitySelector (" + childEntitySelector
+ ") with neverEnding (" + childEntitySelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childEntitySelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
public EntitySelector<Solution_> getChildEntitySelector() {
return childEntitySelector;
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
long childSize = childEntitySelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The selector (" + this
+ ") has a childEntitySelector (" + childEntitySelector
+ ") with childSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
cachedEntityList = new ArrayList<>((int) childSize);
childEntitySelector.iterator().forEachRemaining(cachedEntityList::add);
logger.trace(" Created cachedEntityList: size ({}), entitySelector ({}).",
cachedEntityList.size(), this);
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
cachedEntityList = null;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public long getSize() {
return cachedEntityList.size();
}
@Override
public Iterator<Object> endingIterator() {
return cachedEntityList.iterator();
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
AbstractCachingEntitySelector<?> that = (AbstractCachingEntitySelector<?>) other;
return Objects.equals(childEntitySelector, that.childEntitySelector) && cacheType == that.cacheType;
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, cacheType);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/CachingEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Iterator;
import java.util.ListIterator;
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.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.CachingMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.CachingValueSelector;
/**
* A {@link EntitySelector} that caches the result of its child {@link EntitySelector}.
* <p>
* Keep this code in sync with {@link CachingValueSelector} and {@link CachingMoveSelector}.
*/
public final class CachingEntitySelector<Solution_> extends AbstractCachingEntitySelector<Solution_> {
private final boolean randomSelection;
public CachingEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType,
boolean randomSelection) {
super(childEntitySelector, cacheType);
this.randomSelection = randomSelection;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public Iterator<Object> iterator() {
if (!randomSelection) {
return cachedEntityList.iterator();
} else {
return new CachedListRandomIterator<>(cachedEntityList, workingRandom);
}
}
@Override
public ListIterator<Object> listIterator() {
if (!randomSelection) {
return cachedEntityList.listIterator();
} else {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (" + randomSelection + ").");
}
}
@Override
public ListIterator<Object> listIterator(int index) {
if (!randomSelection) {
return cachedEntityList.listIterator(index);
} else {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (" + randomSelection + ").");
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
if (!super.equals(o))
return false;
CachingEntitySelector<?> that = (CachingEntitySelector<?>) o;
return randomSelection == that.randomSelection;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), randomSelection);
}
@Override
public String toString() {
return "Caching(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/FilteringEntityByEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Supplier;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionListIterator;
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.move.generic.SwapMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.SwapMoveSelectorFactory;
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.ValueRangeManager;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* The decorator returns a list of reachable entities for a specific entity.
* It enables the creation of a filtering tier when using entity-provided value ranges,
* ensuring only valid and reachable entities are returned.
* An entity is considered reachable to another entity
* if the assigned values exist within their respective entity value ranges.
* <p>
* The decorator can only be applied to basic variables.
* <code>
*
* e1 = entity_range[v1, v2, v3]
*
* e2 = entity_range[v1, v4]
*
* e3 = entity_range[v1, v4, v5]
*
* </code>
* <p>
* Let's consider the following use-cases:
* <ol>
* <li>e1(null) - e2(null): e2 is reachable by e1 because both assigned values are null.</li>
* <li>e1(v2) - e2(v1): e2 is not reachable by e1 because its value range does not accept v2.</li>
* <li>e2(v1) - e3(v4): e3 is reachable by e2 because e2 accepts v4 and e3 accepts v1.</li>
* </ol>
* <p>
* This node is currently used by the {@link SwapMoveSelector} selector.
* To explain its functionality, let's consider how moves are generated for the basic swap type.
* Initially, the swap move selector employs a left entity selector to choose one entity.
* Then, it uses a right entity selector to select another entity, with the goal of swapping their values.
* <p>
* Based on the previously described process and the current goal of this node,
* we can observe that once an entity is selected using the left selector,
* the right node can filter out all non-reachable entities and generate a valid move.
* A move is considered valid only if both entities accept each other's values.
* The filtering process of invalid entities allows the solver to explore the solution space more efficiently.
*
* @see SwapMoveSelectorFactory
* @see EntitySelectorFactory
* @param <Solution_> the solution type
*/
public final class FilteringEntityByEntitySelector<Solution_> extends AbstractDemandEnabledSelector<Solution_>
implements EntitySelector<Solution_> {
private final EntitySelector<Solution_> replayingEntitySelector;
private final EntitySelector<Solution_> childEntitySelector;
private final boolean randomSelection;
private Object replayedEntity;
private BasicVariableDescriptor<Solution_>[] basicVariableDescriptors;
private ValueRangeManager<Solution_> valueRangeManager;
private List<Object> allEntities;
public FilteringEntityByEntitySelector(EntitySelector<Solution_> childEntitySelector,
EntitySelector<Solution_> replayingEntitySelector, boolean randomSelection) {
this.childEntitySelector = childEntitySelector;
this.replayingEntitySelector = replayingEntitySelector;
this.randomSelection = randomSelection;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
this.childEntitySelector.solvingStarted(solverScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
var basicVariableList = childEntitySelector.getEntityDescriptor().getGenuineBasicVariableDescriptorList().stream()
.filter(v -> !v.isListVariable() && !v.canExtractValueRangeFromSolution())
.map(v -> (BasicVariableDescriptor<Solution_>) v)
.toList();
if (basicVariableList.isEmpty()) {
throw new IllegalStateException("Impossible state: no basic variable found for the entity %s."
.formatted(childEntitySelector.getEntityDescriptor().getEntityClass()));
}
this.allEntities = childEntitySelector.getEntityDescriptor().extractEntities(phaseScope.getWorkingSolution());
this.basicVariableDescriptors = basicVariableList.toArray(new BasicVariableDescriptor[0]);
this.valueRangeManager = phaseScope.getScoreDirector().getValueRangeManager();
this.childEntitySelector.phaseStarted(phaseScope);
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
this.childEntitySelector.stepStarted(stepScope);
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
this.childEntitySelector.phaseEnded(phaseScope);
this.replayedEntity = null;
this.valueRangeManager = null;
this.basicVariableDescriptors = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public long getSize() {
return allEntities.size();
}
@Override
public boolean isCountable() {
return childEntitySelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childEntitySelector.isNeverEnding();
}
/**
* The expected replayed entity corresponds to the selected entity when the replaying selector has the next value.
* Once it is selected, it will be reused until a new entity is replayed by the recorder selector.
*/
private Object selectReplayedEntity() {
var iterator = replayingEntitySelector.iterator();
if (iterator.hasNext()) {
this.replayedEntity = iterator.next();
}
return replayedEntity;
}
@Override
public Iterator<Object> endingIterator() {
return new OriginalFilteringValueRangeIterator<>(this::selectReplayedEntity, childEntitySelector.endingIterator(),
basicVariableDescriptors, valueRangeManager);
}
@Override
public Iterator<Object> iterator() {
if (randomSelection) {
if (!childEntitySelector.isNeverEnding()) {
throw new IllegalArgumentException(
"Impossible state: childEntitySelector must provide a never-ending approach.");
}
// Experiments have shown that a large number of attempts do not scale well.
// So we won't spend excessive time trying to generate a single move for the current selection.
// If we are unable to generate a move, the move iterator can still be used in later iterations.
var maxBailoutSize = Math.min(10, allEntities.size());
return new RandomFilteringValueRangeIterator<>(this::selectReplayedEntity, childEntitySelector.iterator(),
basicVariableDescriptors, valueRangeManager, maxBailoutSize);
} else {
return new OriginalFilteringValueRangeIterator<>(this::selectReplayedEntity, childEntitySelector.iterator(),
basicVariableDescriptors, valueRangeManager);
}
}
@Override
public ListIterator<Object> listIterator() {
return new OriginalFilteringValueRangeListIterator<>(this::selectReplayedEntity, childEntitySelector.listIterator(),
basicVariableDescriptors, valueRangeManager);
}
@Override
public ListIterator<Object> listIterator(int index) {
return new OriginalFilteringValueRangeListIterator<>(this::selectReplayedEntity,
childEntitySelector.listIterator(index), basicVariableDescriptors, valueRangeManager);
}
@Override
public boolean equals(Object other) {
return other instanceof FilteringEntityByEntitySelector<?> that
&& Objects.equals(childEntitySelector, that.childEntitySelector)
&& Objects.equals(replayingEntitySelector, that.replayingEntitySelector);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, replayingEntitySelector);
}
private abstract static class AbstractFilteringValueRangeIterator<Solution_> implements Iterator<Object> {
private final Supplier<Object> upcomingEntitySupplier;
private final BasicVariableDescriptor<Solution_>[] basicVariableDescriptors;
private final ValueRangeManager<Solution_> valueRangeManager;
private boolean initialized = false;
private Object replayedEntity;
private AbstractFilteringValueRangeIterator(Supplier<Object> upcomingEntitySupplier,
BasicVariableDescriptor<Solution_>[] basicVariableDescriptors, ValueRangeManager<Solution_> valueRangeManager) {
this.upcomingEntitySupplier = upcomingEntitySupplier;
this.basicVariableDescriptors = basicVariableDescriptors;
this.valueRangeManager = valueRangeManager;
}
void initialize() {
if (initialized) {
return;
}
checkReplayedEntity();
initialized = true;
}
void checkReplayedEntity() {
var newReplayedEntity = upcomingEntitySupplier.get();
if (newReplayedEntity != replayedEntity) {
replayedEntity = newReplayedEntity;
load(replayedEntity);
}
}
abstract void load(Object replayedEntity);
/**
* The other entity is reachable if it accepts all assigned values from the replayed entity, and vice versa.
*/
boolean isReachable(Object otherEntity) {
return isReachable(replayedEntity, otherEntity);
}
boolean isReachable(Object entity, Object otherEntity) {
if (entity == otherEntity) {
// Same entity cannot be swapped
return false;
}
for (var basicVariableDescriptor : basicVariableDescriptors) {
if (!isReachable(entity, basicVariableDescriptor.getValue(entity), otherEntity,
basicVariableDescriptor.getValue(otherEntity), basicVariableDescriptor, valueRangeManager)) {
return false;
}
}
return true;
}
private boolean isReachable(Object entity, Object value, Object otherEntity, Object otherValue,
BasicVariableDescriptor<Solution_> variableDescriptor, ValueRangeManager<Solution_> valueRangeManager) {
return valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), entity).contains(otherValue)
&& valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), otherEntity)
.contains(value);
}
}
private static class OriginalFilteringValueRangeIterator<Solution_> extends AbstractFilteringValueRangeIterator<Solution_> {
private final Iterator<Object> entityIterator;
private Object selected = null;
private OriginalFilteringValueRangeIterator(Supplier<Object> upcomingEntitySupplier,
Iterator<Object> entityIterator, BasicVariableDescriptor<Solution_>[] basicVariableDescriptors,
ValueRangeManager<Solution_> valueRangeManager) {
super(upcomingEntitySupplier, basicVariableDescriptors, valueRangeManager);
this.entityIterator = entityIterator;
}
@Override
void load(Object replayedEntity) {
this.selected = null;
}
@Override
public boolean hasNext() {
this.selected = pickNext();
return selected != null;
}
private Object pickNext() {
if (selected != null) {
throw new IllegalStateException("The next value has already been picked.");
}
initialize();
this.selected = null;
while (entityIterator.hasNext()) {
var entity = entityIterator.next();
if (isReachable(entity)) {
return entity;
}
}
return null;
}
private Object pickSelected() {
if (selected == null) {
throw new NoSuchElementException();
}
var result = selected;
this.selected = null;
return result;
}
@Override
public Object next() {
return pickSelected();
}
}
private static class OriginalFilteringValueRangeListIterator<Solution_> extends UpcomingSelectionListIterator<Object> {
private final Supplier<Object> upcomingEntitySupplier;
private final BasicVariableDescriptor<Solution_>[] basicVariableDescriptors;
private final ListIterator<Object> entityIterator;
private final ValueRangeManager<Solution_> valueRangeManager;
private Object replayedEntity;
private OriginalFilteringValueRangeListIterator(Supplier<Object> upcomingEntitySupplier,
ListIterator<Object> entityIterator, BasicVariableDescriptor<Solution_>[] basicVariableDescriptors,
ValueRangeManager<Solution_> valueRangeManager) {
this.upcomingEntitySupplier = upcomingEntitySupplier;
this.entityIterator = entityIterator;
this.basicVariableDescriptors = basicVariableDescriptors;
this.valueRangeManager = valueRangeManager;
}
void checkReplayedEntity() {
var newReplayedEntity = upcomingEntitySupplier.get();
if (newReplayedEntity != replayedEntity) {
replayedEntity = newReplayedEntity;
}
}
@Override
public boolean hasNext() {
checkReplayedEntity();
return super.hasNext();
}
@Override
public boolean hasPrevious() {
checkReplayedEntity();
return super.hasPrevious();
}
@Override
protected Object createUpcomingSelection() {
if (!entityIterator.hasNext()) {
return noUpcomingSelection();
}
while (entityIterator.hasNext()) {
var otherEntity = entityIterator.next();
if (isReachable(replayedEntity, otherEntity)) {
return otherEntity;
}
}
return noUpcomingSelection();
}
@Override
protected Object createPreviousSelection() {
if (!entityIterator.hasPrevious()) {
return noUpcomingSelection();
}
while (entityIterator.hasPrevious()) {
var otherEntity = entityIterator.previous();
if (isReachable(replayedEntity, otherEntity)) {
return otherEntity;
}
}
return noUpcomingSelection();
}
boolean isReachable(Object entity, Object otherEntity) {
if (entity == otherEntity) {
return false;
}
for (var basicVariableDescriptor : basicVariableDescriptors) {
if (!isReachable(entity, basicVariableDescriptor.getValue(entity), otherEntity,
basicVariableDescriptor.getValue(otherEntity), basicVariableDescriptor, valueRangeManager)) {
return false;
}
}
return true;
}
private boolean isReachable(Object entity, Object value, Object otherEntity, Object otherValue,
BasicVariableDescriptor<Solution_> variableDescriptor, ValueRangeManager<Solution_> valueRangeManager) {
return valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), entity).contains(otherValue)
&& valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), otherEntity)
.contains(value);
}
}
private static class RandomFilteringValueRangeIterator<Solution_>
extends AbstractFilteringValueRangeIterator<Solution_> {
private final Iterator<Object> entityIterator;
private final int maxBailoutSize;
private Object currentReplayedEntity = null;
private RandomFilteringValueRangeIterator(Supplier<Object> upcomingEntitySupplier,
Iterator<Object> entityIterator, BasicVariableDescriptor<Solution_>[] basicVariableDescriptors,
ValueRangeManager<Solution_> valueRangeManager, int maxBailoutSize) {
super(upcomingEntitySupplier, basicVariableDescriptors, valueRangeManager);
this.entityIterator = entityIterator;
this.maxBailoutSize = maxBailoutSize;
}
@Override
void load(Object replayedEntity) {
this.currentReplayedEntity = replayedEntity;
}
@Override
public boolean hasNext() {
checkReplayedEntity();
return entityIterator.hasNext();
}
@Override
public Object next() {
if (!entityIterator.hasNext()) {
throw new NoSuchElementException();
}
var bailoutSize = maxBailoutSize;
do {
bailoutSize--;
// We expect the iterator to apply a random selection
var next = entityIterator.next();
if (isReachable(currentReplayedEntity, next)) {
return next;
}
} while (bailoutSize > 0);
// If no reachable entity is found, we return the currently selected entity,
// which will result in a non-doable move
return currentReplayedEntity;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/FilteringEntityByValueSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Random;
import java.util.function.Supplier;
import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacerFactory;
import ai.timefold.solver.core.impl.constructionheuristic.placer.QueuedValuePlacer;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.ReachableValues;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionListIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* The decorator returns a list of reachable entities for a specific value.
* It enables the creation of a filtering tier when using entity-provided value ranges,
* ensuring only valid and reachable entities are returned.
* An entity is considered reachable to a value if its value range includes that value.
* <p>
* The decorator can only be applied to list variables.
* <p>
* <code>
*
* e1 = entity_range[v1, v2, v3]
* e2 = entity_range[v1, v4]
*
* v1 = [e1, e2]
*
* v2 = [e1]
*
* v3 = [e1]
*
* v4 = [e2]
*
* </code>
* <p>
* This node is currently used by the {@link QueuedValuePlacer} to build an initial solution.
* To illustrate its usage, let’s assume how moves are generated.
* First, a value is selected using a value selector.
* Then,
* a change move selector generates all possible moves for that value to the available entities
* and selects the entity and position with the best score.
* <p>
* Considering the previous process and the current goal of this node,
* we can observe that once a value is selected, only change moves to reachable entities will be generated.
* This ensures that entities that do not accept the currently selected value will not produce any change moves.
*
* @see ListChangeMoveSelectorFactory
* @see EntityPlacerFactory
*
* @param <Solution_> the solution type
*/
public final class FilteringEntityByValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_>
implements EntitySelector<Solution_> {
private final IterableValueSelector<Solution_> replayingValueSelector;
private final EntitySelector<Solution_> childEntitySelector;
private final boolean randomSelection;
private Object replayedValue;
private ReachableValues reachableValues;
private long entitiesSize;
public FilteringEntityByValueSelector(EntitySelector<Solution_> childEntitySelector,
IterableValueSelector<Solution_> replayingValueSelector, boolean randomSelection) {
this.replayingValueSelector = replayingValueSelector;
this.childEntitySelector = childEntitySelector;
this.randomSelection = randomSelection;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
this.childEntitySelector.solvingStarted(solverScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
this.entitiesSize = childEntitySelector.getEntityDescriptor().extractEntities(phaseScope.getWorkingSolution()).size();
this.reachableValues = phaseScope.getScoreDirector().getValueRangeManager()
.getReachableValues(Objects.requireNonNull(
phaseScope.getScoreDirector().getSolutionDescriptor().getListVariableDescriptor(),
"Impossible state: the list variable cannot be null."));
this.childEntitySelector.phaseStarted(phaseScope);
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
this.reachableValues = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public EntitySelector<Solution_> getChildEntitySelector() {
return childEntitySelector;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public long getSize() {
return entitiesSize;
}
@Override
public boolean isCountable() {
return childEntitySelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childEntitySelector.isNeverEnding();
}
/**
* The expected replayed value corresponds to the selected value when the replaying selector has the next value.
* Once it is selected, it will be reused until a new value is replayed by the recorder selector.
*/
private Object selectReplayedValue() {
var iterator = replayingValueSelector.iterator();
if (iterator.hasNext()) {
replayedValue = iterator.next();
}
return replayedValue;
}
@Override
public Iterator<Object> endingIterator() {
return new OriginalFilteringValueRangeIterator(this::selectReplayedValue, reachableValues);
}
@Override
public Iterator<Object> iterator() {
if (randomSelection) {
return new RandomFilteringValueRangeIterator(this::selectReplayedValue, reachableValues, workingRandom);
} else {
return new OriginalFilteringValueRangeIterator(this::selectReplayedValue, reachableValues);
}
}
@Override
public ListIterator<Object> listIterator() {
return new OriginalFilteringValueRangeListIterator(this::selectReplayedValue, childEntitySelector.listIterator(),
reachableValues);
}
@Override
public ListIterator<Object> listIterator(int index) {
return new OriginalFilteringValueRangeListIterator(this::selectReplayedValue, childEntitySelector.listIterator(index),
reachableValues);
}
@Override
public boolean equals(Object other) {
return other instanceof FilteringEntityByValueSelector<?> that
&& Objects.equals(childEntitySelector, that.childEntitySelector)
&& Objects.equals(replayingValueSelector, that.replayingValueSelector);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, replayingValueSelector);
}
private static class OriginalFilteringValueRangeIterator extends UpcomingSelectionIterator<Object> {
private final Supplier<Object> upcomingValueSupplier;
private final ReachableValues reachableValues;
private Iterator<Object> valueIterator;
private OriginalFilteringValueRangeIterator(Supplier<Object> upcomingValueSupplier, ReachableValues reachableValues) {
this.reachableValues = Objects.requireNonNull(reachableValues);
this.upcomingValueSupplier = Objects.requireNonNull(upcomingValueSupplier);
}
private void initialize() {
if (valueIterator != null) {
return;
}
var currentUpcomingValue = upcomingValueSupplier.get();
if (currentUpcomingValue == null) {
valueIterator = Collections.emptyIterator();
} else {
var allValues = reachableValues.extractEntitiesAsList(Objects.requireNonNull(currentUpcomingValue));
this.valueIterator = Objects.requireNonNull(allValues).iterator();
}
}
@Override
protected Object createUpcomingSelection() {
initialize();
if (!valueIterator.hasNext()) {
return noUpcomingSelection();
}
return valueIterator.next();
}
}
private static class OriginalFilteringValueRangeListIterator extends UpcomingSelectionListIterator<Object> {
private final Supplier<Object> upcomingValueSupplier;
private final ListIterator<Object> entityIterator;
private final ReachableValues reachableValues;
private Object replayedValue;
private OriginalFilteringValueRangeListIterator(Supplier<Object> upcomingValueSupplier,
ListIterator<Object> entityIterator, ReachableValues reachableValues) {
this.upcomingValueSupplier = upcomingValueSupplier;
this.entityIterator = entityIterator;
this.reachableValues = reachableValues;
}
void checkReplayedValue() {
var newReplayedValue = upcomingValueSupplier.get();
if (newReplayedValue != replayedValue) {
replayedValue = newReplayedValue;
}
}
@Override
public boolean hasNext() {
checkReplayedValue();
return super.hasNext();
}
@Override
public boolean hasPrevious() {
checkReplayedValue();
return super.hasPrevious();
}
@Override
protected Object createUpcomingSelection() {
if (!entityIterator.hasNext()) {
return noUpcomingSelection();
}
while (entityIterator.hasNext()) {
var otherEntity = entityIterator.next();
if (reachableValues.isEntityReachable(replayedValue, otherEntity)) {
return otherEntity;
}
}
return noUpcomingSelection();
}
@Override
protected Object createPreviousSelection() {
if (!entityIterator.hasPrevious()) {
return noUpcomingSelection();
}
while (entityIterator.hasPrevious()) {
var otherEntity = entityIterator.previous();
if (reachableValues.isEntityReachable(replayedValue, otherEntity)) {
return otherEntity;
}
}
return noUpcomingSelection();
}
}
private static class RandomFilteringValueRangeIterator implements Iterator<Object> {
private final Supplier<Object> upcomingValueSupplier;
private final ReachableValues reachableValues;
private final Random workingRandom;
private Object currentUpcomingValue;
private List<Object> entityList;
private RandomFilteringValueRangeIterator(Supplier<Object> upcomingValueSupplier, ReachableValues reachableValues,
Random workingRandom) {
this.upcomingValueSupplier = upcomingValueSupplier;
this.reachableValues = Objects.requireNonNull(reachableValues);
this.workingRandom = workingRandom;
}
private void checkReplayedValue() {
var oldUpcomingValue = currentUpcomingValue;
currentUpcomingValue = upcomingValueSupplier.get();
if (currentUpcomingValue == null) {
entityList = Collections.emptyList();
} else if (oldUpcomingValue != currentUpcomingValue) {
loadValues();
}
}
private void loadValues() {
this.entityList = reachableValues.extractEntitiesAsList(currentUpcomingValue);
}
@Override
public boolean hasNext() {
checkReplayedValue();
return entityList != null && !entityList.isEmpty();
}
@Override
public Object next() {
if (entityList.isEmpty()) {
throw new NoSuchElementException();
}
var index = workingRandom.nextInt(entityList.size());
return entityList.get(index);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/FilteringEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Objects;
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.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.common.iterator.UpcomingSelectionListIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
public final class FilteringEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntitySelector<Solution_> {
public static <Solution_> FilteringEntitySelector<Solution_> of(EntitySelector<Solution_> childEntitySelector,
SelectionFilter<Solution_, Object> filter) {
if (childEntitySelector instanceof FilteringEntitySelector<Solution_> filteringEntitySelector) {
return new FilteringEntitySelector<>(filteringEntitySelector.childEntitySelector,
SelectionFilter.compose(filteringEntitySelector.selectionFilter, filter));
}
return new FilteringEntitySelector<>(childEntitySelector, filter);
}
private final EntitySelector<Solution_> childEntitySelector;
private final SelectionFilter<Solution_, Object> selectionFilter;
private final boolean bailOutEnabled;
private ScoreDirector<Solution_> scoreDirector = null;
private FilteringEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionFilter<Solution_, Object> filter) {
this.childEntitySelector = Objects.requireNonNull(childEntitySelector);
this.selectionFilter = Objects.requireNonNull(filter);
bailOutEnabled = childEntitySelector.isNeverEnding();
phaseLifecycleSupport.addEventListener(childEntitySelector);
}
// ************************************************************************
// 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 EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return childEntitySelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childEntitySelector.isNeverEnding();
}
@Override
public long getSize() {
return childEntitySelector.getSize();
}
@Override
public Iterator<Object> iterator() {
return new JustInTimeFilteringEntityIterator(childEntitySelector.iterator(), determineBailOutSize());
}
protected class JustInTimeFilteringEntityIterator extends UpcomingSelectionIterator<Object> {
private final Iterator<Object> childEntityIterator;
private final long bailOutSize;
public JustInTimeFilteringEntityIterator(Iterator<Object> childEntityIterator, long bailOutSize) {
this.childEntityIterator = childEntityIterator;
this.bailOutSize = bailOutSize;
}
@Override
protected Object createUpcomingSelection() {
Object next;
long attemptsBeforeBailOut = bailOutSize;
do {
if (!childEntityIterator.hasNext()) {
return noUpcomingSelection();
}
if (bailOutEnabled) {
// if childEntityIterator is neverEnding and nothing is accepted, bail out of the infinite loop
if (attemptsBeforeBailOut <= 0L) {
logger.trace("Bailing out of neverEnding selector ({}) to avoid infinite loop.",
FilteringEntitySelector.this);
return noUpcomingSelection();
}
attemptsBeforeBailOut--;
}
next = childEntityIterator.next();
} while (!selectionFilter.accept(scoreDirector, next));
return next;
}
}
protected class JustInTimeFilteringEntityListIterator extends UpcomingSelectionListIterator<Object> {
private final ListIterator<Object> childEntityListIterator;
public JustInTimeFilteringEntityListIterator(ListIterator<Object> childEntityListIterator) {
this.childEntityListIterator = childEntityListIterator;
}
@Override
protected Object createUpcomingSelection() {
Object next;
do {
if (!childEntityListIterator.hasNext()) {
return noUpcomingSelection();
}
next = childEntityListIterator.next();
} while (!selectionFilter.accept(scoreDirector, next));
return next;
}
@Override
protected Object createPreviousSelection() {
Object previous;
do {
if (!childEntityListIterator.hasPrevious()) {
return noPreviousSelection();
}
previous = childEntityListIterator.previous();
} while (!selectionFilter.accept(scoreDirector, previous));
return previous;
}
}
@Override
public ListIterator<Object> listIterator() {
return new JustInTimeFilteringEntityListIterator(childEntitySelector.listIterator());
}
@Override
public ListIterator<Object> listIterator(int index) {
JustInTimeFilteringEntityListIterator listIterator =
new JustInTimeFilteringEntityListIterator(childEntitySelector.listIterator());
for (int i = 0; i < index; i++) {
listIterator.next();
}
return listIterator;
}
@Override
public Iterator<Object> endingIterator() {
return new JustInTimeFilteringEntityIterator(childEntitySelector.endingIterator(), determineBailOutSize());
}
private long determineBailOutSize() {
if (!bailOutEnabled) {
return -1L;
}
return childEntitySelector.getSize() * 10L;
}
@Override
public boolean equals(Object other) {
return other instanceof FilteringEntitySelector<?> that
&& Objects.equals(childEntitySelector, that.childEntitySelector)
&& Objects.equals(selectionFilter, that.selectionFilter);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, selectionFilter);
}
@Override
public String toString() {
return "Filtering(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/ProbabilityEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Iterator;
import java.util.ListIterator;
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.entity.descriptor.EntityDescriptor;
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.entity.EntitySelector;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public final class ProbabilityEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_>, EntitySelector<Solution_> {
private final EntitySelector<Solution_> childEntitySelector;
private final SelectionCacheType cacheType;
private final SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory;
private NavigableMap<Double, Object> cachedEntityMap = null;
private double probabilityWeightTotal = -1.0;
public ProbabilityEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType,
SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory) {
this.childEntitySelector = childEntitySelector;
this.cacheType = cacheType;
this.probabilityWeightFactory = probabilityWeightFactory;
if (childEntitySelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childEntitySelector (" + childEntitySelector
+ ") with neverEnding (" + childEntitySelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childEntitySelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
cachedEntityMap = new TreeMap<>();
ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector();
double probabilityWeightOffset = 0L;
for (Object entity : childEntitySelector) {
double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(
scoreDirector, entity);
cachedEntityMap.put(probabilityWeightOffset, entity);
probabilityWeightOffset += probabilityWeight;
}
probabilityWeightTotal = probabilityWeightOffset;
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
probabilityWeightTotal = -1.0;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return true;
}
@Override
public long getSize() {
return cachedEntityMap.size();
}
@Override
public Iterator<Object> iterator() {
return new Iterator<>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public Object next() {
double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
// entry is never null because randomOffset < probabilityWeightTotal
return cachedEntityMap.floorEntry(randomOffset)
.getValue();
}
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
};
}
@Override
public ListIterator<Object> listIterator() {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (true).");
}
@Override
public ListIterator<Object> listIterator(int index) {
throw new IllegalStateException("The selector (" + this
+ ") does not support a ListIterator with randomSelection (true).");
}
@Override
public Iterator<Object> endingIterator() {
return childEntitySelector.endingIterator();
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
ProbabilityEntitySelector<?> that = (ProbabilityEntitySelector<?>) other;
return Objects.equals(childEntitySelector, that.childEntitySelector) && cacheType == that.cacheType
&& Objects.equals(probabilityWeightFactory, that.probabilityWeightFactory);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, cacheType, probabilityWeightFactory);
}
@Override
public String toString() {
return "Probability(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/SelectedCountLimitEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
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.entity.EntitySelector;
public final class SelectedCountLimitEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntitySelector<Solution_> {
private final EntitySelector<Solution_> childEntitySelector;
private final boolean randomSelection;
private final long selectedCountLimit;
public SelectedCountLimitEntitySelector(EntitySelector<Solution_> childEntitySelector, boolean randomSelection,
long selectedCountLimit) {
this.childEntitySelector = childEntitySelector;
this.randomSelection = randomSelection;
this.selectedCountLimit = selectedCountLimit;
if (selectedCountLimit < 0L) {
throw new IllegalArgumentException("The selector (" + this
+ ") has a negative selectedCountLimit (" + selectedCountLimit + ").");
}
phaseLifecycleSupport.addEventListener(childEntitySelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public long getSize() {
long childSize = childEntitySelector.getSize();
return Math.min(selectedCountLimit, childSize);
}
@Override
public Iterator<Object> iterator() {
return new SelectedCountLimitEntityIterator(childEntitySelector.iterator());
}
@Override
public ListIterator<Object> listIterator() {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public ListIterator<Object> listIterator(int index) {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public Iterator<Object> endingIterator() {
if (randomSelection) {
// With random selection, the first n elements can differ between iterator calls,
// so it's illegal to only return the first n elements in original order (that breaks NearbySelection)
return childEntitySelector.endingIterator();
} else {
return new SelectedCountLimitEntityIterator(childEntitySelector.endingIterator());
}
}
private class SelectedCountLimitEntityIterator extends SelectionIterator<Object> {
private final Iterator<Object> childEntityIterator;
private long selectedSize;
public SelectedCountLimitEntityIterator(Iterator<Object> childEntityIterator) {
this.childEntityIterator = childEntityIterator;
selectedSize = 0L;
}
@Override
public boolean hasNext() {
return selectedSize < selectedCountLimit && childEntityIterator.hasNext();
}
@Override
public Object next() {
if (selectedSize >= selectedCountLimit) {
throw new NoSuchElementException();
}
selectedSize++;
return childEntityIterator.next();
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
SelectedCountLimitEntitySelector<?> that = (SelectedCountLimitEntitySelector<?>) other;
return randomSelection == that.randomSelection && selectedCountLimit == that.selectedCountLimit
&& Objects.equals(childEntitySelector, that.childEntitySelector);
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, randomSelection, selectedCountLimit);
}
@Override
public String toString() {
return "SelectedCountLimit(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/ShufflingEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Collections;
import java.util.Iterator;
import java.util.ListIterator;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
public final class ShufflingEntitySelector<Solution_> extends AbstractCachingEntitySelector<Solution_> {
public ShufflingEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType) {
super(childEntitySelector, cacheType);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator() {
Collections.shuffle(cachedEntityList, workingRandom);
logger.trace(" Shuffled cachedEntityList with size ({}) in entitySelector({}).",
cachedEntityList.size(), this);
return cachedEntityList.iterator();
}
@Override
public ListIterator<Object> listIterator() {
Collections.shuffle(cachedEntityList, workingRandom);
logger.trace(" Shuffled cachedEntityList with size ({}) in entitySelector({}).",
cachedEntityList.size(), this);
return cachedEntityList.listIterator();
}
@Override
public ListIterator<Object> listIterator(int index) {
// Presumes that listIterator() has already been called and shuffling would be bad
return cachedEntityList.listIterator(index);
}
@Override
public String toString() {
return "Shuffling(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/SortingEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator;
import java.util.Iterator;
import java.util.ListIterator;
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.entity.EntitySelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public final class SortingEntitySelector<Solution_> extends AbstractCachingEntitySelector<Solution_> {
private final SelectionSorter<Solution_, Object> sorter;
public SortingEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType,
SelectionSorter<Solution_, Object> sorter) {
super(childEntitySelector, cacheType);
this.sorter = sorter;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
super.constructCache(solverScope);
sorter.sort(solverScope.getScoreDirector(), cachedEntityList);
logger.trace(" Sorted cachedEntityList: size ({}), entitySelector ({}).",
cachedEntityList.size(), this);
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Object> iterator() {
return cachedEntityList.iterator();
}
@Override
public ListIterator<Object> listIterator() {
return cachedEntityList.listIterator();
}
@Override
public ListIterator<Object> listIterator(int index) {
return cachedEntityList.listIterator(index);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
if (!super.equals(o))
return false;
SortingEntitySelector<?> that = (SortingEntitySelector<?>) o;
return Objects.equals(sorter, that.sorter);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sorter);
}
@Override
public String toString() {
return "Sorting(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/mimic/EntityMimicRecorder.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.mimic;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
public interface EntityMimicRecorder<Solution_> {
/**
* @param replayingEntitySelector never null
*/
void addMimicReplayingEntitySelector(MimicReplayingEntitySelector<Solution_> replayingEntitySelector);
/**
* @return As defined by {@link EntitySelector#getEntityDescriptor()}
* @see EntitySelector#getEntityDescriptor()
*/
EntityDescriptor<Solution_> getEntityDescriptor();
/**
* @return As defined by {@link EntitySelector#isCountable()}
* @see EntitySelector#isCountable()
*/
boolean isCountable();
/**
* @return As defined by {@link EntitySelector#isNeverEnding()}
* @see EntitySelector#isNeverEnding()
*/
boolean isNeverEnding();
/**
* @return As defined by {@link EntitySelector#getSize()}
* @see EntitySelector#getSize()
*/
long getSize();
/**
* @return As defined by {@link EntitySelector#endingIterator()}
* @see EntitySelector#endingIterator()
*/
Iterator<Object> endingIterator();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/mimic/ManualEntityMimicRecorder.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.mimic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
public class ManualEntityMimicRecorder<Solution_> implements EntityMimicRecorder<Solution_> {
protected final EntitySelector<Solution_> sourceEntitySelector;
protected final List<MimicReplayingEntitySelector<Solution_>> replayingEntitySelectorList;
protected Object recordedEntity;
public ManualEntityMimicRecorder(EntitySelector<Solution_> sourceEntitySelector) {
this.sourceEntitySelector = sourceEntitySelector;
replayingEntitySelectorList = new ArrayList<>();
}
@Override
public void addMimicReplayingEntitySelector(MimicReplayingEntitySelector<Solution_> replayingEntitySelector) {
replayingEntitySelectorList.add(replayingEntitySelector);
}
public Object getRecordedEntity() {
return recordedEntity;
}
public void setRecordedEntity(Object recordedEntity) {
this.recordedEntity = recordedEntity;
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedNext(recordedEntity);
}
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return sourceEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return sourceEntitySelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return sourceEntitySelector.isNeverEnding();
}
@Override
public long getSize() {
return sourceEntitySelector.getSize();
}
@Override
public Iterator<Object> endingIterator() {
return sourceEntitySelector.endingIterator();
}
@Override
public String toString() {
return "Manual(" + sourceEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/mimic/MimicRecordingEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.mimic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
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.common.iterator.SelectionListIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
public final class MimicRecordingEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements EntityMimicRecorder<Solution_>, EntitySelector<Solution_> {
private final EntitySelector<Solution_> childEntitySelector;
private final List<MimicReplayingEntitySelector<Solution_>> replayingEntitySelectorList;
public MimicRecordingEntitySelector(EntitySelector<Solution_> childEntitySelector) {
this.childEntitySelector = childEntitySelector;
phaseLifecycleSupport.addEventListener(childEntitySelector);
replayingEntitySelectorList = new ArrayList<>();
}
@Override
public void addMimicReplayingEntitySelector(MimicReplayingEntitySelector<Solution_> replayingEntitySelector) {
replayingEntitySelectorList.add(replayingEntitySelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return childEntitySelector.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return childEntitySelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childEntitySelector.isNeverEnding();
}
@Override
public long getSize() {
return childEntitySelector.getSize();
}
@Override
public Iterator<Object> iterator() {
return new RecordingEntityIterator(childEntitySelector.iterator());
}
private class RecordingEntityIterator extends SelectionIterator<Object> {
private final Iterator<Object> childEntityIterator;
public RecordingEntityIterator(Iterator<Object> childEntityIterator) {
this.childEntityIterator = childEntityIterator;
}
@Override
public boolean hasNext() {
boolean hasNext = childEntityIterator.hasNext();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedHasNext(hasNext);
}
return hasNext;
}
@Override
public Object next() {
Object next = childEntityIterator.next();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedNext(next);
}
return next;
}
}
@Override
public Iterator<Object> endingIterator() {
// No recording, because the endingIterator() is used for determining size
return childEntitySelector.endingIterator();
}
@Override
public ListIterator<Object> listIterator() {
return new RecordingEntityListIterator(childEntitySelector.listIterator());
}
@Override
public ListIterator<Object> listIterator(int index) {
return new RecordingEntityListIterator(childEntitySelector.listIterator(index));
}
private class RecordingEntityListIterator extends SelectionListIterator<Object> {
private final ListIterator<Object> childEntityIterator;
public RecordingEntityListIterator(ListIterator<Object> childEntityIterator) {
this.childEntityIterator = childEntityIterator;
}
@Override
public boolean hasNext() {
boolean hasNext = childEntityIterator.hasNext();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedHasNext(hasNext);
}
return hasNext;
}
@Override
public Object next() {
Object next = childEntityIterator.next();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
replayingEntitySelector.recordedNext(next);
}
return next;
}
@Override
public boolean hasPrevious() {
boolean hasPrevious = childEntityIterator.hasPrevious();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
// The replay only cares that the recording changed, not in which direction
replayingEntitySelector.recordedHasNext(hasPrevious);
}
return hasPrevious;
}
@Override
public Object previous() {
Object previous = childEntityIterator.previous();
for (MimicReplayingEntitySelector<Solution_> replayingEntitySelector : replayingEntitySelectorList) {
// The replay only cares that the recording changed, not in which direction
replayingEntitySelector.recordedNext(previous);
}
return previous;
}
@Override
public int nextIndex() {
return childEntityIterator.nextIndex();
}
@Override
public int previousIndex() {
return childEntityIterator.previousIndex();
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MimicRecordingEntitySelector<?> that = (MimicRecordingEntitySelector<?>) 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(childEntitySelector, that.childEntitySelector)
&& Objects.equals(replayingEntitySelectorList.size(), that.replayingEntitySelectorList.size());
}
@Override
public int hashCode() {
return Objects.hash(childEntitySelector, replayingEntitySelectorList.size());
}
@Override
public String toString() {
return "Recording(" + childEntitySelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/mimic/MimicReplayingEntitySelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.mimic;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
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.phase.scope.AbstractPhaseScope;
public class MimicReplayingEntitySelector<Solution_>
extends AbstractDemandEnabledSelector<Solution_>
implements ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector<Solution_> {
private final EntityMimicRecorder<Solution_> entityMimicRecorder;
private boolean hasRecordingCreated;
private boolean hasRecording;
private boolean recordingCreated;
private Object recording;
private boolean recordingAlreadyReturned;
public MimicReplayingEntitySelector(EntityMimicRecorder<Solution_> entityMimicRecorder) {
this.entityMimicRecorder = entityMimicRecorder;
// No PhaseLifecycleSupport because the MimicRecordingEntitySelector is hooked up elsewhere too
entityMimicRecorder.addMimicReplayingEntitySelector(this);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
// Doing this in phaseStarted instead of stepStarted due to QueuedEntityPlacer compatibility
hasRecordingCreated = false;
recordingCreated = false;
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
// Doing this in phaseEnded instead of stepEnded due to QueuedEntityPlacer compatibility
hasRecordingCreated = false;
hasRecording = false;
recordingCreated = false;
recording = null;
}
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return entityMimicRecorder.getEntityDescriptor();
}
@Override
public boolean isCountable() {
return entityMimicRecorder.isCountable();
}
@Override
public boolean isNeverEnding() {
return entityMimicRecorder.isNeverEnding();
}
@Override
public long getSize() {
return entityMimicRecorder.getSize();
}
@Override
public Iterator<Object> iterator() {
return new ReplayingEntityIterator();
}
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 ReplayingEntityIterator extends SelectionIterator<Object> {
private ReplayingEntityIterator() {
// 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 recordingEntitySelector (" + entityMimicRecorder
+ ")'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 recordingEntitySelector (" + entityMimicRecorder
+ ")'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() {
// No replaying, because the endingIterator() is used for determining size
return entityMimicRecorder.endingIterator();
}
@Override
public ListIterator<Object> listIterator() {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public ListIterator<Object> listIterator(int index) {
// TODO Not yet implemented
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MimicReplayingEntitySelector<?> that = (MimicReplayingEntitySelector<?>) other;
return Objects.equals(entityMimicRecorder, that.entityMimicRecorder);
}
@Override
public int hashCode() {
return Objects.hash(entityMimicRecorder);
}
@Override
public String toString() {
return "Replaying(" + entityMimicRecorder + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/pillar/DefaultPillarSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.pillar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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.config.heuristic.selector.entity.pillar.SubPillarConfigPolicy;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.SubPillarType;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
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.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.CachedListRandomIterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.PillarDemand;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* @see PillarSelector
*/
public final class DefaultPillarSelector<Solution_> extends AbstractSelector<Solution_>
implements PillarSelector<Solution_>, SelectionCacheLifecycleListener<Solution_> {
private static final SelectionCacheType CACHE_TYPE = SelectionCacheType.STEP;
private final EntitySelector<Solution_> entitySelector;
private final boolean randomSelection;
private final SubPillarConfigPolicy subpillarConfigPolicy;
private final PillarDemand<Solution_> pillarDemand;
private List<List<Object>> cachedBasePillarList = null;
public DefaultPillarSelector(EntitySelector<Solution_> entitySelector,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors, boolean randomSelection,
SubPillarConfigPolicy subpillarConfigPolicy) {
this.entitySelector = entitySelector;
this.randomSelection = randomSelection;
this.subpillarConfigPolicy = subpillarConfigPolicy;
this.pillarDemand = new PillarDemand<>(entitySelector, variableDescriptors, subpillarConfigPolicy);
Class<?> entityClass = entitySelector.getEntityDescriptor().getEntityClass();
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptors) {
if (!entityClass.equals(
variableDescriptor.getEntityDescriptor().getEntityClass())) {
throw new IllegalStateException("The selector (" + this
+ ") has a variableDescriptor (" + variableDescriptor
+ ") with a entityClass (" + variableDescriptor.getEntityDescriptor().getEntityClass()
+ ") which is not equal to the entitySelector's entityClass (" + entityClass + ").");
}
boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.isChained();
if (isChained) {
throw new IllegalStateException("The selector (%s) has a variableDescriptor (%s) which is chained (%s)."
.formatted(this, variableDescriptor, isChained));
}
}
if (entitySelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has an entitySelector (" + entitySelector
+ ") with neverEnding (" + entitySelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(entitySelector);
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(CACHE_TYPE, this));
boolean subPillarEnabled = subpillarConfigPolicy.isSubPillarEnabled();
if (!randomSelection && subPillarEnabled) {
throw new IllegalStateException("The selector (" + this
+ ") with randomSelection (" + randomSelection + ") does not support non random selection with "
+ "sub pillars because the number of sub pillars scales exponentially.\n"
+ "Either set subPillarType to " + SubPillarType.NONE + " or use JIT random selection.");
}
}
// ************************************************************************
// Cache lifecycle methods
// ************************************************************************
@Override
public EntityDescriptor<Solution_> getEntityDescriptor() {
return entitySelector.getEntityDescriptor();
}
@Override
public SelectionCacheType getCacheType() {
return CACHE_TYPE;
}
PillarDemand<Solution_> getPillarDemand() {
return pillarDemand;
}
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
/*
* The first pillar selector creates the supply.
* Other matching pillar selectors, if there are any, reuse the supply.
*/
cachedBasePillarList = solverScope.getScoreDirector().getSupplyManager()
.demand(pillarDemand)
.read();
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
/*
* Cancel the demand of each pillar selector.
* The final pillar selector's demand cancellation will cause the supply to be removed entirely.
*/
solverScope.getScoreDirector().getSupplyManager()
.cancel(pillarDemand);
cachedBasePillarList = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public long getSize() {
if (!subpillarConfigPolicy.isSubPillarEnabled()) {
return cachedBasePillarList.size();
} else {
// For each pillar, the number of combinations is: the sum of every (n! / (k! (n-k)!)) for which n is
// pillar.getSize() and k iterates from minimumSubPillarSize to maximumSubPillarSize. This implies that a
// single pillar of size 64 is already too big to be held in a long.
throw new UnsupportedOperationException("The selector (" + this
+ ") with randomSelection (" + randomSelection + ") and sub pillars does not support getSize() "
+ "because the number of sub pillars scales exponentially.");
}
}
@Override
public Iterator<List<Object>> iterator() {
boolean subPillarEnabled = subpillarConfigPolicy.isSubPillarEnabled();
if (!randomSelection) {
if (!subPillarEnabled) {
return cachedBasePillarList.iterator();
} else {
throw new IllegalStateException(getSubPillarExceptionMessage());
}
} else {
if (!subPillarEnabled) {
return new CachedListRandomIterator<>(cachedBasePillarList, workingRandom);
} else {
return new RandomSubPillarIterator();
}
}
}
private String getSubPillarExceptionMessage() {
return "Impossible state because the constructors fails with randomSelection (" + randomSelection
+ ") and sub pillars.";
}
private String getListIteratorExceptionMessage() {
return "The selector (" + this + ") does not support a ListIterator with randomSelection (" + randomSelection
+ ").";
}
@Override
public ListIterator<List<Object>> listIterator() {
boolean subPillarEnabled = subpillarConfigPolicy.isSubPillarEnabled();
if (!randomSelection) {
if (!subPillarEnabled) {
return cachedBasePillarList.listIterator();
} else {
throw new IllegalStateException(getSubPillarExceptionMessage());
}
} else {
throw new IllegalStateException(getListIteratorExceptionMessage());
}
}
@Override
public ListIterator<List<Object>> listIterator(int index) {
boolean subPillarEnabled = subpillarConfigPolicy.isSubPillarEnabled();
if (!randomSelection) {
if (!subPillarEnabled) {
return cachedBasePillarList.listIterator(index);
} else {
throw new IllegalStateException(getSubPillarExceptionMessage());
}
} else {
throw new IllegalStateException(getListIteratorExceptionMessage());
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entitySelector + ")";
}
private class RandomSubPillarIterator extends UpcomingSelectionIterator<List<Object>> {
public RandomSubPillarIterator() {
if (cachedBasePillarList.isEmpty()) {
upcomingSelection = noUpcomingSelection();
upcomingCreated = true;
}
}
@Override
protected List<Object> createUpcomingSelection() {
List<Object> basePillar = selectBasePillar();
int basePillarSize = basePillar.size();
if (basePillarSize == 1) { // no subpillar to select
return basePillar;
}
// Known issue/compromise: Every subPillar should have same probability, but doesn't.
// Instead, every subPillar size has the same probability.
int min = Math.min(subpillarConfigPolicy.getMinimumSubPillarSize(), basePillarSize);
int max = Math.min(subpillarConfigPolicy.getMaximumSubPillarSize(), basePillarSize);
int subPillarSize = min + workingRandom.nextInt(max - min + 1);
if (subPillarSize == basePillarSize) { // subpillar is equal to the base pillar, use shortcut
return basePillar;
} else if (subPillarSize == 1) { // subpillar is just one element, use shortcut
final int randomIndex = workingRandom.nextInt(basePillarSize);
final Object randomElement = basePillar.get(randomIndex);
return Collections.singletonList(randomElement);
}
Comparator<?> comparator = subpillarConfigPolicy.getEntityComparator();
if (comparator == null) {
return selectRandom(basePillar, subPillarSize);
} else { // sequential subpillars
return selectSublist(basePillar, subPillarSize);
}
}
private List<Object> selectSublist(final List<Object> basePillar, final int subPillarSize) {
final int randomStartingIndex = workingRandom.nextInt(basePillar.size() - subPillarSize);
return basePillar.subList(randomStartingIndex, randomStartingIndex + subPillarSize);
}
private List<Object> selectRandom(final List<Object> basePillar, final int subPillarSize) {
// Random sampling: See http://eyalsch.wordpress.com/2010/04/01/random-sample/
// Used Swapping instead of Floyd because subPillarSize is large, to avoid hashCode() hit
Object[] sandboxPillar = basePillar.toArray(); // Clone to avoid changing basePillar
List<Object> subPillar = new ArrayList<>(subPillarSize);
for (int i = 0; i < subPillarSize; i++) {
int index = i + workingRandom.nextInt(basePillar.size() - i);
subPillar.add(sandboxPillar[index]);
sandboxPillar[index] = sandboxPillar[i];
}
return subPillar;
}
private List<Object> selectBasePillar() {
// Known issue/compromise: Every subPillar should have same probability, but doesn't.
// Instead, every basePillar has the same probability.
int baseListIndex = workingRandom.nextInt(cachedBasePillarList.size());
return cachedBasePillarList.get(baseListIndex);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/pillar/PillarSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.pillar;
import java.util.List;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.ListIterableSelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
/**
* A pillar is a {@link List} of entities that have the same planning value for each (or a subset)
* of their planning values.
* Selects a {@link List} of such entities that are moved together.
*
* @see EntitySelector
*/
public interface PillarSelector<Solution_> extends ListIterableSelector<Solution_, List<Object>> {
/**
* @return never null
*/
EntityDescriptor<Solution_> getEntityDescriptor();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/entity/pillar/PillarSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.entity.pillar;
import java.util.Comparator;
import java.util.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.entity.pillar.PillarSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.entity.pillar.SubPillarConfigPolicy;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.SubPillarType;
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.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
import ai.timefold.solver.core.impl.solver.ClassInstanceCache;
public class PillarSelectorFactory<Solution_>
extends AbstractSelectorFactory<Solution_, PillarSelectorConfig> {
public static <Solution_> PillarSelectorFactory<Solution_> create(PillarSelectorConfig pillarSelectorConfig) {
return new PillarSelectorFactory<>(pillarSelectorConfig);
}
public PillarSelectorFactory(PillarSelectorConfig pillarSelectorConfig) {
super(pillarSelectorConfig);
}
/**
* @param configPolicy never null
* @param subPillarType if null, defaults to {@link SubPillarType#ALL} for backwards compatibility reasons.
* @param subPillarSequenceComparatorClass if not null, will force entities in the pillar to come in this order
* @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
* @param variableNameIncludeList sometimes null
* @return never null
*/
public PillarSelector<Solution_> buildPillarSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SubPillarType subPillarType, Class<? extends Comparator<Object>> subPillarSequenceComparatorClass,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder,
List<String> variableNameIncludeList) {
if (subPillarType != SubPillarType.SEQUENCE && subPillarSequenceComparatorClass != null) {
throw new IllegalArgumentException("Subpillar type (" + subPillarType + ") on pillarSelectorConfig (" + config +
") is not " + SubPillarType.SEQUENCE + ", yet subPillarSequenceComparatorClass (" +
subPillarSequenceComparatorClass + ") is provided.");
}
if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) {
throw new IllegalArgumentException("The pillarSelectorConfig (" + config
+ ")'s minimumCacheType (" + minimumCacheType
+ ") must not be higher than " + SelectionCacheType.STEP
+ " because the pillars change every step.");
}
boolean subPillarEnabled = subPillarType != SubPillarType.NONE;
// EntitySelector uses SelectionOrder.ORIGINAL because a DefaultPillarSelector STEP caches the values
EntitySelectorConfig entitySelectorConfig =
Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new);
EntitySelector<Solution_> entitySelector =
EntitySelectorFactory.<Solution_> create(entitySelectorConfig)
.buildEntitySelector(configPolicy, minimumCacheType, SelectionOrder.ORIGINAL);
List<GenuineVariableDescriptor<Solution_>> variableDescriptors =
deduceVariableDescriptorList(entitySelector.getEntityDescriptor(), variableNameIncludeList);
if (!subPillarEnabled
&& (config.getMinimumSubPillarSize() != null || config.getMaximumSubPillarSize() != null)) {
throw new IllegalArgumentException("The pillarSelectorConfig (" + config
+ ") must not disable subpillars while providing minimumSubPillarSize (" + config.getMinimumSubPillarSize()
+ ") or maximumSubPillarSize (" + config.getMaximumSubPillarSize() + ").");
}
SubPillarConfigPolicy subPillarPolicy = subPillarEnabled
? configureSubPillars(subPillarType, subPillarSequenceComparatorClass, entitySelector,
config.getMinimumSubPillarSize(), config.getMaximumSubPillarSize(),
configPolicy.getClassInstanceCache())
: SubPillarConfigPolicy.withoutSubpillars();
return new DefaultPillarSelector<>(entitySelector, variableDescriptors,
inheritedSelectionOrder.toRandomSelectionBoolean(), subPillarPolicy);
}
private SubPillarConfigPolicy configureSubPillars(SubPillarType pillarType,
Class<? extends Comparator<Object>> pillarOrderComparatorClass, EntitySelector<Solution_> entitySelector,
Integer minimumSubPillarSize, Integer maximumSubPillarSize, ClassInstanceCache instanceCache) {
int actualMinimumSubPillarSize = Objects.requireNonNullElse(minimumSubPillarSize, 1);
int actualMaximumSubPillarSize = Objects.requireNonNullElse(maximumSubPillarSize, Integer.MAX_VALUE);
if (pillarType == null) { // for backwards compatibility reasons
return SubPillarConfigPolicy.withSubpillars(actualMinimumSubPillarSize, actualMaximumSubPillarSize);
}
switch (pillarType) {
case ALL:
return SubPillarConfigPolicy.withSubpillars(actualMinimumSubPillarSize, actualMaximumSubPillarSize);
case SEQUENCE:
if (pillarOrderComparatorClass == null) {
Class<?> entityClass = entitySelector.getEntityDescriptor().getEntityClass();
boolean isComparable = Comparable.class.isAssignableFrom(entityClass);
if (!isComparable) {
throw new IllegalArgumentException("Pillar type (" + pillarType + ") on pillarSelectorConfig (" +
config + ") does not provide pillarOrderComparatorClass while the entity (" +
entityClass.getCanonicalName() + ") does not implement Comparable.");
}
return SubPillarConfigPolicy.sequential(actualMinimumSubPillarSize, actualMaximumSubPillarSize,
Comparator.naturalOrder());
} else {
Comparator<Object> comparator = instanceCache.newInstance(config, "pillarOrderComparatorClass",
pillarOrderComparatorClass);
return SubPillarConfigPolicy.sequential(actualMinimumSubPillarSize, actualMaximumSubPillarSize, comparator);
}
default:
throw new IllegalStateException("Subpillars cannot be enabled and disabled at the same time.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/DestinationSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
public interface DestinationSelector<Solution_> extends IterableSelector<Solution_, ElementPosition> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/DestinationSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.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.common.nearby.NearbySelectionConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
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.AbstractSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.common.ValueRangeRecorderId;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public final class DestinationSelectorFactory<Solution_> extends AbstractSelectorFactory<Solution_, DestinationSelectorConfig> {
public static <Solution_> DestinationSelectorFactory<Solution_>
create(DestinationSelectorConfig destinationSelectorConfig) {
return new DestinationSelectorFactory<>(destinationSelectorConfig);
}
private DestinationSelectorFactory(DestinationSelectorConfig destinationSelectorConfig) {
super(destinationSelectorConfig);
}
public DestinationSelector<Solution_> buildDestinationSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
return buildDestinationSelector(configPolicy, minimumCacheType, randomSelection, null);
}
public DestinationSelector<Solution_> buildDestinationSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection, String entityValueRangeRecorderId) {
var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
var entitySelector = EntitySelectorFactory.<Solution_> create(Objects.requireNonNull(config.getEntitySelectorConfig()))
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder,
new ValueRangeRecorderId(entityValueRangeRecorderId, false));
var valueSelector = buildIterableValueSelector(configPolicy, entitySelector.getEntityDescriptor(),
minimumCacheType, selectionOrder, entityValueRangeRecorderId);
var baseDestinationSelector =
new ElementDestinationSelector<>(entitySelector, valueSelector, selectionOrder.toRandomSelectionBoolean());
return applyNearbySelection(configPolicy, minimumCacheType, selectionOrder, baseDestinationSelector,
entityValueRangeRecorderId != null);
}
private IterableValueSelector<Solution_> buildIterableValueSelector(
HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, String entityValueRangeRecorderId) {
// Destination selector does not require asserting both sides,
// which means checking only if the destination entity accept the selected value
ValueSelector<Solution_> valueSelector = ValueSelectorFactory
.<Solution_> create(Objects.requireNonNull(config.getValueSelectorConfig()))
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder,
// Do not override reinitializeVariableFilterEnabled.
configPolicy.isReinitializeVariableFilterEnabled(),
/*
* Filter assigned values (but only if this filtering type is allowed by the configPolicy).
*
* The destination selector requires the child value selector to only select assigned values.
* To guarantee this during CH, where not all values are assigned, the UnassignedValueSelector filter
* must be applied.
*
* In the LS phase, not only is the filter redundant because there are no unassigned values,
* but it would also crash if the base value selector inherits random selection order,
* because the filter cannot work on a never-ending child value selector.
* Therefore, it must not be applied even though it is requested here. This is accomplished by
* the configPolicy that only allows this filtering type in the CH phase.
*/
ValueSelectorFactory.ListValueFilteringType.ACCEPT_ASSIGNED,
entityValueRangeRecorderId, false);
return (IterableValueSelector<Solution_>) valueSelector;
}
private DestinationSelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, SelectionOrder selectionOrder,
ElementDestinationSelector<Solution_> destinationSelector, boolean enableEntityValueRange) {
NearbySelectionConfig nearbySelectionConfig = config.getNearbySelectionConfig();
if (nearbySelectionConfig == null) {
return destinationSelector;
}
// The nearby selector will implement its own logic to filter out unreachable elements.
// It requires the child selectors to not be FilteringEntityValueRangeSelector or FilteringValueRangeSelector,
// as it needs to iterate over all available values to construct the distance matrix.
if (enableEntityValueRange) {
var entitySelector =
EntitySelectorFactory.<Solution_> create(Objects.requireNonNull(config.getEntitySelectorConfig()))
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
var valueSelector = ValueSelectorFactory
.<Solution_> create(Objects.requireNonNull(config.getValueSelectorConfig()))
.buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType,
selectionOrder, configPolicy.isReinitializeVariableFilterEnabled(),
ValueSelectorFactory.ListValueFilteringType.ACCEPT_ASSIGNED, null, false);
var updatedDestinationSelector =
new ElementDestinationSelector<>(entitySelector, (IterableValueSelector<Solution_>) valueSelector,
selectionOrder.toRandomSelectionBoolean());
return TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION)
.applyNearbySelection(config, configPolicy, minimumCacheType, selectionOrder,
updatedDestinationSelector);
} else {
return TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION)
.applyNearbySelection(config, configPolicy, minimumCacheType, selectionOrder, destinationSelector);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/ElementDestinationSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex;
import java.util.Collections;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
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.AbstractSelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
/**
* Selects destinations for list variable change moves. The destination specifies a future position in a list variable,
* expressed as an {@link PositionInList}, where a moved element or subList can be inserted.
* <p>
* Destination completeness is achieved by using both entity and value child selectors.
* When an entity <em>A</em> is selected, the destination becomes <em>A[0]</em>.
* When a value <em>x</em> is selected, its current position <em>A[i]</em> is determined using inverse and index supplies and
* the destination becomes <em>A[i + 1]</em>.
* <p>
* Fairness in random selection is achieved by first deciding between entity and value selector with a probability that is
* proportional to the entity/value ratio. The child entity and value selectors are assumed to be fair.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ElementDestinationSelector<Solution_> extends AbstractSelector<Solution_>
implements DestinationSelector<Solution_> {
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final EntitySelector<Solution_> entitySelector;
private final IterableValueSelector<Solution_> valueSelector;
private final boolean randomSelection;
private ListVariableStateSupply<Solution_> listVariableStateSupply;
public ElementDestinationSelector(EntitySelector<Solution_> entitySelector, IterableValueSelector<Solution_> valueSelector,
boolean randomSelection) {
this.listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor();
this.entitySelector = entitySelector;
var selector = filterPinnedListPlanningVariableValuesWithIndex(valueSelector, this::getListVariableStateSupply);
this.valueSelector = listVariableDescriptor.allowsUnassignedValues() ? filterUnassignedValues(selector) : selector;
this.randomSelection = randomSelection;
phaseLifecycleSupport.addEventListener(this.entitySelector);
phaseLifecycleSupport.addEventListener(this.valueSelector);
}
private ListVariableStateSupply<Solution_> getListVariableStateSupply() {
return Objects.requireNonNull(listVariableStateSupply,
"Impossible state: The listVariableStateSupply is not initialized yet.");
}
private IterableValueSelector<Solution_> filterUnassignedValues(
IterableValueSelector<Solution_> valueSelector) {
/*
* In case of list variable that allows unassigned values,
* unassigned elements will show up in the valueSelector.
* These skew the selection probability, so we need to exclude them.
* The option to unassign needs to be added to the iterator once later,
* to make sure that it can get selected.
*
* Example: for destination elements [A, B, C] where C is not initialized,
* the probability of unassigning a source element is 1/3 as it should be.
* (If destination is not initialized, it means source will be unassigned.)
* However, if B and C were not initialized, the probability of unassigning goes up to 2/3.
* The probability should be 1/2 instead.
* (Either select A as the destination, or unassign.)
* If we always remove unassigned elements from the iterator,
* and always add one option to unassign at the end,
* we can keep the correct probabilities throughout.
*/
return FilteringValueSelector.ofAssigned(valueSelector, this::getListVariableStateSupply);
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
var supplyManager = solverScope.getScoreDirector().getSupplyManager();
listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand());
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
listVariableStateSupply = null;
}
@Override
public long getSize() {
if (entitySelector.getSize() == 0) {
return 0;
}
return entitySelector.getSize() + valueSelector.getSize();
}
@Override
public Iterator<ElementPosition> iterator() {
if (randomSelection) {
var allowsUnassignedValues = listVariableDescriptor.allowsUnassignedValues();
// In case of list var which allows unassigned values, we need to exclude unassigned elements.
var totalValueSize = valueSelector.getSize()
- (allowsUnassignedValues ? listVariableStateSupply.getUnassignedCount() : 0);
var totalSize = Math.addExact(entitySelector.getSize(), totalValueSize);
return new ElementPositionRandomIterator<>(listVariableStateSupply, entitySelector, valueSelector,
workingRandom, totalSize, allowsUnassignedValues);
} else {
if (entitySelector.getSize() == 0) {
return Collections.emptyIterator();
}
// Start with the first unpinned value of each entity, or zero if no pinning.
// Entity selector is guaranteed to return only unpinned entities.
Stream<ElementPosition> stream = StreamSupport.stream(entitySelector.spliterator(), false)
.map(entity -> ElementPosition.of(entity, listVariableDescriptor.getFirstUnpinnedIndex(entity)));
// Filter guarantees that we only get values that are actually in one of the lists.
// Value selector guarantees only unpinned values.
// Simplify tests.
stream = Stream.concat(stream,
StreamSupport.stream(valueSelector.spliterator(), false)
.map(v -> listVariableStateSupply.getElementPosition(v).ensureAssigned())
.map(positionInList -> ElementPosition.of(positionInList.entity(), positionInList.index() + 1)));
// If the list variable allows unassigned values, add the option of unassigning.
if (listVariableDescriptor.allowsUnassignedValues()) {
stream = Stream.concat(stream, Stream.of(ElementPosition.unassigned()));
}
return stream.iterator();
}
}
@Override
public boolean isCountable() {
return entitySelector.isCountable() && valueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || entitySelector.isNeverEnding() || valueSelector.isNeverEnding();
}
public ListVariableDescriptor<Solution_> getVariableDescriptor() {
return (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor();
}
public EntityDescriptor<Solution_> getEntityDescriptor() {
return entitySelector.getEntityDescriptor();
}
public Iterator<Object> endingIterator() {
return Stream.concat(
StreamSupport.stream(Spliterators.spliterator(entitySelector.endingIterator(), entitySelector.getSize(), 0),
false),
StreamSupport.stream(Spliterators.spliterator(valueSelector.endingIterator(null), valueSelector.getSize(), 0),
false))
.iterator();
}
@Override
public boolean equals(Object o) {
return o instanceof ElementDestinationSelector<?> that
&& randomSelection == that.randomSelection
&& Objects.equals(entitySelector, that.entitySelector)
&& Objects.equals(valueSelector, that.valueSelector);
}
@Override
public int hashCode() {
return Objects.hash(entitySelector, valueSelector, randomSelection);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entitySelector + ", " + valueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/ElementPositionRandomIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
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.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
final class ElementPositionRandomIterator<Solution_> implements Iterator<ElementPosition> {
private final ListVariableStateSupply<Solution_> listVariableStateSupply;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final EntitySelector<Solution_> entitySelector;
private final IterableValueSelector<Solution_> valueSelector;
private final Iterator<Object> entityIterator;
private final Random workingRandom;
private final long totalSize;
private final boolean allowsUnassignedValues;
private Iterator<Object> valueIterator;
public ElementPositionRandomIterator(ListVariableStateSupply<Solution_> listVariableStateSupply,
EntitySelector<Solution_> entitySelector, IterableValueSelector<Solution_> valueSelector,
Random workingRandom, long totalSize, boolean allowsUnassignedValues) {
this.listVariableStateSupply = listVariableStateSupply;
this.listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
this.entitySelector = entitySelector;
this.valueSelector = valueSelector;
this.entityIterator = entitySelector.iterator();
this.workingRandom = workingRandom;
this.totalSize = totalSize;
if (totalSize < 1) {
throw new IllegalStateException("Impossible state: totalSize (%d) < 1"
.formatted(totalSize));
}
this.allowsUnassignedValues = allowsUnassignedValues;
this.valueIterator = null;
}
@Override
public boolean hasNext() {
// The valueSelector's hasNext() is insignificant.
// The next random destination exists if and only if there is a next entity.
return entityIterator.hasNext();
}
@Override
public ElementPosition next() {
// This code operates under the assumption that the entity selector already filtered out all immovable entities.
// At this point, entities are only partially pinned, or not pinned at all.
var entitySize = entitySelector.getSize();
// If we support unassigned values, we have to add 1 to all the sizes
// to account for the unassigned destination, which is an extra element.
var entityBoundary = allowsUnassignedValues ? entitySize + 1 : entitySize;
var random = RandomUtils.nextLong(workingRandom, allowsUnassignedValues ? totalSize + 1 : totalSize);
if (allowsUnassignedValues && random == 0) {
// We have already excluded all unassigned elements,
// the only way to get an unassigned destination is to explicitly add it.
return ElementPosition.unassigned();
} else if (random < entityBoundary) {
// Start with the first unpinned value of each entity, or zero if no pinning.
var entity = entityIterator.next();
return ElementPosition.of(entity, listVariableDescriptor.getFirstUnpinnedIndex(entity));
} else { // Value selector already returns only unpinned values.
if (valueIterator == null) {
valueIterator = valueSelector.iterator();
}
var value = valueIterator.hasNext() ? valueIterator.next() : null;
if (value == null) {
// No more values are available; happens with pinning and/or unassigned.
// This is effectively an off-by-N error where the filtering selectors report incorrect sizes
// on account of not knowing how many values are going to be filtered out.
// As a fallback, start picking random unpinned destinations until the iteration stops externally.
// This skews the selection probability towards entities with fewer unpinned values,
// but at this point, there is no other thing we could possibly do.
var entity = entityIterator.next();
var unpinnedSize = listVariableDescriptor.getUnpinnedSubListSize(entity);
if (unpinnedSize == 0) { // Only the last destination remains.
return ElementPosition.of(entity, listVariableDescriptor.getListSize(entity));
} else { // +1 to include the destination after the final element in the list.
var randomIndex = workingRandom.nextInt(unpinnedSize + 1);
return ElementPosition.of(entity, listVariableDescriptor.getFirstUnpinnedIndex(entity) + randomIndex);
}
} else {
var elementPosition = listVariableStateSupply.getElementPosition(value);
if (elementPosition instanceof PositionInList positionInList) {
// +1 to include the destination after the final element in the list.
return ElementPosition.of(positionInList.entity(), positionInList.index() + 1);
}
// Some selectors, like FilteringValueRangeSelector can still return unassigned values when bailing out
return ElementPosition.unassigned();
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/NextPreviousInList.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
/**
* Points to a list variable next and previous elements position specified by an entity.
*/
public class NextPreviousInList {
private Object tuple;
private NextPreviousInList next;
private NextPreviousInList previous;
public NextPreviousInList(Object tuple, NextPreviousInList previous, NextPreviousInList next) {
this.tuple = tuple;
this.next = next;
this.previous = previous;
}
public NextPreviousInList(Object tuple, NextPreviousInList next) {
this.tuple = tuple;
this.next = next;
}
public Object getTuple() {
return tuple;
}
public void setTuple(Object tuple) {
this.tuple = tuple;
}
public NextPreviousInList getNext() {
return next;
}
public void setNext(NextPreviousInList next) {
this.next = next;
}
public NextPreviousInList getPrevious() {
return previous;
}
public void setPrevious(NextPreviousInList previous) {
this.previous = previous;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/RandomSubListSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex;
import java.util.Iterator;
import java.util.Objects;
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.AbstractSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class RandomSubListSelector<Solution_> extends AbstractSelector<Solution_> implements SubListSelector<Solution_> {
private final EntitySelector<Solution_> entitySelector;
private final IterableValueSelector<Solution_> valueSelector;
private final ListVariableDescriptor<Solution_> listVariableDescriptor;
private final int minimumSubListSize;
private final int maximumSubListSize;
private TriangleElementFactory triangleElementFactory;
private ListVariableStateSupply<Solution_> listVariableStateSupply;
public RandomSubListSelector(
EntitySelector<Solution_> entitySelector,
IterableValueSelector<Solution_> valueSelector,
int minimumSubListSize, int maximumSubListSize) {
this.entitySelector = entitySelector;
this.valueSelector = filterPinnedListPlanningVariableValuesWithIndex(valueSelector, this::getListVariableStateSupply);
this.listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor();
if (minimumSubListSize < 1) {
// TODO raise this to 2 in Timefold Solver 2.0
throw new IllegalArgumentException(
"The minimumSubListSize (" + minimumSubListSize + ") must be greater than 0.");
}
if (minimumSubListSize > maximumSubListSize) {
throw new IllegalArgumentException("The minimumSubListSize (" + minimumSubListSize
+ ") must be less than or equal to the maximumSubListSize (" + maximumSubListSize + ").");
}
this.minimumSubListSize = minimumSubListSize;
this.maximumSubListSize = maximumSubListSize;
phaseLifecycleSupport.addEventListener(this.entitySelector);
phaseLifecycleSupport.addEventListener(this.valueSelector);
}
private ListVariableStateSupply<Solution_> getListVariableStateSupply() {
return Objects.requireNonNull(listVariableStateSupply,
"Impossible state: The listVariableStateSupply is not initialized yet.");
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
triangleElementFactory = new TriangleElementFactory(minimumSubListSize, maximumSubListSize, workingRandom);
var supplyManager = solverScope.getScoreDirector().getSupplyManager();
listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand());
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
listVariableStateSupply = null;
}
@Override
public ListVariableDescriptor<Solution_> getVariableDescriptor() {
return listVariableDescriptor;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return true;
}
@Override
public long getSize() {
long subListCount = 0;
for (Object entity : ((Iterable<Object>) entitySelector::endingIterator)) {
int listSize = listVariableDescriptor.getUnpinnedSubListSize(entity);
// Add subLists bigger than minimum subList size.
if (listSize >= minimumSubListSize) {
subListCount += TriangularNumbers.nthTriangle(listSize - minimumSubListSize + 1);
// Subtract moves with subLists bigger than maximum subList size.
if (listSize > maximumSubListSize) {
subListCount -= TriangularNumbers.nthTriangle(listSize - maximumSubListSize);
}
}
}
return subListCount;
}
@Override
public Iterator<Object> endingValueIterator() {
// Child value selector is entity independent, so passing null entity is OK.
return valueSelector.endingIterator(null);
}
@Override
public long getValueCount() {
return valueSelector.getSize();
}
@Override
public Iterator<SubList> iterator() {
// TODO make this incremental https://issues.redhat.com/browse/PLANNER-2507
int biggestListSize = 0;
for (Object entity : ((Iterable<Object>) entitySelector::endingIterator)) {
biggestListSize = Math.max(biggestListSize, listVariableDescriptor.getUnpinnedSubListSize(entity));
}
if (biggestListSize < minimumSubListSize) {
return new UpcomingSelectionIterator<>() {
@Override
protected SubList createUpcomingSelection() {
return noUpcomingSelection();
}
};
}
return new RandomSubListIterator(valueSelector.iterator());
}
private final class RandomSubListIterator extends UpcomingSelectionIterator<SubList> {
private final Iterator<Object> valueIterator;
private RandomSubListIterator(Iterator<Object> valueIterator) {
this.valueIterator = valueIterator;
}
@Override
protected SubList createUpcomingSelection() {
Object sourceEntity = null;
int listSize = 0;
var firstUnpinnedIndex = 0;
while (listSize < minimumSubListSize) {
if (!valueIterator.hasNext()) {
throw new IllegalStateException("The valueIterator (" + valueIterator + ") should never end.");
}
// Using valueSelector instead of entitySelector is fairer
// because entities with bigger list variables will be selected more often.
var value = valueIterator.next();
sourceEntity = listVariableStateSupply.getInverseSingleton(value);
if (sourceEntity == null) { // Ignore values which are unassigned.
continue;
}
firstUnpinnedIndex = listVariableDescriptor.getFirstUnpinnedIndex(sourceEntity);
listSize = listVariableDescriptor.getListSize(sourceEntity) - firstUnpinnedIndex;
}
TriangleElementFactory.TriangleElement triangleElement = triangleElementFactory.nextElement(listSize);
int subListLength = listSize - triangleElement.level() + 1;
if (subListLength < 1) {
throw new IllegalStateException("Impossible state: The subListLength (%s) must be greater than 0."
.formatted(subListLength));
}
int sourceIndex = triangleElement.indexOnLevel() - 1 + firstUnpinnedIndex;
return new SubList(sourceEntity, sourceIndex, subListLength);
}
}
public int getMinimumSubListSize() {
return minimumSubListSize;
}
public int getMaximumSubListSize() {
return maximumSubListSize;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + valueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/SubList.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
public record SubList(Object entity, int fromIndex, int length) {
public int getToIndex() {
return fromIndex + length;
}
public SubList rebase(ScoreDirector<?> destinationScoreDirector) {
return new SubList(destinationScoreDirector.lookUpWorkingObject(entity), fromIndex, length);
}
@Override
public String toString() {
return entity + "[" + fromIndex + ".." + getToIndex() + "]";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/SubListSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector;
public interface SubListSelector<Solution_> extends IterableSelector<Solution_, SubList> {
ListVariableDescriptor<Solution_> getVariableDescriptor();
Iterator<Object> endingValueIterator();
long getValueCount();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/SubListSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.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.common.nearby.NearbySelectionConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import ai.timefold.solver.core.impl.AbstractFromConfigFactory;
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.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.MimicRecordingSubListSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.MimicReplayingSubListSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.SubListMimicRecorder;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public final class SubListSelectorFactory<Solution_> extends AbstractFromConfigFactory<Solution_, SubListSelectorConfig> {
private static final int DEFAULT_MINIMUM_SUB_LIST_SIZE = 1; // TODO Bump this to 2 in Timefold Solver 2.0
private static final int DEFAULT_MAXIMUM_SUB_LIST_SIZE = Integer.MAX_VALUE;
private SubListSelectorFactory(SubListSelectorConfig config) {
super(config);
}
public static <Solution_> SubListSelectorFactory<Solution_> create(SubListSelectorConfig subListSelectorConfig) {
return new SubListSelectorFactory<>(subListSelectorConfig);
}
public SubListSelector<Solution_> buildSubListSelector(HeuristicConfigPolicy<Solution_> configPolicy,
EntitySelector<Solution_> entitySelector, SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder) {
if (config.getMimicSelectorRef() != null) {
return buildMimicReplaying(configPolicy);
}
if (inheritedSelectionOrder != SelectionOrder.RANDOM) {
throw new IllegalArgumentException(
"The subListSelector (%s) has an inheritedSelectionOrder(%s) which is not supported. SubListSelector only supports random selection order."
.formatted(config, inheritedSelectionOrder));
}
var valueSelector = buildIterableValueSelector(configPolicy, entitySelector.getEntityDescriptor(),
minimumCacheType, inheritedSelectionOrder);
var minimumSubListSize = Objects.requireNonNullElse(config.getMinimumSubListSize(), DEFAULT_MINIMUM_SUB_LIST_SIZE);
var maximumSubListSize = Objects.requireNonNullElse(config.getMaximumSubListSize(), DEFAULT_MAXIMUM_SUB_LIST_SIZE);
var baseSubListSelector =
new RandomSubListSelector<>(entitySelector, valueSelector, minimumSubListSize, maximumSubListSize);
var subListSelector =
applyNearbySelection(configPolicy, minimumCacheType, inheritedSelectionOrder, baseSubListSelector);
subListSelector = applyMimicRecording(configPolicy, subListSelector);
return subListSelector;
}
SubListSelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy) {
if (config.getId() != null
|| config.getMinimumSubListSize() != null
|| config.getMaximumSubListSize() != null
|| config.getValueSelectorConfig() != null
|| config.getNearbySelectionConfig() != null) {
throw new IllegalArgumentException(
"The subListSelectorConfig (%s) with mimicSelectorRef (%s) has another property that is not null."
.formatted(config, config.getMimicSelectorRef()));
}
SubListMimicRecorder<Solution_> subListMimicRecorder =
configPolicy.getSubListMimicRecorder(config.getMimicSelectorRef());
if (subListMimicRecorder == null) {
throw new IllegalArgumentException(
"The subListSelectorConfig (%s) has a mimicSelectorRef (%s) for which no subListSelector with that id exists (in its solver phase)."
.formatted(config, config.getMimicSelectorRef()));
}
return new MimicReplayingSubListSelector<>(subListMimicRecorder);
}
private SubListSelector<Solution_> applyMimicRecording(HeuristicConfigPolicy<Solution_> configPolicy,
SubListSelector<Solution_> subListSelector) {
var id = config.getId();
if (id != null) {
if (id.isEmpty()) {
throw new IllegalArgumentException(
"The subListSelectorConfig (%s) has an empty id (%s).".formatted(config, id));
}
var mimicRecordingSubListSelector = new MimicRecordingSubListSelector<>(subListSelector);
configPolicy.addSubListMimicRecorder(id, mimicRecordingSubListSelector);
subListSelector = mimicRecordingSubListSelector;
}
return subListSelector;
}
private SubListSelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder,
RandomSubListSelector<Solution_> subListSelector) {
NearbySelectionConfig nearbySelectionConfig = config.getNearbySelectionConfig();
if (nearbySelectionConfig == null) {
return subListSelector;
}
return TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION)
.applyNearbySelection(config, configPolicy, minimumCacheType, resolvedSelectionOrder, subListSelector);
}
private IterableValueSelector<Solution_> buildIterableValueSelector(
HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) {
ValueSelectorConfig valueSelectorConfig = config != null ? config.getValueSelectorConfig() : null;
if (valueSelectorConfig == null) {
valueSelectorConfig = new ValueSelectorConfig();
}
// Mixed models require that the variable name be set
if (configPolicy.getSolutionDescriptor().hasBothBasicAndListVariables()
&& valueSelectorConfig.getVariableName() == null) {
var variableName = entityDescriptor.getGenuineListVariableDescriptor().getVariableName();
valueSelectorConfig.setVariableName(variableName);
}
ValueSelector<Solution_> valueSelector = ValueSelectorFactory
.<Solution_> create(valueSelectorConfig)
.buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder);
return (IterableValueSelector<Solution_>) valueSelector;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/TriangleElementFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
import static ai.timefold.solver.core.impl.heuristic.selector.list.TriangularNumbers.nthTriangle;
import static ai.timefold.solver.core.impl.heuristic.selector.list.TriangularNumbers.triangularRoot;
import java.util.Random;
final class TriangleElementFactory {
private final int minimumSubListSize;
private final int maximumSubListSize;
private final Random workingRandom;
TriangleElementFactory(int minimumSubListSize, int maximumSubListSize, Random workingRandom) {
if (minimumSubListSize > maximumSubListSize) {
throw new IllegalArgumentException("The minimumSubListSize (" + minimumSubListSize
+ ") must be less than or equal to the maximumSubListSize (" + maximumSubListSize + ").");
}
if (minimumSubListSize < 1) {
throw new IllegalArgumentException(
"The minimumSubListSize (" + minimumSubListSize + ") must be greater than 0.");
}
this.minimumSubListSize = minimumSubListSize;
this.maximumSubListSize = maximumSubListSize;
this.workingRandom = workingRandom;
}
/**
* Produce next random element of Triangle(listSize) observing the given minimum and maximum subList size.
*
* @param listSize determines the Triangle to select an element from
* @return next random triangle element
* @throws IllegalArgumentException if {@code listSize} is less than {@code minimumSubListSize}
*/
TriangleElement nextElement(int listSize) throws IllegalArgumentException {
// Reduce the triangle base by the minimum subList size.
int subListCount = nthTriangle(listSize - minimumSubListSize + 1);
// The top triangle represents all subLists of size greater or equal to maximum subList size. Remove them all.
int topTriangleSize = listSize <= maximumSubListSize ? 0 : nthTriangle(listSize - maximumSubListSize);
// Triangle elements are indexed from 1.
int subListIndex = workingRandom.nextInt(subListCount - topTriangleSize) + topTriangleSize + 1;
return TriangleElement.valueOf(subListIndex);
}
record TriangleElement(int index, int level, int indexOnLevel) {
static TriangleElement valueOf(int index) {
int level = (int) Math.ceil(triangularRoot(index));
return new TriangleElement(index, level, index - nthTriangle(level - 1));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/TriangularNumbers.java | package ai.timefold.solver.core.impl.heuristic.selector.list;
public final class TriangularNumbers {
/**
* This is the highest <em>n</em> for which the <em>n</em>th triangular number can be calculated using int arithmetic.
*/
static final int HIGHEST_SAFE_N = 46340;
/**
* Calculate <em>n</em>th <a href="https://en.wikipedia.org/wiki/Triangular_number">triangular number</a>.
* This is used to calculate the number of subLists for a given list variable of size <em>n</em>.
* To be able to use {@code int} arithmetic to calculate the triangular number, <em>n</em> must be less than or equal to
* {@link #HIGHEST_SAFE_N}. If the <em>n</em> is higher, the method throws an exception.
*
* @param n size of the triangle (the length of its side)
* @return <em>n</em>th triangular number
* @throws ArithmeticException if {@code n} is higher than {@link #HIGHEST_SAFE_N}
*/
public static int nthTriangle(int n) throws ArithmeticException {
return Math.multiplyExact(n, n + 1) / 2;
}
static double triangularRoot(int x) {
double d = 8L * x + 1;
return (Math.sqrt(d) - 1) / 2;
}
private TriangularNumbers() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/mimic/MimicRecordingSubListSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.list.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.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector;
public class MimicRecordingSubListSelector<Solution_> extends AbstractSelector<Solution_>
implements SubListMimicRecorder<Solution_>, SubListSelector<Solution_> {
protected final SubListSelector<Solution_> childSubListSelector;
protected final List<MimicReplayingSubListSelector<Solution_>> replayingSubListSelectorList;
public MimicRecordingSubListSelector(SubListSelector<Solution_> childSubListSelector) {
this.childSubListSelector = childSubListSelector;
phaseLifecycleSupport.addEventListener(childSubListSelector);
replayingSubListSelectorList = new ArrayList<>();
}
@Override
public void addMimicReplayingSubListSelector(MimicReplayingSubListSelector<Solution_> replayingSubListSelector) {
replayingSubListSelectorList.add(replayingSubListSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public ListVariableDescriptor<Solution_> getVariableDescriptor() {
return childSubListSelector.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return childSubListSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childSubListSelector.isNeverEnding();
}
@Override
public long getSize() {
return childSubListSelector.getSize();
}
@Override
public Iterator<SubList> iterator() {
return new RecordingSubListIterator(childSubListSelector.iterator());
}
private class RecordingSubListIterator extends SelectionIterator<SubList> {
private final Iterator<SubList> childSubListIterator;
public RecordingSubListIterator(Iterator<SubList> childSubListIterator) {
this.childSubListIterator = childSubListIterator;
}
@Override
public boolean hasNext() {
boolean hasNext = childSubListIterator.hasNext();
for (MimicReplayingSubListSelector<Solution_> replayingValueSelector : replayingSubListSelectorList) {
replayingValueSelector.recordedHasNext(hasNext);
}
return hasNext;
}
@Override
public SubList next() {
SubList next = childSubListIterator.next();
for (MimicReplayingSubListSelector<Solution_> replayingValueSelector : replayingSubListSelectorList) {
replayingValueSelector.recordedNext(next);
}
return next;
}
}
@Override
public Iterator<Object> endingValueIterator() {
// No recording, because the endingIterator() is used for determining size
return childSubListSelector.endingValueIterator();
}
@Override
public long getValueCount() {
return childSubListSelector.getValueCount();
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MimicRecordingSubListSelector<?> that = (MimicRecordingSubListSelector<?>) 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(childSubListSelector, that.childSubListSelector)
&& Objects.equals(replayingSubListSelectorList.size(), that.replayingSubListSelectorList.size());
}
@Override
public int hashCode() {
return Objects.hash(childSubListSelector, replayingSubListSelectorList.size());
}
@Override
public String toString() {
return "Recording(" + childSubListSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/mimic/MimicReplayingSubListSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.list.mimic;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
public class MimicReplayingSubListSelector<Solution_> extends AbstractSelector<Solution_>
implements SubListSelector<Solution_> {
protected final SubListMimicRecorder<Solution_> subListMimicRecorder;
protected boolean hasRecordingCreated;
protected boolean hasRecording;
protected boolean recordingCreated;
protected SubList recording;
protected boolean recordingAlreadyReturned;
public MimicReplayingSubListSelector(SubListMimicRecorder<Solution_> subListMimicRecorder) {
this.subListMimicRecorder = subListMimicRecorder;
// No PhaseLifecycleSupport because the MimicRecordingSubListSelector is hooked up elsewhere too
subListMimicRecorder.addMimicReplayingSubListSelector(this);
}
// ************************************************************************
// 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 ListVariableDescriptor<Solution_> getVariableDescriptor() {
return subListMimicRecorder.getVariableDescriptor();
}
@Override
public boolean isCountable() {
return subListMimicRecorder.isCountable();
}
@Override
public boolean isNeverEnding() {
return subListMimicRecorder.isNeverEnding();
}
@Override
public long getSize() {
return subListMimicRecorder.getSize();
}
@Override
public Iterator<Object> endingValueIterator() {
// No replaying, because the endingIterator() is used for determining size
return subListMimicRecorder.endingValueIterator();
}
@Override
public long getValueCount() {
return subListMimicRecorder.getValueCount();
}
@Override
public Iterator<SubList> iterator() {
return new ReplayingSubListIterator();
}
public void recordedHasNext(boolean hasNext) {
hasRecordingCreated = true;
hasRecording = hasNext;
recordingCreated = false;
recording = null;
recordingAlreadyReturned = false;
}
public void recordedNext(SubList next) {
hasRecordingCreated = true;
hasRecording = true;
recordingCreated = true;
recording = next;
recordingAlreadyReturned = false;
}
private class ReplayingSubListIterator extends SelectionIterator<SubList> {
private ReplayingSubListIterator() {
// Reset so the last recording plays again even if it has already played
recordingAlreadyReturned = false;
}
@Override
public boolean hasNext() {
if (!hasRecordingCreated) {
throw new IllegalStateException("Replay must occur after record."
+ " The recordingSubListSelector (" + subListMimicRecorder
+ ")'s hasNext() has not been called yet. ");
}
return hasRecording && !recordingAlreadyReturned;
}
@Override
public SubList next() {
if (!recordingCreated) {
throw new IllegalStateException("Replay must occur after record."
+ " The recordingSubListSelector (" + subListMimicRecorder
+ ")'s next() has not been called yet. ");
}
if (recordingAlreadyReturned) {
throw new NoSuchElementException("The recordingAlreadyReturned (" + recordingAlreadyReturned
+ ") is impossible. Check if hasNext() returns true before this call.");
}
// Until the recorder records something, this iterator has no next.
recordingAlreadyReturned = true;
return recording;
}
@Override
public String toString() {
if (hasRecordingCreated && !hasRecording) {
return "No next replay";
}
return "Next replay (" + (recordingCreated ? recording : "?") + ")";
}
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
MimicReplayingSubListSelector<?> that = (MimicReplayingSubListSelector<?>) other;
return Objects.equals(subListMimicRecorder, that.subListMimicRecorder);
}
@Override
public int hashCode() {
return Objects.hash(subListMimicRecorder);
}
@Override
public String toString() {
return "Replaying(" + subListMimicRecorder + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/list/mimic/SubListMimicRecorder.java | package ai.timefold.solver.core.impl.heuristic.selector.list.mimic;
import java.util.Iterator;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
public interface SubListMimicRecorder<Solution_> {
void addMimicReplayingSubListSelector(MimicReplayingSubListSelector<Solution_> replayingSubListSelector);
ListVariableDescriptor<Solution_> getVariableDescriptor();
boolean isCountable();
boolean isNeverEnding();
long getSize();
Iterator<Object> endingValueIterator();
long getValueCount();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/AbstractMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move;
import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector;
/**
* Abstract superclass for {@link MoveSelector}.
*
* @see MoveSelector
*/
public abstract class AbstractMoveSelector<Solution_> extends AbstractSelector<Solution_>
implements MoveSelector<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/AbstractMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move;
import java.util.Comparator;
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.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.move.Move;
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.move.decorator.CachingMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.FilteringMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.ProbabilityMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.SelectedCountLimitMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.ShufflingMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.SortingMoveSelector;
public abstract class AbstractMoveSelectorFactory<Solution_, MoveSelectorConfig_ extends MoveSelectorConfig<MoveSelectorConfig_>>
extends AbstractSelectorFactory<Solution_, MoveSelectorConfig_> implements MoveSelectorFactory<Solution_> {
public AbstractMoveSelectorFactory(MoveSelectorConfig_ moveSelectorConfig) {
super(moveSelectorConfig);
}
/**
* Builds a base {@link MoveSelector} without any advanced capabilities (filtering, sorting, ...).
*
* @param configPolicy 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 randomSelection true is equivalent to {@link SelectionOrder#RANDOM},
* false is equivalent to {@link SelectionOrder#ORIGINAL}
* @return never null
*/
protected abstract MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection);
/**
* {@inheritDoc}
*/
@Override
public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, boolean skipNonDoableMoves) {
MoveSelectorConfig<?> unfoldedMoveSelectorConfig = buildUnfoldedMoveSelectorConfig(configPolicy);
if (unfoldedMoveSelectorConfig != null) {
return MoveSelectorFactory.<Solution_> create(unfoldedMoveSelectorConfig)
.buildMoveSelector(configPolicy, minimumCacheType, inheritedSelectionOrder, skipNonDoableMoves);
}
SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(config.getCacheType(), minimumCacheType);
SelectionOrder resolvedSelectionOrder =
SelectionOrder.resolve(config.getSelectionOrder(), inheritedSelectionOrder);
validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder);
validateSorting(resolvedSelectionOrder);
validateProbability(resolvedSelectionOrder);
validateSelectedLimit(minimumCacheType);
boolean randomMoveSelection = determineBaseRandomSelection(resolvedCacheType, resolvedSelectionOrder);
SelectionCacheType selectionCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType);
MoveSelector<Solution_> moveSelector = buildBaseMoveSelector(configPolicy, selectionCacheType, randomMoveSelection);
validateResolvedCacheType(resolvedCacheType, moveSelector);
moveSelector = applyFiltering(moveSelector, skipNonDoableMoves);
moveSelector = applySorting(resolvedCacheType, resolvedSelectionOrder, moveSelector);
moveSelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, moveSelector);
moveSelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, moveSelector);
moveSelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, moveSelector);
moveSelector = applySelectedLimit(moveSelector);
return moveSelector;
}
/**
* To provide unfolded MoveSelectorConfig, override this method in a subclass.
*
* @param configPolicy never null
* @return null if no unfolding is needed
*/
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(
HeuristicConfigPolicy<Solution_> configPolicy) {
return null;
}
protected static <T> T checkUnfolded(String configPropertyName, T configProperty) {
if (configProperty == null) {
throw new IllegalStateException("The %s (%s) should haven been initialized during unfolding."
.formatted(configPropertyName, configProperty));
}
return configProperty;
}
private void validateResolvedCacheType(SelectionCacheType resolvedCacheType, MoveSelector<Solution_> moveSelector) {
if (!moveSelector.supportsPhaseAndSolverCaching() && resolvedCacheType.compareTo(SelectionCacheType.PHASE) >= 0) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") has a resolvedCacheType (" + resolvedCacheType + ") that is not supported.\n"
+ "Maybe don't use a <cacheType> on this type of moveSelector.");
}
}
protected boolean determineBaseRandomSelection(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder) {
return switch (resolvedSelectionOrder) {
case ORIGINAL, SORTED, SHUFFLED, PROBABILISTIC ->
// baseValueSelector and lower should be ORIGINAL if they are going to get cached completely
false;
case RANDOM ->
// Predict if caching will occur
resolvedCacheType.isNotCached() || isBaseInherentlyCached() && config.getFilterClass() == null;
default -> throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder
+ ") is not implemented.");
};
}
protected boolean isBaseInherentlyCached() {
return false;
}
private MoveSelector<Solution_> applyFiltering(MoveSelector<Solution_> moveSelector, boolean skipNonDoableMoves) {
/*
* Do not filter out pointless moves in Construction Heuristics and Exhaustive Search,
* because the original value of the entity is irrelevant.
* If the original value is null and the variable allows unassigned values,
* the change move to null must be done too.
*/
SelectionFilter<Solution_, Move<Solution_>> baseFilter = skipNonDoableMoves
? DoableMoveSelectionFilter.INSTANCE
: null;
var filterClass = config.getFilterClass();
if (filterClass != null) {
SelectionFilter<Solution_, Move<Solution_>> selectionFilter =
ConfigUtils.newInstance(config, "filterClass", filterClass);
SelectionFilter<Solution_, Move<Solution_>> finalFilter =
baseFilter == null ? selectionFilter : SelectionFilter.compose(baseFilter, selectionFilter);
return FilteringMoveSelector.of(moveSelector, finalFilter);
} else if (baseFilter != null) {
return FilteringMoveSelector.of(moveSelector, baseFilter);
} else {
return moveSelector;
}
}
protected void validateSorting(SelectionOrder resolvedSelectionOrder) {
if ((config.getSorterComparatorClass() != null || config.getSorterWeightFactoryClass() != null
|| config.getSorterOrder() != null || config.getSorterClass() != null)
&& resolvedSelectionOrder != SelectionOrder.SORTED) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") with 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.getSorterComparatorClass() != null && config.getSorterWeightFactoryClass() != null) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") has both a sorterComparatorClass (" + config.getSorterComparatorClass()
+ ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ").");
}
if (config.getSorterComparatorClass() != null && config.getSorterClass() != null) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") has both a sorterComparatorClass (" + config.getSorterComparatorClass()
+ ") and a sorterClass (" + config.getSorterClass() + ").");
}
if (config.getSorterWeightFactoryClass() != null && config.getSorterClass() != null) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") has both a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass()
+ ") and a sorterClass (" + config.getSorterClass() + ").");
}
if (config.getSorterClass() != null && config.getSorterOrder() != null) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") with sorterClass (" + config.getSorterClass()
+ ") has a non-null sorterOrder (" + config.getSorterOrder() + ").");
}
}
protected MoveSelector<Solution_> applySorting(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) {
if (resolvedSelectionOrder == SelectionOrder.SORTED) {
SelectionSorter<Solution_, Move<Solution_>> sorter;
var sorterComparatorClass = config.getSorterComparatorClass();
var sorterWeightFactoryClass = config.getSorterWeightFactoryClass();
var sorterClass = config.getSorterClass();
if (sorterComparatorClass != null) {
Comparator<Move<Solution_>> sorterComparator =
ConfigUtils.newInstance(config, "sorterComparatorClass", sorterComparatorClass);
sorter = new ComparatorSelectionSorter<>(sorterComparator,
SelectionSorterOrder.resolve(config.getSorterOrder()));
} else if (sorterWeightFactoryClass != null) {
SelectionSorterWeightFactory<Solution_, Move<Solution_>> sorterWeightFactory =
ConfigUtils.newInstance(config, "sorterWeightFactoryClass", sorterWeightFactoryClass);
sorter = new WeightFactorySelectionSorter<>(sorterWeightFactory,
SelectionSorterOrder.resolve(config.getSorterOrder()));
} else if (sorterClass != null) {
sorter = ConfigUtils.newInstance(config, "sorterClass", sorterClass);
} else {
throw new IllegalArgumentException(
"The moveSelectorConfig (%s) with resolvedSelectionOrder (%s) needs a sorterComparatorClass (%s) or a sorterWeightFactoryClass (%s) or a sorterClass (%s)."
.formatted(config, resolvedSelectionOrder, sorterComparatorClass, sorterWeightFactoryClass,
sorterClass));
}
moveSelector = new SortingMoveSelector<>(moveSelector, resolvedCacheType, sorter);
}
return moveSelector;
}
private void validateProbability(SelectionOrder resolvedSelectionOrder) {
var probabilityWeightFactoryClass = config.getProbabilityWeightFactoryClass();
if (probabilityWeightFactoryClass != null && resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) {
throw new IllegalArgumentException(
"The moveSelectorConfig (%s) with probabilityWeightFactoryClass (%s) has a resolvedSelectionOrder (%s) that is not %s."
.formatted(config, probabilityWeightFactoryClass, resolvedSelectionOrder,
SelectionOrder.PROBABILISTIC));
}
}
private MoveSelector<Solution_> applyProbability(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) {
if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) {
var probabilityWeightFactoryClass = config.getProbabilityWeightFactoryClass();
if (probabilityWeightFactoryClass == null) {
throw new IllegalArgumentException(
"The moveSelectorConfig (%s) with resolvedSelectionOrder (%s) needs a probabilityWeightFactoryClass (%s)."
.formatted(config, resolvedSelectionOrder, probabilityWeightFactoryClass));
}
SelectionProbabilityWeightFactory<Solution_, Move<Solution_>> probabilityWeightFactory =
ConfigUtils.newInstance(config, "probabilityWeightFactoryClass", probabilityWeightFactoryClass);
moveSelector = new ProbabilityMoveSelector<>(moveSelector, resolvedCacheType, probabilityWeightFactory);
}
return moveSelector;
}
private MoveSelector<Solution_> applyShuffling(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) {
if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) {
moveSelector = new ShufflingMoveSelector<>(moveSelector, resolvedCacheType);
}
return moveSelector;
}
private MoveSelector<Solution_> applyCaching(SelectionCacheType resolvedCacheType,
SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) {
if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(moveSelector.getCacheType()) > 0) {
moveSelector =
new CachingMoveSelector<>(moveSelector, resolvedCacheType,
resolvedSelectionOrder.toRandomSelectionBoolean());
}
return moveSelector;
}
private void validateSelectedLimit(SelectionCacheType minimumCacheType) {
if (config.getSelectedCountLimit() != null
&& minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) {
throw new IllegalArgumentException("The moveSelectorConfig (" + config
+ ") with selectedCountLimit (" + config.getSelectedCountLimit()
+ ") has a minimumCacheType (" + minimumCacheType
+ ") that is higher than " + SelectionCacheType.JUST_IN_TIME + ".");
}
}
private MoveSelector<Solution_> applySelectedLimit(MoveSelector<Solution_> moveSelector) {
if (config.getSelectedCountLimit() != null) {
moveSelector = new SelectedCountLimitMoveSelector<>(moveSelector, config.getSelectedCountLimit());
}
return moveSelector;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/DoableMoveSelectionFilter.java | package ai.timefold.solver.core.impl.heuristic.selector.move;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
final class DoableMoveSelectionFilter<Solution_> implements SelectionFilter<Solution_, Move<Solution_>> {
static final SelectionFilter INSTANCE = new DoableMoveSelectionFilter<>();
@Override
public boolean accept(ScoreDirector<Solution_> scoreDirector, Move<Solution_> move) {
return move.isMoveDoable(scoreDirector);
}
private DoableMoveSelectionFilter() {
}
@Override
public String toString() {
return "Doable moves only";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/MoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector;
/**
* Generates {@link Move}s.
*
* @see AbstractMoveSelector
*/
public interface MoveSelector<Solution_> extends IterableSelector<Solution_, Move<Solution_>> {
default boolean supportsPhaseAndSolverCaching() {
return false;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/MoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move;
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.CartesianProductMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveListFactoryConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.RuinRecreateMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.KOptMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig;
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.ListRuinRecreateMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.composite.CartesianProductMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.composite.UnionMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.factory.MoveIteratorFactoryFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.factory.MoveListFactoryFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.ChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.PillarChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.PillarSwapMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.SwapMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.KOptMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListSwapMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.SubListChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.SubListSwapMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin.ListRuinRecreateMoveSelectorFactory;
public interface MoveSelectorFactory<Solution_> {
static <Solution_> AbstractMoveSelectorFactory<Solution_, ?> create(MoveSelectorConfig<?> moveSelectorConfig) {
if (moveSelectorConfig instanceof ChangeMoveSelectorConfig changeMoveSelectorConfig) {
return new ChangeMoveSelectorFactory<>(changeMoveSelectorConfig);
} else if (moveSelectorConfig instanceof ListChangeMoveSelectorConfig listChangeMoveSelectorConfig) {
return new ListChangeMoveSelectorFactory<>(listChangeMoveSelectorConfig);
} else if (moveSelectorConfig instanceof SwapMoveSelectorConfig swapMoveSelectorConfig) {
return new SwapMoveSelectorFactory<>(swapMoveSelectorConfig);
} else if (moveSelectorConfig instanceof ListSwapMoveSelectorConfig listSwapMoveSelectorConfig) {
return new ListSwapMoveSelectorFactory<>(listSwapMoveSelectorConfig);
} else if (moveSelectorConfig instanceof PillarChangeMoveSelectorConfig pillarChangeMoveSelectorConfig) {
return new PillarChangeMoveSelectorFactory<>(pillarChangeMoveSelectorConfig);
} else if (moveSelectorConfig instanceof PillarSwapMoveSelectorConfig pillarSwapMoveSelectorConfig) {
return new PillarSwapMoveSelectorFactory<>(pillarSwapMoveSelectorConfig);
} else if (moveSelectorConfig instanceof SubChainChangeMoveSelectorConfig subChainChangeMoveSelectorConfig) {
return new SubChainChangeMoveSelectorFactory<>(subChainChangeMoveSelectorConfig);
} else if (moveSelectorConfig instanceof SubListChangeMoveSelectorConfig subListChangeMoveSelectorConfig) {
return new SubListChangeMoveSelectorFactory<>(subListChangeMoveSelectorConfig);
} else if (moveSelectorConfig instanceof SubChainSwapMoveSelectorConfig subChainSwapMoveSelectorConfig) {
return new SubChainSwapMoveSelectorFactory<>(subChainSwapMoveSelectorConfig);
} else if (moveSelectorConfig instanceof SubListSwapMoveSelectorConfig subListSwapMoveSelectorConfig) {
return new SubListSwapMoveSelectorFactory<>(subListSwapMoveSelectorConfig);
} else if (moveSelectorConfig instanceof TailChainSwapMoveSelectorConfig tailChainSwapMoveSelectorConfig) {
return new TailChainSwapMoveSelectorFactory<>(tailChainSwapMoveSelectorConfig);
} else if (KOptMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) {
return new KOptMoveSelectorFactory<>((KOptMoveSelectorConfig) moveSelectorConfig);
} else if (KOptListMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) {
return new KOptListMoveSelectorFactory<>((KOptListMoveSelectorConfig) moveSelectorConfig);
} else if (moveSelectorConfig instanceof RuinRecreateMoveSelectorConfig ruinRecreateMoveSelectorConfig) {
return new RuinRecreateMoveSelectorFactory<>(ruinRecreateMoveSelectorConfig);
} else if (moveSelectorConfig instanceof ListRuinRecreateMoveSelectorConfig listRuinRecreateMoveSelectorConfig) {
return new ListRuinRecreateMoveSelectorFactory<>(listRuinRecreateMoveSelectorConfig);
} else if (moveSelectorConfig instanceof MoveIteratorFactoryConfig moveIteratorFactoryConfig) {
return new MoveIteratorFactoryFactory<>(moveIteratorFactoryConfig);
} else if (moveSelectorConfig instanceof MoveListFactoryConfig moveListFactoryConfig) {
return new MoveListFactoryFactory<>(moveListFactoryConfig);
} else if (moveSelectorConfig instanceof UnionMoveSelectorConfig unionMoveSelectorConfig) {
return new UnionMoveSelectorFactory<>(unionMoveSelectorConfig);
} else if (moveSelectorConfig instanceof CartesianProductMoveSelectorConfig cartesianProductMoveSelectorConfig) {
return new CartesianProductMoveSelectorFactory<>(cartesianProductMoveSelectorConfig);
} else {
throw new IllegalArgumentException(String.format("Unknown %s type: (%s).",
MoveSelectorConfig.class.getSimpleName(), moveSelectorConfig.getClass().getName()));
}
}
/**
* Builds {@link MoveSelector} from the {@link MoveSelectorConfig} and provided parameters.
*
* @param configPolicy 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
* @param skipNonDoableMoves
* @return never null
*/
MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, boolean skipNonDoableMoves);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/AbstractCompositeMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.List;
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.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;
abstract class AbstractCompositeMoveSelectorFactory<Solution_, MoveSelectorConfig_ extends MoveSelectorConfig<MoveSelectorConfig_>>
extends AbstractMoveSelectorFactory<Solution_, MoveSelectorConfig_> {
protected AbstractCompositeMoveSelectorFactory(MoveSelectorConfig_ moveSelectorConfig) {
super(moveSelectorConfig);
}
protected List<MoveSelector<Solution_>> buildInnerMoveSelectors(List<MoveSelectorConfig> innerMoveSelectorList,
HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) {
return innerMoveSelectorList.stream()
.map(moveSelectorConfig -> {
AbstractMoveSelectorFactory<Solution_, ?> moveSelectorFactory =
MoveSelectorFactory.create(moveSelectorConfig);
var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
return moveSelectorFactory.buildMoveSelector(configPolicy, minimumCacheType, selectionOrder, false);
}).toList();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/BiasedRandomUnionMoveIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
import java.util.function.ToDoubleFunction;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
final class BiasedRandomUnionMoveIterator<Solution_> extends SelectionIterator<Move<Solution_>> {
private final Map<Iterator<Move<Solution_>>, ProbabilityItem<Solution_>> probabilityItemMap;
private final NavigableMap<Double, Iterator<Move<Solution_>>> moveIteratorMap;
private final Random workingRandom;
private double probabilityWeightTotal;
private boolean stale;
public BiasedRandomUnionMoveIterator(List<MoveSelector<Solution_>> childMoveSelectorList,
ToDoubleFunction<MoveSelector<Solution_>> probabilityWeightFunction,
Random workingRandom) {
this.probabilityItemMap = new LinkedHashMap<>(childMoveSelectorList.size());
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
Iterator<Move<Solution_>> moveIterator = moveSelector.iterator();
ProbabilityItem<Solution_> probabilityItem = new ProbabilityItem<>();
probabilityItem.moveSelector = moveSelector;
probabilityItem.moveIterator = moveIterator;
probabilityItem.probabilityWeight = probabilityWeightFunction.applyAsDouble(moveSelector);
probabilityItemMap.put(moveIterator, probabilityItem);
}
this.moveIteratorMap = new TreeMap<>();
this.stale = true;
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
if (stale) {
refreshMoveIteratorMap();
}
return !moveIteratorMap.isEmpty();
}
@Override
public Move<Solution_> next() {
if (stale) {
refreshMoveIteratorMap();
}
double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
Map.Entry<Double, Iterator<Move<Solution_>>> entry = moveIteratorMap.floorEntry(randomOffset);
// The entry is never null because randomOffset < probabilityWeightTotal
Iterator<Move<Solution_>> moveIterator = entry.getValue();
Move<Solution_> next = moveIterator.next();
if (!moveIterator.hasNext()) {
stale = true;
}
return next;
}
private void refreshMoveIteratorMap() {
moveIteratorMap.clear();
double probabilityWeightOffset = 0.0;
for (ProbabilityItem<Solution_> probabilityItem : probabilityItemMap.values()) {
if (probabilityItem.probabilityWeight != 0.0
&& probabilityItem.moveIterator.hasNext()) {
moveIteratorMap.put(probabilityWeightOffset, probabilityItem.moveIterator);
probabilityWeightOffset += probabilityItem.probabilityWeight;
}
}
probabilityWeightTotal = probabilityWeightOffset;
}
private static final class ProbabilityItem<Solution_> {
MoveSelector<Solution_> moveSelector;
Iterator<Move<Solution_>> moveIterator;
double probabilityWeight;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/CartesianProductMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
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.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
/**
* A {@link CompositeMoveSelector} that Cartesian products 2 or more {@link MoveSelector}s.
* <p>
* For example: a Cartesian product of {A, B, C} and {X, Y} will result in {AX, AY, BX, BY, CX, CY}.
* <p>
* Warning: there is no duplicated {@link Move} check, so union of {A, B} and {B} will result in {AB, BB}.
*
* @see CompositeMoveSelector
*/
public class CartesianProductMoveSelector<Solution_> extends CompositeMoveSelector<Solution_> {
private static final Move<?> EMPTY_MARK = NoChangeMove.getInstance();
private final boolean ignoreEmptyChildIterators;
public CartesianProductMoveSelector(List<MoveSelector<Solution_>> childMoveSelectorList,
boolean ignoreEmptyChildIterators, boolean randomSelection) {
super(childMoveSelectorList, randomSelection);
this.ignoreEmptyChildIterators = ignoreEmptyChildIterators;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
if (randomSelection) {
return true;
} else {
// Only the last childMoveSelector can be neverEnding
return !childMoveSelectorList.isEmpty()
&& childMoveSelectorList.get(childMoveSelectorList.size() - 1).isNeverEnding();
}
}
@Override
public long getSize() {
long size = 0L;
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
long childSize = moveSelector.getSize();
if (childSize == 0L) {
if (!ignoreEmptyChildIterators) {
return 0L;
}
// else ignore that child
} else {
if (size == 0L) {
// There must be at least 1 non-empty child to change the size from 0
size = childSize;
} else {
size *= childSize;
}
}
}
return size;
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return new OriginalCartesianProductMoveIterator();
} else {
return new RandomCartesianProductMoveIterator();
}
}
public class OriginalCartesianProductMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private List<Iterator<Move<Solution_>>> moveIteratorList;
private Move<Solution_>[] subSelections;
public OriginalCartesianProductMoveIterator() {
moveIteratorList = new ArrayList<>(childMoveSelectorList.size());
for (int i = 0; i < childMoveSelectorList.size(); i++) {
moveIteratorList.add(null);
}
subSelections = null;
}
@Override
protected Move<Solution_> createUpcomingSelection() {
int childSize = moveIteratorList.size();
int startingIndex;
Move<Solution_>[] moveList = new Move[childSize];
if (subSelections == null) {
startingIndex = -1;
} else {
startingIndex = childSize - 1;
while (startingIndex >= 0) {
Iterator<Move<Solution_>> moveIterator = moveIteratorList.get(startingIndex);
if (moveIterator.hasNext()) {
break;
}
startingIndex--;
}
if (startingIndex < 0) {
return noUpcomingSelection();
}
// Clone to avoid CompositeMove corruption
System.arraycopy(subSelections, 0, moveList, 0, startingIndex);
moveList[startingIndex] = moveIteratorList.get(startingIndex).next(); // Increment the 4 in 004999
}
for (int i = startingIndex + 1; i < childSize; i++) { // Increment the 9s in 004999
Iterator<Move<Solution_>> moveIterator = childMoveSelectorList.get(i).iterator();
moveIteratorList.set(i, moveIterator);
Move<Solution_> next;
if (!moveIterator.hasNext()) { // in case a moveIterator is empty
if (ignoreEmptyChildIterators) {
next = (Move<Solution_>) EMPTY_MARK;
} else {
return noUpcomingSelection();
}
} else {
next = moveIterator.next();
}
moveList[i] = next;
}
// No need to clone to avoid CompositeMove corruption because subSelections's elements never change
subSelections = moveList;
if (ignoreEmptyChildIterators) {
// Clone because EMPTY_MARK should survive in subSelections
Move<Solution_>[] newMoveList = new Move[childSize];
int newSize = 0;
for (int i = 0; i < childSize; i++) {
if (moveList[i] != EMPTY_MARK) {
newMoveList[newSize] = moveList[i];
newSize++;
}
}
if (newSize == 0) {
return noUpcomingSelection();
} else if (newSize == 1) {
return newMoveList[0];
}
moveList = Arrays.copyOfRange(newMoveList, 0, newSize);
}
return CompositeMove.buildMove(moveList);
}
}
public class RandomCartesianProductMoveIterator extends SelectionIterator<Move<Solution_>> {
private List<Iterator<Move<Solution_>>> moveIteratorList;
private Boolean empty;
public RandomCartesianProductMoveIterator() {
moveIteratorList = new ArrayList<>(childMoveSelectorList.size());
empty = null;
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
moveIteratorList.add(moveSelector.iterator());
}
}
@Override
public boolean hasNext() {
if (empty == null) { // Only done in the first call
int emptyCount = 0;
for (Iterator<Move<Solution_>> moveIterator : moveIteratorList) {
if (!moveIterator.hasNext()) {
emptyCount++;
if (!ignoreEmptyChildIterators) {
break;
}
}
}
empty = ignoreEmptyChildIterators ? emptyCount == moveIteratorList.size() : emptyCount > 0;
}
return !empty;
}
@Override
public Move<Solution_> next() {
List<Move<Solution_>> moveList = new ArrayList<>(moveIteratorList.size());
for (int i = 0; i < moveIteratorList.size(); i++) {
Iterator<Move<Solution_>> moveIterator = moveIteratorList.get(i);
boolean skip = false;
if (!moveIterator.hasNext()) {
MoveSelector<Solution_> moveSelector = childMoveSelectorList.get(i);
moveIterator = moveSelector.iterator();
moveIteratorList.set(i, moveIterator);
if (!moveIterator.hasNext()) {
if (ignoreEmptyChildIterators) {
skip = true;
} else {
throw new NoSuchElementException("The iterator of childMoveSelector (" + moveSelector
+ ") is empty.");
}
}
}
if (!skip) {
moveList.add(moveIterator.next());
}
}
if (ignoreEmptyChildIterators) {
if (moveList.isEmpty()) {
throw new NoSuchElementException("All iterators of childMoveSelectorList (" + childMoveSelectorList
+ ") are empty.");
} else if (moveList.size() == 1) {
return moveList.get(0);
}
}
return CompositeMove.buildMove(moveList.toArray(new Move[0]));
}
}
@Override
public String toString() {
return "CartesianProduct(" + childMoveSelectorList + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/CartesianProductMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class CartesianProductMoveSelectorFactory<Solution_>
extends AbstractCompositeMoveSelectorFactory<Solution_, CartesianProductMoveSelectorConfig> {
public CartesianProductMoveSelectorFactory(CartesianProductMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
if (configPolicy.getNearbyDistanceMeterClass() != null) {
throw new IllegalArgumentException(
"""
The cartesianProductMoveSelector (%s) is not compatible with using the top-level property nearbyDistanceMeterClass (%s).
Enabling nearbyDistanceMeterClass will duplicate move selector configurations that accept Nearby autoconfiguration.
For example, if there are four selectors (2 non-nearby + 2 nearby), it will be A×B×C×D moves, which may be expensive.
Specify move selectors manually or remove the top-level nearbyDistanceMeterClass from your solver config."""
.formatted(config, configPolicy.getNearbyDistanceMeterClass()));
}
List<MoveSelector<Solution_>> moveSelectorList = buildInnerMoveSelectors(config.getMoveSelectorList(),
configPolicy, minimumCacheType, randomSelection);
boolean ignoreEmptyChildIterators_ = Objects.requireNonNullElse(config.getIgnoreEmptyChildIterators(), true);
return new CartesianProductMoveSelector<>(moveSelectorList, ignoreEmptyChildIterators_, randomSelection);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/CompositeMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.Collection;
import java.util.List;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
/**
* Abstract superclass for every composite {@link MoveSelector}.
*
* @see MoveSelector
*/
public abstract class CompositeMoveSelector<Solution_> extends AbstractMoveSelector<Solution_> {
protected final List<MoveSelector<Solution_>> childMoveSelectorList;
protected final boolean randomSelection;
protected CompositeMoveSelector(List<MoveSelector<Solution_>> childMoveSelectorList, boolean randomSelection) {
this.childMoveSelectorList = childMoveSelectorList;
this.randomSelection = randomSelection;
for (MoveSelector<Solution_> childMoveSelector : childMoveSelectorList) {
phaseLifecycleSupport.addEventListener(childMoveSelector);
}
if (!randomSelection) {
// Only the last childMoveSelector can be neverEnding
if (!childMoveSelectorList.isEmpty()) {
for (MoveSelector<Solution_> childMoveSelector : childMoveSelectorList.subList(0,
childMoveSelectorList.size() - 1)) {
if (childMoveSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ")'s non-last childMoveSelector (" + childMoveSelector
+ ") has neverEnding (" + childMoveSelector.isNeverEnding()
+ ") with randomSelection (" + randomSelection + ")."
+ (childMoveSelector.isCountable() ? ""
: "\nThe selector is not countable, check the "
+ ValueRange.class.getSimpleName() + "s involved.\n"
+ "Verify that a @" + ValueRangeProvider.class.getSimpleName()
+ " does not return " + ValueRange.class.getSimpleName()
+ " when it can return " + CountableValueRange.class.getSimpleName()
+ " or " + Collection.class.getSimpleName() + "."));
}
}
}
}
}
public List<MoveSelector<Solution_>> getChildMoveSelectorList() {
return childMoveSelectorList;
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return true;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
if (!moveSelector.isCountable()) {
return false;
}
}
return true;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + childMoveSelectorList + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/FixedSelectorProbabilityWeightFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.Map;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.selector.Selector;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
final class FixedSelectorProbabilityWeightFactory<Solution_, Selector_ extends Selector>
implements SelectionProbabilityWeightFactory<Solution_, Selector_> {
private final Map<Selector_, Double> fixedProbabilityWeightMap;
public FixedSelectorProbabilityWeightFactory(Map<Selector_, Double> fixedProbabilityWeightMap) {
this.fixedProbabilityWeightMap = fixedProbabilityWeightMap;
}
@Override
public double createProbabilityWeight(ScoreDirector<Solution_> scoreDirector, Selector_ selector) {
return fixedProbabilityWeightMap.getOrDefault(selector, 1.0);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/UniformRandomUnionMoveIterator.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
final class UniformRandomUnionMoveIterator<Solution_> extends SelectionIterator<Move<Solution_>> {
private static <Solution_> List<Iterator<Move<Solution_>>> toMoveIteratorList(
List<MoveSelector<Solution_>> childMoveSelectorList) {
var list = new ArrayList<Iterator<Move<Solution_>>>(childMoveSelectorList.size());
for (var moves : childMoveSelectorList) {
var iterator = moves.iterator();
if (iterator.hasNext()) {
list.add(iterator);
}
}
return list;
}
private final List<Iterator<Move<Solution_>>> moveIteratorList;
private final Random workingRandom;
public UniformRandomUnionMoveIterator(List<MoveSelector<Solution_>> childMoveSelectorList, Random workingRandom) {
this.moveIteratorList = toMoveIteratorList(childMoveSelectorList);
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return !moveIteratorList.isEmpty();
}
@Override
public Move<Solution_> next() {
int index = workingRandom.nextInt(moveIteratorList.size());
Iterator<Move<Solution_>> moveIterator = moveIteratorList.get(index);
Move<Solution_> next = moveIterator.next();
if (!moveIterator.hasNext()) {
moveIteratorList.remove(index);
}
return next;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/UnionMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
/**
* A {@link CompositeMoveSelector} that unions 2 or more {@link MoveSelector}s.
* <p>
* For example: a union of {A, B, C} and {X, Y} will result in {A, B, C, X, Y}.
* <p>
* Warning: there is no duplicated {@link Move} check, so union of {A, B, C} and {B, D} will result in {A, B, C, B, D}.
*
* @see CompositeMoveSelector
*/
public class UnionMoveSelector<Solution_> extends CompositeMoveSelector<Solution_> {
protected final SelectionProbabilityWeightFactory<Solution_, MoveSelector<Solution_>> selectorProbabilityWeightFactory;
protected ScoreDirector<Solution_> scoreDirector;
public UnionMoveSelector(List<MoveSelector<Solution_>> childMoveSelectorList, boolean randomSelection) {
this(childMoveSelectorList, randomSelection, null);
}
public UnionMoveSelector(List<MoveSelector<Solution_>> childMoveSelectorList, boolean randomSelection,
SelectionProbabilityWeightFactory<Solution_, MoveSelector<Solution_>> selectorProbabilityWeightFactory) {
super(childMoveSelectorList, randomSelection);
this.selectorProbabilityWeightFactory = selectorProbabilityWeightFactory;
if (!randomSelection) {
if (selectorProbabilityWeightFactory != null) {
throw new IllegalArgumentException("The selector (" + this
+ ") without randomSelection (" + randomSelection
+ ") cannot have a selectorProbabilityWeightFactory (" + selectorProbabilityWeightFactory
+ ").");
}
}
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
scoreDirector = stepScope.getScoreDirector();
super.stepStarted(stepScope);
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
scoreDirector = null;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
if (randomSelection) {
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
if (moveSelector.isNeverEnding()) {
return true;
}
}
// The UnionMoveSelector is special: it can be randomSelection true and still neverEnding false
return false;
} else {
// Only the last childMoveSelector can be neverEnding
return !childMoveSelectorList.isEmpty()
&& childMoveSelectorList.get(childMoveSelectorList.size() - 1).isNeverEnding();
}
}
@Override
public long getSize() {
long size = 0L;
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
size += moveSelector.getSize();
}
return size;
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
Stream<Move<Solution_>> stream = Stream.empty();
for (MoveSelector<Solution_> moveSelector : childMoveSelectorList) {
stream = Stream.concat(stream, toStream(moveSelector));
}
return stream.iterator();
} else if (selectorProbabilityWeightFactory == null) {
return new UniformRandomUnionMoveIterator<>(childMoveSelectorList, workingRandom);
} else {
return new BiasedRandomUnionMoveIterator<>(childMoveSelectorList,
moveSelector -> {
double weight = selectorProbabilityWeightFactory.createProbabilityWeight(scoreDirector, moveSelector);
if (weight < 0.0) {
throw new IllegalStateException(
"The selectorProbabilityWeightFactory (" + selectorProbabilityWeightFactory
+ ") returned a negative probabilityWeight (" + weight + ").");
}
return weight;
}, workingRandom);
}
}
private static <Solution_> Stream<Move<Solution_>> toStream(MoveSelector<Solution_> moveSelector) {
return StreamSupport.stream(moveSelector.spliterator(), false);
}
@Override
public String toString() {
return "Union(" + childMoveSelectorList + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/UnionMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.composite;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.NearbyAutoConfigurationEnabled;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class UnionMoveSelectorFactory<Solution_>
extends AbstractCompositeMoveSelectorFactory<Solution_, UnionMoveSelectorConfig> {
public UnionMoveSelectorFactory(UnionMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
var moveSelectorConfigList = new LinkedList<>(config.getMoveSelectorList());
if (configPolicy.getNearbyDistanceMeterClass() != null) {
var isMixedModel = configPolicy.getSolutionDescriptor().hasBothBasicAndListVariables();
for (var selectorConfig : config.getMoveSelectorList()) {
if (selectorConfig instanceof NearbyAutoConfigurationEnabled nearbySelectorConfig) {
if (selectorConfig.hasNearbySelectionConfig()) {
throw new IllegalArgumentException(
"""
The selector configuration (%s) already includes the Nearby Selection setting, making it incompatible with the top-level property nearbyDistanceMeterClass (%s).
Remove the Nearby setting from the selector configuration or remove the top-level nearbyDistanceMeterClass."""
.formatted(nearbySelectorConfig, configPolicy.getNearbyDistanceMeterClass()));
}
// We delay the autoconfiguration to the deepest UnionMoveSelectorConfig node in the tree
// to avoid duplicating configuration
// when there are nested unionMoveSelector configurations
var isUnionMoveSelectorConfig = selectorConfig instanceof UnionMoveSelectorConfig;
// When using a mixed model, we do not enable nearby for basic variables,
// as it applies only to list or chained variables.
// Chained variables are forbidden in mixed models.
var isNearbyDisabled = isMixedModel && !nearbySelectorConfig.canEnableNearbyInMixedModels();
if (isUnionMoveSelectorConfig || isNearbyDisabled) {
continue;
}
// Add a new configuration with Nearby Selection enabled
moveSelectorConfigList
.add(nearbySelectorConfig.enableNearbySelection(configPolicy.getNearbyDistanceMeterClass(),
configPolicy.getRandom()));
}
}
}
List<MoveSelector<Solution_>> moveSelectorList =
buildInnerMoveSelectors(moveSelectorConfigList, configPolicy, minimumCacheType, randomSelection);
SelectionProbabilityWeightFactory<Solution_, MoveSelector<Solution_>> selectorProbabilityWeightFactory;
var selectorProbabilityWeightFactoryClass = config.getSelectorProbabilityWeightFactoryClass();
if (selectorProbabilityWeightFactoryClass != null) {
if (!randomSelection) {
throw new IllegalArgumentException(
"The moveSelectorConfig (%s) with selectorProbabilityWeightFactoryClass (%s) has non-random randomSelection (%s)."
.formatted(configPolicy, selectorProbabilityWeightFactoryClass, randomSelection));
}
selectorProbabilityWeightFactory = ConfigUtils.newInstance(config, "selectorProbabilityWeightFactoryClass",
selectorProbabilityWeightFactoryClass);
} else if (randomSelection) {
Map<MoveSelector<Solution_>, Double> fixedProbabilityWeightMap =
new HashMap<>(moveSelectorConfigList.size());
for (int i = 0; i < moveSelectorConfigList.size(); i++) {
MoveSelectorConfig<?> innerMoveSelectorConfig = moveSelectorConfigList.get(i);
MoveSelector<Solution_> moveSelector = moveSelectorList.get(i);
Double fixedProbabilityWeight = innerMoveSelectorConfig.getFixedProbabilityWeight();
if (fixedProbabilityWeight != null) {
fixedProbabilityWeightMap.put(moveSelector, fixedProbabilityWeight);
}
}
if (fixedProbabilityWeightMap.isEmpty()) { // Will end up using UniformRandomUnionMoveIterator.
selectorProbabilityWeightFactory = null;
} else { // Will end up using BiasedRandomUnionMoveIterator.
selectorProbabilityWeightFactory = new FixedSelectorProbabilityWeightFactory<>(fixedProbabilityWeightMap);
}
} else {
selectorProbabilityWeightFactory = null;
}
return new UnionMoveSelector<>(moveSelectorList, randomSelection, selectorProbabilityWeightFactory);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/AbstractCachingMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.decorator;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.move.Move;
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.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public abstract class AbstractCachingMoveSelector<Solution_> extends AbstractMoveSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_> {
protected final MoveSelector<Solution_> childMoveSelector;
protected final SelectionCacheType cacheType;
protected List<Move<Solution_>> cachedMoveList = null;
public AbstractCachingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType) {
this.childMoveSelector = childMoveSelector;
this.cacheType = cacheType;
if (childMoveSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childMoveSelector (" + childMoveSelector
+ ") with neverEnding (" + childMoveSelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childMoveSelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
public MoveSelector<Solution_> getChildMoveSelector() {
return childMoveSelector;
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
long childSize = childMoveSelector.getSize();
if (childSize > Integer.MAX_VALUE) {
throw new IllegalStateException("The selector (" + this
+ ") has a childMoveSelector (" + childMoveSelector
+ ") with childSize (" + childSize
+ ") which is higher than Integer.MAX_VALUE.");
}
cachedMoveList = new ArrayList<>((int) childSize);
childMoveSelector.iterator().forEachRemaining(cachedMoveList::add);
logger.trace(" Created cachedMoveList: size ({}), moveSelector ({}).",
cachedMoveList.size(), this);
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
cachedMoveList = null;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public long getSize() {
return cachedMoveList.size();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/CachingMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.decorator;
import java.util.Iterator;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.move.Move;
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.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.CachingValueSelector;
/**
* A {@link MoveSelector} that caches the result of its child {@link MoveSelector}.
* <p>
* Keep this code in sync with {@link CachingEntitySelector} and {@link CachingValueSelector}.
*/
public class CachingMoveSelector<Solution_> extends AbstractCachingMoveSelector<Solution_> {
protected final boolean randomSelection;
public CachingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType,
boolean randomSelection) {
super(childMoveSelector, cacheType);
this.randomSelection = randomSelection;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return cachedMoveList.iterator();
} else {
return new CachedListRandomIterator<>(cachedMoveList, workingRandom);
}
}
@Override
public String toString() {
return "Caching(" + childMoveSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/FilteringMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.decorator;
import java.util.Iterator;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
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.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
public final class FilteringMoveSelector<Solution_> extends AbstractMoveSelector<Solution_> {
private static final long BAIL_OUT_MULTIPLIER = 10L;
public static <Solution_> FilteringMoveSelector<Solution_> of(MoveSelector<Solution_> moveSelector,
SelectionFilter<Solution_, Move<Solution_>> filter) {
if (moveSelector instanceof FilteringMoveSelector<Solution_> filteringMoveSelector) {
return new FilteringMoveSelector<>(filteringMoveSelector.childMoveSelector,
SelectionFilter.compose(filteringMoveSelector.filter, filter));
}
return new FilteringMoveSelector<>(moveSelector, filter);
}
private final MoveSelector<Solution_> childMoveSelector;
private final SelectionFilter<Solution_, Move<Solution_>> filter;
private final boolean bailOutEnabled;
private AbstractPhaseScope<Solution_> phaseScope;
private ScoreDirector<Solution_> scoreDirector = null;
private FilteringMoveSelector(MoveSelector<Solution_> childMoveSelector,
SelectionFilter<Solution_, Move<Solution_>> filter) {
this.childMoveSelector = childMoveSelector;
this.filter = filter;
bailOutEnabled = childMoveSelector.isNeverEnding();
phaseLifecycleSupport.addEventListener(childMoveSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
this.scoreDirector = phaseScope.getScoreDirector();
this.phaseScope = phaseScope;
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
this.scoreDirector = null;
this.phaseScope = null;
}
@Override
public boolean isCountable() {
return childMoveSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return childMoveSelector.isNeverEnding();
}
@Override
public long getSize() {
return childMoveSelector.getSize();
}
@Override
public Iterator<Move<Solution_>> iterator() {
return new JustInTimeFilteringMoveIterator(childMoveSelector.iterator(), determineBailOutSize(), phaseScope);
}
private long determineBailOutSize() {
if (!bailOutEnabled) {
return -1L;
}
try {
return childMoveSelector.getSize() * BAIL_OUT_MULTIPLIER;
} catch (Exception ex) {
// Some move selectors throw an exception when getSize() is called.
// In this case, we choose to disregard it and pick a large-enough bail-out size anyway.
// The ${bailOutSize+1}th move could in theory show up where previous ${bailOutSize} moves did not,
// but we consider this to be an acceptable risk,
// outweighed by the benefit of the solver never running into an endless loop.
// The exception itself is swallowed, as it doesn't bring any useful information.
long bailOutSize = Short.MAX_VALUE * BAIL_OUT_MULTIPLIER;
logger.trace(
" Never-ending move selector ({}) failed to provide size, choosing a bail-out size of ({}) attempts.",
childMoveSelector, bailOutSize);
return bailOutSize;
}
}
private class JustInTimeFilteringMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private final long TERMINATION_BAIL_OUT_SIZE = 1000L;
private final Iterator<Move<Solution_>> childMoveIterator;
private final long bailOutSize;
private final AbstractPhaseScope<Solution_> phaseScope;
private final PhaseTermination<Solution_> termination;
public JustInTimeFilteringMoveIterator(Iterator<Move<Solution_>> childMoveIterator, long bailOutSize,
AbstractPhaseScope<Solution_> phaseScope) {
this.childMoveIterator = childMoveIterator;
this.bailOutSize = bailOutSize;
this.phaseScope = phaseScope;
this.termination = phaseScope != null ? phaseScope.getTermination() : null;
}
@Override
protected Move<Solution_> createUpcomingSelection() {
Move<Solution_> next;
long attemptsBeforeBailOut = bailOutSize;
// To reduce the impact of checking for termination on each move,
// we only check for termination after filtering out 1000 moves.
long attemptsBeforeCheckTermination = TERMINATION_BAIL_OUT_SIZE;
do {
if (!childMoveIterator.hasNext()) {
return noUpcomingSelection();
}
if (bailOutEnabled) {
// if childMoveIterator is neverEnding and nothing is accepted, bail out of the infinite loop
if (attemptsBeforeBailOut <= 0L) {
logger.trace("Bailing out of neverEnding selector ({}) after ({}) attempts to avoid infinite loop.",
FilteringMoveSelector.this, bailOutSize);
return noUpcomingSelection();
} else if (termination != null && attemptsBeforeCheckTermination <= 0L) {
// Reset the counter
attemptsBeforeCheckTermination = TERMINATION_BAIL_OUT_SIZE;
if (termination.isPhaseTerminated(phaseScope)) {
logger.trace(
"Bailing out of neverEnding selector ({}) because the termination setting has been triggered.",
FilteringMoveSelector.this);
return noUpcomingSelection();
}
}
attemptsBeforeBailOut--;
attemptsBeforeCheckTermination--;
}
next = childMoveIterator.next();
} while (!accept(scoreDirector, next));
return next;
}
}
private boolean accept(ScoreDirector<Solution_> scoreDirector, Move<Solution_> move) {
if (filter != null && !filter.accept(scoreDirector, move)) {
logger.trace(" Move ({}) filtered out by a selection filter ({}).", move, filter);
return false;
}
return true;
}
@Override
public String toString() {
return "Filtering(" + childMoveSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/ProbabilityMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.decorator;
import java.util.Iterator;
import java.util.NavigableMap;
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.heuristic.move.Move;
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.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class ProbabilityMoveSelector<Solution_> extends AbstractMoveSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_> {
protected final MoveSelector<Solution_> childMoveSelector;
protected final SelectionCacheType cacheType;
protected final SelectionProbabilityWeightFactory<Solution_, Move<Solution_>> probabilityWeightFactory;
protected NavigableMap<Double, Move<Solution_>> cachedMoveMap = null;
protected double probabilityWeightTotal = -1.0;
public ProbabilityMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType,
SelectionProbabilityWeightFactory<Solution_, ? extends Move<Solution_>> probabilityWeightFactory) {
this.childMoveSelector = childMoveSelector;
this.cacheType = cacheType;
this.probabilityWeightFactory =
(SelectionProbabilityWeightFactory<Solution_, Move<Solution_>>) probabilityWeightFactory;
if (childMoveSelector.isNeverEnding()) {
throw new IllegalStateException("The selector (" + this
+ ") has a childMoveSelector (" + childMoveSelector
+ ") with neverEnding (" + childMoveSelector.isNeverEnding() + ").");
}
phaseLifecycleSupport.addEventListener(childMoveSelector);
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge(cacheType, this));
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
cachedMoveMap = new TreeMap<>();
ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector();
double probabilityWeightOffset = 0L;
for (Move<Solution_> entity : childMoveSelector) {
double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(scoreDirector, entity);
cachedMoveMap.put(probabilityWeightOffset, entity);
probabilityWeightOffset += probabilityWeight;
}
probabilityWeightTotal = probabilityWeightOffset;
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
probabilityWeightTotal = -1.0;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return true;
}
@Override
public long getSize() {
return cachedMoveMap.size();
}
@Override
public Iterator<Move<Solution_>> iterator() {
return new Iterator<Move<Solution_>>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public Move<Solution_> next() {
double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
// entry is never null because randomOffset < probabilityWeightTotal
return cachedMoveMap.floorEntry(randomOffset)
.getValue();
}
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
};
}
@Override
public String toString() {
return "Probability(" + childMoveSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/SelectedCountLimitMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.decorator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class SelectedCountLimitMoveSelector<Solution_> extends AbstractMoveSelector<Solution_> {
protected final MoveSelector<Solution_> childMoveSelector;
protected final long selectedCountLimit;
public SelectedCountLimitMoveSelector(MoveSelector<Solution_> childMoveSelector, long selectedCountLimit) {
this.childMoveSelector = childMoveSelector;
this.selectedCountLimit = selectedCountLimit;
if (selectedCountLimit < 0L) {
throw new IllegalArgumentException("The selector (" + this
+ ") has a negative selectedCountLimit (" + selectedCountLimit + ").");
}
phaseLifecycleSupport.addEventListener(childMoveSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public long getSize() {
long childSize = childMoveSelector.getSize();
return Math.min(selectedCountLimit, childSize);
}
@Override
public Iterator<Move<Solution_>> iterator() {
return new SelectedCountLimitMoveIterator(childMoveSelector.iterator());
}
private class SelectedCountLimitMoveIterator extends SelectionIterator<Move<Solution_>> {
private final Iterator<Move<Solution_>> childMoveIterator;
private long selectedSize;
public SelectedCountLimitMoveIterator(Iterator<Move<Solution_>> childMoveIterator) {
this.childMoveIterator = childMoveIterator;
selectedSize = 0L;
}
@Override
public boolean hasNext() {
return selectedSize < selectedCountLimit && childMoveIterator.hasNext();
}
@Override
public Move<Solution_> next() {
if (selectedSize >= selectedCountLimit) {
throw new NoSuchElementException();
}
selectedSize++;
return childMoveIterator.next();
}
}
@Override
public String toString() {
return "SelectedCountLimit(" + childMoveSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/ShufflingMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.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.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class ShufflingMoveSelector<Solution_> extends AbstractCachingMoveSelector<Solution_> {
public ShufflingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType) {
super(childMoveSelector, cacheType);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Move<Solution_>> iterator() {
Collections.shuffle(cachedMoveList, workingRandom);
logger.trace(" Shuffled cachedMoveList with size ({}) in moveSelector({}).",
cachedMoveList.size(), this);
return cachedMoveList.iterator();
}
@Override
public String toString() {
return "Shuffling(" + childMoveSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/SortingMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.decorator;
import java.util.Iterator;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class SortingMoveSelector<Solution_> extends AbstractCachingMoveSelector<Solution_> {
protected final SelectionSorter<Solution_, Move<Solution_>> sorter;
public SortingMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType,
SelectionSorter<Solution_, Move<Solution_>> sorter) {
super(childMoveSelector, cacheType);
this.sorter = sorter;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
super.constructCache(solverScope);
sorter.sort(solverScope.getScoreDirector(), cachedMoveList);
logger.trace(" Sorted cachedMoveList: size ({}), moveSelector ({}).",
cachedMoveList.size(), this);
}
@Override
public boolean isNeverEnding() {
return false;
}
@Override
public Iterator<Move<Solution_>> iterator() {
return cachedMoveList.iterator();
}
@Override
public String toString() {
return "Sorting(" + childMoveSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/LegacyIteratorAdapter.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.move.LegacyMoveAdapter;
import ai.timefold.solver.core.preview.api.move.Move;
final class LegacyIteratorAdapter<Solution_> implements Iterator<Move<Solution_>> {
private final Iterator<ai.timefold.solver.core.impl.heuristic.move.Move<Solution_>> moveIterator;
public LegacyIteratorAdapter(Iterator<ai.timefold.solver.core.impl.heuristic.move.Move<Solution_>> moveIterator) {
this.moveIterator = moveIterator;
}
@Override
public boolean hasNext() {
return moveIterator.hasNext();
}
@Override
public Move<Solution_> next() {
return new LegacyMoveAdapter<>(moveIterator.next());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveIteratorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import java.util.Iterator;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.heuristic.move.Move;
/**
* An interface to generate an {@link Iterator} of custom {@link Move}s.
* <p>
* For a more simple version, see {@link MoveListFactory}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public interface MoveIteratorFactory<Solution_, Move_ extends Move<Solution_>> {
static <Solution_> Iterator<ai.timefold.solver.core.preview.api.move.Move<Solution_>>
adaptIterator(Iterator<Move<Solution_>> moveIterator) {
return new LegacyIteratorAdapter<>(moveIterator);
}
/**
* Called when the phase (for example Local Search) starts.
*
* @param scoreDirector never null
*/
default void phaseStarted(ScoreDirector<Solution_> scoreDirector) {
}
/**
* Called when the phase (for example Local Search) ends,
* to clean up anything cached since {@link #phaseStarted(ScoreDirector)}.
*
* @param scoreDirector never null
*/
default void phaseEnded(ScoreDirector<Solution_> scoreDirector) {
}
/**
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} of which the {@link Move}s need to be generated
* @return the approximate number of elements generated by {@link #createOriginalMoveIterator(ScoreDirector)}
* @throws UnsupportedOperationException if not supported
*/
long getSize(ScoreDirector<Solution_> scoreDirector);
/**
* When it is called depends on the configured {@link SelectionCacheType}.
*
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} of which the {@link Move}s need to be generated
* @return never null, an {@link Iterator} that will end sooner or later
* @throws UnsupportedOperationException if only {@link #createRandomMoveIterator(ScoreDirector, Random)} is
* supported
*/
Iterator<Move_> createOriginalMoveIterator(ScoreDirector<Solution_> scoreDirector);
/**
* When it is called depends on the configured {@link SelectionCacheType}.
*
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} of which the {@link Move}s need to be generated
* @param workingRandom never null, the {@link Random} to use when any random number is needed,
* so {@link EnvironmentMode#PHASE_ASSERT} works correctly
* @return never null, an {@link Iterator} that is allowed (or even presumed) to be never ending
* @throws UnsupportedOperationException if only {@link #createOriginalMoveIterator(ScoreDirector)} is supported
*/
Iterator<Move_> createRandomMoveIterator(ScoreDirector<Solution_> scoreDirector, Random workingRandom);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveIteratorFactoryFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
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;
public class MoveIteratorFactoryFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, MoveIteratorFactoryConfig> {
public MoveIteratorFactoryFactory(MoveIteratorFactoryConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
var moveIteratorFactoryClass = config.getMoveIteratorFactoryClass();
if (moveIteratorFactoryClass == null) {
throw new IllegalArgumentException("The moveIteratorFactoryConfig (%s) lacks a moveListFactoryClass (%s)."
.formatted(config, moveIteratorFactoryClass));
}
var moveIteratorFactory = ConfigUtils.newInstance(config, "moveIteratorFactoryClass", moveIteratorFactoryClass);
ConfigUtils.applyCustomProperties(moveIteratorFactory, "moveIteratorFactoryClass",
config.getMoveIteratorFactoryCustomProperties(), "moveIteratorFactoryCustomProperties");
return new MoveIteratorFactoryToMoveSelectorBridge<>(moveIteratorFactory, randomSelection);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveIteratorFactoryToMoveSelectorBridge.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import java.util.Iterator;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
/**
* Bridges a {@link MoveIteratorFactory} to a {@link MoveSelector}.
*/
public class MoveIteratorFactoryToMoveSelectorBridge<Solution_> extends AbstractMoveSelector<Solution_> {
protected final MoveIteratorFactory<Solution_, ?> moveIteratorFactory;
protected final boolean randomSelection;
protected ScoreDirector<Solution_> scoreDirector = null;
public MoveIteratorFactoryToMoveSelectorBridge(MoveIteratorFactory<Solution_, ?> moveIteratorFactory,
boolean randomSelection) {
this.moveIteratorFactory = moveIteratorFactory;
this.randomSelection = randomSelection;
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return true;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
scoreDirector = phaseScope.getScoreDirector();
super.phaseStarted(phaseScope);
moveIteratorFactory.phaseStarted(scoreDirector);
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
moveIteratorFactory.phaseEnded(scoreDirector);
super.phaseEnded(phaseScope);
scoreDirector = null;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
return randomSelection;
}
@Override
public long getSize() {
long size = moveIteratorFactory.getSize(scoreDirector);
if (size < 0L) {
throw new IllegalStateException("The moveIteratorFactoryClass (" + moveIteratorFactory.getClass()
+ ") has size (" + size
+ ") which is negative, but a correct size is required in this Solver configuration.");
}
return size;
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return (Iterator<Move<Solution_>>) moveIteratorFactory.createOriginalMoveIterator(scoreDirector);
} else {
return (Iterator<Move<Solution_>>) moveIteratorFactory.createRandomMoveIterator(scoreDirector,
workingRandom);
}
}
@Override
public String toString() {
return "MoveIteratorFactory(" + moveIteratorFactory.getClass() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveListFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import java.util.Iterator;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.move.Move;
/**
* A simple interface to generate a {@link List} of custom {@link Move}s.
* <p>
* For a more powerful version, see {@link MoveIteratorFactory}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public interface MoveListFactory<Solution_> {
/**
* When it is called depends on the configured {@link SelectionCacheType}.
* <p>
* It can never support {@link SelectionCacheType#JUST_IN_TIME},
* because it returns a {@link List}, not an {@link Iterator}.
*
* @param solution never null, the {@link PlanningSolution} of which the {@link Move}s need to be generated
* @return never null
*/
List<? extends Move<Solution_>> createMoveList(Solution_ solution);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveListFactoryFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveListFactoryConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
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;
public class MoveListFactoryFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, MoveListFactoryConfig> {
public MoveListFactoryFactory(MoveListFactoryConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
var moveListFactoryClass = config.getMoveListFactoryClass();
if (moveListFactoryClass == null) {
throw new IllegalArgumentException("The moveListFactoryConfig (%s) lacks a moveListFactoryClass (%s)."
.formatted(config, moveListFactoryClass));
}
MoveListFactory<Solution_> moveListFactory =
ConfigUtils.newInstance(config, "moveListFactoryClass", moveListFactoryClass);
ConfigUtils.applyCustomProperties(moveListFactory, "moveListFactoryClass",
config.getMoveListFactoryCustomProperties(), "moveListFactoryCustomProperties");
// MoveListFactoryToMoveSelectorBridge caches by design, so it uses the minimumCacheType
if (minimumCacheType.compareTo(SelectionCacheType.STEP) < 0) {
// cacheType upgrades to SelectionCacheType.STEP (without shuffling) because JIT is not supported
minimumCacheType = SelectionCacheType.STEP;
}
return new MoveListFactoryToMoveSelectorBridge<>(moveListFactory, minimumCacheType, randomSelection);
}
@Override
protected boolean isBaseInherentlyCached() {
return true;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveListFactoryToMoveSelectorBridge.java | package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
import java.util.Iterator;
import java.util.List;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.impl.heuristic.move.Move;
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.CachedListRandomIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* Bridges a {@link MoveListFactory} to a {@link MoveSelector}.
*/
public class MoveListFactoryToMoveSelectorBridge<Solution_> extends AbstractMoveSelector<Solution_>
implements SelectionCacheLifecycleListener<Solution_> {
protected final MoveListFactory<Solution_> moveListFactory;
protected final SelectionCacheType cacheType;
protected final boolean randomSelection;
protected List<Move<Solution_>> cachedMoveList = null;
public MoveListFactoryToMoveSelectorBridge(MoveListFactory<Solution_> moveListFactory,
SelectionCacheType cacheType, boolean randomSelection) {
this.moveListFactory = moveListFactory;
this.cacheType = cacheType;
this.randomSelection = randomSelection;
if (cacheType.isNotCached()) {
throw new IllegalArgumentException("The selector (" + this
+ ") does not support the cacheType (" + cacheType + ").");
}
phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this));
}
@Override
public SelectionCacheType getCacheType() {
return cacheType;
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return true;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void constructCache(SolverScope<Solution_> solverScope) {
cachedMoveList =
(List<Move<Solution_>>) moveListFactory.createMoveList(solverScope.getScoreDirector().getWorkingSolution());
logger.trace(" Created cachedMoveList: size ({}), moveSelector ({}).",
cachedMoveList.size(), this);
}
@Override
public void disposeCache(SolverScope<Solution_> solverScope) {
cachedMoveList = null;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isNeverEnding() {
// CachedListRandomIterator is neverEnding
return randomSelection;
}
@Override
public long getSize() {
return cachedMoveList.size();
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return cachedMoveList.iterator();
} else {
return new CachedListRandomIterator<>(cachedMoveList, workingRandom);
}
}
@Override
public String toString() {
return "MoveListFactory(" + moveListFactory.getClass() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/ChangeMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
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.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ChangeMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final Object entity;
protected final Object toPlanningValue;
public ChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue) {
this.variableDescriptor = variableDescriptor;
this.entity = entity;
this.toPlanningValue = toPlanningValue;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public Object getEntity() {
return entity;
}
public Object getToPlanningValue() {
return toPlanningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
Object oldValue = variableDescriptor.getValue(entity);
return !Objects.equals(oldValue, toPlanningValue);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
castScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue);
}
@Override
public ChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new ChangeMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(entity),
destinationScoreDirector.lookUpWorkingObject(toPlanningValue));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<?> getPlanningEntities() {
return Collections.singletonList(entity);
}
@Override
public Collection<?> 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 ChangeMove<?> other = (ChangeMove<?>) o;
return Objects.equals(variableDescriptor, other.variableDescriptor) &&
Objects.equals(entity, other.entity) &&
Objects.equals(toPlanningValue, other.toPlanningValue);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, entity, toPlanningValue);
}
@Override
public String toString() {
Object oldValue = variableDescriptor.getValue(entity);
return entity + " {" + oldValue + " -> " + toPlanningValue + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/ChangeMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.Iterator;
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.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractOriginalChangeIterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractRandomChangeIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.ChainedChangeMove;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public class ChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final EntitySelector<Solution_> entitySelector;
protected final ValueSelector<Solution_> valueSelector;
protected final boolean randomSelection;
protected final boolean chained;
protected SingletonInverseVariableSupply inverseVariableSupply = null;
public ChangeMoveSelector(EntitySelector<Solution_> entitySelector, ValueSelector<Solution_> valueSelector,
boolean randomSelection) {
this.entitySelector = entitySelector;
this.valueSelector = valueSelector;
this.randomSelection = randomSelection;
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
chained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.isChained();
phaseLifecycleSupport.addEventListener(entitySelector);
phaseLifecycleSupport.addEventListener(valueSelector);
}
@Override
public boolean supportsPhaseAndSolverCaching() {
return !chained;
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
if (chained) {
SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager();
inverseVariableSupply =
supplyManager.demand(new SingletonInverseVariableDemand<>(valueSelector.getVariableDescriptor()));
}
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
if (chained) {
inverseVariableSupply = null;
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return entitySelector.isCountable() && valueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || entitySelector.isNeverEnding() || valueSelector.isNeverEnding();
}
@Override
public long getSize() {
if (valueSelector instanceof IterableSelector) {
return entitySelector.getSize() * ((IterableSelector<Solution_, ?>) valueSelector).getSize();
} else {
long size = 0;
for (Iterator<?> it = entitySelector.endingIterator(); it.hasNext();) {
Object entity = it.next();
size += valueSelector.getSize(entity);
}
return size;
}
}
@Override
public Iterator<Move<Solution_>> iterator() {
final GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
if (!randomSelection) {
if (chained) {
return new AbstractOriginalChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChainedChangeMove<>(variableDescriptor, entity, toValue, inverseVariableSupply);
}
};
} else {
return new AbstractOriginalChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChangeMove<>(variableDescriptor, entity, toValue);
}
};
}
} else {
if (chained) {
return new AbstractRandomChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChainedChangeMove<>(variableDescriptor, entity, toValue, inverseVariableSupply);
}
};
} else {
return new AbstractRandomChangeIterator<>(entitySelector, valueSelector) {
@Override
protected Move<Solution_> newChangeSelection(Object entity, Object toValue) {
return new ChangeMove<>(variableDescriptor, entity, toValue);
}
};
}
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entitySelector + ", " + valueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/ChangeMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
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.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
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.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
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.generic.list.ListChangeMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ChangeMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, ChangeMoveSelectorConfig> {
private static final Logger LOGGER = LoggerFactory.getLogger(ChangeMoveSelectorFactory.class);
public ChangeMoveSelectorFactory(ChangeMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
checkUnfolded("entitySelectorConfig", config.getEntitySelectorConfig());
checkUnfolded("valueSelectorConfig", config.getValueSelectorConfig());
var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
var entitySelector = EntitySelectorFactory
.<Solution_> create(config.getEntitySelectorConfig())
.buildEntitySelector(configPolicy, minimumCacheType, selectionOrder);
var valueSelector = ValueSelectorFactory
.<Solution_> create(config.getValueSelectorConfig())
.buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder);
return new ChangeMoveSelector<>(entitySelector, valueSelector, randomSelection);
}
@Override
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {
Collection<EntityDescriptor<Solution_>> entityDescriptors;
var onlyEntityDescriptor = config.getEntitySelectorConfig() == null ? null
: EntitySelectorFactory.<Solution_> create(config.getEntitySelectorConfig())
.extractEntityDescriptor(configPolicy);
if (onlyEntityDescriptor != null) {
entityDescriptors = Collections.singletonList(onlyEntityDescriptor);
} else {
entityDescriptors = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors();
}
var variableDescriptorList = new ArrayList<GenuineVariableDescriptor<Solution_>>();
for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptors) {
var onlyVariableDescriptor = config.getValueSelectorConfig() == null ? null
: ValueSelectorFactory.<Solution_> create(config.getValueSelectorConfig())
.extractVariableDescriptor(configPolicy, entityDescriptor);
if (onlyVariableDescriptor != null) {
if (onlyEntityDescriptor != null) {
if (onlyVariableDescriptor.isListVariable()) {
return buildListChangeMoveSelectorConfig((ListVariableDescriptor<?>) onlyVariableDescriptor, true);
}
// No need for unfolding or deducing
return null;
}
variableDescriptorList.add(onlyVariableDescriptor);
} else {
variableDescriptorList.addAll(entityDescriptor.getGenuineVariableDescriptorList());
}
}
return buildUnfoldedMoveSelectorConfig(configPolicy, variableDescriptorList);
}
protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy,
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList) {
var moveSelectorConfigList = new ArrayList<MoveSelectorConfig>(variableDescriptorList.size());
for (var variableDescriptor : variableDescriptorList) {
if (variableDescriptor.isListVariable()) {
if (configPolicy.getSolutionDescriptor().hasBothBasicAndListVariables()) {
// When using a mixed model,
// we do not create a list move
// and delegate it to the ListChangeMoveSelectorFactory.
// The strategy aims to provide a more normalized move selector collection for mixed models.
continue;
}
// No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded()
var childMoveSelectorConfig =
buildListChangeMoveSelectorConfig((ListVariableDescriptor<?>) variableDescriptor, false);
moveSelectorConfigList.add(childMoveSelectorConfig);
} else {
// No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded()
var childMoveSelectorConfig = new ChangeMoveSelectorConfig();
// Different EntitySelector per child because it is a union
var childEntitySelectorConfig = new EntitySelectorConfig(config.getEntitySelectorConfig());
if (childEntitySelectorConfig.getMimicSelectorRef() == null) {
childEntitySelectorConfig.setEntityClass(variableDescriptor.getEntityDescriptor().getEntityClass());
}
childMoveSelectorConfig.setEntitySelectorConfig(childEntitySelectorConfig);
var childValueSelectorConfig = new ValueSelectorConfig(config.getValueSelectorConfig());
if (childValueSelectorConfig.getMimicSelectorRef() == null) {
childValueSelectorConfig.setVariableName(variableDescriptor.getVariableName());
}
childMoveSelectorConfig.setValueSelectorConfig(childValueSelectorConfig);
moveSelectorConfigList.add(childMoveSelectorConfig);
}
}
MoveSelectorConfig<?> unfoldedMoveSelectorConfig;
if (moveSelectorConfigList.size() == 1) {
unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0);
} else {
unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList);
}
unfoldedMoveSelectorConfig.inheritFolded(config);
return unfoldedMoveSelectorConfig;
}
private ListChangeMoveSelectorConfig buildListChangeMoveSelectorConfig(ListVariableDescriptor<?> variableDescriptor,
boolean inheritFoldedConfig) {
LOGGER.warn(
"""
The changeMoveSelectorConfig ({}) is being used for a list variable.
We are keeping this option through the 1.x release stream for backward compatibility reasons.
Please update your solver config to use {} now.""",
config, ListChangeMoveSelectorConfig.class.getSimpleName());
var listChangeMoveSelectorConfig = ListChangeMoveSelectorFactory.buildChildMoveSelectorConfig(variableDescriptor,
config.getValueSelectorConfig(), createDestinationSelectorConfig());
if (inheritFoldedConfig) {
listChangeMoveSelectorConfig.inheritFolded(config);
}
return listChangeMoveSelectorConfig;
}
private DestinationSelectorConfig createDestinationSelectorConfig() {
var entitySelectorConfig = config.getEntitySelectorConfig();
var valueSelectorConfig = config.getValueSelectorConfig();
if (entitySelectorConfig == null) {
if (valueSelectorConfig == null) {
return new DestinationSelectorConfig();
} else {
return new DestinationSelectorConfig()
.withValueSelectorConfig(valueSelectorConfig);
}
} else {
if (valueSelectorConfig == null) {
return new DestinationSelectorConfig()
.withEntitySelectorConfig(entitySelectorConfig);
} else {
return new DestinationSelectorConfig()
.withEntitySelectorConfig(entitySelectorConfig)
.withValueSelectorConfig(valueSelectorConfig);
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/CountSupplier.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
/**
* Used for converting selector size to some other value.
* Selector size is always long, for legacy reasons.
* The rest of the code uses ints though, so this functional interface implies a conversion to int,
* so that the rest of the code doesn't have to worry about it anymore.
*/
@FunctionalInterface
public interface CountSupplier {
int applyAsInt(long valueCount);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/GenericMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
/**
* Abstract superclass for every generic {@link MoveSelector}.
*
* @see MoveSelector
*/
public abstract class GenericMoveSelector<Solution_> extends AbstractMoveSelector<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarChangeMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.Collection;
import java.util.Collections;
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.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
/**
* This {@link Move} is not cacheable.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class PillarChangeMove<Solution_> extends AbstractMove<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final List<Object> pillar;
protected final Object toPlanningValue;
public PillarChangeMove(List<Object> pillar, GenuineVariableDescriptor<Solution_> variableDescriptor,
Object toPlanningValue) {
this.pillar = pillar;
this.variableDescriptor = variableDescriptor;
this.toPlanningValue = toPlanningValue;
}
public List<Object> getPillar() {
return pillar;
}
public String getVariableName() {
return variableDescriptor.getVariableName();
}
public Object getToPlanningValue() {
return toPlanningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
var oldValue = variableDescriptor.getValue(pillar.get(0));
if (Objects.equals(oldValue, toPlanningValue)) {
return false;
}
if (!variableDescriptor.canExtractValueRangeFromSolution()) {
var valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
for (Object entity : pillar) {
var rightValueRange = extractValueRangeFromEntity(scoreDirector, valueRangeDescriptor, entity);
if (!rightValueRange.contains(toPlanningValue)) {
return false;
}
}
}
return true;
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
for (var entity : pillar) {
castScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue);
}
}
@Override
public PillarChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new PillarChangeMove<>(rebaseList(pillar, destinationScoreDirector), variableDescriptor,
destinationScoreDirector.lookUpWorkingObject(toPlanningValue));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return pillar;
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toPlanningValue);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final PillarChangeMove<?> other = (PillarChangeMove<?>) o;
return Objects.equals(variableDescriptor, other.variableDescriptor) &&
Objects.equals(pillar, other.pillar) &&
Objects.equals(toPlanningValue, other.toPlanningValue);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor, pillar, toPlanningValue);
}
@Override
public String toString() {
Object oldValue = variableDescriptor.getValue(pillar.get(0));
return pillar + " {" + oldValue + " -> " + toPlanningValue + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarChangeMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
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.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
public class PillarChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final PillarSelector<Solution_> pillarSelector;
protected final ValueSelector<Solution_> valueSelector;
protected final boolean randomSelection;
public PillarChangeMoveSelector(PillarSelector<Solution_> pillarSelector, ValueSelector<Solution_> valueSelector,
boolean randomSelection) {
this.pillarSelector = pillarSelector;
this.valueSelector = valueSelector;
this.randomSelection = randomSelection;
GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor();
boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.isChained();
if (isChained) {
throw new IllegalStateException("The selector (%s) has a variableDescriptor (%s) which is chained (%s)."
.formatted(this, variableDescriptor, isChained));
}
phaseLifecycleSupport.addEventListener(pillarSelector);
phaseLifecycleSupport.addEventListener(valueSelector);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return pillarSelector.isCountable() && valueSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || pillarSelector.isNeverEnding() || valueSelector.isNeverEnding();
}
@Override
public long getSize() {
return pillarSelector.getSize() * ((IterableValueSelector<Solution_>) valueSelector).getSize();
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return new OriginalPillarChangeMoveIterator();
} else {
return new RandomPillarChangeMoveIterator();
}
}
private class OriginalPillarChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private Iterator<List<Object>> pillarIterator;
private Iterator<Object> valueIterator;
private List<Object> upcomingPillar;
private OriginalPillarChangeMoveIterator() {
pillarIterator = pillarSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
if (!valueIterator.hasNext()) {
if (!pillarIterator.hasNext()) {
return noUpcomingSelection();
}
upcomingPillar = pillarIterator.next();
valueIterator = valueSelector.iterator(upcomingPillar.get(0));
if (!valueIterator.hasNext()) {
// valueSelector is completely empty
return noUpcomingSelection();
}
}
Object toValue = valueIterator.next();
return new PillarChangeMove<>(upcomingPillar, valueSelector.getVariableDescriptor(), toValue);
}
}
private class RandomPillarChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> {
private Iterator<List<Object>> pillarIterator;
private Iterator<Object> valueIterator;
private RandomPillarChangeMoveIterator() {
pillarIterator = pillarSelector.iterator();
// Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
valueIterator = Collections.emptyIterator();
}
@Override
protected Move<Solution_> createUpcomingSelection() {
// Ideally, this code should have read:
// Object pillar = pillarIterator.next();
// Object toValue = valueIterator.next();
// But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
if (!pillarIterator.hasNext()) {
pillarIterator = pillarSelector.iterator();
if (!pillarIterator.hasNext()) {
// pillarSelector is completely empty
return noUpcomingSelection();
}
}
List<Object> pillar = pillarIterator.next();
if (!valueIterator.hasNext()) {
valueIterator = valueSelector.iterator(pillar.get(0));
if (!valueIterator.hasNext()) {
// valueSelector is completely empty
return noUpcomingSelection();
}
}
Object toValue = valueIterator.next();
return new PillarChangeMove<>(pillar, valueSelector.getVariableDescriptor(), toValue);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + pillarSelector + ", " + valueSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarChangeMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.Collections;
import java.util.Comparator;
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.pillar.PillarSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelectorFactory;
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 PillarChangeMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, PillarChangeMoveSelectorConfig> {
public PillarChangeMoveSelectorFactory(PillarChangeMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
var pillarSelectorConfig = Objects.requireNonNullElseGet(config.getPillarSelectorConfig(), PillarSelectorConfig::new);
var valueSelectorConfig = config.getValueSelectorConfig();
var variableNameIncludeList = valueSelectorConfig == null
|| valueSelectorConfig.getVariableName() == null ? null
: Collections.singletonList(valueSelectorConfig.getVariableName());
var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection);
var pillarSelector = PillarSelectorFactory.<Solution_> create(pillarSelectorConfig)
.buildPillarSelector(configPolicy, config.getSubPillarType(),
(Class<? extends Comparator<Object>>) config.getSubPillarSequenceComparatorClass(),
minimumCacheType, selectionOrder, variableNameIncludeList);
var valueSelector = ValueSelectorFactory
.<Solution_> create(Objects.requireNonNullElseGet(valueSelectorConfig, ValueSelectorConfig::new))
.buildValueSelector(configPolicy, pillarSelector.getEntityDescriptor(), minimumCacheType, selectionOrder);
return new PillarChangeMoveSelector<>(pillarSelector, valueSelector, randomSelection);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarDemand.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import ai.timefold.solver.core.config.heuristic.selector.entity.pillar.SubPillarConfigPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.util.MemoizingSupply;
public final class PillarDemand<Solution_> implements Demand<MemoizingSupply<List<List<Object>>>> {
private final EntitySelector<Solution_> entitySelector;
private final List<GenuineVariableDescriptor<Solution_>> variableDescriptors;
private final SubPillarConfigPolicy subpillarConfigPolicy;
public PillarDemand(EntitySelector<Solution_> entitySelector,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors, SubPillarConfigPolicy subpillarConfigPolicy) {
this.entitySelector = entitySelector;
this.variableDescriptors = variableDescriptors;
this.subpillarConfigPolicy = subpillarConfigPolicy;
}
@Override
public MemoizingSupply<List<List<Object>>> createExternalizedSupply(SupplyManager supplyManager) {
Supplier<List<List<Object>>> supplier = () -> {
long entitySize = entitySelector.getSize();
if (entitySize > Integer.MAX_VALUE) {
throw new IllegalStateException("The selector (" + this + ") has an entitySelector ("
+ entitySelector + ") with entitySize (" + entitySize
+ ") which is higher than Integer.MAX_VALUE.");
}
Stream<Object> entities = StreamSupport.stream(entitySelector.spliterator(), false);
Comparator<?> comparator = subpillarConfigPolicy.getEntityComparator();
if (comparator != null) {
/*
* The entity selection will be sorted. This will result in all the pillars being sorted without having to
* sort them individually later.
*/
entities = entities.sorted((Comparator<? super Object>) comparator);
}
// Create all the pillars from a stream of entities; if sorted, the pillars will be sequential.
Map<List<Object>, List<Object>> valueStateToPillarMap = new LinkedHashMap<>((int) entitySize);
int variableCount = variableDescriptors.size();
entities.forEach(entity -> {
List<Object> valueState = variableCount == 1 ? getSingleVariableValueState(entity, variableDescriptors)
: getMultiVariableValueState(entity, variableDescriptors, variableCount);
List<Object> pillar = valueStateToPillarMap.computeIfAbsent(valueState, key -> new ArrayList<>());
pillar.add(entity);
});
// Store the cache. Exclude pillars of size lower than the minimumSubPillarSize, as we shouldn't select those.
Collection<List<Object>> pillarLists = valueStateToPillarMap.values();
int minimumSubPillarSize = subpillarConfigPolicy.getMinimumSubPillarSize();
return minimumSubPillarSize > 1 ? pillarLists.stream()
.filter(pillar -> pillar.size() >= minimumSubPillarSize)
.collect(Collectors.toList())
: new ArrayList<>(pillarLists);
};
return new MemoizingSupply<>(supplier);
}
private static <Solution_> List<Object> getSingleVariableValueState(Object entity,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors) {
Object value = variableDescriptors.get(0).getValue(entity);
return Collections.singletonList(value);
}
private static <Solution_> List<Object> getMultiVariableValueState(Object entity,
List<GenuineVariableDescriptor<Solution_>> variableDescriptors, int variableCount) {
List<Object> valueState = new ArrayList<>(variableCount);
for (int i = 0; i < variableCount; i++) {
Object value = variableDescriptors.get(i).getValue(entity);
valueState.add(value);
}
return valueState;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
PillarDemand<?> that = (PillarDemand<?>) other;
return Objects.equals(entitySelector, that.entitySelector)
&& Objects.equals(variableDescriptors, that.variableDescriptors)
&& Objects.equals(subpillarConfigPolicy, that.subpillarConfigPolicy);
}
@Override
public int hashCode() {
return Objects.hash(entitySelector, variableDescriptors, subpillarConfigPolicy);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarSwapMove.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
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.heuristic.move.AbstractMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
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 PillarSwapMove<Solution_> extends AbstractMove<Solution_> {
protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList;
protected final List<Object> leftPillar;
protected final List<Object> rightPillar;
public PillarSwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList,
List<Object> leftPillar, List<Object> rightPillar) {
this.variableDescriptorList = variableDescriptorList;
this.leftPillar = leftPillar;
this.rightPillar = rightPillar;
}
public List<String> getVariableNameList() {
List<String> variableNameList = new ArrayList<>(variableDescriptorList.size());
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
variableNameList.add(variableDescriptor.getVariableName());
}
return variableNameList;
}
public List<Object> getLeftPillar() {
return leftPillar;
}
public List<Object> getRightPillar() {
return rightPillar;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
var movable = false;
for (var variableDescriptor : variableDescriptorList) {
var leftValue = variableDescriptor.getValue(leftPillar.get(0));
var rightValue = variableDescriptor.getValue(rightPillar.get(0));
if (!Objects.equals(leftValue, rightValue)) {
movable = true;
if (!variableDescriptor.canExtractValueRangeFromSolution()) {
var valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
for (var rightEntity : rightPillar) {
var rightValueRange =
extractValueRangeFromEntity(scoreDirector, valueRangeDescriptor, rightEntity);
if (!rightValueRange.contains(leftValue)) {
return false;
}
}
for (var leftEntity : leftPillar) {
var leftValueRange =
extractValueRangeFromEntity(scoreDirector, valueRangeDescriptor, leftEntity);
if (!leftValueRange.contains(rightValue)) {
return false;
}
}
}
}
}
return movable;
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
Object oldLeftValue = variableDescriptor.getValue(leftPillar.get(0));
Object oldRightValue = variableDescriptor.getValue(rightPillar.get(0));
if (!Objects.equals(oldLeftValue, oldRightValue)) {
for (Object leftEntity : leftPillar) {
castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue);
}
for (Object rightEntity : rightPillar) {
castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue);
}
}
}
}
@Override
public PillarSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
return new PillarSwapMove<>(variableDescriptorList,
rebaseList(leftPillar, destinationScoreDirector), rebaseList(rightPillar, destinationScoreDirector));
}
// ************************************************************************
// Introspection methods
// ************************************************************************
@Override
public String getSimpleMoveTypeDescription() {
StringBuilder moveTypeDescription = new StringBuilder(20 * (variableDescriptorList.size() + 1));
moveTypeDescription.append(getClass().getSimpleName()).append("(");
String delimiter = "";
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
moveTypeDescription.append(delimiter).append(variableDescriptor.getSimpleEntityAndVariableName());
delimiter = ", ";
}
moveTypeDescription.append(")");
return moveTypeDescription.toString();
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return CollectionUtils.concat(leftPillar, rightPillar);
}
@Override
public Collection<? extends Object> getPlanningValues() {
List<Object> values = new ArrayList<>(variableDescriptorList.size() * 2);
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
values.add(variableDescriptor.getValue(leftPillar.get(0)));
values.add(variableDescriptor.getValue(rightPillar.get(0)));
}
return values;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final PillarSwapMove<?> other = (PillarSwapMove<?>) o;
return Objects.equals(variableDescriptorList, other.variableDescriptorList) &&
Objects.equals(leftPillar, other.leftPillar) &&
Objects.equals(rightPillar, other.rightPillar);
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptorList, leftPillar, rightPillar);
}
@Override
public String toString() {
StringBuilder s = new StringBuilder(variableDescriptorList.size() * 16);
s.append(leftPillar).append(" {");
appendVariablesToString(s, leftPillar);
s.append("} <-> ");
s.append(rightPillar).append(" {");
appendVariablesToString(s, rightPillar);
s.append("}");
return s.toString();
}
protected void appendVariablesToString(StringBuilder s, List<Object> pillar) {
boolean first = true;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
if (!first) {
s.append(", ");
}
var value = variableDescriptor.getValue(pillar.get(0));
s.append(value == null ? null : value.toString());
first = false;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarSwapMoveSelector.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.Iterator;
import java.util.List;
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.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractOriginalSwapIterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractRandomSwapIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelector;
public class PillarSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> {
protected final PillarSelector<Solution_> leftPillarSelector;
protected final PillarSelector<Solution_> rightPillarSelector;
protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList;
protected final boolean randomSelection;
public PillarSwapMoveSelector(PillarSelector<Solution_> leftPillarSelector,
PillarSelector<Solution_> rightPillarSelector,
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, boolean randomSelection) {
this.leftPillarSelector = leftPillarSelector;
this.rightPillarSelector = rightPillarSelector;
this.variableDescriptorList = variableDescriptorList;
this.randomSelection = randomSelection;
Class<?> leftEntityClass = leftPillarSelector.getEntityDescriptor().getEntityClass();
if (!leftEntityClass.equals(rightPillarSelector.getEntityDescriptor().getEntityClass())) {
throw new IllegalStateException("The selector (" + this
+ ") has a leftPillarSelector's entityClass (" + leftEntityClass
+ ") which is not equal to the rightPillarSelector's entityClass ("
+ rightPillarSelector.getEntityDescriptor().getEntityClass() + ").");
}
if (variableDescriptorList.isEmpty()) {
throw new IllegalStateException("The selector (" + this
+ ")'s variableDescriptors (" + variableDescriptorList + ") is empty.");
}
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
if (!leftEntityClass.equals(
variableDescriptor.getEntityDescriptor().getEntityClass())) {
throw new IllegalStateException("The selector (" + this
+ ") has a variableDescriptor (" + variableDescriptor
+ ") with a entityClass (" + variableDescriptor.getEntityDescriptor().getEntityClass()
+ ") which is not equal to the leftPillarSelector's entityClass (" + leftEntityClass + ").");
}
boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.isChained();
if (isChained) {
throw new IllegalStateException("The selector (%s) has a variableDescriptor (%s) which is chained (%s)."
.formatted(this, variableDescriptor, isChained));
}
}
phaseLifecycleSupport.addEventListener(leftPillarSelector);
if (leftPillarSelector != rightPillarSelector) {
phaseLifecycleSupport.addEventListener(rightPillarSelector);
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return leftPillarSelector.isCountable() && rightPillarSelector.isCountable();
}
@Override
public boolean isNeverEnding() {
return randomSelection || leftPillarSelector.isNeverEnding() || rightPillarSelector.isNeverEnding();
}
@Override
public long getSize() {
return AbstractOriginalSwapIterator.getSize(leftPillarSelector, rightPillarSelector);
}
@Override
public Iterator<Move<Solution_>> iterator() {
if (!randomSelection) {
return new AbstractOriginalSwapIterator<>(leftPillarSelector, rightPillarSelector) {
@Override
protected Move<Solution_> newSwapSelection(List<Object> leftSubSelection, List<Object> rightSubSelection) {
return new PillarSwapMove<>(variableDescriptorList, leftSubSelection, rightSubSelection);
}
};
} else {
return new AbstractRandomSwapIterator<>(leftPillarSelector, rightPillarSelector) {
@Override
protected Move<Solution_> newSwapSelection(List<Object> leftSubSelection, List<Object> rightSubSelection) {
return new PillarSwapMove<>(variableDescriptorList, leftSubSelection, rightSubSelection);
}
};
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + leftPillarSelector + ", " + rightPillarSelector + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarSwapMoveSelectorFactory.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import java.util.Comparator;
import java.util.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.pillar.PillarSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig;
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.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class PillarSwapMoveSelectorFactory<Solution_>
extends AbstractMoveSelectorFactory<Solution_, PillarSwapMoveSelectorConfig> {
public PillarSwapMoveSelectorFactory(PillarSwapMoveSelectorConfig moveSelectorConfig) {
super(moveSelectorConfig);
}
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
var leftPillarSelectorConfig =
Objects.requireNonNullElseGet(config.getPillarSelectorConfig(), PillarSelectorConfig::new);
EntityDescriptor<Solution_> leftEntityDescriptor = null;
var leftEntitySelectorConfig = leftPillarSelectorConfig.getEntitySelectorConfig();
if (leftEntitySelectorConfig != null && leftEntitySelectorConfig.getEntityClass() != null) {
leftEntityDescriptor =
configPolicy.getSolutionDescriptor().findEntityDescriptor(leftEntitySelectorConfig.getEntityClass());
}
var leftVariableNameIncludeList = config.getVariableNameIncludeList();
if (leftVariableNameIncludeList == null && leftEntityDescriptor != null
&& leftEntityDescriptor.hasAnyGenuineBasicVariables() && leftEntityDescriptor.hasAnyGenuineListVariables()) {
// Mixed models filter out the list variable
leftVariableNameIncludeList = leftEntityDescriptor.getGenuineBasicVariableDescriptorList().stream()
.map(GenuineVariableDescriptor::getVariableName)
.toList();
}
var rightPillarSelectorConfig = config.getSecondaryPillarSelectorConfig();
if (rightPillarSelectorConfig == null) {
rightPillarSelectorConfig = leftPillarSelectorConfig;
}
EntityDescriptor<Solution_> rightEntityDescriptor = null;
var rightEntitySelectorConfig = rightPillarSelectorConfig.getEntitySelectorConfig();
if (rightEntitySelectorConfig != null && rightEntitySelectorConfig.getEntityClass() != null) {
rightEntityDescriptor =
configPolicy.getSolutionDescriptor().findEntityDescriptor(rightEntitySelectorConfig.getEntityClass());
}
var rightVariableNameIncludeList = config.getVariableNameIncludeList();
if (rightVariableNameIncludeList == null && rightEntityDescriptor != null
&& rightEntityDescriptor.hasAnyGenuineBasicVariables() && rightEntityDescriptor.hasAnyGenuineListVariables()) {
// Mixed models filter out the list variable
rightVariableNameIncludeList = rightEntityDescriptor.getGenuineBasicVariableDescriptorList().stream()
.map(GenuineVariableDescriptor::getVariableName)
.toList();
}
var leftPillarSelector =
buildPillarSelector(leftPillarSelectorConfig, configPolicy, leftVariableNameIncludeList, minimumCacheType,
randomSelection);
var rightPillarSelector =
buildPillarSelector(rightPillarSelectorConfig, configPolicy, rightVariableNameIncludeList, minimumCacheType,
randomSelection);
var variableDescriptorList =
deduceVariableDescriptorList(leftPillarSelector.getEntityDescriptor(), leftVariableNameIncludeList);
return new PillarSwapMoveSelector<>(leftPillarSelector, rightPillarSelector, variableDescriptorList, randomSelection);
}
private PillarSelector<Solution_> buildPillarSelector(PillarSelectorConfig pillarSelectorConfig,
HeuristicConfigPolicy<Solution_> configPolicy, List<String> variableNameIncludeList,
SelectionCacheType minimumCacheType, boolean randomSelection) {
return PillarSelectorFactory.<Solution_> create(pillarSelectorConfig)
.buildPillarSelector(configPolicy, config.getSubPillarType(),
(Class<? extends Comparator<Object>>) config.getSubPillarSequenceComparatorClass(), minimumCacheType,
SelectionOrder.fromRandomSelectionBoolean(randomSelection), variableNameIncludeList);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/RuinRecreateConstructionHeuristicDecider.java | package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider;
import ai.timefold.solver.core.impl.constructionheuristic.decider.forager.ConstructionHeuristicForager;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
final class RuinRecreateConstructionHeuristicDecider<Solution_>
extends ConstructionHeuristicDecider<Solution_> {
RuinRecreateConstructionHeuristicDecider(PhaseTermination<Solution_> termination,
ConstructionHeuristicForager<Solution_> forager) {
super("", termination, forager);
}
@Override
public boolean isLoggingEnabled() {
return false;
}
@Override
public void enableAssertions(EnvironmentMode environmentMode) {
throw new UnsupportedOperationException(
"Impossible state: Construction heuristics inside Ruin and Recreate moves cannot be asserted.");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.