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/selector/move
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/RuinRecreateConstructionHeuristicPhase.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import ai.timefold.solver.core.impl.constructionheuristic.ConstructionHeuristicPhase; import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.jspecify.annotations.NullMarked; @NullMarked public final class RuinRecreateConstructionHeuristicPhase<Solution_> extends DefaultConstructionHeuristicPhase<Solution_> implements ConstructionHeuristicPhase<Solution_> { private final Set<Object> elementsToRuinSet; // Store the original value list of elements that are not included in the initial list of ruined elements private final Map<Object, List<Object>> missingUpdatedElementsMap; RuinRecreateConstructionHeuristicPhase(RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> builder) { super(builder); this.elementsToRuinSet = Objects.requireNonNullElse(builder.elementsToRuin, Collections.emptySet()); this.missingUpdatedElementsMap = new IdentityHashMap<>(); } @Override protected ConstructionHeuristicPhaseScope<Solution_> buildPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex) { return new RuinRecreateConstructionHeuristicPhaseScope<>(solverScope, phaseIndex); } @Override protected boolean isNested() { return true; } @Override public String getPhaseTypeString() { return "Ruin & Recreate Construction Heuristics"; } @Override protected void doStep(ConstructionHeuristicStepScope<Solution_> stepScope) { if (!elementsToRuinSet.isEmpty()) { var listVariableDescriptor = stepScope.getPhaseScope().getSolverScope().getSolutionDescriptor() .getListVariableDescriptor(); var entity = stepScope.getStep().extractPlanningEntities().iterator().next(); if (!elementsToRuinSet.contains(entity)) { // Sometimes, the list of elements to be ruined does not include new destinations selected by the CH. // In these cases, we need to record the element list before making any move changes // so that it can be referenced to restore the solution to its original state when undoing changes. missingUpdatedElementsMap.computeIfAbsent(entity, e -> List.copyOf(listVariableDescriptor.getValue(e))); } } super.doStep(stepScope); } public Map<Object, List<Object>> getMissingUpdatedElementsMap() { return missingUpdatedElementsMap; } }
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/RuinRecreateConstructionHeuristicPhaseBuilder.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.List; import java.util.Set; import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.config.solver.termination.TerminationConfig; import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase; import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase.DefaultConstructionHeuristicPhaseBuilder; import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider; import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.termination.PhaseTermination; import ai.timefold.solver.core.impl.solver.termination.SolverTermination; import ai.timefold.solver.core.impl.solver.termination.TerminationFactory; public final class RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> extends DefaultConstructionHeuristicPhaseBuilder<Solution_> { public static <Solution_> RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> create(HeuristicConfigPolicy<Solution_> solverConfigPolicy, EntitySelectorConfig entitySelectorConfig) { var queuedEntityPlacerConfig = new QueuedEntityPlacerConfig() .withEntitySelectorConfig(entitySelectorConfig); var constructionHeuristicConfig = new ConstructionHeuristicPhaseConfig() .withEntityPlacerConfig(queuedEntityPlacerConfig); return create(solverConfigPolicy, constructionHeuristicConfig); } public static <Solution_> RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> create( HeuristicConfigPolicy<Solution_> solverConfigPolicy, ConstructionHeuristicPhaseConfig constructionHeuristicConfig) { var constructionHeuristicPhaseFactory = new RuinRecreateConstructionHeuristicPhaseFactory<Solution_>(constructionHeuristicConfig); var builder = (RuinRecreateConstructionHeuristicPhaseBuilder<Solution_>) constructionHeuristicPhaseFactory.getBuilder(0, false, solverConfigPolicy, (SolverTermination<Solution_>) TerminationFactory .<Solution_> create(new TerminationConfig()).buildTermination(solverConfigPolicy)); if (solverConfigPolicy.getMoveThreadCount() != null && solverConfigPolicy.getMoveThreadCount() >= 1) { builder.multithreaded = true; } return builder; } private final HeuristicConfigPolicy<Solution_> configPolicy; private final RuinRecreateConstructionHeuristicPhaseFactory<Solution_> constructionHeuristicPhaseFactory; private final PhaseTermination<Solution_> phaseTermination; Set<Object> elementsToRuin; List<Object> elementsToRecreate; private boolean multithreaded = false; RuinRecreateConstructionHeuristicPhaseBuilder(HeuristicConfigPolicy<Solution_> configPolicy, RuinRecreateConstructionHeuristicPhaseFactory<Solution_> constructionHeuristicPhaseFactory, PhaseTermination<Solution_> phaseTermination, EntityPlacer<Solution_> entityPlacer, ConstructionHeuristicDecider<Solution_> decider) { super(0, false, "", phaseTermination, entityPlacer, decider); this.configPolicy = configPolicy; this.constructionHeuristicPhaseFactory = constructionHeuristicPhaseFactory; this.phaseTermination = phaseTermination; } /** * In a multithreaded environment, the builder will be shared among all moves and threads. * Consequently, the list {@code elementsToRecreate} used by {@code getEntityPlacer} or the {@code decider}, * will be shared between the main and move threads. * This sharing can lead to race conditions. * The method creates a new copy of the builder and the decider to avoid race conditions. */ public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> ensureThreadSafe(InnerScoreDirector<Solution_, ?> scoreDirector) { if (multithreaded && scoreDirector.isDerived()) { return new RuinRecreateConstructionHeuristicPhaseBuilder<>(configPolicy, constructionHeuristicPhaseFactory, phaseTermination, super.getEntityPlacer().copy(), constructionHeuristicPhaseFactory.buildDecider(configPolicy, phaseTermination)); } return this; } public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> withElementsToRecreate(List<Object> elements) { this.elementsToRecreate = elements; return this; } public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> withElementsToRuin(Set<Object> elements) { this.elementsToRuin = elements; return this; } @Override public EntityPlacer<Solution_> getEntityPlacer() { var placer = super.getEntityPlacer(); if (elementsToRecreate == null || elementsToRecreate.isEmpty()) { return placer; } return placer.rebuildWithFilter((scoreDirector, selection) -> { for (var element : elementsToRecreate) { if (selection == element) { return true; } } return false; }); } @Override public DefaultConstructionHeuristicPhase<Solution_> build() { return new RuinRecreateConstructionHeuristicPhase<>(this); } }
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/RuinRecreateConstructionHeuristicPhaseFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory; import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.solver.termination.BasicPlumbingTermination; import ai.timefold.solver.core.impl.solver.termination.PhaseTermination; import ai.timefold.solver.core.impl.solver.termination.SolverTermination; final class RuinRecreateConstructionHeuristicPhaseFactory<Solution_> extends DefaultConstructionHeuristicPhaseFactory<Solution_> { RuinRecreateConstructionHeuristicPhaseFactory(ConstructionHeuristicPhaseConfig phaseConfig) { super(phaseConfig); } @Override protected RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> createBuilder( HeuristicConfigPolicy<Solution_> phaseConfigPolicy, SolverTermination<Solution_> solverTermination, int phaseIndex, boolean lastInitializingPhase, EntityPlacer<Solution_> entityPlacer) { var phaseTermination = PhaseTermination.bridge(new BasicPlumbingTermination<Solution_>(false)); return new RuinRecreateConstructionHeuristicPhaseBuilder<>(phaseConfigPolicy, this, phaseTermination, entityPlacer, buildDecider(phaseConfigPolicy, phaseTermination)); } @Override protected RuinRecreateConstructionHeuristicDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy, PhaseTermination<Solution_> termination) { return new RuinRecreateConstructionHeuristicDecider<>(termination, buildForager(configPolicy)); } }
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/RuinRecreateConstructionHeuristicPhaseScope.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.preview.api.move.Move; final class RuinRecreateConstructionHeuristicPhaseScope<Solution_> extends ConstructionHeuristicPhaseScope<Solution_> { public RuinRecreateConstructionHeuristicPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex) { super(solverScope, phaseIndex); } @Override public void addMoveEvaluationCount(Move<Solution_> move, long count) { // Nested phase does not count moves. } }
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/RuinRecreateMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; 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.move.director.VariableChangeRecordingScoreDirector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public final class RuinRecreateMove<Solution_> extends AbstractMove<Solution_> { private final GenuineVariableDescriptor<Solution_> genuineVariableDescriptor; private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; private final SolverScope<Solution_> solverScope; private final List<Object> ruinedEntityList; private final Set<Object> affectedValueSet; private Object[] recordedNewValues; public RuinRecreateMove(GenuineVariableDescriptor<Solution_> genuineVariableDescriptor, RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, SolverScope<Solution_> solverScope, List<Object> ruinedEntityList, Set<Object> affectedValueSet) { this.genuineVariableDescriptor = genuineVariableDescriptor; this.ruinedEntityList = ruinedEntityList; this.affectedValueSet = affectedValueSet; this.constructionHeuristicPhaseBuilder = constructionHeuristicPhaseBuilder; this.solverScope = solverScope; this.recordedNewValues = null; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { recordedNewValues = new Object[ruinedEntityList.size()]; var recordingScoreDirector = (VariableChangeRecordingScoreDirector<Solution_, ?>) scoreDirector; for (var ruinedEntity : ruinedEntityList) { recordingScoreDirector.beforeVariableChanged(genuineVariableDescriptor, ruinedEntity); genuineVariableDescriptor.setValue(ruinedEntity, null); recordingScoreDirector.afterVariableChanged(genuineVariableDescriptor, ruinedEntity); } recordingScoreDirector.triggerVariableListeners(); var constructionHeuristicPhase = (RuinRecreateConstructionHeuristicPhase<Solution_>) constructionHeuristicPhaseBuilder .ensureThreadSafe(recordingScoreDirector.getBacking()) .withElementsToRecreate(ruinedEntityList) .build(); var nestedSolverScope = new SolverScope<Solution_>(solverScope.getClock()); nestedSolverScope.setSolver(solverScope.getSolver()); nestedSolverScope.setScoreDirector(recordingScoreDirector.getBacking()); constructionHeuristicPhase.solvingStarted(nestedSolverScope); constructionHeuristicPhase.solve(nestedSolverScope); constructionHeuristicPhase.solvingEnded(nestedSolverScope); scoreDirector.triggerVariableListeners(); for (var i = 0; i < ruinedEntityList.size(); i++) { recordedNewValues[i] = genuineVariableDescriptor.getValue(ruinedEntityList.get(i)); } } @Override public Collection<?> getPlanningEntities() { return ruinedEntityList; } @Override public Collection<?> getPlanningValues() { return affectedValueSet; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return true; } @Override public Move<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { var rebasedRuinedEntityList = rebaseList(ruinedEntityList, destinationScoreDirector); var rebasedAffectedValueSet = rebaseSet(affectedValueSet, destinationScoreDirector); return new RuinRecreateMove<>(genuineVariableDescriptor, constructionHeuristicPhaseBuilder, solverScope, rebasedRuinedEntityList, rebasedAffectedValueSet); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RuinRecreateMove<?> that)) return false; return Objects.equals(genuineVariableDescriptor, that.genuineVariableDescriptor) && Objects.equals(ruinedEntityList, that.ruinedEntityList) && Objects.equals(affectedValueSet, that.affectedValueSet); } @Override public int hashCode() { return Objects.hash(genuineVariableDescriptor, ruinedEntityList, affectedValueSet); } @Override public String toString() { return "RuinMove{" + "entities=" + ruinedEntityList + ", newValues=" + ((recordedNewValues != null) ? Arrays.toString(recordedNewValues) : "?") + '}'; } }
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/RuinRecreateMoveIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.ArrayList; import java.util.Collections; import java.util.Random; 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.move.NoChangeMove; 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.solver.scope.SolverScope; import ai.timefold.solver.core.impl.util.CollectionUtils; final class RuinRecreateMoveIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final EntitySelector<Solution_> entitySelector; private final GenuineVariableDescriptor<Solution_> variableDescriptor; private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; private final SolverScope<Solution_> solverScope; private final int minimumRuinedCount; private final int maximumRuinedCount; private final Random workingRandom; public RuinRecreateMoveIterator(EntitySelector<Solution_> entitySelector, GenuineVariableDescriptor<Solution_> variableDescriptor, RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, SolverScope<Solution_> solverScope, int minimumRuinedCount, int maximumRuinedCount, Random workingRandom) { this.entitySelector = entitySelector; this.variableDescriptor = variableDescriptor; this.constructionHeuristicPhaseBuilder = constructionHeuristicPhaseBuilder; this.solverScope = solverScope; this.minimumRuinedCount = minimumRuinedCount; this.maximumRuinedCount = maximumRuinedCount; this.workingRandom = workingRandom; } @Override protected Move<Solution_> createUpcomingSelection() { var entityIterator = entitySelector.iterator(); var ruinedCount = workingRandom.nextInt(minimumRuinedCount, maximumRuinedCount + 1); var selectedEntityList = new ArrayList<>(ruinedCount); var affectedValueSet = CollectionUtils.newLinkedHashSet(ruinedCount); var selectedEntitySet = Collections.newSetFromMap(CollectionUtils.newIdentityHashMap(ruinedCount)); for (var i = 0; i < ruinedCount; i++) { var remainingAttempts = ruinedCount; while (true) { if (!entityIterator.hasNext()) { // Bail out; cannot select enough unique elements. return NoChangeMove.getInstance(); } var selectedEntity = entityIterator.next(); if (selectedEntitySet.add(selectedEntity)) { selectedEntityList.add(selectedEntity); var affectedValue = variableDescriptor.getValue(selectedEntity); if (affectedValue != null) { affectedValueSet.add(affectedValue); } break; } else { remainingAttempts--; } if (remainingAttempts == 0) { // Bail out; cannot select enough unique elements. return NoChangeMove.getInstance(); } } } return new RuinRecreateMove<>(variableDescriptor, constructionHeuristicPhaseBuilder, solverScope, selectedEntityList, affectedValueSet); } }
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/RuinRecreateMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Iterator; 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.entity.EntitySelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.apache.commons.math3.util.CombinatoricsUtils; final class RuinRecreateMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final EntitySelector<Solution_> entitySelector; private final GenuineVariableDescriptor<Solution_> variableDescriptor; private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; private final CountSupplier minimumSelectedCountSupplier; private final CountSupplier maximumSelectedCountSupplier; private SolverScope<Solution_> solverScope; public RuinRecreateMoveSelector(EntitySelector<Solution_> entitySelector, GenuineVariableDescriptor<Solution_> variableDescriptor, RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, CountSupplier minimumSelectedCountSupplier, CountSupplier maximumSelectedCountSupplier) { super(); this.entitySelector = entitySelector; this.variableDescriptor = variableDescriptor; this.constructionHeuristicPhaseBuilder = constructionHeuristicPhaseBuilder; this.minimumSelectedCountSupplier = minimumSelectedCountSupplier; this.maximumSelectedCountSupplier = maximumSelectedCountSupplier; phaseLifecycleSupport.addEventListener(entitySelector); } @Override public long getSize() { var totalSize = 0L; var entityCount = entitySelector.getSize(); var minimumSelectedCount = minimumSelectedCountSupplier.applyAsInt(entityCount); var maximumSelectedCount = maximumSelectedCountSupplier.applyAsInt(entityCount); for (int selectedCount = minimumSelectedCount; selectedCount <= maximumSelectedCount; selectedCount++) { // Order is significant, and each entity can only be picked once totalSize += CombinatoricsUtils.factorial((int) entityCount) / CombinatoricsUtils.factorial(selectedCount); } return totalSize; } @Override public boolean isCountable() { return entitySelector.isCountable(); } @Override public boolean isNeverEnding() { return entitySelector.isNeverEnding(); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); this.solverScope = solverScope; this.workingRandom = solverScope.getWorkingRandom(); } @Override public Iterator<Move<Solution_>> iterator() { var entitySelectorSize = entitySelector.getSize(); return new RuinRecreateMoveIterator<>(entitySelector, variableDescriptor, constructionHeuristicPhaseBuilder, solverScope, minimumSelectedCountSupplier.applyAsInt(entitySelectorSize), maximumSelectedCountSupplier.applyAsInt(entitySelectorSize), 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/generic/RuinRecreateMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; 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.move.generic.RuinRecreateMoveSelectorConfig; 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.EntitySelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; public final class RuinRecreateMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, RuinRecreateMoveSelectorConfig> { private final RuinRecreateMoveSelectorConfig ruinRecreateMoveSelectorConfig; public RuinRecreateMoveSelectorFactory(RuinRecreateMoveSelectorConfig ruinRecreateMoveSelectorConfig) { super(ruinRecreateMoveSelectorConfig); this.ruinRecreateMoveSelectorConfig = ruinRecreateMoveSelectorConfig; } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { CountSupplier minimumSelectedSupplier = ruinRecreateMoveSelectorConfig::determineMinimumRuinedCount; CountSupplier maximumSelectedSupplier = ruinRecreateMoveSelectorConfig::determineMaximumRuinedCount; var entitySelectorConfig = config.getEntitySelectorConfig(); if (entitySelectorConfig == null) { entitySelectorConfig = new EntitySelectorConfig(); } var ruinRecreateEntitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, SelectionOrder.fromRandomSelectionBoolean(true)); var genuineVariableDescriptorList = ruinRecreateEntitySelector.getEntityDescriptor().getGenuineBasicVariableDescriptorList(); if (genuineVariableDescriptorList.size() != 1 && config.getVariableName() == null) { throw new UnsupportedOperationException( """ The entity class %s contains several variables (%s), and it cannot be deduced automatically. Maybe set the property variableName.""" .formatted( ruinRecreateEntitySelector.getEntityDescriptor().getEntityClass().getName(), genuineVariableDescriptorList.stream().map(GenuineVariableDescriptor::getVariableName) .toList())); } var variableDescriptor = genuineVariableDescriptorList.get(0); if (genuineVariableDescriptorList.size() > 1) { variableDescriptor = genuineVariableDescriptorList.stream() .filter(v -> v.getVariableName().equals(config.getVariableName())).findFirst().orElse(null); } if (variableDescriptor == null) { throw new UnsupportedOperationException("The entity class %s has no variable named %s." .formatted(ruinRecreateEntitySelector.getEntityDescriptor().getEntityClass(), config.getVariableName())); } var nestedEntitySelectorConfig = getDefaultEntitySelectorConfigForEntity(configPolicy, ruinRecreateEntitySelector.getEntityDescriptor()); var constructionHeuristicPhaseBuilder = RuinRecreateConstructionHeuristicPhaseBuilder.create(configPolicy, nestedEntitySelectorConfig); return new RuinRecreateMoveSelector<>(ruinRecreateEntitySelector, variableDescriptor, constructionHeuristicPhaseBuilder, minimumSelectedSupplier, maximumSelectedSupplier); } }
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/SwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.ArrayList; import java.util.Arrays; 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.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SwapMove<Solution_> extends AbstractMove<Solution_> { protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList; protected final Object leftEntity; protected final Object rightEntity; public SwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, Object leftEntity, Object rightEntity) { this.variableDescriptorList = variableDescriptorList; this.leftEntity = leftEntity; this.rightEntity = rightEntity; } public Object getLeftEntity() { return leftEntity; } public Object getRightEntity() { return rightEntity; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { if (leftEntity == rightEntity) { return false; } for (var variableDescriptor : variableDescriptorList) { var leftValue = variableDescriptor.getValue(leftEntity); var rightValue = variableDescriptor.getValue(rightEntity); if (!Objects.equals(leftValue, rightValue)) { return true; } } return false; } @Override public SwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SwapMove<>(variableDescriptorList, destinationScoreDirector.lookUpWorkingObject(leftEntity), destinationScoreDirector.lookUpWorkingObject(rightEntity)); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; for (var variableDescriptor : variableDescriptorList) { var oldLeftValue = variableDescriptor.getValue(leftEntity); var oldRightValue = variableDescriptor.getValue(rightEntity); if (!Objects.equals(oldLeftValue, oldRightValue)) { castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); } } } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { StringBuilder moveTypeDescription = new StringBuilder(20 * (variableDescriptorList.size() + 1)); moveTypeDescription.append(getClass().getSimpleName()).append("("); String delimiter = ""; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { moveTypeDescription.append(delimiter).append(variableDescriptor.getSimpleEntityAndVariableName()); delimiter = ", "; } moveTypeDescription.append(")"); return moveTypeDescription.toString(); } @Override public Collection<? extends Object> getPlanningEntities() { return Arrays.asList(leftEntity, rightEntity); } @Override public Collection<? extends Object> getPlanningValues() { List<Object> values = new ArrayList<>(variableDescriptorList.size() * 2); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { values.add(variableDescriptor.getValue(leftEntity)); values.add(variableDescriptor.getValue(rightEntity)); } return values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SwapMove<?> swapMove = (SwapMove<?>) o; return Objects.equals(variableDescriptorList, swapMove.variableDescriptorList) && Objects.equals(leftEntity, swapMove.leftEntity) && Objects.equals(rightEntity, swapMove.rightEntity); } @Override public int hashCode() { return Objects.hash(variableDescriptorList, leftEntity, rightEntity); } @Override public String toString() { StringBuilder s = new StringBuilder(variableDescriptorList.size() * 16); s.append(leftEntity).append(" {"); appendVariablesToString(s, leftEntity); s.append("} <-> "); s.append(rightEntity).append(" {"); appendVariablesToString(s, rightEntity); s.append("}"); return s.toString(); } protected void appendVariablesToString(StringBuilder s, Object entity) { boolean first = true; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { if (!first) { s.append(", "); } var value = variableDescriptor.getValue(entity); 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/SwapMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; 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.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.common.iterator.AbstractOriginalSwapIterator; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractRandomSwapIterator; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.ChainedSwapMove; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class SwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { protected final EntitySelector<Solution_> leftEntitySelector; protected final EntitySelector<Solution_> rightEntitySelector; protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList; protected final boolean randomSelection; protected final boolean anyChained; protected List<SingletonInverseVariableSupply> inverseVariableSupplyList = null; public SwapMoveSelector(EntitySelector<Solution_> leftEntitySelector, EntitySelector<Solution_> rightEntitySelector, List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, boolean randomSelection) { this.leftEntitySelector = leftEntitySelector; this.rightEntitySelector = rightEntitySelector; this.variableDescriptorList = variableDescriptorList; this.randomSelection = randomSelection; EntityDescriptor<Solution_> leftEntityDescriptor = leftEntitySelector.getEntityDescriptor(); EntityDescriptor<Solution_> rightEntityDescriptor = rightEntitySelector.getEntityDescriptor(); if (!leftEntityDescriptor.getEntityClass().equals(rightEntityDescriptor.getEntityClass())) { throw new IllegalStateException("The selector (" + this + ") has a leftEntitySelector's entityClass (" + leftEntityDescriptor.getEntityClass() + ") which is not equal to the rightEntitySelector's entityClass (" + rightEntityDescriptor.getEntityClass() + ")."); } boolean anyChained = false; if (variableDescriptorList.isEmpty()) { throw new IllegalStateException("The selector (" + this + ")'s variableDescriptors (" + variableDescriptorList + ") is empty."); } for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { if (!variableDescriptor.getEntityDescriptor().getEntityClass().isAssignableFrom( leftEntityDescriptor.getEntityClass())) { throw new IllegalStateException("The selector (" + this + ") has a variableDescriptor with a entityClass (" + variableDescriptor.getEntityDescriptor().getEntityClass() + ") which is not equal or a superclass to the leftEntitySelector's entityClass (" + leftEntityDescriptor.getEntityClass() + ")."); } boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (isChained) { anyChained = true; } } this.anyChained = anyChained; phaseLifecycleSupport.addEventListener(leftEntitySelector); if (leftEntitySelector != rightEntitySelector) { phaseLifecycleSupport.addEventListener(rightEntitySelector); } } @Override public boolean supportsPhaseAndSolverCaching() { return !anyChained; } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); if (anyChained) { inverseVariableSupplyList = new ArrayList<>(variableDescriptorList.size()); SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager(); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { SingletonInverseVariableSupply inverseVariableSupply; boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (isChained) { inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor)); } else { inverseVariableSupply = null; } inverseVariableSupplyList.add(inverseVariableSupply); } } } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); if (anyChained) { inverseVariableSupplyList = null; } } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return leftEntitySelector.isCountable() && rightEntitySelector.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || leftEntitySelector.isNeverEnding() || rightEntitySelector.isNeverEnding(); } @Override public long getSize() { return AbstractOriginalSwapIterator.getSize(leftEntitySelector, rightEntitySelector); } @Override public Iterator<Move<Solution_>> iterator() { if (!randomSelection) { return new AbstractOriginalSwapIterator<>(leftEntitySelector, rightEntitySelector) { @Override protected Move<Solution_> newSwapSelection(Object leftSubSelection, Object rightSubSelection) { return anyChained ? new ChainedSwapMove<>(variableDescriptorList, inverseVariableSupplyList, leftSubSelection, rightSubSelection) : new SwapMove<>(variableDescriptorList, leftSubSelection, rightSubSelection); } }; } else { return new AbstractRandomSwapIterator<>(leftEntitySelector, rightEntitySelector) { @Override protected Move<Solution_> newSwapSelection(Object leftSubSelection, Object rightSubSelection) { return anyChained ? new ChainedSwapMove<>(variableDescriptorList, inverseVariableSupplyList, leftSubSelection, rightSubSelection) : new SwapMove<>(variableDescriptorList, leftSubSelection, rightSubSelection); } }; } } @Override public String toString() { return getClass().getSimpleName() + "(" + leftEntitySelector + ", " + rightEntitySelector + ")"; } }
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/SwapMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.ArrayList; import java.util.Collection; 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.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.common.ValueRangeRecorderId; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SwapMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, SwapMoveSelectorConfig> { private static final Logger LOGGER = LoggerFactory.getLogger(SwapMoveSelectorFactory.class); public SwapMoveSelectorFactory(SwapMoveSelectorConfig moveSelectorConfig) { // We copy the configuration, // as the settings may be updated during the autoconfiguration of the entity value range super(Objects.requireNonNull(moveSelectorConfig).copyConfig()); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var entitySelectorConfig = Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new); var secondaryEntitySelectorConfig = Objects.requireNonNullElseGet(config.getSecondaryEntitySelectorConfig(), entitySelectorConfig::copyConfig); var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); // When enabling entity value range filtering, // the recorder ID from the origin selector is required for FilteringEntityValueRangeSelector // to replay the selected value and return only reachable values. var entityDescriptor = deduceEntityDescriptor(configPolicy, entitySelectorConfig.getEntityClass()); var enableEntityValueRangeFilter = entityDescriptor.getSolutionDescriptor().getBasicVariableDescriptorList() .stream() .anyMatch(v -> !v.canExtractValueRangeFromSolution()); // A null ID means to turn off the entity value range filtering String entityRecorderId = null; if (enableEntityValueRangeFilter) { if (entitySelectorConfig.getId() == null && entitySelectorConfig.getMimicSelectorRef() == null) { var entityName = Objects.requireNonNull(entityDescriptor.getEntityClass().getSimpleName()); // We set the id to make sure the value selector will use the mimic recorder entityRecorderId = ConfigUtils.addRandomSuffix(entityName, configPolicy.getRandom()); entitySelectorConfig.setId(entityRecorderId); } else { entityRecorderId = entitySelectorConfig.getId() != null ? entitySelectorConfig.getId() : entitySelectorConfig.getMimicSelectorRef(); } } var leftEntitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); var rightEntitySelector = EntitySelectorFactory.<Solution_> create(secondaryEntitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder, new ValueRangeRecorderId(entityRecorderId, true)); var variableDescriptorList = deduceBasicVariableDescriptorList(entityDescriptor, config.getVariableNameIncludeList()); return new SwapMoveSelector<>(leftEntitySelector, rightEntitySelector, variableDescriptorList, randomSelection); } @Override protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { var onlyEntityDescriptor = config.getEntitySelectorConfig() == null ? null : EntitySelectorFactory.<Solution_> create(config.getEntitySelectorConfig()) .extractEntityDescriptor(configPolicy); if (config.getSecondaryEntitySelectorConfig() != null) { var onlySecondaryEntityDescriptor = EntitySelectorFactory.<Solution_> create(config.getSecondaryEntitySelectorConfig()) .extractEntityDescriptor(configPolicy); if (onlyEntityDescriptor != onlySecondaryEntityDescriptor) { throw new IllegalArgumentException( "The entitySelector (%s)'s entityClass (%s) and secondaryEntitySelectorConfig (%s)'s entityClass (%s) must be the same entity class." .formatted(config.getEntitySelectorConfig(), onlyEntityDescriptor == null ? null : onlyEntityDescriptor.getEntityClass(), config.getSecondaryEntitySelectorConfig(), onlySecondaryEntityDescriptor == null ? null : onlySecondaryEntityDescriptor.getEntityClass())); } } if (onlyEntityDescriptor != null) { var variableDescriptorList = onlyEntityDescriptor.getGenuineVariableDescriptorList(); // If there is a single list variable, unfold to list swap move selector config. if (variableDescriptorList.size() == 1 && variableDescriptorList.get(0).isListVariable()) { return buildListSwapMoveSelectorConfig(variableDescriptorList.get(0), true); } // No need for unfolding or deducing return null; } Collection<EntityDescriptor<Solution_>> entityDescriptors = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors(); return buildUnfoldedMoveSelectorConfig(configPolicy, entityDescriptors); } protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy, Collection<EntityDescriptor<Solution_>> entityDescriptors) { var moveSelectorConfigList = new ArrayList<MoveSelectorConfig>(entityDescriptors.size()); // When using a mixed model, // we only fetch basic variables to avoiding creating a list move, // and delegate it to the ListSwapMoveSelectorFactory. // The strategy aims to provide a more normalized move selector collection for mixed models. var variableDescriptorList = configPolicy.getSolutionDescriptor().hasBothBasicAndListVariables() ? entityDescriptors.iterator().next().getGenuineBasicVariableDescriptorList() : entityDescriptors.iterator().next().getGenuineVariableDescriptorList(); // Only unfold into list swap move selector for the basic scenario with 1 entity and 1 list variable. if (entityDescriptors.size() == 1 && variableDescriptorList.size() == 1 && variableDescriptorList.get(0).isListVariable()) { // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() var childMoveSelectorConfig = buildListSwapMoveSelectorConfig(variableDescriptorList.get(0), false); moveSelectorConfigList.add(childMoveSelectorConfig); } else { // More complex scenarios do not support unfolding into list swap => fail fast if there is any list variable. for (var entityDescriptor : entityDescriptors) { if (!entityDescriptor.hasAnyGenuineBasicVariables()) { // We filter out entities that do not have basic variables (e.g., mixed models) continue; } // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() var childMoveSelectorConfig = new SwapMoveSelectorConfig(); var childEntitySelectorConfig = new EntitySelectorConfig(config.getEntitySelectorConfig()); if (childEntitySelectorConfig.getMimicSelectorRef() == null) { childEntitySelectorConfig.setEntityClass(entityDescriptor.getEntityClass()); } childMoveSelectorConfig.setEntitySelectorConfig(childEntitySelectorConfig); if (config.getSecondaryEntitySelectorConfig() != null) { EntitySelectorConfig childSecondaryEntitySelectorConfig = new EntitySelectorConfig(config.getSecondaryEntitySelectorConfig()); if (childSecondaryEntitySelectorConfig.getMimicSelectorRef() == null) { childSecondaryEntitySelectorConfig.setEntityClass(entityDescriptor.getEntityClass()); } childMoveSelectorConfig.setSecondaryEntitySelectorConfig(childSecondaryEntitySelectorConfig); } childMoveSelectorConfig.setVariableNameIncludeList(config.getVariableNameIncludeList()); moveSelectorConfigList.add(childMoveSelectorConfig); } } if (moveSelectorConfigList.isEmpty()) { throw new IllegalStateException("The swap move selector cannot be created when there is no basic variables."); } MoveSelectorConfig<?> unfoldedMoveSelectorConfig; if (moveSelectorConfigList.size() == 1) { unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0); } else { unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList); } unfoldedMoveSelectorConfig.inheritFolded(config); return unfoldedMoveSelectorConfig; } private ListSwapMoveSelectorConfig buildListSwapMoveSelectorConfig(VariableDescriptor<?> variableDescriptor, boolean inheritFoldedConfig) { LOGGER.warn( """ The swapMoveSelectorConfig ({}) 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, ListSwapMoveSelectorConfig.class.getSimpleName()); var listSwapMoveSelectorConfig = new ListSwapMoveSelectorConfig(); var childValueSelectorConfig = new ValueSelectorConfig( new ValueSelectorConfig(variableDescriptor.getVariableName())); listSwapMoveSelectorConfig.setValueSelectorConfig(childValueSelectorConfig); if (inheritFoldedConfig) { listSwapMoveSelectorConfig.inheritFolded(config); } return listSwapMoveSelectorConfig; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/ChainedChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.ChangeMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ChainedChangeMove<Solution_> extends ChangeMove<Solution_> { protected final Object oldTrailingEntity; protected final Object newTrailingEntity; public ChainedChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue, SingletonInverseVariableSupply inverseVariableSupply) { super(variableDescriptor, entity, toPlanningValue); oldTrailingEntity = inverseVariableSupply.getInverseSingleton(entity); newTrailingEntity = toPlanningValue == null ? null : inverseVariableSupply.getInverseSingleton(toPlanningValue); } public ChainedChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue, Object oldTrailingEntity, Object newTrailingEntity) { super(variableDescriptor, entity, toPlanningValue); this.oldTrailingEntity = oldTrailingEntity; this.newTrailingEntity = newTrailingEntity; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return super.isMoveDoable(scoreDirector) && !Objects.equals(entity, toPlanningValue); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var oldValue = variableDescriptor.getValue(entity); // Close the old chain if (oldTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingEntity, oldValue); } // Change the entity castScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue); // Reroute the new chain if (newTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, entity); } } @Override public ChainedChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ChainedChangeMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(entity), destinationScoreDirector.lookUpWorkingObject(toPlanningValue), destinationScoreDirector.lookUpWorkingObject(oldTrailingEntity), destinationScoreDirector.lookUpWorkingObject(newTrailingEntity)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/ChainedSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.ArrayList; 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.BasicVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.SwapMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ChainedSwapMove<Solution_> extends SwapMove<Solution_> { protected final List<Object> oldLeftTrailingEntityList; protected final List<Object> oldRightTrailingEntityList; public ChainedSwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, List<SingletonInverseVariableSupply> inverseVariableSupplyList, Object leftEntity, Object rightEntity) { super(variableDescriptorList, leftEntity, rightEntity); oldLeftTrailingEntityList = new ArrayList<>(inverseVariableSupplyList.size()); oldRightTrailingEntityList = new ArrayList<>(inverseVariableSupplyList.size()); for (SingletonInverseVariableSupply inverseVariableSupply : inverseVariableSupplyList) { boolean hasSupply = inverseVariableSupply != null; oldLeftTrailingEntityList.add(hasSupply ? inverseVariableSupply.getInverseSingleton(leftEntity) : null); oldRightTrailingEntityList.add(hasSupply ? inverseVariableSupply.getInverseSingleton(rightEntity) : null); } } public ChainedSwapMove(List<GenuineVariableDescriptor<Solution_>> genuineVariableDescriptors, Object leftEntity, Object rightEntity, List<Object> oldLeftTrailingEntityList, List<Object> oldRightTrailingEntityList) { super(genuineVariableDescriptors, leftEntity, rightEntity); this.oldLeftTrailingEntityList = oldLeftTrailingEntityList; this.oldRightTrailingEntityList = oldRightTrailingEntityList; } // ************************************************************************ // Worker methods // ************************************************************************ @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { for (var i = 0; i < variableDescriptorList.size(); i++) { GenuineVariableDescriptor<Solution_> variableDescriptor = variableDescriptorList.get(i); var oldLeftValue = variableDescriptor.getValue(leftEntity); var oldRightValue = variableDescriptor.getValue(rightEntity); if (!Objects.equals(oldLeftValue, oldRightValue)) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (!isChained) { castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); } else { var oldLeftTrailingEntity = oldLeftTrailingEntityList.get(i); var oldRightTrailingEntity = oldRightTrailingEntityList.get(i); if (oldRightValue == leftEntity) { // Change the right entity castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); // Change the left entity castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightEntity); // Reroute the new left chain if (oldRightTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldRightTrailingEntity, leftEntity); } } else if (oldLeftValue == rightEntity) { // Change the right entity castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); // Change the left entity castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftEntity); // Reroute the new left chain if (oldLeftTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldLeftTrailingEntity, rightEntity); } } else { // Change the left entity castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); // Change the right entity castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); // Reroute the new left chain if (oldRightTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldRightTrailingEntity, leftEntity); } // Reroute the new right chain if (oldLeftTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldLeftTrailingEntity, rightEntity); } } } } } } @Override public ChainedSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ChainedSwapMove<>(variableDescriptorList, destinationScoreDirector.lookUpWorkingObject(leftEntity), destinationScoreDirector.lookUpWorkingObject(rightEntity), rebaseList(oldLeftTrailingEntityList, destinationScoreDirector), rebaseList(oldRightTrailingEntityList, destinationScoreDirector)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/KOptMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.ArrayList; import java.util.Arrays; 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.anchor.AnchorVariableSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class KOptMove<Solution_> extends AbstractMove<Solution_> { protected final GenuineVariableDescriptor<Solution_> variableDescriptor; // TODO remove me to enable multithreaded solving, but first fix https://issues.redhat.com/browse/PLANNER-1250 protected final SingletonInverseVariableSupply inverseVariableSupply; protected final AnchorVariableSupply anchorVariableSupply; protected final Object entity; protected final Object[] values; public KOptMove(GenuineVariableDescriptor<Solution_> variableDescriptor, SingletonInverseVariableSupply inverseVariableSupply, AnchorVariableSupply anchorVariableSupply, Object entity, Object[] values) { this.variableDescriptor = variableDescriptor; this.inverseVariableSupply = inverseVariableSupply; this.anchorVariableSupply = anchorVariableSupply; this.entity = entity; this.values = values; } public String getVariableName() { return variableDescriptor.getVariableName(); } public Object getEntity() { return entity; } public Object[] getValues() { return values; } // ************************************************************************ // Worker methods // ************************************************************************ public int getK() { return 1 + values.length; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { Object firstAnchor = anchorVariableSupply.getAnchor(entity); Object firstValue = variableDescriptor.getValue(entity); Object formerAnchor = firstAnchor; Object formerValue = firstValue; for (Object value : values) { Object anchor = variableDescriptor.isValuePotentialAnchor(value) ? value : anchorVariableSupply.getAnchor(value); if (anchor == formerAnchor && compareValuesInSameChain(formerValue, value) >= 0) { return false; } formerAnchor = anchor; formerValue = value; } if (firstAnchor == formerAnchor && compareValuesInSameChain(formerValue, firstValue) >= 0) { return false; } return true; } protected int compareValuesInSameChain(Object a, Object b) { if (a == b) { return 0; } Object afterA = inverseVariableSupply.getInverseSingleton(a); while (afterA != null) { if (afterA == b) { return 1; } afterA = inverseVariableSupply.getInverseSingleton(afterA); } return -1; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var firstValue = variableDescriptor.getValue(entity); var formerEntity = entity; for (Object value : values) { if (formerEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, formerEntity, value); } formerEntity = inverseVariableSupply.getInverseSingleton(value); } if (formerEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, formerEntity, firstValue); } } @Override public KOptMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { throw new UnsupportedOperationException("https://issues.redhat.com/browse/PLANNER-1250"); // TODO test also disabled // return new KOptMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, // destinationScoreDirector.lookUpWorkingObject(entity), // rebaseArray(values, destinationScoreDirector)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<?> getPlanningEntities() { List<Object> allEntityList = new ArrayList<>(values.length + 1); allEntityList.add(entity); for (int i = 0; i < values.length; i++) { Object value = values[i]; allEntityList.add(inverseVariableSupply.getInverseSingleton(value)); } return allEntityList; } @Override public Collection<?> getPlanningValues() { List<Object> allValueList = new ArrayList<>(values.length + 1); allValueList.add(variableDescriptor.getValue(entity)); Collections.addAll(allValueList, values); return allValueList; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final KOptMove<?> kOptMove = (KOptMove<?>) o; return Objects.equals(entity, kOptMove.entity) && Arrays.equals(values, kOptMove.values); } @Override public int hashCode() { return Objects.hash(entity, Arrays.hashCode(values)); } @Override public String toString() { Object leftValue = variableDescriptor.getValue(entity); StringBuilder builder = new StringBuilder(80 * values.length); builder.append(entity).append(" {").append(leftValue); for (int i = 0; i < values.length; i++) { Object value = values[i]; Object oldEntity = inverseVariableSupply.getInverseSingleton(value); builder.append("} -kOpt-> ").append(oldEntity).append(" {").append(value); } builder.append("}"); return builder.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/KOptMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Arrays; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.variable.anchor.AnchorVariableDemand; import ai.timefold.solver.core.impl.domain.variable.anchor.AnchorVariableSupply; 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.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class KOptMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { protected final EntitySelector<Solution_> entitySelector; protected final ValueSelector<Solution_>[] valueSelectors; protected final boolean randomSelection; protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected SingletonInverseVariableSupply inverseVariableSupply; protected AnchorVariableSupply anchorVariableSupply; public KOptMoveSelector(EntitySelector<Solution_> entitySelector, ValueSelector<Solution_>[] valueSelectors, boolean randomSelection) { this.entitySelector = entitySelector; this.valueSelectors = valueSelectors; this.randomSelection = randomSelection; if (!randomSelection) { throw new UnsupportedOperationException( "Non randomSelection (such as original selection) is not yet supported on " + KOptMoveSelector.class.getSimpleName() + "."); // TODO } variableDescriptor = valueSelectors[0].getVariableDescriptor(); boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (!isChained) { throw new IllegalStateException("The selector (%s)'s valueSelector's variableDescriptor (%s) must be chained (%s)." .formatted(this, variableDescriptor, isChained)); } if (!variableDescriptor.getEntityDescriptor().getEntityClass().isAssignableFrom( entitySelector.getEntityDescriptor().getEntityClass())) { throw new IllegalStateException("The selector (" + this + ") has a valueSelector with a entityClass (" + variableDescriptor.getEntityDescriptor().getEntityClass() + ") which is not equal or a superclass to the entitySelector's entityClass (" + entitySelector.getEntityDescriptor().getEntityClass() + ")."); } phaseLifecycleSupport.addEventListener(entitySelector); for (ValueSelector<Solution_> valueSelector : valueSelectors) { if (valueSelector.getVariableDescriptor() != variableDescriptor) { throw new IllegalStateException("The selector (" + this + ") has a valueSelector with a variableDescriptor (" + valueSelector.getVariableDescriptor() + ") that differs from the first variableDescriptor (" + variableDescriptor + ")."); } phaseLifecycleSupport.addEventListener(valueSelector); } } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager(); inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor)); anchorVariableSupply = supplyManager.demand(new AnchorVariableDemand<>(variableDescriptor)); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); inverseVariableSupply = null; anchorVariableSupply = null; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { if (!entitySelector.isCountable()) { return false; } for (ValueSelector<Solution_> valueSelector : valueSelectors) { if (!valueSelector.isCountable()) { return false; } } return true; } @Override public boolean isNeverEnding() { if (randomSelection || entitySelector.isNeverEnding()) { return true; } for (ValueSelector<Solution_> valueSelector : valueSelectors) { if (valueSelector.isNeverEnding()) { return true; } } return false; } @Override public long getSize() { throw new UnsupportedOperationException("Not yet supported."); // TODO // if (valueSelector instanceof IterableSelector) { // return entitySelector.getSize() * (long) Math.pow(((IterableSelector) valueSelector).getSize(), K); // } else { // } } @Override public Iterator<Move<Solution_>> iterator() { if (!randomSelection) { throw new UnsupportedOperationException( "Non randomSelection (such as original selection) is not yet supported on " + KOptMoveSelector.class.getSimpleName() + "."); // TODO } else { final Iterator<Object> entityIterator = entitySelector.iterator(); return new UpcomingSelectionIterator<>() { @Override protected Move<Solution_> createUpcomingSelection() { // TODO currently presumes that entitySelector and all valueSelectors are never ending, despite the hasNext() checks if (!entityIterator.hasNext()) { return noUpcomingSelection(); } Object entity = entityIterator.next(); Object[] values = new Object[valueSelectors.length]; for (int i = 0; i < valueSelectors.length; i++) { Iterator<Object> valueIterator = valueSelectors[i].iterator(entity); if (!valueIterator.hasNext()) { return noUpcomingSelection(); } values[i] = valueIterator.next(); } return new KOptMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, entity, values); } }; } } @Override public String toString() { return getClass().getSimpleName() + "(" + entitySelector + ", " + Arrays.toString(valueSelectors) + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/KOptMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; 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.move.generic.chained.KOptMoveSelectorConfig; 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.EntitySelector; 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.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class KOptMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, KOptMoveSelectorConfig> { private static final int K = 3; public KOptMoveSelectorFactory(KOptMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { EntitySelectorConfig entitySelectorConfig = Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new); ValueSelectorConfig valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); EntitySelector<Solution_> entitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); ValueSelector<Solution_>[] valueSelectors = new ValueSelector[K - 1]; for (int i = 0; i < valueSelectors.length; i++) { valueSelectors[i] = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder); } return new KOptMoveSelector<>(entitySelector, valueSelectors, randomSelection); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Collection; import java.util.Collections; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SubChainChangeMove<Solution_> extends AbstractMove<Solution_> { protected final SubChain subChain; protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final Object toPlanningValue; protected final Object oldTrailingLastEntity; protected final Object newTrailingEntity; public SubChainChangeMove(SubChain subChain, GenuineVariableDescriptor<Solution_> variableDescriptor, SingletonInverseVariableSupply inverseVariableSupply, Object toPlanningValue) { this.subChain = subChain; this.variableDescriptor = variableDescriptor; this.toPlanningValue = toPlanningValue; oldTrailingLastEntity = inverseVariableSupply.getInverseSingleton(subChain.getLastEntity()); newTrailingEntity = toPlanningValue == null ? null : inverseVariableSupply.getInverseSingleton(toPlanningValue); } public SubChainChangeMove(SubChain subChain, GenuineVariableDescriptor<Solution_> variableDescriptor, Object toPlanningValue, Object oldTrailingLastEntity, Object newTrailingEntity) { this.subChain = subChain; this.variableDescriptor = variableDescriptor; this.toPlanningValue = toPlanningValue; this.oldTrailingLastEntity = oldTrailingLastEntity; this.newTrailingEntity = newTrailingEntity; } public String getVariableName() { return variableDescriptor.getVariableName(); } public SubChain getSubChain() { return subChain; } public Object getToPlanningValue() { return toPlanningValue; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { if (subChain.getEntityList().contains(toPlanningValue)) { return false; } Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity()); return !Objects.equals(oldFirstValue, toPlanningValue); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var firstEntity = subChain.getFirstEntity(); var lastEntity = subChain.getLastEntity(); var oldFirstValue = variableDescriptor.getValue(firstEntity); // Close the old chain var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; if (oldTrailingLastEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingLastEntity, oldFirstValue); } // Change the entity castScoreDirector.changeVariableFacade(variableDescriptor, firstEntity, toPlanningValue); // Reroute the new chain if (newTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, lastEntity); } } @Override public SubChainChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubChainChangeMove<>(subChain.rebase(destinationScoreDirector), variableDescriptor, destinationScoreDirector.lookUpWorkingObject(toPlanningValue), destinationScoreDirector.lookUpWorkingObject(oldTrailingLastEntity), destinationScoreDirector.lookUpWorkingObject(newTrailingEntity)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<? extends Object> getPlanningEntities() { return subChain.getEntityList(); } @Override public Collection<? extends Object> getPlanningValues() { return Collections.singletonList(toPlanningValue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SubChainChangeMove<?> other = (SubChainChangeMove<?>) o; return Objects.equals(subChain, other.subChain) && Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(toPlanningValue, other.toPlanningValue); } @Override public int hashCode() { return Objects.hash(subChain, variableDescriptor, toPlanningValue); } @Override public String toString() { Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity()); return subChain.toDottedString() + " {" + oldFirstValue + " -> " + toPlanningValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainChangeMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Collections; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class SubChainChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { protected final SubChainSelector<Solution_> subChainSelector; protected final IterableValueSelector<Solution_> valueSelector; protected final boolean randomSelection; protected final boolean selectReversingMoveToo; protected SingletonInverseVariableSupply inverseVariableSupply = null; public SubChainChangeMoveSelector(SubChainSelector<Solution_> subChainSelector, IterableValueSelector<Solution_> valueSelector, boolean randomSelection, boolean selectReversingMoveToo) { this.subChainSelector = subChainSelector; this.valueSelector = valueSelector; this.randomSelection = randomSelection; this.selectReversingMoveToo = selectReversingMoveToo; if (subChainSelector.getVariableDescriptor() != valueSelector.getVariableDescriptor()) { throw new IllegalStateException("The selector (" + this + ") has a subChainSelector (" + subChainSelector + ") with variableDescriptor (" + subChainSelector.getVariableDescriptor() + ") which is not the same as the valueSelector (" + valueSelector + ")'s variableDescriptor(" + valueSelector.getVariableDescriptor() + ")."); } if (!randomSelection) { if (subChainSelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a subChainSelector (" + subChainSelector + ") with neverEnding (" + subChainSelector.isNeverEnding() + ")."); } if (valueSelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a valueSelector (" + valueSelector + ") with neverEnding (" + valueSelector.isNeverEnding() + ")."); } } phaseLifecycleSupport.addEventListener(subChainSelector); phaseLifecycleSupport.addEventListener(valueSelector); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager(); inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(valueSelector.getVariableDescriptor())); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); inverseVariableSupply = null; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return subChainSelector.isCountable() && valueSelector.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection; } @Override public long getSize() { return subChainSelector.getSize() * valueSelector.getSize(); } @Override public Iterator<Move<Solution_>> iterator() { if (!randomSelection) { return new OriginalSubChainChangeMoveIterator(); } else { return new RandomSubChainChangeMoveIterator(); } } private class OriginalSubChainChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> { private final Iterator<SubChain> subChainIterator; private Iterator<Object> valueIterator = null; private SubChain upcomingSubChain; private Move<Solution_> nextReversingSelection = null; private OriginalSubChainChangeMoveIterator() { subChainIterator = subChainSelector.iterator(); // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording) valueIterator = Collections.emptyIterator(); } @Override protected Move<Solution_> createUpcomingSelection() { if (selectReversingMoveToo && nextReversingSelection != null) { Move<Solution_> upcomingSelection = nextReversingSelection; nextReversingSelection = null; return upcomingSelection; } if (!valueIterator.hasNext()) { if (!subChainIterator.hasNext()) { return noUpcomingSelection(); } upcomingSubChain = subChainIterator.next(); valueIterator = valueSelector.iterator(); if (!valueIterator.hasNext()) { // valueSelector is completely empty return noUpcomingSelection(); } } Object toValue = valueIterator.next(); Move<Solution_> upcomingSelection = new SubChainChangeMove<>(upcomingSubChain, valueSelector.getVariableDescriptor(), inverseVariableSupply, toValue); if (selectReversingMoveToo) { nextReversingSelection = new SubChainReversingChangeMove<>(upcomingSubChain, valueSelector.getVariableDescriptor(), inverseVariableSupply, toValue); } return upcomingSelection; } } private class RandomSubChainChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> { private Iterator<SubChain> subChainIterator; private Iterator<Object> valueIterator; private RandomSubChainChangeMoveIterator() { subChainIterator = subChainSelector.iterator(); valueIterator = valueSelector.iterator(); // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording) valueIterator = Collections.emptyIterator(); } @Override protected Move<Solution_> createUpcomingSelection() { // Ideally, this code should have read: // SubChain subChain = subChainIterator.next(); // Object toValue = valueIterator.next(); // But empty selectors and ending selectors (such as non-random or shuffled) make it more complex if (!subChainIterator.hasNext()) { subChainIterator = subChainSelector.iterator(); if (!subChainIterator.hasNext()) { // subChainSelector is completely empty return noUpcomingSelection(); } } SubChain subChain = subChainIterator.next(); if (!valueIterator.hasNext()) { valueIterator = valueSelector.iterator(); if (!valueIterator.hasNext()) { // valueSelector is completely empty return noUpcomingSelection(); } } Object toValue = valueIterator.next(); boolean reversing = selectReversingMoveToo && workingRandom.nextBoolean(); return reversing ? new SubChainReversingChangeMove<>(subChain, valueSelector.getVariableDescriptor(), inverseVariableSupply, toValue) : new SubChainChangeMove<>(subChain, valueSelector.getVariableDescriptor(), inverseVariableSupply, toValue); } } @Override public String toString() { return getClass().getSimpleName() + "(" + subChainSelector + ", " + valueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainChangeMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.chained.SubChainSelectorConfig; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelectorFactory; public class SubChainChangeMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, SubChainChangeMoveSelectorConfig> { public SubChainChangeMoveSelectorFactory(SubChainChangeMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { EntityDescriptor<Solution_> entityDescriptor = deduceEntityDescriptor(configPolicy, config.getEntityClass()); SubChainSelectorConfig subChainSelectorConfig = Objects.requireNonNullElseGet(config.getSubChainSelectorConfig(), SubChainSelectorConfig::new); ValueSelectorConfig valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); SubChainSelector<Solution_> subChainSelector = SubChainSelectorFactory.<Solution_> create(subChainSelectorConfig) .buildSubChainSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder); ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder); return new SubChainChangeMoveSelector<>(subChainSelector, (IterableValueSelector<Solution_>) valueSelector, randomSelection, Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainReversingChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Collection; import java.util.Collections; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SubChainReversingChangeMove<Solution_> extends AbstractMove<Solution_> { protected final SubChain subChain; protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final Object toPlanningValue; protected final Object oldTrailingLastEntity; protected final Object newTrailingEntity; public SubChainReversingChangeMove(SubChain subChain, GenuineVariableDescriptor<Solution_> variableDescriptor, SingletonInverseVariableSupply inverseVariableSupply, Object toPlanningValue) { this.subChain = subChain; this.variableDescriptor = variableDescriptor; this.toPlanningValue = toPlanningValue; oldTrailingLastEntity = inverseVariableSupply.getInverseSingleton(subChain.getLastEntity()); newTrailingEntity = toPlanningValue == null ? null : inverseVariableSupply.getInverseSingleton(toPlanningValue); } public SubChainReversingChangeMove(SubChain subChain, GenuineVariableDescriptor<Solution_> variableDescriptor, Object toPlanningValue, Object oldTrailingLastEntity, Object newTrailingEntity) { this.subChain = subChain; this.variableDescriptor = variableDescriptor; this.toPlanningValue = toPlanningValue; this.oldTrailingLastEntity = oldTrailingLastEntity; this.newTrailingEntity = newTrailingEntity; } public String getVariableName() { return variableDescriptor.getVariableName(); } public SubChain getSubChain() { return subChain; } public Object getToPlanningValue() { return toPlanningValue; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { if (subChain.getEntityList().contains(toPlanningValue)) { return false; } Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity()); return !Objects.equals(oldFirstValue, toPlanningValue); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var firstEntity = subChain.getFirstEntity(); var lastEntity = subChain.getLastEntity(); var oldFirstValue = variableDescriptor.getValue(firstEntity); var unmovedReverse = toPlanningValue == oldFirstValue; // Close the old chain var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; if (!unmovedReverse) { if (oldTrailingLastEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingLastEntity, oldFirstValue); } } var lastEntityValue = variableDescriptor.getValue(lastEntity); // Change the entity castScoreDirector.changeVariableFacade(variableDescriptor, lastEntity, toPlanningValue); // Reverse the chain reverseChain(castScoreDirector, variableDescriptor, lastEntity, lastEntityValue, firstEntity); // Reroute the new chain if (!unmovedReverse) { if (newTrailingEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, firstEntity); } } else { if (oldTrailingLastEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingLastEntity, firstEntity); } } } static <Solution_> void reverseChain(VariableDescriptorAwareScoreDirector<Solution_> scoreDirector, VariableDescriptor<Solution_> variableDescriptor, Object entity, Object previous, Object toEntity) { while (entity != toEntity) { var value = variableDescriptor.getValue(previous); scoreDirector.changeVariableFacade(variableDescriptor, previous, entity); entity = previous; previous = value; } } @Override public SubChainReversingChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubChainReversingChangeMove<>(subChain.rebase(destinationScoreDirector), variableDescriptor, destinationScoreDirector.lookUpWorkingObject(toPlanningValue), destinationScoreDirector.lookUpWorkingObject(oldTrailingLastEntity), destinationScoreDirector.lookUpWorkingObject(newTrailingEntity)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<? extends Object> getPlanningEntities() { return subChain.getEntityList(); } @Override public Collection<? extends Object> getPlanningValues() { return Collections.singletonList(toPlanningValue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SubChainReversingChangeMove<?> other = (SubChainReversingChangeMove<?>) o; return Objects.equals(subChain, other.subChain) && Objects.equals(variableDescriptor.getVariableName(), other.variableDescriptor.getVariableName()) && Objects.equals(toPlanningValue, other.toPlanningValue); } @Override public int hashCode() { return Objects.hash(subChain, variableDescriptor.getVariableName(), toPlanningValue); } @Override public String toString() { Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity()); return subChain.toDottedString() + " {" + oldFirstValue + " -reversing-> " + toPlanningValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainReversingSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.SubChainReversingChangeMove.reverseChain; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain; import ai.timefold.solver.core.impl.score.director.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 SubChainReversingSwapMove<Solution_> extends AbstractMove<Solution_> { private final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final SubChain leftSubChain; protected final Object leftTrailingLastEntity; protected final SubChain rightSubChain; protected final Object rightTrailingLastEntity; public SubChainReversingSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, SingletonInverseVariableSupply inverseVariableSupply, SubChain leftSubChain, SubChain rightSubChain) { this.variableDescriptor = variableDescriptor; this.leftSubChain = leftSubChain; leftTrailingLastEntity = inverseVariableSupply.getInverseSingleton(leftSubChain.getLastEntity()); this.rightSubChain = rightSubChain; rightTrailingLastEntity = inverseVariableSupply.getInverseSingleton(rightSubChain.getLastEntity()); } public SubChainReversingSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, SubChain leftSubChain, Object leftTrailingLastEntity, SubChain rightSubChain, Object rightTrailingLastEntity) { this.variableDescriptor = variableDescriptor; this.leftSubChain = leftSubChain; this.rightSubChain = rightSubChain; this.leftTrailingLastEntity = leftTrailingLastEntity; this.rightTrailingLastEntity = rightTrailingLastEntity; } public SubChain getLeftSubChain() { return leftSubChain; } public SubChain getRightSubChain() { return rightSubChain; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { // Because leftFirstEntity and rightFirstEntity are unequal, chained guarantees their values are unequal too. return !SubChainSwapMove.containsAnyOf(rightSubChain, leftSubChain); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var leftFirstEntity = leftSubChain.getFirstEntity(); var leftFirstValue = variableDescriptor.getValue(leftFirstEntity); var leftLastEntity = leftSubChain.getLastEntity(); var rightFirstEntity = rightSubChain.getFirstEntity(); var rightFirstValue = variableDescriptor.getValue(rightFirstEntity); var rightLastEntity = rightSubChain.getLastEntity(); var leftLastEntityValue = variableDescriptor.getValue(leftLastEntity); var rightLastEntityValue = variableDescriptor.getValue(rightLastEntity); // Change the entities var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; if (leftLastEntity != rightFirstValue) { castScoreDirector.changeVariableFacade(variableDescriptor, leftLastEntity, rightFirstValue); } if (rightLastEntity != leftFirstValue) { castScoreDirector.changeVariableFacade(variableDescriptor, rightLastEntity, leftFirstValue); } // Reverse the chains reverseChain(castScoreDirector, variableDescriptor, leftLastEntity, leftLastEntityValue, leftFirstEntity); reverseChain(castScoreDirector, variableDescriptor, rightLastEntity, rightLastEntityValue, rightFirstEntity); // Reroute the new chains if (leftTrailingLastEntity != null) { if (leftTrailingLastEntity != rightFirstEntity) { castScoreDirector.changeVariableFacade(variableDescriptor, leftTrailingLastEntity, rightFirstEntity); } else { castScoreDirector.changeVariableFacade(variableDescriptor, leftLastEntity, rightFirstEntity); } } if (rightTrailingLastEntity != null) { if (rightTrailingLastEntity != leftFirstEntity) { castScoreDirector.changeVariableFacade(variableDescriptor, rightTrailingLastEntity, leftFirstEntity); } else { castScoreDirector.changeVariableFacade(variableDescriptor, rightLastEntity, leftFirstEntity); } } } @Override public SubChainReversingSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubChainReversingSwapMove<>(variableDescriptor, leftSubChain.rebase(destinationScoreDirector), destinationScoreDirector.lookUpWorkingObject(leftTrailingLastEntity), rightSubChain.rebase(destinationScoreDirector), destinationScoreDirector.lookUpWorkingObject(rightTrailingLastEntity)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<?> getPlanningEntities() { return CollectionUtils.concat(leftSubChain.getEntityList(), rightSubChain.getEntityList()); } @Override public Collection<?> getPlanningValues() { List<Object> values = new ArrayList<>(2); values.add(variableDescriptor.getValue(leftSubChain.getFirstEntity())); values.add(variableDescriptor.getValue(rightSubChain.getFirstEntity())); return values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SubChainReversingSwapMove<?> other = (SubChainReversingSwapMove<?>) o; return Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(leftSubChain, other.leftSubChain) && Objects.equals(rightSubChain, other.rightSubChain); } @Override public int hashCode() { return Objects.hash(variableDescriptor, leftSubChain, rightSubChain); } @Override public String toString() { Object oldLeftValue = variableDescriptor.getValue(leftSubChain.getFirstEntity()); Object oldRightValue = variableDescriptor.getValue(rightSubChain.getFirstEntity()); return leftSubChain.toDottedString() + " {" + oldLeftValue + "} <-reversing-> " + rightSubChain.toDottedString() + " {" + oldRightValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain; import ai.timefold.solver.core.impl.score.director.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 SubChainSwapMove<Solution_> extends AbstractMove<Solution_> { protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final SubChain leftSubChain; protected final Object leftTrailingLastEntity; protected final SubChain rightSubChain; protected final Object rightTrailingLastEntity; public SubChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, SingletonInverseVariableSupply inverseVariableSupply, SubChain leftSubChain, SubChain rightSubChain) { this.variableDescriptor = variableDescriptor; this.leftSubChain = leftSubChain; leftTrailingLastEntity = inverseVariableSupply.getInverseSingleton(leftSubChain.getLastEntity()); this.rightSubChain = rightSubChain; rightTrailingLastEntity = inverseVariableSupply.getInverseSingleton(rightSubChain.getLastEntity()); } public SubChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, SubChain leftSubChain, Object leftTrailingLastEntity, SubChain rightSubChain, Object rightTrailingLastEntity) { this.variableDescriptor = variableDescriptor; this.leftSubChain = leftSubChain; this.rightSubChain = rightSubChain; this.leftTrailingLastEntity = leftTrailingLastEntity; this.rightTrailingLastEntity = rightTrailingLastEntity; } public String getVariableName() { return variableDescriptor.getVariableName(); } public SubChain getLeftSubChain() { return leftSubChain; } public SubChain getRightSubChain() { return rightSubChain; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return !containsAnyOf(rightSubChain, leftSubChain); } static boolean containsAnyOf(SubChain rightSubChain, SubChain leftSubChain) { int leftSubChainSize = leftSubChain.getSize(); if (leftSubChainSize == 0) { return false; } else if (leftSubChainSize == 1) { // No optimization possible. return rightSubChain.getEntityList().contains(leftSubChain.getFirstEntity()); } /* * In order to find an entity in another subchain, we need to do contains() on a List. * List.contains() is O(n), the performance gets worse with increasing size. * Subchains here can easily have hundreds, thousands of elements. * As Set.contains() is O(1), independent of set size, copying the list outperforms the lookup by a lot. * Therefore this code converts the List lookup to HashSet lookup, in situations with repeat lookup. */ Set<Object> rightSubChainEntityFastLookupSet = new HashSet<>(rightSubChain.getEntityList()); for (Object leftEntity : leftSubChain.getEntityList()) { if (rightSubChainEntityFastLookupSet.contains(leftEntity)) { return true; } } return false; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var leftFirstEntity = leftSubChain.getFirstEntity(); var leftFirstValue = variableDescriptor.getValue(leftFirstEntity); var leftLastEntity = leftSubChain.getLastEntity(); var rightFirstEntity = rightSubChain.getFirstEntity(); var rightFirstValue = variableDescriptor.getValue(rightFirstEntity); var rightLastEntity = rightSubChain.getLastEntity(); // Change the entities var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; if (leftLastEntity != rightFirstValue) { castScoreDirector.changeVariableFacade(variableDescriptor, leftFirstEntity, rightFirstValue); } if (rightLastEntity != leftFirstValue) { castScoreDirector.changeVariableFacade(variableDescriptor, rightFirstEntity, leftFirstValue); } // Reroute the new chains if (leftTrailingLastEntity != null) { if (leftTrailingLastEntity != rightFirstEntity) { castScoreDirector.changeVariableFacade(variableDescriptor, leftTrailingLastEntity, rightLastEntity); } else { castScoreDirector.changeVariableFacade(variableDescriptor, leftFirstEntity, rightLastEntity); } } if (rightTrailingLastEntity != null) { if (rightTrailingLastEntity != leftFirstEntity) { castScoreDirector.changeVariableFacade(variableDescriptor, rightTrailingLastEntity, leftLastEntity); } else { castScoreDirector.changeVariableFacade(variableDescriptor, rightFirstEntity, leftLastEntity); } } } @Override public SubChainSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubChainSwapMove<>(variableDescriptor, leftSubChain.rebase(destinationScoreDirector), destinationScoreDirector.lookUpWorkingObject(leftTrailingLastEntity), rightSubChain.rebase(destinationScoreDirector), destinationScoreDirector.lookUpWorkingObject(rightTrailingLastEntity)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<?> getPlanningEntities() { return CollectionUtils.concat(leftSubChain.getEntityList(), rightSubChain.getEntityList()); } @Override public Collection<?> getPlanningValues() { return Arrays.asList( variableDescriptor.getValue(leftSubChain.getFirstEntity()), variableDescriptor.getValue(rightSubChain.getFirstEntity())); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SubChainSwapMove<?> other = (SubChainSwapMove<?>) o; return Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(leftSubChain, other.leftSubChain) && Objects.equals(rightSubChain, other.rightSubChain); } @Override public int hashCode() { return Objects.hash(variableDescriptor, leftSubChain, rightSubChain); } @Override public String toString() { Object oldLeftValue = variableDescriptor.getValue(leftSubChain.getFirstEntity()); Object oldRightValue = variableDescriptor.getValue(rightSubChain.getFirstEntity()); return leftSubChain.toDottedString() + " {" + oldLeftValue + "} <-> " + rightSubChain.toDottedString() + " {" + oldRightValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainSwapMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Iterator; 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.common.iterator.AbstractOriginalSwapIterator; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractRandomSwapIterator; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChain; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class SubChainSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { protected final SubChainSelector<Solution_> leftSubChainSelector; protected final SubChainSelector<Solution_> rightSubChainSelector; protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final boolean randomSelection; protected final boolean selectReversingMoveToo; protected SingletonInverseVariableSupply inverseVariableSupply = null; public SubChainSwapMoveSelector(SubChainSelector<Solution_> leftSubChainSelector, SubChainSelector<Solution_> rightSubChainSelector, boolean randomSelection, boolean selectReversingMoveToo) { this.leftSubChainSelector = leftSubChainSelector; this.rightSubChainSelector = rightSubChainSelector; this.randomSelection = randomSelection; this.selectReversingMoveToo = selectReversingMoveToo; variableDescriptor = leftSubChainSelector.getVariableDescriptor(); if (leftSubChainSelector.getVariableDescriptor() != rightSubChainSelector.getVariableDescriptor()) { throw new IllegalStateException("The selector (" + this + ") has a leftSubChainSelector's variableDescriptor (" + leftSubChainSelector.getVariableDescriptor() + ") which is not equal to the rightSubChainSelector's variableDescriptor (" + rightSubChainSelector.getVariableDescriptor() + ")."); } phaseLifecycleSupport.addEventListener(leftSubChainSelector); if (leftSubChainSelector != rightSubChainSelector) { phaseLifecycleSupport.addEventListener(rightSubChainSelector); } } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager(); inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor)); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); inverseVariableSupply = null; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return leftSubChainSelector.isCountable() && rightSubChainSelector.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || leftSubChainSelector.isNeverEnding() || rightSubChainSelector.isNeverEnding(); } @Override public long getSize() { return AbstractOriginalSwapIterator.getSize(leftSubChainSelector, rightSubChainSelector); } @Override public Iterator<Move<Solution_>> iterator() { if (!randomSelection) { return new AbstractOriginalSwapIterator<>(leftSubChainSelector, rightSubChainSelector) { private Move<Solution_> nextReversingSelection = null; @Override protected Move<Solution_> createUpcomingSelection() { if (selectReversingMoveToo && nextReversingSelection != null) { Move<Solution_> upcomingSelection = nextReversingSelection; nextReversingSelection = null; return upcomingSelection; } return super.createUpcomingSelection(); } @Override protected Move<Solution_> newSwapSelection(SubChain leftSubSelection, SubChain rightSubSelection) { if (selectReversingMoveToo) { nextReversingSelection = new SubChainReversingSwapMove<>(variableDescriptor, inverseVariableSupply, leftSubSelection, rightSubSelection); } return new SubChainSwapMove<>(variableDescriptor, inverseVariableSupply, leftSubSelection, rightSubSelection); } }; } else { return new AbstractRandomSwapIterator<>(leftSubChainSelector, rightSubChainSelector) { @Override protected Move<Solution_> newSwapSelection(SubChain leftSubSelection, SubChain rightSubSelection) { boolean reversing = selectReversingMoveToo && workingRandom.nextBoolean(); return reversing ? new SubChainReversingSwapMove<>(variableDescriptor, inverseVariableSupply, leftSubSelection, rightSubSelection) : new SubChainSwapMove<>(variableDescriptor, inverseVariableSupply, leftSubSelection, rightSubSelection); } }; } } @Override public String toString() { return getClass().getSimpleName() + "(" + leftSubChainSelector + ", " + rightSubChainSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/SubChainSwapMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.chained.SubChainSelectorConfig; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.chained.SubChainSelectorFactory; public class SubChainSwapMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, SubChainSwapMoveSelectorConfig> { public SubChainSwapMoveSelectorFactory(SubChainSwapMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { EntityDescriptor<Solution_> entityDescriptor = deduceEntityDescriptor(configPolicy, config.getEntityClass()); SubChainSelectorConfig subChainSelectorConfig = Objects.requireNonNullElseGet(config.getSubChainSelectorConfig(), SubChainSelectorConfig::new); SubChainSelectorConfig secondarySubChainSelectorConfig = Objects.requireNonNullElse(config.getSecondarySubChainSelectorConfig(), subChainSelectorConfig); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); SubChainSelector<Solution_> leftSubChainSelector = SubChainSelectorFactory.<Solution_> create(subChainSelectorConfig) .buildSubChainSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder); SubChainSelector<Solution_> rightSubChainSelector = SubChainSelectorFactory.<Solution_> create(secondarySubChainSelectorConfig) .buildSubChainSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder); return new SubChainSwapMoveSelector<>(leftSubChainSelector, rightSubChainSelector, randomSelection, Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/TailChainSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.anchor.AnchorVariableSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * Also known as a 2-opt move. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class TailChainSwapMove<Solution_> extends AbstractMove<Solution_> { protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final Object leftEntity; protected final Object leftValue; protected final Object leftAnchor; protected final Object rightEntity; // Sometimes null protected final Object rightValue; protected final Object rightAnchor; protected final boolean sameAnchor; protected final Object leftNextEntity; protected final Object rightNextEntity; protected final boolean reverseAnchorSide; protected final Object lastEntityInChain; protected final Object entityAfterAnchor; public TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, SingletonInverseVariableSupply inverseVariableSupply, AnchorVariableSupply anchorVariableSupply, Object leftEntity, Object rightValue) { this.variableDescriptor = variableDescriptor; this.leftEntity = leftEntity; leftValue = variableDescriptor.getValue(leftEntity); leftAnchor = anchorVariableSupply.getAnchor(leftEntity); rightEntity = inverseVariableSupply.getInverseSingleton(rightValue); this.rightValue = rightValue; rightAnchor = variableDescriptor.isValuePotentialAnchor(rightValue) ? rightValue : anchorVariableSupply.getAnchor(rightValue); sameAnchor = leftAnchor == rightAnchor; if (!sameAnchor) { leftNextEntity = null; rightNextEntity = null; reverseAnchorSide = false; lastEntityInChain = null; entityAfterAnchor = null; } else { leftNextEntity = inverseVariableSupply.getInverseSingleton(leftEntity); rightNextEntity = rightEntity == null ? null : inverseVariableSupply.getInverseSingleton(rightEntity); Object lastEntityInChainOrLeftEntity = findLastEntityInChainOrLeftEntity(inverseVariableSupply); reverseAnchorSide = lastEntityInChainOrLeftEntity != leftEntity; if (reverseAnchorSide) { lastEntityInChain = lastEntityInChainOrLeftEntity; entityAfterAnchor = inverseVariableSupply.getInverseSingleton(leftAnchor); } else { lastEntityInChain = null; entityAfterAnchor = null; } } } // TODO Workaround until https://issues.redhat.com/browse/PLANNER-1250 is fixed protected TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object leftEntity, Object leftValue, Object leftAnchor, Object rightEntity, Object rightValue, Object rightAnchor) { this.variableDescriptor = variableDescriptor; this.leftEntity = leftEntity; this.leftValue = leftValue; this.leftAnchor = leftAnchor; this.rightEntity = rightEntity; this.rightValue = rightValue; this.rightAnchor = rightAnchor; this.sameAnchor = false; this.leftNextEntity = null; this.rightNextEntity = null; this.reverseAnchorSide = false; this.lastEntityInChain = null; this.entityAfterAnchor = null; } // TODO Workaround until https://issues.redhat.com/browse/PLANNER-1250 is fixed protected TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object leftEntity, Object leftValue, Object leftAnchor, Object rightEntity, Object rightValue, Object rightAnchor, Object leftNextEntity, Object rightNextEntity) { this.variableDescriptor = variableDescriptor; this.leftEntity = leftEntity; this.leftValue = leftValue; this.leftAnchor = leftAnchor; this.rightEntity = rightEntity; this.rightValue = rightValue; this.rightAnchor = rightAnchor; this.sameAnchor = true; this.leftNextEntity = leftNextEntity; this.rightNextEntity = rightNextEntity; this.reverseAnchorSide = false; this.lastEntityInChain = null; this.entityAfterAnchor = null; } // TODO Workaround until https://issues.redhat.com/browse/PLANNER-1250 is fixed protected TailChainSwapMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object leftEntity, Object leftValue, Object leftAnchor, Object rightEntity, Object rightValue, Object rightAnchor, Object leftNextEntity, Object rightNextEntity, Object lastEntityInChain, Object entityAfterAnchor) { this.variableDescriptor = variableDescriptor; this.leftEntity = leftEntity; this.leftValue = leftValue; this.leftAnchor = leftAnchor; this.rightEntity = rightEntity; this.rightValue = rightValue; this.rightAnchor = rightAnchor; this.sameAnchor = true; this.leftNextEntity = leftNextEntity; this.rightNextEntity = rightNextEntity; this.reverseAnchorSide = true; this.lastEntityInChain = lastEntityInChain; this.entityAfterAnchor = entityAfterAnchor; } private Object findLastEntityInChainOrLeftEntity(SingletonInverseVariableSupply inverseVariableSupply) { Object entity = rightValue; while (entity != leftEntity) { Object nextEntity = inverseVariableSupply.getInverseSingleton(entity); if (nextEntity == null) { return entity; } entity = nextEntity; } return leftEntity; } public String getVariableName() { return variableDescriptor.getVariableName(); } public Object getLeftEntity() { return leftEntity; } public Object getRightValue() { return rightValue; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { if (Objects.equals(leftValue, rightValue) || Objects.equals(leftEntity, rightValue) || Objects.equals(rightEntity, leftValue)) { return false; } if (rightEntity == null) { // TODO Currently unsupported because we fail to create a valid undoMove... even though doMove supports it if (leftAnchor == rightAnchor) { return false; } } if (!variableDescriptor.canExtractValueRangeFromSolution()) { var valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); if (rightEntity != null) { var rightValueRange = extractValueRangeFromEntity(scoreDirector, valueRangeDescriptor, rightEntity); if (!rightValueRange.contains(leftValue)) { return false; } } var leftValueRange = extractValueRangeFromEntity(scoreDirector, valueRangeDescriptor, leftEntity); return leftValueRange.contains(rightValue); } return true; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; if (!sameAnchor) { // Change the left entity castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue); // Change the right entity if (rightEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftValue); } } else { if (!reverseAnchorSide) { // Reverses loop on the side that doesn't include the anchor, because rightValue is earlier than leftEntity castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue); reverseChain(castScoreDirector, leftValue, leftEntity, rightEntity); if (leftNextEntity != null) { castScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity); } } else { // Reverses loop on the side that does include the anchor, because rightValue is later than leftEntity // Change the head of the chain reverseChain(castScoreDirector, leftValue, leftEntity, entityAfterAnchor); // Change leftEntity castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue); // Change the tail of the chain reverseChain(castScoreDirector, lastEntityInChain, leftAnchor, rightEntity); castScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity); } } } protected void reverseChain(VariableDescriptorAwareScoreDirector<Solution_> scoreDirector, Object fromValue, Object fromEntity, Object toEntity) { var entity = fromValue; var newValue = fromEntity; while (newValue != toEntity) { var oldValue = variableDescriptor.getValue(entity); scoreDirector.changeVariableFacade(variableDescriptor, entity, newValue); newValue = entity; entity = oldValue; } } @Override public TailChainSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { if (!sameAnchor) { return new TailChainSwapMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(leftEntity), destinationScoreDirector.lookUpWorkingObject(leftValue), destinationScoreDirector.lookUpWorkingObject(leftAnchor), destinationScoreDirector.lookUpWorkingObject(rightEntity), destinationScoreDirector.lookUpWorkingObject(rightValue), destinationScoreDirector.lookUpWorkingObject(rightAnchor)); } else { if (!reverseAnchorSide) { return new TailChainSwapMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(leftEntity), destinationScoreDirector.lookUpWorkingObject(leftValue), destinationScoreDirector.lookUpWorkingObject(leftAnchor), destinationScoreDirector.lookUpWorkingObject(rightEntity), destinationScoreDirector.lookUpWorkingObject(rightValue), destinationScoreDirector.lookUpWorkingObject(rightAnchor), destinationScoreDirector.lookUpWorkingObject(leftNextEntity), destinationScoreDirector.lookUpWorkingObject(rightNextEntity)); } else { return new TailChainSwapMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(leftEntity), destinationScoreDirector.lookUpWorkingObject(leftValue), destinationScoreDirector.lookUpWorkingObject(leftAnchor), destinationScoreDirector.lookUpWorkingObject(rightEntity), destinationScoreDirector.lookUpWorkingObject(rightValue), destinationScoreDirector.lookUpWorkingObject(rightAnchor), destinationScoreDirector.lookUpWorkingObject(leftNextEntity), destinationScoreDirector.lookUpWorkingObject(rightNextEntity), destinationScoreDirector.lookUpWorkingObject(lastEntityInChain), destinationScoreDirector.lookUpWorkingObject(entityAfterAnchor)); } } } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<?> getPlanningEntities() { if (rightEntity == null) { return Collections.singleton(leftEntity); } return Arrays.asList(leftEntity, rightEntity); } @Override public Collection<?> getPlanningValues() { Object leftValue = variableDescriptor.getValue(leftEntity); return Arrays.asList(leftValue, rightValue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final TailChainSwapMove<?> other = (TailChainSwapMove<?>) o; return Objects.equals(leftEntity, other.leftEntity) && Objects.equals(rightValue, other.rightValue); } @Override public int hashCode() { return Objects.hash(leftEntity, rightValue); } @Override public String toString() { return leftEntity + " {" + leftValue + "} <-tailChainSwap-> " + rightEntity + " {" + rightValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/TailChainSwapMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.variable.anchor.AnchorVariableDemand; import ai.timefold.solver.core.impl.domain.variable.anchor.AnchorVariableSupply; 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.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * Also known as a 2-opt move selector. */ public class TailChainSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { protected final EntitySelector<Solution_> entitySelector; protected final ValueSelector<Solution_> valueSelector; protected final boolean randomSelection; protected SingletonInverseVariableSupply inverseVariableSupply; protected AnchorVariableSupply anchorVariableSupply; public TailChainSwapMoveSelector(EntitySelector<Solution_> entitySelector, ValueSelector<Solution_> valueSelector, boolean randomSelection) { this.entitySelector = entitySelector; 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)'s valueSelector's variableDescriptor (%s) must be chained (%s)." .formatted(this, variableDescriptor, isChained)); } if (!variableDescriptor.getEntityDescriptor().getEntityClass().isAssignableFrom( entitySelector.getEntityDescriptor().getEntityClass())) { throw new IllegalStateException("The selector (" + this + ") has a valueSelector with a entityClass (" + variableDescriptor.getEntityDescriptor().getEntityClass() + ") which is not equal or a superclass to the entitySelector's entityClass (" + entitySelector.getEntityDescriptor().getEntityClass() + ")."); } phaseLifecycleSupport.addEventListener(entitySelector); phaseLifecycleSupport.addEventListener(valueSelector); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager(); GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor(); inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor)); anchorVariableSupply = supplyManager.demand(new AnchorVariableDemand<>(variableDescriptor)); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); inverseVariableSupply = null; anchorVariableSupply = 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) { return new AbstractOriginalChangeIterator<>(entitySelector, valueSelector) { @Override protected Move<Solution_> newChangeSelection(Object entity, Object toValue) { return new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, entity, toValue); } }; } else { return new AbstractRandomChangeIterator<>(entitySelector, valueSelector) { @Override protected Move<Solution_> newChangeSelection(Object entity, Object toValue) { return new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, 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/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/TailChainSwapMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained; 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.move.generic.chained.TailChainSwapMoveSelectorConfig; 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.EntitySelector; 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.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class TailChainSwapMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, TailChainSwapMoveSelectorConfig> { public TailChainSwapMoveSelectorFactory(TailChainSwapMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { EntitySelectorConfig entitySelectorConfig = Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new); ValueSelectorConfig valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); EntitySelector<Solution_> entitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder); return new TailChainSwapMoveSelector<>(entitySelector, valueSelector, randomSelection); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListAssignMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collection; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; public final class ListAssignMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object planningValue; private final Object destinationEntity; private final int destinationIndex; public ListAssignMove(ListVariableDescriptor<Solution_> variableDescriptor, Object planningValue, Object destinationEntity, int destinationIndex) { this.variableDescriptor = variableDescriptor; this.planningValue = planningValue; this.destinationEntity = destinationEntity; this.destinationIndex = destinationIndex; } public Object getDestinationEntity() { return destinationEntity; } public int getDestinationIndex() { return destinationIndex; } public Object getMovedValue() { return planningValue; } @Override public Collection<?> getPlanningEntities() { return List.of(destinationEntity); } @Override public Collection<?> getPlanningValues() { return List.of(planningValue); } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return destinationIndex >= 0 && variableDescriptor.getListSize(destinationEntity) >= destinationIndex; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var variableDescriptorAwareScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; // Add planningValue to destinationEntity's list variable (at destinationIndex). variableDescriptorAwareScoreDirector.beforeListVariableElementAssigned(variableDescriptor, planningValue); variableDescriptorAwareScoreDirector.beforeListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex); variableDescriptor.addElement(destinationEntity, destinationIndex, planningValue); variableDescriptorAwareScoreDirector.afterListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex + 1); variableDescriptorAwareScoreDirector.afterListVariableElementAssigned(variableDescriptor, planningValue); } @Override public ListAssignMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ListAssignMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(planningValue), destinationScoreDirector.lookUpWorkingObject(destinationEntity), destinationIndex); } @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ListAssignMove<?> other = (ListAssignMove<?>) o; return destinationIndex == other.destinationIndex && Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(planningValue, other.planningValue) && Objects.equals(destinationEntity, other.destinationEntity); } @Override public int hashCode() { return Objects.hash(variableDescriptor, planningValue, destinationEntity, destinationIndex); } @Override public String toString() { return String.format("%s {null -> %s[%d]}", getMovedValue(), destinationEntity, destinationIndex); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * Moves an element of a {@link PlanningListVariable list variable}. The moved element is identified * by an entity instance and a position in that entity's list variable. The element is inserted at the given index * in the given destination entity's list variable. * <p> * An undo move is simply created by flipping the source and destination entity+index. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ListChangeMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object sourceEntity; private final int sourceIndex; private final Object destinationEntity; private final int destinationIndex; private Object planningValue; /** * The move removes a planning value element from {@code sourceEntity.listVariable[sourceIndex]} * and inserts the planning value at {@code destinationEntity.listVariable[destinationIndex]}. * * <h4>ListChangeMove anatomy</h4> * * <pre> * {@code * / destinationEntity * | / destinationIndex * | | * A {Ann[0]}->{Bob[2]} * | | | * planning value / | \ sourceIndex * \ sourceEntity * } * </pre> * * <h4>Example 1 - source and destination entities are different</h4> * * <pre> * {@code * GIVEN * Ann.tasks = [A, B, C] * Bob.tasks = [X, Y] * * WHEN * ListChangeMove: A {Ann[0]->Bob[2]} * * THEN * Ann.tasks = [B, C] * Bob.tasks = [X, Y, A] * } * </pre> * * <h4>Example 2 - source and destination is the same entity</h4> * * <pre> * {@code * GIVEN * Ann.tasks = [A, B, C] * * WHEN * ListChangeMove: A {Ann[0]->Ann[2]} * * THEN * Ann.tasks = [B, C, A] * } * </pre> * * @param variableDescriptor descriptor of a list variable, for example {@code Employee.taskList} * @param sourceEntity planning entity instance from which a planning value will be removed, for example "Ann" * @param sourceIndex index in sourceEntity's list variable from which a planning value will be removed * @param destinationEntity planning entity instance to which a planning value will be moved, for example "Bob" * @param destinationIndex index in destinationEntity's list variable where the moved planning value will be inserted */ public ListChangeMove(ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex, Object destinationEntity, int destinationIndex) { this.variableDescriptor = variableDescriptor; this.sourceEntity = sourceEntity; this.sourceIndex = sourceIndex; this.destinationEntity = destinationEntity; this.destinationIndex = destinationIndex; } public Object getSourceEntity() { return sourceEntity; } public int getSourceIndex() { return sourceIndex; } public Object getDestinationEntity() { return destinationEntity; } public int getDestinationIndex() { return destinationIndex; } public Object getMovedValue() { if (planningValue == null) { planningValue = variableDescriptor.getElement(sourceEntity, sourceIndex); } return planningValue; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { // TODO maybe remove this because no such move should be generated // Do not use Object#equals on user-provided domain objects. Relying on user's implementation of Object#equals // opens the opportunity to shoot themselves in the foot if different entities can be equal. var sameEntity = destinationEntity == sourceEntity; return !sameEntity || (destinationIndex != sourceIndex && destinationIndex != variableDescriptor.getListSize(sourceEntity)); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; if (sourceEntity == destinationEntity) { int fromIndex = Math.min(sourceIndex, destinationIndex); int toIndex = Math.max(sourceIndex, destinationIndex) + 1; castScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex); Object element = variableDescriptor.removeElement(sourceEntity, sourceIndex); variableDescriptor.addElement(destinationEntity, destinationIndex, element); castScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex); planningValue = element; } else { castScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + 1); Object element = variableDescriptor.removeElement(sourceEntity, sourceIndex); castScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex); castScoreDirector.beforeListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex); variableDescriptor.addElement(destinationEntity, destinationIndex, element); castScoreDirector.afterListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex + 1); planningValue = element; } } @Override public ListChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ListChangeMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(sourceEntity), sourceIndex, destinationScoreDirector.lookUpWorkingObject(destinationEntity), destinationIndex); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<Object> getPlanningEntities() { // Use LinkedHashSet for predictable iteration order. Set<Object> entities = new LinkedHashSet<>(2); entities.add(sourceEntity); entities.add(destinationEntity); return entities; } @Override public Collection<Object> getPlanningValues() { return Collections.singleton(planningValue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ListChangeMove<?> other = (ListChangeMove<?>) o; return sourceIndex == other.sourceIndex && destinationIndex == other.destinationIndex && Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(sourceEntity, other.sourceEntity) && Objects.equals(destinationEntity, other.destinationEntity); } @Override public int hashCode() { return Objects.hash(variableDescriptor, sourceEntity, sourceIndex, destinationEntity, destinationIndex); } @Override public String toString() { return String.format("%s {%s[%d] -> %s[%d]}", getMovedValue(), sourceEntity, sourceIndex, destinationEntity, destinationIndex); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListChangeMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Iterator; import java.util.Objects; import java.util.function.Supplier; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; 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.UnassignedElement; public class ListChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final IterableValueSelector<Solution_> sourceValueSelector; private final DestinationSelector<Solution_> destinationSelector; private final boolean randomSelection; private ListVariableStateSupply<Solution_> listVariableStateSupply; public ListChangeMoveSelector(IterableValueSelector<Solution_> sourceValueSelector, DestinationSelector<Solution_> destinationSelector, boolean randomSelection) { this.sourceValueSelector = filterPinnedListPlanningVariableValuesWithIndex(sourceValueSelector, this::getListVariableStateSupply); this.destinationSelector = destinationSelector; this.randomSelection = randomSelection; phaseLifecycleSupport.addEventListener(this.sourceValueSelector); phaseLifecycleSupport.addEventListener(this.destinationSelector); } 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); var listVariableDescriptor = (ListVariableDescriptor<Solution_>) sourceValueSelector.getVariableDescriptor(); var supplyManager = solverScope.getScoreDirector().getSupplyManager(); this.listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand()); } public static <Solution_> IterableValueSelector<Solution_> filterPinnedListPlanningVariableValuesWithIndex( IterableValueSelector<Solution_> sourceValueSelector, Supplier<ListVariableStateSupply<Solution_>> listVariableStateSupplier) { var listVariableDescriptor = (ListVariableDescriptor<Solution_>) sourceValueSelector.getVariableDescriptor(); var supportsPinning = listVariableDescriptor.supportsPinning(); if (!supportsPinning) { // Don't incur the overhead of filtering values if there is no pinning support. return sourceValueSelector; } return (IterableValueSelector<Solution_>) FilteringValueSelector.of(sourceValueSelector, (scoreDirector, selection) -> { var listVariableStateSupply = listVariableStateSupplier.get(); var elementPosition = listVariableStateSupply.getElementPosition(selection); if (elementPosition instanceof UnassignedElement) { return true; } var elementDestination = elementPosition.ensureAssigned(); var entity = elementDestination.entity(); return !listVariableDescriptor.isElementPinned(scoreDirector.getWorkingSolution(), entity, elementDestination.index()); }); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); listVariableStateSupply = null; } @Override public long getSize() { return sourceValueSelector.getSize() * destinationSelector.getSize(); } @Override public Iterator<Move<Solution_>> iterator() { if (randomSelection) { return new RandomListChangeIterator<>( listVariableStateSupply, sourceValueSelector, destinationSelector); } else { return new OriginalListChangeIterator<>( listVariableStateSupply, sourceValueSelector, destinationSelector); } } @Override public boolean isCountable() { return sourceValueSelector.isCountable() && destinationSelector.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || sourceValueSelector.isNeverEnding() || destinationSelector.isNeverEnding(); } @Override public String toString() { return getClass().getSimpleName() + "(" + sourceValueSelector + ", " + destinationSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListChangeMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.ArrayList; import java.util.Collections; import java.util.Objects; import java.util.Optional; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class ListChangeMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, ListChangeMoveSelectorConfig> { public ListChangeMoveSelectorFactory(ListChangeMoveSelectorConfig moveSelectorConfig) { // We copy the configuration, // as the settings may be updated during the autoconfiguration of the entity value range super(Objects.requireNonNull(moveSelectorConfig).copyConfig()); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var valueSelectorConfig = checkUnfolded("valueSelectorConfig", config.getValueSelectorConfig()); var destinationSelectorConfig = checkUnfolded("destinationSelectorConfig", config.getDestinationSelectorConfig()); var destinationEntitySelectorConfig = checkUnfolded("destinationEntitySelectorConfig", destinationSelectorConfig.getEntitySelectorConfig()); checkUnfolded("destinationValueSelectorConfig", destinationSelectorConfig.getValueSelectorConfig()); var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); var entityDescriptor = EntitySelectorFactory .<Solution_> create(destinationEntitySelectorConfig) .extractEntityDescriptor(configPolicy); // When enabling entity value range filtering, // the recorder ID from the origin selector is required for FilteringEntityValueRangeSelector and FilteringValueRangeSelector // to replay the selected value and return only reachable values. var enableEntityValueRangeFilter = !entityDescriptor.getGenuineListVariableDescriptor().canExtractValueRangeFromSolution(); // A null ID means to turn off the entity value range filtering String entityValueRangeRecorderId = null; if (enableEntityValueRangeFilter) { var mimicSelectorConfig = Objects.requireNonNull(valueSelectorConfig); if (mimicSelectorConfig.getMimicSelectorRef() == null && mimicSelectorConfig.getId() == null) { var variableName = Objects.requireNonNull(mimicSelectorConfig.getVariableName()); // We set the id to make sure the value selector will use the mimic recorder entityValueRangeRecorderId = ConfigUtils.addRandomSuffix(variableName, configPolicy.getRandom()); mimicSelectorConfig.setId(entityValueRangeRecorderId); } else { entityValueRangeRecorderId = mimicSelectorConfig.getMimicSelectorRef() != null ? mimicSelectorConfig.getMimicSelectorRef() : mimicSelectorConfig.getId(); } } if (enableEntityValueRangeFilter && entityValueRangeRecorderId == null) { throw new IllegalStateException( "Impossible state: when enabling entity value range, the origin value selector ID is required for the destination selector %s." .formatted(destinationSelectorConfig)); } var sourceValueSelector = ValueSelectorFactory .<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder); var destinationSelector = DestinationSelectorFactory .<Solution_> create(destinationSelectorConfig) .buildDestinationSelector(configPolicy, minimumCacheType, randomSelection, entityValueRangeRecorderId); return new ListChangeMoveSelector<>((IterableValueSelector<Solution_>) sourceValueSelector, destinationSelector, randomSelection); } @Override protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { var destinationSelectorConfig = config.getDestinationSelectorConfig(); var destinationEntitySelectorConfig = destinationSelectorConfig == null ? null : destinationSelectorConfig.getEntitySelectorConfig(); var onlyEntityDescriptor = destinationEntitySelectorConfig == null ? null : EntitySelectorFactory.<Solution_> create(destinationEntitySelectorConfig) .extractEntityDescriptor(configPolicy); var entityDescriptors = onlyEntityDescriptor == null ? configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors().stream() // We need to filter the entity that defines the list variable .filter(EntityDescriptor::hasAnyGenuineListVariables) .toList() : Collections.singletonList(onlyEntityDescriptor); if (entityDescriptors.isEmpty()) { throw new IllegalArgumentException( "The listChangeMoveSelector (%s) cannot unfold because there are no planning list variables." .formatted(config)); } if (entityDescriptors.size() > 1) { throw new IllegalArgumentException(""" The listChangeMoveSelector (%s) cannot unfold when there are multiple entities (%s). Please use one listChangeMoveSelector per each planning list variable.""" .formatted(config, entityDescriptors)); } var entityDescriptor = entityDescriptors.iterator().next(); var variableDescriptorList = new ArrayList<ListVariableDescriptor<Solution_>>(); var valueSelectorConfig = config.getValueSelectorConfig(); var onlyVariableDescriptor = valueSelectorConfig == null ? null : ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .extractVariableDescriptor(configPolicy, entityDescriptor); var destinationValueSelectorConfig = destinationSelectorConfig == null ? null : destinationSelectorConfig.getValueSelectorConfig(); var onlyDestinationVariableDescriptor = destinationValueSelectorConfig == null ? null : ValueSelectorFactory.<Solution_> create(destinationValueSelectorConfig) .extractVariableDescriptor(configPolicy, entityDescriptor); if (onlyVariableDescriptor != null && onlyDestinationVariableDescriptor != null) { if (!onlyVariableDescriptor.isListVariable()) { throw new IllegalArgumentException(""" The listChangeMoveSelector (%s) is configured to use a planning variable (%s), \ which is not a planning list variable. Either fix your annotations and use a @%s on the variable to make it work with listChangeMoveSelector or use a changeMoveSelector instead.""" .formatted(config, onlyVariableDescriptor, PlanningListVariable.class.getSimpleName())); } if (!onlyDestinationVariableDescriptor.isListVariable()) { throw new IllegalArgumentException( "The destinationSelector (%s) is configured to use a planning variable (%s), which is not a planning list variable." .formatted(destinationSelectorConfig, onlyDestinationVariableDescriptor)); } if (onlyVariableDescriptor != onlyDestinationVariableDescriptor) { throw new IllegalArgumentException( "The listChangeMoveSelector's valueSelector (%s) and destinationSelector's valueSelector (%s) must be configured for the same planning variable." .formatted(valueSelectorConfig, destinationValueSelectorConfig)); } if (onlyEntityDescriptor != null) { // No need for unfolding or deducing return null; } variableDescriptorList.add((ListVariableDescriptor<Solution_>) onlyVariableDescriptor); } else { variableDescriptorList.addAll( entityDescriptor.getGenuineVariableDescriptorList().stream() .filter(VariableDescriptor::isListVariable) .map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor)) .toList()); } if (variableDescriptorList.size() > 1) { throw new IllegalArgumentException( "The listChangeMoveSelector (%s) cannot unfold because there are multiple planning list variables." .formatted(config)); } var listChangeMoveSelectorConfig = buildChildMoveSelectorConfig(variableDescriptorList.get(0), valueSelectorConfig, destinationSelectorConfig); listChangeMoveSelectorConfig.inheritFolded(config); return listChangeMoveSelectorConfig; } public static ListChangeMoveSelectorConfig buildChildMoveSelectorConfig( ListVariableDescriptor<?> variableDescriptor, ValueSelectorConfig inheritedValueSelectorConfig, DestinationSelectorConfig inheritedDestinationSelectorConfig) { var childValueSelectorConfig = new ValueSelectorConfig(inheritedValueSelectorConfig); if (childValueSelectorConfig.getMimicSelectorRef() == null) { childValueSelectorConfig.setVariableName(variableDescriptor.getVariableName()); } return new ListChangeMoveSelectorConfig() .withValueSelectorConfig(childValueSelectorConfig) .withDestinationSelectorConfig(new DestinationSelectorConfig(inheritedDestinationSelectorConfig) .withEntitySelectorConfig( Optional.ofNullable(inheritedDestinationSelectorConfig) .map(DestinationSelectorConfig::getEntitySelectorConfig) .map(EntitySelectorConfig::new) // use copy constructor if inherited not null .orElseGet(EntitySelectorConfig::new) // otherwise create new instance // override entity class (destination entity selector is never replaying) .withEntityClass(variableDescriptor.getEntityDescriptor().getEntityClass())) .withValueSelectorConfig( Optional.ofNullable(inheritedDestinationSelectorConfig) .map(DestinationSelectorConfig::getValueSelectorConfig) .map(ValueSelectorConfig::new) // use copy constructor if inherited not null .orElseGet(ValueSelectorConfig::new) // otherwise create new instance // override variable name (destination value selector is never replaying) .withVariableName(variableDescriptor.getVariableName()))); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * Swaps two elements of a {@link PlanningListVariable list variable}. * Each element is identified by an entity instance and an index in that entity's list variable. * The swap move has two sides called left and right. The element at {@code leftIndex} in {@code leftEntity}'s list variable * is replaced by the element at {@code rightIndex} in {@code rightEntity}'s list variable and vice versa. * Left and right entity can be the same instance. * <p> * An undo move is created by flipping the left and right-hand entity and index. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ListSwapMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object leftEntity; private final int leftIndex; private final Object rightEntity; private final int rightIndex; /** * Create a move that swaps a list variable element at {@code leftEntity.listVariable[leftIndex]} with * {@code rightEntity.listVariable[rightIndex]}. * * <h4>ListSwapMove anatomy</h4> * * <pre> * {@code * / rightEntity * right element \ | / rightIndex * | | | * A {Ann[0]} <-> Y {Bob[1]} * | | | * left element / | \ leftIndex * \ leftEntity * } * </pre> * * <h4>Example</h4> * * <pre> * {@code * GIVEN * Ann.tasks = [A, B, C] * Bob.tasks = [X, Y] * * WHEN * ListSwapMove: A {Ann[0]} <-> Y {Bob[1]} * * THEN * Ann.tasks = [Y, B, C] * Bob.tasks = [X, A] * } * </pre> * * @param variableDescriptor descriptor of a list variable, for example {@code Employee.taskList} * @param leftEntity together with {@code leftIndex} identifies the left element to be moved * @param leftIndex together with {@code leftEntity} identifies the left element to be moved * @param rightEntity together with {@code rightIndex} identifies the right element to be moved * @param rightIndex together with {@code rightEntity} identifies the right element to be moved */ public ListSwapMove(ListVariableDescriptor<Solution_> variableDescriptor, Object leftEntity, int leftIndex, Object rightEntity, int rightIndex) { this.variableDescriptor = variableDescriptor; this.leftEntity = leftEntity; this.leftIndex = leftIndex; this.rightEntity = rightEntity; this.rightIndex = rightIndex; } public Object getLeftEntity() { return leftEntity; } public int getLeftIndex() { return leftIndex; } public Object getRightEntity() { return rightEntity; } public int getRightIndex() { return rightIndex; } public Object getLeftValue() { return variableDescriptor.getElement(leftEntity, leftIndex); } public Object getRightValue() { return variableDescriptor.getElement(rightEntity, rightIndex); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { // Do not use Object#equals on user-provided domain objects. Relying on user's implementation of Object#equals // opens the opportunity to shoot themselves in the foot if different entities can be equal. var sameEntity = leftEntity == rightEntity; return !(sameEntity && leftIndex == rightIndex); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var leftElement = variableDescriptor.getElement(leftEntity, leftIndex); var rightElement = variableDescriptor.getElement(rightEntity, rightIndex); if (leftEntity == rightEntity) { var fromIndex = Math.min(leftIndex, rightIndex); var toIndex = Math.max(leftIndex, rightIndex) + 1; castScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex); variableDescriptor.setElement(leftEntity, leftIndex, rightElement); variableDescriptor.setElement(rightEntity, rightIndex, leftElement); castScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex); } else { castScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, leftIndex, leftIndex + 1); castScoreDirector.beforeListVariableChanged(variableDescriptor, rightEntity, rightIndex, rightIndex + 1); variableDescriptor.setElement(leftEntity, leftIndex, rightElement); variableDescriptor.setElement(rightEntity, rightIndex, leftElement); castScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, leftIndex, leftIndex + 1); castScoreDirector.afterListVariableChanged(variableDescriptor, rightEntity, rightIndex, rightIndex + 1); } } @Override public ListSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ListSwapMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(leftEntity), leftIndex, destinationScoreDirector.lookUpWorkingObject(rightEntity), rightIndex); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<Object> getPlanningEntities() { // Use LinkedHashSet for predictable iteration order. Set<Object> entities = new LinkedHashSet<>(2); entities.add(leftEntity); entities.add(rightEntity); return entities; } @Override public Collection<Object> getPlanningValues() { return Arrays.asList(getLeftValue(), getRightValue()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ListSwapMove<?> other = (ListSwapMove<?>) o; return leftIndex == other.leftIndex && rightIndex == other.rightIndex && Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(leftEntity, other.leftEntity) && Objects.equals(rightEntity, other.rightEntity); } @Override public int hashCode() { return Objects.hash(variableDescriptor, leftEntity, leftIndex, rightEntity, rightIndex); } @Override public String toString() { return String.format("%s {%s[%d]} <-> %s {%s[%d]}", getLeftValue(), leftEntity, leftIndex, getRightValue(), rightEntity, rightIndex); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListSwapMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex; import java.util.Iterator; import 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.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class ListSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final IterableValueSelector<Solution_> leftValueSelector; private final IterableValueSelector<Solution_> rightValueSelector; private final boolean randomSelection; private ListVariableStateSupply<Solution_> listVariableStateSupply; public ListSwapMoveSelector(IterableValueSelector<Solution_> leftValueSelector, IterableValueSelector<Solution_> rightValueSelector, boolean randomSelection) { this.leftValueSelector = filterPinnedListPlanningVariableValuesWithIndex(leftValueSelector, this::getListVariableStateSupply); this.rightValueSelector = filterPinnedListPlanningVariableValuesWithIndex(rightValueSelector, this::getListVariableStateSupply); this.randomSelection = randomSelection; phaseLifecycleSupport.addEventListener(this.leftValueSelector); phaseLifecycleSupport.addEventListener(this.rightValueSelector); } 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); var listVariableDescriptor = (ListVariableDescriptor<Solution_>) leftValueSelector.getVariableDescriptor(); var supplyManager = solverScope.getScoreDirector().getSupplyManager(); listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand()); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); listVariableStateSupply = null; } @Override public Iterator<Move<Solution_>> iterator() { if (randomSelection) { return new RandomListSwapIterator<>(listVariableStateSupply, leftValueSelector, rightValueSelector); } else { return new OriginalListSwapIterator<>(listVariableStateSupply, leftValueSelector, rightValueSelector); } } @Override public boolean isCountable() { return leftValueSelector.isCountable() && rightValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || leftValueSelector.isNeverEnding() || rightValueSelector.isNeverEnding(); } @Override public long getSize() { return leftValueSelector.getSize() * rightValueSelector.getSize(); } @Override public String toString() { return getClass().getSimpleName() + "(" + leftValueSelector + ", " + rightValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListSwapMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.ArrayList; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class ListSwapMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, ListSwapMoveSelectorConfig> { public ListSwapMoveSelectorFactory(ListSwapMoveSelectorConfig moveSelectorConfig) { // We copy the configuration, // as the settings may be updated during the autoconfiguration of the entity value range super(Objects.requireNonNull(moveSelectorConfig).copyConfig()); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); var secondaryValueSelectorConfig = Objects.requireNonNullElseGet(config.getSecondaryValueSelectorConfig(), valueSelectorConfig::copyConfig); var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); var entityDescriptor = getTheOnlyEntityDescriptorWithListVariable(configPolicy.getSolutionDescriptor()); // When enabling entity value range filtering, // the recorder ID from the origin selector is required for FilteringEntityValueRangeSelector and FilteringValueRangeSelector // to replay the selected value and return only reachable values. var enableEntityValueRangeFilter = !entityDescriptor.getGenuineListVariableDescriptor().canExtractValueRangeFromSolution(); // A null ID means to turn off the entity value range filtering String entityValueRangeRecorderId = null; if (enableEntityValueRangeFilter) { if (valueSelectorConfig.getId() == null && valueSelectorConfig.getMimicSelectorRef() == null) { var variableName = Objects.requireNonNull(valueSelectorConfig.getVariableName()); // We set the id to make sure the value selector will use the mimic recorder entityValueRangeRecorderId = ConfigUtils.addRandomSuffix(variableName, configPolicy.getRandom()); valueSelectorConfig.setId(entityValueRangeRecorderId); } else { entityValueRangeRecorderId = valueSelectorConfig.getId() != null ? valueSelectorConfig.getId() : valueSelectorConfig.getMimicSelectorRef(); } } var leftValueSelector = buildIterableValueSelector(configPolicy, entityDescriptor, valueSelectorConfig, minimumCacheType, selectionOrder, null); var rightValueSelector = buildIterableValueSelector(configPolicy, entityDescriptor, secondaryValueSelectorConfig, minimumCacheType, selectionOrder, entityValueRangeRecorderId); var variableDescriptor = leftValueSelector.getVariableDescriptor(); // This may be redundant but emphasizes that the ListSwapMove is not designed to swap elements // on multiple list variables, unlike the SwapMove, which swaps all (basic) variables between left and right entities. if (variableDescriptor != rightValueSelector.getVariableDescriptor()) { throw new IllegalStateException( "Impossible state: the leftValueSelector (%s) and the rightValueSelector (%s) have different variable descriptors. This should have failed fast during config unfolding." .formatted(leftValueSelector, rightValueSelector)); } return new ListSwapMoveSelector<>( leftValueSelector, rightValueSelector, randomSelection); } private IterableValueSelector<Solution_> buildIterableValueSelector(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, ValueSelectorConfig valueSelectorConfig, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, String entityValueRangeRecorderId) { // Swap moves require asserting both sides, // which means checking if the left and right entities accept the swapped values var valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder, configPolicy.isReinitializeVariableFilterEnabled(), ValueSelectorFactory.ListValueFilteringType.NONE, entityValueRangeRecorderId, true); return (IterableValueSelector<Solution_>) valueSelector; } @Override protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { var entityDescriptor = getTheOnlyEntityDescriptorWithListVariable(configPolicy.getSolutionDescriptor()); var onlyVariableDescriptor = config.getValueSelectorConfig() == null ? null : ValueSelectorFactory.<Solution_> create(config.getValueSelectorConfig()) .extractVariableDescriptor(configPolicy, entityDescriptor); if (config.getSecondaryValueSelectorConfig() != null) { var onlySecondaryVariableDescriptor = ValueSelectorFactory.<Solution_> create(config.getSecondaryValueSelectorConfig()) .extractVariableDescriptor(configPolicy, entityDescriptor); if (onlyVariableDescriptor != onlySecondaryVariableDescriptor) { throw new IllegalArgumentException( "The valueSelector (%s)'s variableName (%s) and secondaryValueSelectorConfig (%s)'s variableName (%s) must be the same planning list variable." .formatted(config.getValueSelectorConfig(), onlyVariableDescriptor == null ? null : onlyVariableDescriptor.getVariableName(), config.getSecondaryValueSelectorConfig(), onlySecondaryVariableDescriptor == null ? null : onlySecondaryVariableDescriptor.getVariableName())); } } if (onlyVariableDescriptor != null) { if (!onlyVariableDescriptor.isListVariable()) { throw new IllegalArgumentException( "Impossible state: the listSwapMoveSelector (%s) is configured to use a planning variable (%s), which is not a planning list variable. Either fix your annotations and use a @%s on the variable to make it work with listSwapMoveSelector or use a swapMoveSelector instead." .formatted(config, onlyVariableDescriptor, PlanningListVariable.class.getSimpleName())); } // No need for unfolding or deducing return null; } var variableDescriptorList = entityDescriptor.getGenuineVariableDescriptorList().stream() .filter(VariableDescriptor::isListVariable) .map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor)) .toList(); if (variableDescriptorList.isEmpty()) { throw new IllegalArgumentException( "Impossible state: the listSwapMoveSelector (%s) cannot unfold because there are no planning list variables for the only entity (%s) or no planning list variables at all." .formatted(config, entityDescriptor)); } return buildUnfoldedMoveSelectorConfig(variableDescriptorList); } protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(List<ListVariableDescriptor<Solution_>> variableDescriptorList) { var moveSelectorConfigList = new ArrayList<MoveSelectorConfig>(variableDescriptorList.size()); for (var variableDescriptor : variableDescriptorList) { // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() var childMoveSelectorConfig = new ListSwapMoveSelectorConfig(); var childValueSelectorConfig = new ValueSelectorConfig(config.getValueSelectorConfig()); if (childValueSelectorConfig.getMimicSelectorRef() == null) { childValueSelectorConfig.setVariableName(variableDescriptor.getVariableName()); } childMoveSelectorConfig.setValueSelectorConfig(childValueSelectorConfig); if (config.getSecondaryValueSelectorConfig() != null) { var childSecondaryValueSelectorConfig = new ValueSelectorConfig(config.getSecondaryValueSelectorConfig()); if (childSecondaryValueSelectorConfig.getMimicSelectorRef() == null) { childSecondaryValueSelectorConfig.setVariableName(variableDescriptor.getVariableName()); } childMoveSelectorConfig.setSecondaryValueSelectorConfig(childSecondaryValueSelectorConfig); } moveSelectorConfigList.add(childMoveSelectorConfig); } MoveSelectorConfig<?> unfoldedMoveSelectorConfig; if (moveSelectorConfigList.size() == 1) { unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0); } else { unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList); } unfoldedMoveSelectorConfig.inheritFolded(config); return unfoldedMoveSelectorConfig; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ListUnassignMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collection; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; public class ListUnassignMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object sourceEntity; private final int sourceIndex; private Object movedValue; public ListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex) { this.variableDescriptor = variableDescriptor; this.sourceEntity = sourceEntity; this.sourceIndex = sourceIndex; } public Object getSourceEntity() { return sourceEntity; } public int getSourceIndex() { return sourceIndex; } public Object getMovedValue() { if (movedValue == null) { movedValue = variableDescriptor.getElement(sourceEntity, sourceIndex); } return movedValue; } @Override public Collection<?> getPlanningEntities() { return List.of(sourceEntity); } @Override public Collection<?> getPlanningValues() { return List.of(getMovedValue()); } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return variableDescriptor.getElement(sourceEntity, sourceIndex) != null; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var listVariable = variableDescriptor.getValue(sourceEntity); var element = getMovedValue(); // Remove an element from sourceEntity's list variable (at sourceIndex). castScoreDirector.beforeListVariableElementUnassigned(variableDescriptor, element); castScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + 1); movedValue = listVariable.remove(sourceIndex); castScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex); castScoreDirector.afterListVariableElementUnassigned(variableDescriptor, element); } @Override public Move<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ListUnassignMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(sourceEntity), sourceIndex); } @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public boolean equals(Object o) { if (o instanceof ListUnassignMove<?> other) { return sourceIndex == other.sourceIndex && Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(sourceEntity, other.sourceEntity); } return false; } @Override public int hashCode() { return Objects.hash(variableDescriptor, sourceEntity, sourceIndex); } @Override public String toString() { return String.format("%s {%s[%d] -> null}", getMovedValue(), sourceEntity, sourceIndex); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/OriginalListChangeIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collections; import java.util.Iterator; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition; import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList; /** * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class OriginalListChangeIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final Iterator<Object> valueIterator; private final DestinationSelector<Solution_> destinationSelector; private Iterator<ElementPosition> destinationIterator; private Object upcomingValue; public OriginalListChangeIterator(ListVariableStateSupply<Solution_> listVariableStateSupply, IterableValueSelector<Solution_> valueSelector, DestinationSelector<Solution_> destinationSelector) { this.listVariableStateSupply = listVariableStateSupply; this.valueIterator = valueSelector.iterator(); this.destinationSelector = destinationSelector; this.destinationIterator = Collections.emptyIterator(); } @Override protected Move<Solution_> createUpcomingSelection() { while (!destinationIterator.hasNext()) { if (!valueIterator.hasNext()) { return noUpcomingSelection(); } upcomingValue = valueIterator.next(); destinationIterator = destinationSelector.iterator(); } var move = buildChangeMove(listVariableStateSupply, upcomingValue, destinationIterator); if (move == null) { return noUpcomingSelection(); } else { return move; } } static <Solution_> Move<Solution_> buildChangeMove(ListVariableStateSupply<Solution_> listVariableStateSupply, Object upcomingLeftValue, Iterator<ElementPosition> destinationIterator) { var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); var upcomingDestination = findUnpinnedDestination(destinationIterator, listVariableDescriptor); if (upcomingDestination == null) { return null; } var upcomingSource = listVariableStateSupply.getElementPosition(upcomingLeftValue); if (upcomingSource instanceof PositionInList sourceElement) { if (upcomingDestination instanceof PositionInList destinationElement) { return new ListChangeMove<>(listVariableDescriptor, sourceElement.entity(), sourceElement.index(), destinationElement.entity(), destinationElement.index()); } else { return new ListUnassignMove<>(listVariableDescriptor, sourceElement.entity(), sourceElement.index()); } } else { if (upcomingDestination instanceof PositionInList destinationElement) { return new ListAssignMove<>(listVariableDescriptor, upcomingLeftValue, destinationElement.entity(), destinationElement.index()); } else { // Only used in construction heuristics to give the CH an option to leave the element unassigned. return NoChangeMove.getInstance(); } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/OriginalListSwapIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collections; import java.util.Iterator; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.heuristic.move.CompositeMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.preview.api.domain.metamodel.UnassignedElement; /** * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class OriginalListSwapIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final Iterator<Object> leftValueIterator; private final IterableValueSelector<Solution_> rightValueSelector; private Iterator<Object> rightValueIterator; private Object upcomingLeftValue; public OriginalListSwapIterator(ListVariableStateSupply<Solution_> listVariableStateSupply, IterableValueSelector<Solution_> leftValueSelector, IterableValueSelector<Solution_> rightValueSelector) { this.listVariableStateSupply = listVariableStateSupply; this.leftValueIterator = leftValueSelector.iterator(); this.rightValueSelector = rightValueSelector; this.rightValueIterator = Collections.emptyIterator(); } @Override protected Move<Solution_> createUpcomingSelection() { while (!rightValueIterator.hasNext()) { if (!leftValueIterator.hasNext()) { return noUpcomingSelection(); } upcomingLeftValue = leftValueIterator.next(); rightValueIterator = rightValueSelector.iterator(); } var upcomingRightValue = rightValueIterator.next(); return buildSwapMove(listVariableStateSupply, upcomingLeftValue, upcomingRightValue); } static <Solution_> Move<Solution_> buildSwapMove(ListVariableStateSupply<Solution_> listVariableStateSupply, Object upcomingLeftValue, Object upcomingRightValue) { if (upcomingLeftValue == upcomingRightValue) { return NoChangeMove.getInstance(); } var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); var upcomingLeft = listVariableStateSupply.getElementPosition(upcomingLeftValue); var upcomingRight = listVariableStateSupply.getElementPosition(upcomingRightValue); var leftUnassigned = upcomingLeft instanceof UnassignedElement; var rightUnassigned = upcomingRight instanceof UnassignedElement; if (leftUnassigned && rightUnassigned) { // No need to swap two unassigned elements. return NoChangeMove.getInstance(); } else if (leftUnassigned) { // Unassign right, put left where right used to be. var rightDestination = upcomingRight.ensureAssigned(); var unassignMove = new ListUnassignMove<>(listVariableDescriptor, rightDestination.entity(), rightDestination.index()); var assignMove = new ListAssignMove<>(listVariableDescriptor, upcomingLeftValue, rightDestination.entity(), rightDestination.index()); return CompositeMove.buildMove(unassignMove, assignMove); } else if (rightUnassigned) { // Unassign left, put right where left used to be. var leftDestination = upcomingLeft.ensureAssigned(); var unassignMove = new ListUnassignMove<>(listVariableDescriptor, leftDestination.entity(), leftDestination.index()); var assignMove = new ListAssignMove<>(listVariableDescriptor, upcomingRightValue, leftDestination.entity(), leftDestination.index()); return CompositeMove.buildMove(unassignMove, assignMove); } else { var leftDestination = upcomingLeft.ensureAssigned(); var rightDestination = upcomingRight.ensureAssigned(); return new ListSwapMove<>(listVariableDescriptor, leftDestination.entity(), leftDestination.index(), rightDestination.entity(), rightDestination.index()); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomListChangeIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Iterator; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class RandomListChangeIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final Iterator<Object> valueIterator; private final Iterator<ElementPosition> destinationIterator; public RandomListChangeIterator(ListVariableStateSupply<Solution_> listVariableStateSupply, IterableValueSelector<Solution_> valueSelector, DestinationSelector<Solution_> destinationSelector) { this.listVariableStateSupply = listVariableStateSupply; this.valueIterator = valueSelector.iterator(); this.destinationIterator = destinationSelector.iterator(); } @Override protected Move<Solution_> createUpcomingSelection() { if (!valueIterator.hasNext()) { return noUpcomingSelection(); } // The destination may depend on selecting the value before checking if it has a next value var upcomingValue = valueIterator.next(); if (!destinationIterator.hasNext()) { return noUpcomingSelection(); } var move = OriginalListChangeIterator.buildChangeMove(listVariableStateSupply, upcomingValue, destinationIterator); if (move == null) { return noUpcomingSelection(); } else { return move; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomListSwapIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.OriginalListSwapIterator.buildSwapMove; import java.util.Iterator; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class RandomListSwapIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final Iterator<Object> leftValueIterator; private final Iterator<Object> rightValueIterator; public RandomListSwapIterator(ListVariableStateSupply<Solution_> listVariableStateSupply, IterableValueSelector<Solution_> leftValueSelector, IterableValueSelector<Solution_> rightValueSelector) { this.listVariableStateSupply = listVariableStateSupply; this.leftValueIterator = leftValueSelector.iterator(); this.rightValueIterator = rightValueSelector.iterator(); } @Override protected Move<Solution_> createUpcomingSelection() { if (!leftValueIterator.hasNext()) { return noUpcomingSelection(); } var upcomingLeftValue = leftValueIterator.next(); // The right iterator may depend on a selected value from the left iterator if (!rightValueIterator.hasNext()) { return noUpcomingSelection(); } var upcomingRightValue = rightValueIterator.next(); return buildSwapMove(listVariableStateSupply, upcomingLeftValue, upcomingRightValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomSubListChangeMoveIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Iterator; import java.util.Random; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector; import ai.timefold.solver.core.impl.heuristic.selector.list.SubList; import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector; import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition; import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList; class RandomSubListChangeMoveIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final Iterator<SubList> subListIterator; private final Iterator<ElementPosition> destinationIterator; private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final Random workingRandom; private final boolean selectReversingMoveToo; RandomSubListChangeMoveIterator( SubListSelector<Solution_> subListSelector, DestinationSelector<Solution_> destinationSelector, Random workingRandom, boolean selectReversingMoveToo) { this.subListIterator = subListSelector.iterator(); this.destinationIterator = destinationSelector.iterator(); this.listVariableDescriptor = subListSelector.getVariableDescriptor(); this.workingRandom = workingRandom; this.selectReversingMoveToo = selectReversingMoveToo; } @Override protected Move<Solution_> createUpcomingSelection() { if (!subListIterator.hasNext() || !destinationIterator.hasNext()) { return noUpcomingSelection(); } var subList = subListIterator.next(); var destination = findUnpinnedDestination(destinationIterator, listVariableDescriptor); if (destination == null) { return noUpcomingSelection(); } else if (destination instanceof PositionInList destinationElement) { var reversing = selectReversingMoveToo && workingRandom.nextBoolean(); return new SubListChangeMove<>(listVariableDescriptor, subList, destinationElement.entity(), destinationElement.index(), reversing); } else { // TODO add SubListAssignMove return new SubListUnassignMove<>(listVariableDescriptor, subList); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomSubListChangeMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Iterator; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector; import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; public class RandomSubListChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final SubListSelector<Solution_> subListSelector; private final DestinationSelector<Solution_> destinationSelector; private final boolean selectReversingMoveToo; public RandomSubListChangeMoveSelector( SubListSelector<Solution_> subListSelector, DestinationSelector<Solution_> destinationSelector, boolean selectReversingMoveToo) { this.subListSelector = subListSelector; this.destinationSelector = destinationSelector; this.selectReversingMoveToo = selectReversingMoveToo; phaseLifecycleSupport.addEventListener(subListSelector); phaseLifecycleSupport.addEventListener(destinationSelector); } @Override public Iterator<Move<Solution_>> iterator() { return new RandomSubListChangeMoveIterator<>( subListSelector, destinationSelector, workingRandom, selectReversingMoveToo); } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return true; } @Override public long getSize() { long subListCount = subListSelector.getSize(); long destinationCount = destinationSelector.getSize(); return subListCount * destinationCount * (selectReversingMoveToo ? 2 : 1); } boolean isSelectReversingMoveToo() { return selectReversingMoveToo; } SubListSelector<Solution_> getSubListSelector() { return subListSelector; } @Override public String toString() { return getClass().getSimpleName() + "(" + subListSelector + ", " + destinationSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/RandomSubListSwapMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.AbstractRandomSwapIterator; 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.heuristic.selector.move.generic.GenericMoveSelector; public class RandomSubListSwapMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final SubListSelector<Solution_> leftSubListSelector; private final SubListSelector<Solution_> rightSubListSelector; private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final boolean selectReversingMoveToo; public RandomSubListSwapMoveSelector( SubListSelector<Solution_> leftSubListSelector, SubListSelector<Solution_> rightSubListSelector, boolean selectReversingMoveToo) { this.leftSubListSelector = leftSubListSelector; this.rightSubListSelector = rightSubListSelector; this.listVariableDescriptor = leftSubListSelector.getVariableDescriptor(); if (leftSubListSelector.getVariableDescriptor() != rightSubListSelector.getVariableDescriptor()) { throw new IllegalStateException("The selector (" + this + ") has a leftSubListSelector's variableDescriptor (" + leftSubListSelector.getVariableDescriptor() + ") which is not equal to the rightSubListSelector's variableDescriptor (" + rightSubListSelector.getVariableDescriptor() + ")."); } this.selectReversingMoveToo = selectReversingMoveToo; phaseLifecycleSupport.addEventListener(leftSubListSelector); phaseLifecycleSupport.addEventListener(rightSubListSelector); } @Override public Iterator<Move<Solution_>> iterator() { return new AbstractRandomSwapIterator<>(leftSubListSelector, rightSubListSelector) { @Override protected Move<Solution_> newSwapSelection(SubList leftSubSelection, SubList rightSubSelection) { boolean reversing = selectReversingMoveToo && workingRandom.nextBoolean(); return new SubListSwapMove<>(listVariableDescriptor, leftSubSelection, rightSubSelection, reversing); } }; } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return true; } @Override public long getSize() { long leftSubListCount = leftSubListSelector.getSize(); long rightSubListCount = rightSubListSelector.getSize(); return leftSubListCount * rightSubListCount * (selectReversingMoveToo ? 2 : 1); } boolean isSelectReversingMoveToo() { return selectReversingMoveToo; } SubListSelector<Solution_> getLeftSubListSelector() { return leftSubListSelector; } SubListSelector<Solution_> getRightSubListSelector() { return rightSubListSelector; } @Override public String toString() { return getClass().getSimpleName() + "(" + leftSubListSelector + ", " + rightSubListSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.selector.list.SubList; import ai.timefold.solver.core.impl.score.director.ValueRangeManager; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SubListChangeMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object sourceEntity; private final int sourceIndex; private final int length; private final Object destinationEntity; private final int destinationIndex; private final boolean reversing; private Collection<Object> planningValues; public SubListChangeMove(ListVariableDescriptor<Solution_> variableDescriptor, SubList subList, Object destinationEntity, int destinationIndex, boolean reversing) { this(variableDescriptor, subList.entity(), subList.fromIndex(), subList.length(), destinationEntity, destinationIndex, reversing); } public SubListChangeMove( ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex, int length, Object destinationEntity, int destinationIndex, boolean reversing) { this.variableDescriptor = variableDescriptor; this.sourceEntity = sourceEntity; this.sourceIndex = sourceIndex; this.length = length; this.destinationEntity = destinationEntity; this.destinationIndex = destinationIndex; this.reversing = reversing; } public Object getSourceEntity() { return sourceEntity; } public int getFromIndex() { return sourceIndex; } public int getSubListSize() { return length; } public int getToIndex() { return sourceIndex + length; } public boolean isReversing() { return reversing; } public Object getDestinationEntity() { return destinationEntity; } public int getDestinationIndex() { return destinationIndex; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { var sameEntity = destinationEntity == sourceEntity; if (sameEntity && destinationIndex == sourceIndex) { return false; } var doable = !sameEntity || destinationIndex + length <= variableDescriptor.getListSize(destinationEntity); if (!doable || sameEntity || variableDescriptor.canExtractValueRangeFromSolution()) { return doable; } // When the first and second elements are different, // and the value range is located at the entity, // we need to check if the destination's value range accepts the upcoming values ValueRangeManager<Solution_> valueRangeManager = ((VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector).getValueRangeManager(); var destinationValueRange = valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), destinationEntity); var sourceList = variableDescriptor.getValue(sourceEntity); var subList = sourceList.subList(sourceIndex, sourceIndex + length); return subList.stream().allMatch(destinationValueRange::contains); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var sourceList = variableDescriptor.getValue(sourceEntity); var subList = sourceList.subList(sourceIndex, sourceIndex + length); planningValues = CollectionUtils.copy(subList, reversing); if (sourceEntity == destinationEntity) { var fromIndex = Math.min(sourceIndex, destinationIndex); var toIndex = Math.max(sourceIndex, destinationIndex) + length; castScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex); subList.clear(); variableDescriptor.getValue(destinationEntity).addAll(destinationIndex, planningValues); castScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, fromIndex, toIndex); } else { castScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + length); subList.clear(); castScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex); castScoreDirector.beforeListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex); variableDescriptor.getValue(destinationEntity).addAll(destinationIndex, planningValues); castScoreDirector.afterListVariableChanged(variableDescriptor, destinationEntity, destinationIndex, destinationIndex + length); } } @Override public SubListChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubListChangeMove<>( variableDescriptor, destinationScoreDirector.lookUpWorkingObject(sourceEntity), sourceIndex, length, destinationScoreDirector.lookUpWorkingObject(destinationEntity), destinationIndex, reversing); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<Object> getPlanningEntities() { // Use LinkedHashSet for predictable iteration order. Set<Object> entities = new LinkedHashSet<>(2); entities.add(sourceEntity); entities.add(destinationEntity); return entities; } @Override public Collection<Object> getPlanningValues() { return planningValues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubListChangeMove<?> other = (SubListChangeMove<?>) o; return sourceIndex == other.sourceIndex && length == other.length && destinationIndex == other.destinationIndex && reversing == other.reversing && variableDescriptor.equals(other.variableDescriptor) && sourceEntity.equals(other.sourceEntity) && destinationEntity.equals(other.destinationEntity); } @Override public int hashCode() { return Objects.hash(variableDescriptor, sourceEntity, sourceIndex, length, destinationEntity, destinationIndex, reversing); } @Override public String toString() { return String.format("|%d| {%s[%d..%d] -%s> %s[%d]}", length, sourceEntity, sourceIndex, getToIndex(), reversing ? "reversing-" : "", destinationEntity, destinationIndex); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListChangeMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.Optional; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class SubListChangeMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, SubListChangeMoveSelectorConfig> { public SubListChangeMoveSelectorFactory(SubListChangeMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var subListSelectorConfig = checkUnfolded("subListSelectorConfig", config.getSubListSelectorConfig()); var destinationSelectorConfig = checkUnfolded("destinationSelectorConfig", config.getDestinationSelectorConfig()); if (!randomSelection) { throw new IllegalArgumentException("The subListChangeMoveSelector (%s) only supports random selection order." .formatted(config)); } var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); var entitySelector = EntitySelectorFactory .<Solution_> create(destinationSelectorConfig.getEntitySelectorConfig()) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); var subListSelector = SubListSelectorFactory .<Solution_> create(subListSelectorConfig) .buildSubListSelector(configPolicy, entitySelector, minimumCacheType, selectionOrder); var destinationSelector = DestinationSelectorFactory .<Solution_> create(destinationSelectorConfig) .buildDestinationSelector(configPolicy, minimumCacheType, randomSelection); var selectReversingMoveToo = Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true); return new RandomSubListChangeMoveSelector<>(subListSelector, destinationSelector, selectReversingMoveToo); } @Override protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { var destinationSelectorConfig = config.getDestinationSelectorConfig(); var destinationEntitySelectorConfig = destinationSelectorConfig == null ? null : destinationSelectorConfig.getEntitySelectorConfig(); Collection<EntityDescriptor<Solution_>> entityDescriptors; var onlyEntityDescriptor = destinationEntitySelectorConfig == null ? null : EntitySelectorFactory.<Solution_> create(destinationEntitySelectorConfig) .extractEntityDescriptor(configPolicy); if (onlyEntityDescriptor != null) { entityDescriptors = Collections.singletonList(onlyEntityDescriptor); } else { // We select a single entity since there is only one descriptor that includes a list variable var onlyEntityDescriptorWithListVariable = getTheOnlyEntityDescriptorWithListVariable(configPolicy.getSolutionDescriptor()); entityDescriptors = new ArrayList<>(); if (onlyEntityDescriptorWithListVariable != null) { entityDescriptors.add(onlyEntityDescriptorWithListVariable); } } if (entityDescriptors.isEmpty()) { throw new IllegalArgumentException( "The subListChangeMoveSelector (%s) cannot unfold because there are no planning list variables." .formatted(config)); } var entityDescriptor = entityDescriptors.iterator().next(); var subListSelectorConfig = config.getSubListSelectorConfig(); var subListValueSelectorConfig = subListSelectorConfig == null ? null : subListSelectorConfig.getValueSelectorConfig(); var variableDescriptorList = new ArrayList<ListVariableDescriptor<Solution_>>(); var onlySubListVariableDescriptor = subListValueSelectorConfig == null ? null : ValueSelectorFactory.<Solution_> create(subListValueSelectorConfig) .extractVariableDescriptor(configPolicy, entityDescriptor); var destinationValueSelectorConfig = destinationSelectorConfig == null ? null : destinationSelectorConfig.getValueSelectorConfig(); var onlyDestinationVariableDescriptor = destinationValueSelectorConfig == null ? null : ValueSelectorFactory.<Solution_> create(destinationValueSelectorConfig) .extractVariableDescriptor(configPolicy, entityDescriptor); if (onlySubListVariableDescriptor != null && onlyDestinationVariableDescriptor != null) { if (!onlySubListVariableDescriptor.isListVariable()) { throw new IllegalArgumentException( "The subListChangeMoveSelector (%s) is configured to use a planning variable (%s), which is not a planning list variable." .formatted(config, onlySubListVariableDescriptor)); } if (!onlyDestinationVariableDescriptor.isListVariable()) { throw new IllegalArgumentException( "The subListChangeMoveSelector (%s) is configured to use a planning variable (%s), which is not a planning list variable." .formatted(config, onlyDestinationVariableDescriptor)); } if (onlySubListVariableDescriptor != onlyDestinationVariableDescriptor) { throw new IllegalArgumentException( "The subListSelector's valueSelector (%s) and destinationSelector's valueSelector (%s) must be configured for the same planning variable." .formatted(subListValueSelectorConfig, destinationEntitySelectorConfig)); } if (onlyEntityDescriptor != null) { // No need for unfolding or deducing return null; } variableDescriptorList.add((ListVariableDescriptor<Solution_>) onlySubListVariableDescriptor); } else { variableDescriptorList.addAll( entityDescriptor.getGenuineVariableDescriptorList().stream() .filter(VariableDescriptor::isListVariable) .map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor)) .toList()); } if (variableDescriptorList.size() > 1) { throw new IllegalArgumentException( "The subListChangeMoveSelector (%s) cannot unfold because there are multiple planning list variables." .formatted(config)); } return buildChildMoveSelectorConfig(variableDescriptorList.get(0)); } private SubListChangeMoveSelectorConfig buildChildMoveSelectorConfig(ListVariableDescriptor<?> variableDescriptor) { var subListSelectorConfig = config.getSubListSelectorConfig(); var destinationSelectorConfig = config.getDestinationSelectorConfig(); var subListChangeMoveSelectorConfig = config.copyConfig() .withSubListSelectorConfig(new SubListSelectorConfig(subListSelectorConfig) .withValueSelectorConfig(Optional.ofNullable(subListSelectorConfig) .map(SubListSelectorConfig::getValueSelectorConfig) .map(ValueSelectorConfig::new) // use copy constructor if inherited not null .orElseGet(ValueSelectorConfig::new))) .withDestinationSelectorConfig(new DestinationSelectorConfig(destinationSelectorConfig) .withEntitySelectorConfig( Optional.ofNullable(destinationSelectorConfig) .map(DestinationSelectorConfig::getEntitySelectorConfig) .map(EntitySelectorConfig::new) // use copy constructor if inherited not null .orElseGet(EntitySelectorConfig::new) // otherwise create new instance // override entity class (destination entity selector is never replaying) .withEntityClass(variableDescriptor.getEntityDescriptor().getEntityClass())) .withValueSelectorConfig( Optional.ofNullable(destinationSelectorConfig) .map(DestinationSelectorConfig::getValueSelectorConfig) .map(ValueSelectorConfig::new) // use copy constructor if inherited not null .orElseGet(ValueSelectorConfig::new) // otherwise create new instance // override variable name (destination value selector is never replaying) .withVariableName(variableDescriptor.getVariableName()))); subListSelectorConfig = Objects.requireNonNull(subListChangeMoveSelectorConfig.getSubListSelectorConfig()); SubListConfigUtil.transferDeprecatedMinimumSubListSize( subListChangeMoveSelectorConfig, SubListChangeMoveSelectorConfig::getMinimumSubListSize, "subListSelector", subListSelectorConfig); SubListConfigUtil.transferDeprecatedMaximumSubListSize( subListChangeMoveSelectorConfig, SubListChangeMoveSelectorConfig::getMaximumSubListSize, "subListSelector", subListSelectorConfig); if (subListSelectorConfig.getMimicSelectorRef() == null) { Objects.requireNonNull(subListSelectorConfig.getValueSelectorConfig()) .setVariableName(variableDescriptor.getVariableName()); } return subListChangeMoveSelectorConfig; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListConfigUtil.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.function.BiConsumer; import java.util.function.Function; import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig; 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 org.slf4j.LoggerFactory; /** * Provides backward-compatible way to handle minimumSubListSize and maximumSubListSize properties used on * {@link SubListChangeMoveSelectorConfig} and {@link SubListSwapMoveSelectorConfig}. * <p> * If the property is used, a warning message is logged. If the corresponding property on a child {@link SubListSelectorConfig} * is uninitialized, it will be transferred. Thanks to this, configs that used the properties before they became deprecated * will continue working as if they defined the properties at the child selector. The user will be warned about the deprecation. * <p> * Using both the deprecated and the new property is a mistake and will throw an exception. * <p> * This class should be removed together with its usages and tests for the property transfer and wrong config detection once * the deprecated properties are removed. */ final class SubListConfigUtil { private SubListConfigUtil() { } static <Config_> void transferDeprecatedMinimumSubListSize( Config_ moveSelectorConfig, Function<Config_, Integer> sourceGetter, String subListSelectorRole, SubListSelectorConfig subListSelectorConfig) { transferDeprecatedProperty( "minimumSubListSize", moveSelectorConfig, sourceGetter, subListSelectorRole, subListSelectorConfig, SubListSelectorConfig::getMinimumSubListSize, SubListSelectorConfig::setMinimumSubListSize); } static <Config_> void transferDeprecatedMaximumSubListSize( Config_ moveSelectorConfig, Function<Config_, Integer> sourceGetter, String subListSelectorRole, SubListSelectorConfig subListSelectorConfig) { transferDeprecatedProperty( "maximumSubListSize", moveSelectorConfig, sourceGetter, subListSelectorRole, subListSelectorConfig, SubListSelectorConfig::getMaximumSubListSize, SubListSelectorConfig::setMaximumSubListSize); } private static <Config_> void transferDeprecatedProperty( String propertyName, Config_ moveSelectorConfig, Function<Config_, Integer> sourceGetter, String childConfigName, SubListSelectorConfig subListSelectorConfig, Function<SubListSelectorConfig, Integer> targetGetter, BiConsumer<SubListSelectorConfig, Integer> targetSetter) { Integer moveSelectorSubListSize = sourceGetter.apply(moveSelectorConfig); if (moveSelectorSubListSize != null) { LoggerFactory.getLogger(moveSelectorConfig.getClass()).warn( "{}'s {} property is deprecated. Set {} on the child {}.", moveSelectorConfig.getClass().getSimpleName(), propertyName, propertyName, SubListSelectorConfig.class.getSimpleName()); Integer subListSize = targetGetter.apply(subListSelectorConfig); if (subListSize != null) { throw new IllegalArgumentException("The moveSelector (" + moveSelectorConfig + ") and its " + childConfigName + " (" + subListSelectorConfig + ") both set the " + propertyName + ", which is a conflict.\n" + "Use " + SubListSelectorConfig.class.getSimpleName() + "." + propertyName + " only."); } targetSetter.accept(subListSelectorConfig, moveSelectorSubListSize); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.selector.list.SubList; import ai.timefold.solver.core.impl.score.director.ValueRangeManager; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SubListSwapMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final SubList leftSubList; private final SubList rightSubList; private final boolean reversing; private final int rightFromIndex; private final int leftToIndex; private List<Object> leftPlanningValueList; private List<Object> rightPlanningValueList; public SubListSwapMove(ListVariableDescriptor<Solution_> variableDescriptor, Object leftEntity, int leftFromIndex, int leftToIndex, Object rightEntity, int rightFromIndex, int rightToIndex, boolean reversing) { this(variableDescriptor, new SubList(leftEntity, leftFromIndex, leftToIndex - leftFromIndex), new SubList(rightEntity, rightFromIndex, rightToIndex - rightFromIndex), reversing); } public SubListSwapMove(ListVariableDescriptor<Solution_> variableDescriptor, SubList leftSubList, SubList rightSubList, boolean reversing) { this.variableDescriptor = variableDescriptor; if (leftSubList.entity() == rightSubList.entity() && leftSubList.fromIndex() > rightSubList.fromIndex()) { this.leftSubList = rightSubList; this.rightSubList = leftSubList; } else { this.leftSubList = leftSubList; this.rightSubList = rightSubList; } this.reversing = reversing; rightFromIndex = this.rightSubList.fromIndex(); leftToIndex = this.leftSubList.getToIndex(); } public SubList getLeftSubList() { return leftSubList; } public SubList getRightSubList() { return rightSubList; } public boolean isReversing() { return reversing; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { // If both subLists are on the same entity, then they must not overlap. var doable = leftSubList.entity() != rightSubList.entity() || rightFromIndex >= leftToIndex; if (!doable || variableDescriptor.canExtractValueRangeFromSolution()) { return doable; } // When the left and right elements are different, // and the value range is located at the entity, // we need to check if the destination's value range accepts the upcoming values ValueRangeManager<Solution_> valueRangeManager = ((VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector).getValueRangeManager(); var leftEntity = leftSubList.entity(); var leftList = subList(leftSubList); var leftValueRange = valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), leftEntity); var rightEntity = rightSubList.entity(); var rightList = subList(rightSubList); var rightValueRange = valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), rightEntity); return leftList.stream().allMatch(rightValueRange::contains) && rightList.stream().allMatch(leftValueRange::contains); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var leftEntity = leftSubList.entity(); var rightEntity = rightSubList.entity(); var leftSubListLength = leftSubList.length(); var rightSubListLength = rightSubList.length(); var leftFromIndex = leftSubList.fromIndex(); var leftList = variableDescriptor.getValue(leftEntity); var rightList = variableDescriptor.getValue(rightEntity); var leftSubListView = subList(leftSubList); var rightSubListView = subList(rightSubList); leftPlanningValueList = CollectionUtils.copy(leftSubListView, reversing); rightPlanningValueList = CollectionUtils.copy(rightSubListView, reversing); if (leftEntity == rightEntity) { var fromIndex = Math.min(leftFromIndex, rightFromIndex); var toIndex = leftFromIndex > rightFromIndex ? leftFromIndex + leftSubListLength : rightFromIndex + rightSubListLength; var leftSubListDestinationIndex = rightFromIndex + rightSubListLength - leftSubListLength; castScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex); rightSubListView.clear(); subList(leftSubList).clear(); leftList.addAll(leftFromIndex, rightPlanningValueList); rightList.addAll(leftSubListDestinationIndex, leftPlanningValueList); castScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, fromIndex, toIndex); } else { castScoreDirector.beforeListVariableChanged(variableDescriptor, leftEntity, leftFromIndex, leftFromIndex + leftSubListLength); castScoreDirector.beforeListVariableChanged(variableDescriptor, rightEntity, rightFromIndex, rightFromIndex + rightSubListLength); rightSubListView.clear(); leftSubListView.clear(); leftList.addAll(leftFromIndex, rightPlanningValueList); rightList.addAll(rightFromIndex, leftPlanningValueList); castScoreDirector.afterListVariableChanged(variableDescriptor, leftEntity, leftFromIndex, leftFromIndex + rightSubListLength); castScoreDirector.afterListVariableChanged(variableDescriptor, rightEntity, rightFromIndex, rightFromIndex + leftSubListLength); } } @Override public SubListSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubListSwapMove<>( variableDescriptor, leftSubList.rebase(destinationScoreDirector), rightSubList.rebase(destinationScoreDirector), reversing); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<Object> getPlanningEntities() { // Use LinkedHashSet for predictable iteration order. Set<Object> entities = new LinkedHashSet<>(2); entities.add(leftSubList.entity()); entities.add(rightSubList.entity()); return entities; } @Override public Collection<Object> getPlanningValues() { return CollectionUtils.concat(leftPlanningValueList, rightPlanningValueList); } private List<Object> subList(SubList subList) { return variableDescriptor.getValue(subList.entity()).subList(subList.fromIndex(), subList.getToIndex()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubListSwapMove<?> other = (SubListSwapMove<?>) o; return reversing == other.reversing && rightFromIndex == other.rightFromIndex && leftToIndex == other.leftToIndex && variableDescriptor.equals(other.variableDescriptor) && leftSubList.equals(other.leftSubList) && rightSubList.equals(other.rightSubList); } @Override public int hashCode() { return Objects.hash(variableDescriptor, leftSubList, rightSubList, reversing, rightFromIndex, leftToIndex); } @Override public String toString() { return "{" + leftSubList + "} <-" + (reversing ? "reversing-" : "") + "> {" + rightSubList + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListSwapMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; public class SubListSwapMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, SubListSwapMoveSelectorConfig> { public SubListSwapMoveSelectorFactory(SubListSwapMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { if (!randomSelection) { throw new IllegalArgumentException("The subListSwapMoveSelector (" + config + ") only supports random selection order."); } var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); var onlyEntityDescriptor = getTheOnlyEntityDescriptorWithListVariable(configPolicy.getSolutionDescriptor()); // We defined the entity class since there is a single entity descriptor that includes a list variable var entitySelector = EntitySelectorFactory .<Solution_> create(new EntitySelectorConfig().withEntityClass(onlyEntityDescriptor.getEntityClass())) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); var subListSelectorConfig = Objects.requireNonNullElseGet(config.getSubListSelectorConfig(), SubListSelectorConfig::new); var secondarySubListSelectorConfig = Objects.requireNonNullElse(config.getSecondarySubListSelectorConfig(), subListSelectorConfig); // minimum -> subListSelector SubListConfigUtil.transferDeprecatedMinimumSubListSize( config, SubListSwapMoveSelectorConfig::getMinimumSubListSize, "subListSelector", subListSelectorConfig); // maximum -> subListSelector SubListConfigUtil.transferDeprecatedMaximumSubListSize( config, SubListSwapMoveSelectorConfig::getMaximumSubListSize, "subListSelector", subListSelectorConfig); if (subListSelectorConfig != secondarySubListSelectorConfig) { // minimum -> secondarySubListSelector SubListConfigUtil.transferDeprecatedMinimumSubListSize( config, SubListSwapMoveSelectorConfig::getMinimumSubListSize, "secondarySubListSelector", secondarySubListSelectorConfig); // maximum -> secondarySubListSelector SubListConfigUtil.transferDeprecatedMaximumSubListSize( config, SubListSwapMoveSelectorConfig::getMaximumSubListSize, "secondarySubListSelector", secondarySubListSelectorConfig); } var leftSubListSelector = SubListSelectorFactory .<Solution_> create(subListSelectorConfig) .buildSubListSelector(configPolicy, entitySelector, minimumCacheType, selectionOrder); var rightSubListSelector = SubListSelectorFactory .<Solution_> create(secondarySubListSelectorConfig) .buildSubListSelector(configPolicy, entitySelector, minimumCacheType, selectionOrder); var selectReversingMoveToo = Objects.requireNonNullElse(config.getSelectReversingMoveToo(), true); return new RandomSubListSwapMoveSelector<>(leftSubListSelector, rightSubListSelector, selectReversingMoveToo); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/SubListUnassignMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list; import java.util.Collection; import java.util.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.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.selector.list.SubList; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SubListUnassignMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object sourceEntity; private final int sourceIndex; private final int length; private Collection<Object> planningValues; public SubListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, SubList subList) { this(variableDescriptor, subList.entity(), subList.fromIndex(), subList.length()); } private SubListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex, int length) { this.variableDescriptor = variableDescriptor; this.sourceEntity = sourceEntity; this.sourceIndex = sourceIndex; this.length = length; } public Object getSourceEntity() { return sourceEntity; } public int getFromIndex() { return sourceIndex; } public int getSubListSize() { return length; } public int getToIndex() { return sourceIndex + length; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { if (sourceIndex < 0) { return false; } return variableDescriptor.getListSize(sourceEntity) >= getToIndex(); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var sourceList = variableDescriptor.getValue(sourceEntity); var subList = sourceList.subList(sourceIndex, getToIndex()); planningValues = List.copyOf(subList); for (var element : subList) { castScoreDirector.beforeListVariableElementUnassigned(variableDescriptor, element); castScoreDirector.afterListVariableElementUnassigned(variableDescriptor, element); } castScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, getToIndex()); subList.clear(); castScoreDirector.afterListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex); } @Override public SubListUnassignMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SubListUnassignMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(sourceEntity), sourceIndex, length); } @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<Object> getPlanningEntities() { return List.of(sourceEntity); } @Override public Collection<Object> getPlanningValues() { return planningValues; } @Override public boolean equals(Object o) { if (o instanceof SubListUnassignMove<?> other) { return sourceIndex == other.sourceIndex && length == other.length && variableDescriptor.equals(other.variableDescriptor) && sourceEntity.equals(other.sourceEntity); } return false; } @Override public int hashCode() { return Objects.hash(variableDescriptor, sourceEntity, sourceIndex, length); } @Override public String toString() { return String.format("|%d| {%s[%d..%d] -> null}", length, sourceEntity, sourceIndex, getToIndex()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/EntityOrderInfo.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.Arrays; import java.util.IdentityHashMap; import java.util.Map; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; record EntityOrderInfo(Object[] entities, Map<Object, Integer> entityToEntityIndex, int[] offsets) { public static <Node_> EntityOrderInfo of(Node_[] pickedValues, ListVariableStateSupply<?> listVariableStateSupply) { var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); var entityToEntityIndex = new IdentityHashMap<Object, Integer>(); for (var i = 1; i < pickedValues.length && pickedValues[i] != null; i++) { var value = pickedValues[i]; var entity = listVariableStateSupply.getInverseSingleton(value); if (!listVariableDescriptor.getEntityDescriptor().isMovable(null, entity)) { throw new IllegalStateException("Impossible state: immovable entity (%s) picked through value (%s)." .formatted(entity, value)); } entityToEntityIndex.computeIfAbsent(entity, __ -> entityToEntityIndex.size()); } var entities = new Object[entityToEntityIndex.size()]; var offsets = new int[entities.length]; for (var entityAndIndex : entityToEntityIndex.entrySet()) { entities[entityAndIndex.getValue()] = entityAndIndex.getKey(); } for (var i = 1; i < offsets.length; i++) { offsets[i] = offsets[i - 1] + listVariableDescriptor.getListSize(entities[i - 1]); } return new EntityOrderInfo(entities, entityToEntityIndex, offsets); } public <Node_> EntityOrderInfo withNewNode(Node_ node, ListVariableStateSupply<?> listVariableStateSupply) { var entity = listVariableStateSupply.getInverseSingleton(node); if (entityToEntityIndex.containsKey(entity)) { return this; } else { var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); var newEntities = Arrays.copyOf(entities, entities.length + 1); Map<Object, Integer> newEntityToEntityIndex = new IdentityHashMap<>(entityToEntityIndex); var newOffsets = Arrays.copyOf(offsets, offsets.length + 1); newEntities[entities.length] = entity; newEntityToEntityIndex.put(entity, entities.length); newOffsets[entities.length] = offsets[entities.length - 1] + listVariableDescriptor.getListSize(entities[entities.length - 1]); return new EntityOrderInfo(newEntities, newEntityToEntityIndex, newOffsets); } } @SuppressWarnings("unchecked") public <Node_> Node_ successor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) { var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); var elementPosition = listVariableStateSupply.getElementPosition(object) .ensureAssigned(); var entity = elementPosition.entity(); var indexInEntityList = elementPosition.index(); var listVariable = listVariableDescriptor.getValue(entity); if (indexInEntityList == listVariable.size() - 1) { var nextEntityIndex = (entityToEntityIndex.get(entity) + 1) % entities.length; var nextEntity = entities[nextEntityIndex]; var firstUnpinnedIndexInList = listVariableDescriptor.getFirstUnpinnedIndex(nextEntity); return listVariableDescriptor.getElement(nextEntity, firstUnpinnedIndexInList); } else { return (Node_) listVariable.get(indexInEntityList + 1); } } @SuppressWarnings("unchecked") public <Node_> Node_ predecessor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) { var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); var elementPosition = listVariableStateSupply.getElementPosition(object) .ensureAssigned(); var entity = elementPosition.entity(); var indexInEntityList = elementPosition.index(); var firstUnpinnedIndexInList = listVariableDescriptor.getFirstUnpinnedIndex(entity); if (indexInEntityList == firstUnpinnedIndexInList) { // add entities.length to ensure modulo result is positive var previousEntityIndex = (entityToEntityIndex.get(entity) - 1 + entities.length) % entities.length; var listVariable = listVariableDescriptor.getValue(entities[previousEntityIndex]); return (Node_) listVariable.get(listVariable.size() - 1); } else { return listVariableDescriptor.getElement(entity, indexInEntityList - 1); } } public <Node_> boolean between(Node_ start, Node_ middle, Node_ end, ListVariableStateSupply<?> listVariableStateSupply) { var startElementPosition = listVariableStateSupply.getElementPosition(start) .ensureAssigned(); var middleElementPosition = listVariableStateSupply.getElementPosition(middle) .ensureAssigned(); var endElementPosition = listVariableStateSupply.getElementPosition(end) .ensureAssigned(); int startEntityIndex = entityToEntityIndex.get(startElementPosition.entity()); int middleEntityIndex = entityToEntityIndex.get(middleElementPosition.entity()); int endEntityIndex = entityToEntityIndex.get(endElementPosition.entity()); var startIndex = startElementPosition.index() + offsets[startEntityIndex]; var middleIndex = middleElementPosition.index() + offsets[middleEntityIndex]; var endIndex = endElementPosition.index() + offsets[endEntityIndex]; if (startIndex <= endIndex) { // test middleIndex in [startIndex, endIndex] return startIndex <= middleIndex && middleIndex <= endIndex; } else { // test middleIndex in [0, endIndex] or middleIndex in [startIndex, listSize) return middleIndex >= startIndex || middleIndex <= endIndex; } } @Override public boolean equals(Object o) { return o instanceof EntityOrderInfo that && Arrays.equals(entities, that.entities) && Objects.equals(entityToEntityIndex, that.entityToEntityIndex) && Arrays.equals(offsets, that.offsets); } @Override public int hashCode() { var result = Objects.hash(entityToEntityIndex); result = 31 * result + Arrays.hashCode(entities); result = 31 * result + Arrays.hashCode(offsets); return result; } @Override public String toString() { return "EntityOrderInfo{" + "entities=" + Arrays.toString(entities) + ", entityToEntityIndex=" + entityToEntityIndex + ", offsets=" + Arrays.toString(offsets) + '}'; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/FlipSublistAction.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.Collections; import java.util.List; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; /** * Flips a sublist of a list variable, (the same thing as a {@link TwoOptListMove}, but no shift to restore the original * origin). * For instance, given [0, 1, 2, 3, 4], fromIndexInclusive = 1, toIndexExclusive = 3, * the list after the move would be [0, 3, 2, 1, 4]. * If toIndexExclusive is before fromIndexInclusive, * the flip is performed on the combined sublists [fromIndexInclusive, size) and [0, toIndexExclusive). * For instance, given [0, 1, 2, 3, 4, 5, 6], fromIndexInclusive = 5, toIndexExclusive = 2, * the list after the move would be [6, 5, 2, 3, 4, 1, 0] (and not [0, 6, 5, 2, 3, 4, 1]). */ record FlipSublistAction(ListVariableDescriptor<?> variableDescriptor, int fromIndexInclusive, int toIndexExclusive) { FlipSublistAction createUndoMove() { return new FlipSublistAction(variableDescriptor, fromIndexInclusive, toIndexExclusive); } public KOptAffectedElements getAffectedElements() { if (fromIndexInclusive < toIndexExclusive) { return KOptAffectedElements.forMiddleRange(fromIndexInclusive, toIndexExclusive); } else { return KOptAffectedElements.forWrappedRange(fromIndexInclusive, toIndexExclusive); } } void execute(MultipleDelegateList<?> combinedList) { // MultipleDelegateList uses subLists starting from entityFirstUnpinnedIndex, // so we should use 0 as the start of the list (as we are flipping the entire // combinedList of sub-lists instead of a particular entity list). flipSublist(combinedList, 0, fromIndexInclusive, toIndexExclusive); } public FlipSublistAction rebase() { return new FlipSublistAction(variableDescriptor, fromIndexInclusive, toIndexExclusive); } public static <T> void flipSublist(List<T> originalList, int entityFirstUnpinnedIndex, int fromIndexInclusive, int toIndexExclusive) { if (fromIndexInclusive < toIndexExclusive) { Collections.reverse(originalList.subList(fromIndexInclusive, toIndexExclusive)); } else { var firstHalfReversedPath = originalList.subList(fromIndexInclusive, originalList.size()); var secondHalfReversedPath = originalList.subList(entityFirstUnpinnedIndex, toIndexExclusive); // Reverse the combined list firstHalfReversedPath + secondHalfReversedPath // For instance, (1, 2, 3)(4, 5, 6, 7, 8, 9) becomes // (9, 8, 7)(6, 5, 4, 3, 2, 1) var totalLength = firstHalfReversedPath.size() + secondHalfReversedPath.size(); for (var i = 0; (i < totalLength >> 1); i++) { if (i < firstHalfReversedPath.size()) { if (i < secondHalfReversedPath.size()) { // firstHalfIndex = i var secondHalfIndex = secondHalfReversedPath.size() - i - 1; var savedFirstItem = firstHalfReversedPath.get(i); firstHalfReversedPath.set(i, secondHalfReversedPath.get(secondHalfIndex)); secondHalfReversedPath.set(secondHalfIndex, savedFirstItem); } else { // firstIndex = i var secondIndex = firstHalfReversedPath.size() - i + secondHalfReversedPath.size() - 1; var savedFirstItem = firstHalfReversedPath.get(i); firstHalfReversedPath.set(i, firstHalfReversedPath.get(secondIndex)); firstHalfReversedPath.set(secondIndex, savedFirstItem); } } else { var firstIndex = i - firstHalfReversedPath.size(); var secondIndex = secondHalfReversedPath.size() - i - 1; var savedFirstItem = secondHalfReversedPath.get(firstIndex); secondHalfReversedPath.set(firstIndex, secondHalfReversedPath.get(secondIndex)); secondHalfReversedPath.set(secondIndex, savedFirstItem); } } } } @Override public String toString() { return "FlipSublistAction(from=" + fromIndexInclusive + ", to=" + toIndexExclusive + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptAffectedElements.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.Collections; import java.util.List; import ai.timefold.solver.core.impl.util.CollectionUtils; record KOptAffectedElements(int wrappedStartIndex, int wrappedEndIndex, List<Range> affectedMiddleRangeList) { static KOptAffectedElements forMiddleRange(int startInclusive, int endExclusive) { return new KOptAffectedElements(-1, -1, List.of(new Range(startInclusive, endExclusive))); } static KOptAffectedElements forWrappedRange(int startInclusive, int endExclusive) { return new KOptAffectedElements(startInclusive, endExclusive, Collections.emptyList()); } public KOptAffectedElements merge(KOptAffectedElements other) { var newWrappedStartIndex = this.wrappedStartIndex; var newWrappedEndIndex = this.wrappedEndIndex; if (other.wrappedStartIndex != -1) { if (newWrappedStartIndex != -1) { newWrappedStartIndex = Math.min(other.wrappedStartIndex, newWrappedStartIndex); newWrappedEndIndex = Math.max(other.wrappedEndIndex, newWrappedEndIndex); } else { newWrappedStartIndex = other.wrappedStartIndex; newWrappedEndIndex = other.wrappedEndIndex; } } var newAffectedMiddleRangeList = CollectionUtils.concat(affectedMiddleRangeList, other.affectedMiddleRangeList); boolean removedAny; SearchForIntersectingRange: do { removedAny = false; final var listSize = newAffectedMiddleRangeList.size(); for (var i = 0; i < listSize; i++) { for (var j = i + 1; j < listSize; j++) { var leftRange = newAffectedMiddleRangeList.get(i); var rightRange = newAffectedMiddleRangeList.get(j); if (leftRange.startInclusive() <= rightRange.endExclusive()) { if (rightRange.startInclusive() <= leftRange.endExclusive()) { var mergedRange = new Range(Math.min(leftRange.startInclusive(), rightRange.startInclusive()), Math.max(leftRange.endExclusive(), rightRange.endExclusive())); newAffectedMiddleRangeList.set(i, mergedRange); newAffectedMiddleRangeList.remove(j); removedAny = true; continue SearchForIntersectingRange; } } } } } while (removedAny); return new KOptAffectedElements(newWrappedStartIndex, newWrappedEndIndex, newAffectedMiddleRangeList); } public record Range(int startInclusive, int endExclusive) { } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptCycle.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Describes the minimal amount of cycles a permutation can be expressed as * and provide a mapping of removed edge endpoint index to cycle identifier * (where all indices that are in the same k-cycle have the same identifier). * * @param cycleCount The total number of k-cycles in the permutation. * This is one more than the maximal value in {@link KOptCycle#indexToCycleIdentifier}. * @param indexToCycleIdentifier Maps an index in the removed endpoints to the cycle it belongs to * after the new edges are added. * Ranges from 0 to {@link #cycleCount} - 1. */ record KOptCycle(int cycleCount, int[] indexToCycleIdentifier) { @Override public boolean equals(Object o) { return o instanceof KOptCycle that && cycleCount == that.cycleCount && Arrays.equals(indexToCycleIdentifier, that.indexToCycleIdentifier); } @Override public int hashCode() { var result = Objects.hash(cycleCount); result = 31 * result + Arrays.hashCode(indexToCycleIdentifier); return result; } @Override public String toString() { var arrayString = IntStream.of(indexToCycleIdentifier) .sequential() .skip(1) .mapToObj(Integer::toString) .collect(Collectors.joining(", ", "[", "]")); return "KOptCycleInfo(" + "cycleCount=" + cycleCount + ", indexToCycleIdentifier=" + arrayString + ')'; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptDescriptor.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.IntStream; import ai.timefold.solver.core.api.function.TriPredicate; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.index.IndexVariableSupply; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; /** * * @param k the number of edges being added * @param removedEdges sequence of 2k nodes that forms the sequence of edges being removed * @param removedEdgeIndexToTourOrder node visit order when the tour is traveled in the successor direction. * This forms a 2k-cycle representing the permutation performed by the K-opt move. * @param inverseRemovedEdgeIndexToTourOrder node visit order when the tour is traveled in the predecessor direction. * It is the inverse of {@link KOptDescriptor#removedEdgeIndexToTourOrder} * (i.e. {@link KOptDescriptor#removedEdgeIndexToTourOrder}[inverseRemovedEdgeIndexToTourOrder[i]] == i * @param addedEdgeToOtherEndpoint maps the index of a removed edge endpoint to its corresponding added edge other endpoint. * For instance, if the removed edges are (a, b), (c, d), (e, f) and the added edges are (a, d), (c, f), (e, b), then * <br /> * removedEdges = [null, a, b, c, d, e, f] <br /> * addedEdgeToOtherEndpoint = [null, 4, 5, 6, 1, 2, 3] <br /> * <br /> * For any valid removedEdges index, (removedEdges[index], removedEdges[addedEdgeToOtherEndpoint[index]]) * is an edge added by this K-Opt move. * @param <Node_> */ record KOptDescriptor<Node_>(int k, Node_[] removedEdges, int[] removedEdgeIndexToTourOrder, int[] inverseRemovedEdgeIndexToTourOrder, int[] addedEdgeToOtherEndpoint) { static <Node_> int[] computeInEdgesForSequentialMove(Node_[] removedEdges) { var out = new int[removedEdges.length]; var k = (removedEdges.length - 1) >> 1; out[1] = removedEdges.length - 1; out[removedEdges.length - 1] = 1; for (var i = 1; i < k; i++) { out[2 * i + 1] = 2 * i; out[2 * i] = 2 * i + 1; } return out; } /** * Create a sequential {@link KOptDescriptor} from the given removed edges. * * @param removedEdges The edges removed from the tour. The added edges will * be formed from opposite endpoints for consecutive edges. * @param endpointToSuccessorFunction A {@link Function} that maps an endpoint to its successor * @param betweenPredicate A {@link TriPredicate} that return true if and only if its middle * argument is between its first and last argument when the tour is * taken in the successor direction. */ KOptDescriptor( Node_[] removedEdges, Function<Node_, Node_> endpointToSuccessorFunction, TriPredicate<Node_, Node_, Node_> betweenPredicate) { this(removedEdges, computeInEdgesForSequentialMove(removedEdges), endpointToSuccessorFunction, betweenPredicate); } /** * Create as sequential or non-sequential {@link KOptDescriptor} from the given removed * and added edges. * * @param removedEdges The edges removed from the tour. * @param addedEdgeToOtherEndpoint The edges added to the tour. * @param endpointToSuccessorFunction A {@link Function} that maps an endpoint to its successor * @param betweenPredicate A {@link TriPredicate} that return true if and only if its middle * argument is between its first and last argument when the tour is * taken in the successor direction. */ KOptDescriptor( Node_[] removedEdges, int[] addedEdgeToOtherEndpoint, Function<Node_, Node_> endpointToSuccessorFunction, TriPredicate<Node_, Node_, Node_> betweenPredicate) { this((removedEdges.length - 1) >> 1, removedEdges, new int[removedEdges.length], new int[removedEdges.length], addedEdgeToOtherEndpoint); // Compute the permutation as described in FindPermutation // (Section 5.3 "Determination of the feasibility of a move", // An Effective Implementation of K-opt Moves for the Lin-Kernighan TSP Heuristic) for (int i = 1, j = 1; j <= k; i += 2, j++) { removedEdgeIndexToTourOrder[j] = (endpointToSuccessorFunction.apply(removedEdges[i]) == removedEdges[i + 1]) ? i : i + 1; } Comparator<Integer> comparator = (pa, pb) -> pa.equals(pb) ? 0 : (betweenPredicate.test(removedEdges[removedEdgeIndexToTourOrder[1]], removedEdges[pa], removedEdges[pb]) ? -1 : 1); var wrappedRemovedEdgeIndexToTourOrder = IntStream.of(removedEdgeIndexToTourOrder).boxed() .toArray(Integer[]::new); Arrays.sort(wrappedRemovedEdgeIndexToTourOrder, 2, k + 1, comparator); for (var i = 0; i < removedEdgeIndexToTourOrder.length; i++) { removedEdgeIndexToTourOrder[i] = wrappedRemovedEdgeIndexToTourOrder[i]; } for (int i, j = 2 * k; j >= 2; j -= 2) { removedEdgeIndexToTourOrder[j - 1] = i = removedEdgeIndexToTourOrder[j / 2]; removedEdgeIndexToTourOrder[j] = ((i & 1) == 1) ? i + 1 : i - 1; } for (var i = 1; i <= 2 * k; i++) { inverseRemovedEdgeIndexToTourOrder[removedEdgeIndexToTourOrder[i]] = i; } } // **************************************************** // Complex Methods // **************************************************** /** * This return a {@link KOptListMove} that corresponds to this {@link KOptDescriptor}. <br /> * <br /> * It implements the algorithm described in the paper * <a href="https://dl.acm.org/doi/pdf/10.1145/300515.300516">"Transforming Cabbage into Turnip: Polynomial * Algorithm for Sorting Signed Permutations by Reversals"</a> which is used in the paper * <a href="http://webhotel4.ruc.dk/~keld/research/LKH/KoptReport.pdf">"An Effective Implementation of K-opt Moves * for the Lin-Kernighan TSP Heuristic"</a> (Section 5.4 "Execution of a feasible move") to perform a K-opt move * by performing the minimal number of list reversals to transform the current route into the new route after the * K-opt. We use it here to calculate the {@link FlipSublistAction} list for the {@link KOptListMove} that is * described by this {@link KOptDescriptor}.<br /> * <br /> * The algorithm goal is to convert a signed permutation (p_1, p_2, ..., p_(2k)) into the identify permutation * (+1, +2, +3, ..., +(2k - 1), +2k). It can be summarized as: * * <ul> * <li> * As long as there are oriented pairs, perform the reversal that corresponds to the oriented pair with the * maximal score (described in {@link #countOrientedPairsForReversal}). * </li> * <li> * If there are no oriented pairs, Find the pair (p_i, p_j) for which |p_j – p_i| = 1, j >= i + 3, * and i is minimal. Then reverse the segment (p_(i+1) ... p_(j-1). This corresponds to a * hurdle cutting operation. Normally, this is not enough to guarantee the number of reversals * is optimal, but since each hurdle corresponds to a unique cycle, the number of hurdles in * the list at any point is at most 1 (and thus, hurdle cutting is the optimal move). (A hurdle * is an subsequence [i, p_j, p_(j+1)..., p_(j+k-1) i+k] that can be sorted so * [i, p_j, p_(j+1)..., p_(j+k-1), i+k] are all consecutive integers, which does not contain a subsequence * with the previous property ([4, 7, 6, 5, 8] is a hurdle, since the subsequence [7, 6, 5] does not * contain all the items between 7 and 5 [8, 1, 2, 3, 4]). This create enough enough oriented pairs * to completely sort the permutation. * </li> * <li> * When there are no oriented pairs and no hurdles, the algorithm is completed. * </li> * </ul> */ public <Solution_> KOptListMove<Solution_> getKOptListMove(ListVariableStateSupply<Solution_> listVariableStateSupply) { var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); if (!isFeasible()) { // A KOptListMove move with an empty flip move list is not feasible, since if executed, it's a no-op. return new KOptListMove<>(listVariableDescriptor, this, new MultipleDelegateList<>(), List.of(), 0, new int[] {}); } var combinedList = computeCombinedList(listVariableDescriptor, listVariableStateSupply); IndexVariableSupply indexVariableSupply = node -> combinedList.getIndexOfValue(listVariableStateSupply, node); var entityListSize = combinedList.size(); List<FlipSublistAction> out = new ArrayList<>(); var originalToCurrentIndexList = new int[entityListSize]; for (var index = 0; index < entityListSize; index++) { originalToCurrentIndexList[index] = index; } var isMoveNotDone = true; var bestOrientedPairFirstEndpoint = -1; var bestOrientedPairSecondEndpoint = -1; // Copy removedEdgeIndexToTourOrder and inverseRemovedEdgeIndexToTourOrder // to avoid mutating the original arrays // since this function mutates the arrays into the sorted signed permutation (+1, +2, ...). var currentRemovedEdgeIndexToTourOrder = Arrays.copyOf(removedEdgeIndexToTourOrder, removedEdgeIndexToTourOrder.length); var currentInverseRemovedEdgeIndexToTourOrder = Arrays.copyOf(inverseRemovedEdgeIndexToTourOrder, inverseRemovedEdgeIndexToTourOrder.length); FindNextReversal: while (isMoveNotDone) { var maximumOrientedPairCountAfterReversal = -1; for (var firstEndpoint = 1; firstEndpoint <= 2 * k - 2; firstEndpoint++) { var firstEndpointCurrentTourIndex = currentRemovedEdgeIndexToTourOrder[firstEndpoint]; var nextEndpointTourIndex = addedEdgeToOtherEndpoint[firstEndpointCurrentTourIndex]; var secondEndpoint = currentInverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex]; if (secondEndpoint >= firstEndpoint + 2 && (firstEndpoint & 1) == (secondEndpoint & 1)) { var orientedPairCountAfterReversal = ((firstEndpoint & 1) == 1) ? countOrientedPairsForReversal(currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, firstEndpoint + 1, secondEndpoint) : countOrientedPairsForReversal(currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, firstEndpoint, secondEndpoint - 1); if (orientedPairCountAfterReversal > maximumOrientedPairCountAfterReversal) { maximumOrientedPairCountAfterReversal = orientedPairCountAfterReversal; bestOrientedPairFirstEndpoint = firstEndpoint; bestOrientedPairSecondEndpoint = secondEndpoint; } } } if (maximumOrientedPairCountAfterReversal >= 0) { if ((bestOrientedPairFirstEndpoint & 1) == 1) { out.add(getListReversalMoveForEdgePair(listVariableDescriptor, indexVariableSupply, originalToCurrentIndexList, removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint + 1]], removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint]], removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint]], removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint + 1]])); reversePermutationPart(currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, bestOrientedPairFirstEndpoint + 1, bestOrientedPairSecondEndpoint); } else { out.add(getListReversalMoveForEdgePair(listVariableDescriptor, indexVariableSupply, originalToCurrentIndexList, removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint - 1]], removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairFirstEndpoint]], removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint]], removedEdges[currentRemovedEdgeIndexToTourOrder[bestOrientedPairSecondEndpoint - 1]])); reversePermutationPart(currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, bestOrientedPairFirstEndpoint, bestOrientedPairSecondEndpoint - 1); } continue; } // There are no oriented pairs; check for a hurdle for (var firstEndpoint = 1; firstEndpoint <= 2 * k - 1; firstEndpoint += 2) { var firstEndpointCurrentTourIndex = currentRemovedEdgeIndexToTourOrder[firstEndpoint]; var nextEndpointTourIndex = addedEdgeToOtherEndpoint[firstEndpointCurrentTourIndex]; var secondEndpoint = currentInverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex]; if (secondEndpoint >= firstEndpoint + 2) { out.add(getListReversalMoveForEdgePair(listVariableDescriptor, indexVariableSupply, originalToCurrentIndexList, removedEdges[currentRemovedEdgeIndexToTourOrder[firstEndpoint]], removedEdges[currentRemovedEdgeIndexToTourOrder[firstEndpoint + 1]], removedEdges[currentRemovedEdgeIndexToTourOrder[secondEndpoint]], removedEdges[currentRemovedEdgeIndexToTourOrder[secondEndpoint - 1]])); reversePermutationPart(currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, firstEndpoint + 1, secondEndpoint - 1); continue FindNextReversal; } } isMoveNotDone = false; } var startElementShift = -indexOf(originalToCurrentIndexList, 0); var newEndIndices = new int[combinedList.delegates.length]; var totalOffset = 0; for (var i = 0; i < newEndIndices.length; i++) { var listSize = combinedList.delegateSizes[i]; newEndIndices[i] = totalOffset + listSize - 1; totalOffset += listSize; } newEndIndices = IntStream.of(newEndIndices) .map(index -> indexOf(originalToCurrentIndexList, index)) .sorted() .toArray(); newEndIndices[newEndIndices.length - 1] = originalToCurrentIndexList.length - 1; return new KOptListMove<>(listVariableDescriptor, this, combinedList, out, startElementShift, newEndIndices); } /** * Return true if and only if performing the K-opt move described by this {@link KOptDescriptor} will result in a * single cycle. * * @param minK * @param maxK * @return true if and only if performing the K-opt move described by this {@link KOptDescriptor} will result in a * single cycle, false otherwise. */ public boolean isFeasible(int minK, int maxK) { if (k < minK || k > maxK) { throw new IllegalStateException("Impossible state: The k-opt move k-value (%d) is not in the range [%d, %d]." .formatted(k, minK, maxK)); } return isFeasible(); } private boolean isFeasible() { var count = 0; var currentEndpoint = 2 * k; // This loop calculate the length of the cycle that the endpoint at removedEdges[2k] is connected // to by iterating the loop in reverse. We know that the successor of removedEdges[2k] is 0, which // give us our terminating condition. while (currentEndpoint != 0) { count++; var currentEndpointTourIndex = removedEdgeIndexToTourOrder[currentEndpoint]; var nextEndpointTourIndex = addedEdgeToOtherEndpoint[currentEndpointTourIndex]; currentEndpoint = inverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex] ^ 1; } return (count == k); } /** * Reverse an array between two indices and update its inverse array to point at the new locations. * * @param startInclusive Reverse the array starting at and including this index. * @param endExclusive Reverse the array ending at and excluding this index. */ private void reversePermutationPart(int[] currentRemovedEdgeIndexToTourOrder, int[] currentInverseRemovedEdgeIndexToTourOrder, int startInclusive, int endExclusive) { while (startInclusive < endExclusive) { var savedFirstElement = currentRemovedEdgeIndexToTourOrder[startInclusive]; currentRemovedEdgeIndexToTourOrder[startInclusive] = currentRemovedEdgeIndexToTourOrder[endExclusive]; currentInverseRemovedEdgeIndexToTourOrder[currentRemovedEdgeIndexToTourOrder[endExclusive]] = startInclusive; currentRemovedEdgeIndexToTourOrder[endExclusive] = savedFirstElement; currentInverseRemovedEdgeIndexToTourOrder[savedFirstElement] = endExclusive; startInclusive++; endExclusive--; } } /** * Calculate the "score" of performing a flip on a signed permutation p.<br> * <br> * Let p = (p_1 ..., p_n) be a signed permutation. An oriented pair (p_i, p_j) is a pair * of adjacent integers, that is |p_i| - |p_j| = ±1, with opposite signs. For example, * the signed permutation <br /> * (+1 -2 -5 +4 +3) <br /> * contains three oriented pairs: (+1, -2), (-2, +3), and (-5, +4). * Oriented pairs are useful as they indicate reversals that cause adjacent integers to be * consecutive in the resulting permutation. For example, the oriented pair (-2, +3) induces * the reversal <br> * (+1 -2 -5 +4 +3) -> (+1 -4 +5 +2 +3) <br> * creating a permutation where +3 is consecutive to +2. <br /> * <br /> * In general, the reversal induced by and oriented pair (p_i, p_j) is <br /> * p(i, j-1), if p_i + p_j = +1, and <br /> * p(i+1, j), if p_i + p_j = -1 <br /> * Such a reversal is called an oriented reversal. <br /> * * The score of an oriented reversal is defined as the number of oriented pairs * in the resulting permutation. <br /> * <br /> * This function perform the reversal indicated by the oriented pair, count the * number of oriented pairs in the new permutation, undo the reversal and return * the score. * * @param left The left endpoint of the flip * @param right the right endpoint of the flip * @return The score of the performing the signed reversal */ private int countOrientedPairsForReversal(int[] currentRemovedEdgeIndexToTourOrder, int[] currentInverseRemovedEdgeIndexToTourOrder, int left, int right) { int count = 0, i, j; reversePermutationPart( currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, left, right); for (i = 1; i <= 2 * k - 2; i++) { var currentTourIndex = currentRemovedEdgeIndexToTourOrder[i]; var otherEndpointTourIndex = addedEdgeToOtherEndpoint[currentTourIndex]; j = currentInverseRemovedEdgeIndexToTourOrder[otherEndpointTourIndex]; if (j >= i + 2 && (i & 1) == (j & 1)) { count++; } } reversePermutationPart( currentRemovedEdgeIndexToTourOrder, currentInverseRemovedEdgeIndexToTourOrder, left, right); return count; } /** * Get a {@link FlipSublistAction} that reverses the sublist that consists of the path * between the start and end of the given edges. * * @param listVariableDescriptor * @param indexVariableSupply * @param originalToCurrentIndexList * @param firstEdgeStart * @param firstEdgeEnd * @param secondEdgeStart * @param secondEdgeEnd * @return */ @SuppressWarnings("unchecked") private static <Node_> FlipSublistAction getListReversalMoveForEdgePair( ListVariableDescriptor<?> listVariableDescriptor, IndexVariableSupply indexVariableSupply, int[] originalToCurrentIndexList, Node_ firstEdgeStart, Node_ firstEdgeEnd, Node_ secondEdgeStart, Node_ secondEdgeEnd) { var originalFirstEdgeStartIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(firstEdgeStart)); var originalFirstEdgeEndIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(firstEdgeEnd)); var originalSecondEdgeStartIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(secondEdgeStart)); var originalSecondEdgeEndIndex = indexOf(originalToCurrentIndexList, indexVariableSupply.getIndex(secondEdgeEnd)); var firstEndpoint = ((originalFirstEdgeStartIndex + 1) % originalToCurrentIndexList.length) == originalFirstEdgeEndIndex ? originalFirstEdgeEndIndex : originalFirstEdgeStartIndex; var secondEndpoint = ((originalSecondEdgeStartIndex + 1) % originalToCurrentIndexList.length) == originalSecondEdgeEndIndex ? originalSecondEdgeEndIndex : originalSecondEdgeStartIndex; KOptUtils.flipSubarray(originalToCurrentIndexList, firstEndpoint, secondEndpoint); return new FlipSublistAction(listVariableDescriptor, firstEndpoint, secondEndpoint); } @SuppressWarnings("unchecked") private MultipleDelegateList<Node_> computeCombinedList(ListVariableDescriptor<?> listVariableDescriptor, SingletonInverseVariableSupply inverseVariableSupply) { var entityToEntityIndex = new IdentityHashMap<Object, Integer>(); for (var i = 1; i < removedEdges.length; i++) { entityToEntityIndex.computeIfAbsent(inverseVariableSupply.getInverseSingleton(removedEdges[i]), entity -> entityToEntityIndex.size()); } var entities = new Object[entityToEntityIndex.size()]; List<Node_>[] entityLists = new List[entities.length]; for (var entry : entityToEntityIndex.entrySet()) { int index = entry.getValue(); Object entity = entry.getKey(); entities[index] = entity; entityLists[index] = (List<Node_>) listVariableDescriptor.getUnpinnedSubList(entity); } return new MultipleDelegateList<>(entities, entityLists); } private static int indexOf(int[] search, int query) { for (var i = 0; i < search.length; i++) { if (search[i] == query) { return i; } } return -1; } @Override public boolean equals(Object o) { return o instanceof KOptDescriptor<?> that && k == that.k && Arrays.equals(removedEdges, that.removedEdges) && Arrays.equals(removedEdgeIndexToTourOrder, that.removedEdgeIndexToTourOrder) && Arrays.equals(inverseRemovedEdgeIndexToTourOrder, that.inverseRemovedEdgeIndexToTourOrder) && Arrays.equals(addedEdgeToOtherEndpoint, that.addedEdgeToOtherEndpoint); } @Override public int hashCode() { int result = Objects.hash(k); result = 31 * result + Arrays.hashCode(removedEdges); result = 31 * result + Arrays.hashCode(removedEdgeIndexToTourOrder); result = 31 * result + Arrays.hashCode(inverseRemovedEdgeIndexToTourOrder); result = 31 * result + Arrays.hashCode(addedEdgeToOtherEndpoint); return result; } public String toString() { return k + "-opt(removed=" + KOptUtils.getRemovedEdgeList(this) + "\n, added=" + KOptUtils.getAddedEdgeList(this) + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.ValueRangeManager; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class KOptListMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final KOptDescriptor<?> descriptor; private final List<FlipSublistAction> equivalent2Opts; private final KOptAffectedElements affectedElementsInfo; private final int postShiftAmount; private final int[] newEndIndices; private final Object[] originalEntities; KOptListMove(ListVariableDescriptor<Solution_> listVariableDescriptor, KOptDescriptor<?> descriptor, MultipleDelegateList<?> combinedList, List<FlipSublistAction> equivalent2Opts, int postShiftAmount, int[] newEndIndices) { this.listVariableDescriptor = listVariableDescriptor; this.descriptor = descriptor; this.equivalent2Opts = equivalent2Opts; this.postShiftAmount = postShiftAmount; this.newEndIndices = newEndIndices; if (equivalent2Opts.isEmpty()) { affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, 0); } else if (postShiftAmount != 0) { affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, combinedList.size()); } else { var currentAffectedElements = equivalent2Opts.get(0).getAffectedElements(); for (var i = 1; i < equivalent2Opts.size(); i++) { currentAffectedElements = currentAffectedElements.merge(equivalent2Opts.get(i).getAffectedElements()); } affectedElementsInfo = currentAffectedElements; } originalEntities = combinedList.delegateEntities; } private KOptListMove(ListVariableDescriptor<Solution_> listVariableDescriptor, KOptDescriptor<?> descriptor, List<FlipSublistAction> equivalent2Opts, int postShiftAmount, int[] newEndIndices, Object[] originalEntities) { this.listVariableDescriptor = listVariableDescriptor; this.descriptor = descriptor; this.equivalent2Opts = equivalent2Opts; this.postShiftAmount = postShiftAmount; this.newEndIndices = newEndIndices; if (equivalent2Opts.isEmpty()) { affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, 0); } else if (postShiftAmount != 0) { affectedElementsInfo = KOptAffectedElements.forMiddleRange(0, computeCombinedList(listVariableDescriptor, originalEntities).size()); } else { var currentAffectedElements = equivalent2Opts.get(0).getAffectedElements(); for (var i = 1; i < equivalent2Opts.size(); i++) { currentAffectedElements = currentAffectedElements.merge(equivalent2Opts.get(i).getAffectedElements()); } affectedElementsInfo = currentAffectedElements; } this.originalEntities = originalEntities; } KOptDescriptor<?> getDescriptor() { return descriptor; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var combinedList = computeCombinedList(listVariableDescriptor, originalEntities); combinedList.actOnAffectedElements(listVariableDescriptor, originalEntities, (entity, start, end) -> castScoreDirector.beforeListVariableChanged(listVariableDescriptor, entity, start, end)); // subLists will get corrupted by ConcurrentModifications, so do the operations // on a clone var combinedListCopy = combinedList.copy(); flipSublists(equivalent2Opts, combinedListCopy, postShiftAmount); // At this point, all related genuine variables are actually updated combinedList.applyChangesFromCopy(combinedListCopy); combinedList.actOnAffectedElements(listVariableDescriptor, originalEntities, (entity, start, end) -> castScoreDirector.afterListVariableChanged(listVariableDescriptor, entity, start, end)); } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { var doable = !equivalent2Opts.isEmpty(); if (!doable || listVariableDescriptor.canExtractValueRangeFromSolution()) { return doable; } var singleEntity = originalEntities.length == 1; if (singleEntity) { // The changes will be applied to a single entity. No need to check the value ranges. return true; } // When the value range is located at the entity, // we need to check if the destination's value range accepts the upcoming values ValueRangeManager<Solution_> valueRangeManager = ((VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector).getValueRangeManager(); // We need to compute the combined list of values to check the source and destination var combinedList = computeCombinedList(listVariableDescriptor, originalEntities).copy(); flipSublists(equivalent2Opts, combinedList, postShiftAmount); // We now check if the new arrangement of elements meets the entity value ranges return combinedList.isElementsFromDelegateInEntityValueRange(listVariableDescriptor, valueRangeManager); } @Override public KOptListMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { var rebasedEquivalent2Opts = new ArrayList<FlipSublistAction>(equivalent2Opts.size()); var castScoreDirector = (VariableDescriptorAwareScoreDirector<?>) destinationScoreDirector; var newEntities = new Object[originalEntities.length]; for (var i = 0; i < newEntities.length; i++) { newEntities[i] = castScoreDirector.lookUpWorkingObject(originalEntities[i]); } for (var twoOpt : equivalent2Opts) { rebasedEquivalent2Opts.add(twoOpt.rebase()); } return new KOptListMove<>(listVariableDescriptor, descriptor, rebasedEquivalent2Opts, postShiftAmount, newEndIndices, newEntities); } @Override public String getSimpleMoveTypeDescription() { return descriptor.k() + "-opt(" + listVariableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<?> getPlanningEntities() { return List.of(originalEntities); } @Override public Collection<?> getPlanningValues() { var out = new ArrayList<>(); var combinedList = computeCombinedList(listVariableDescriptor, originalEntities); if (affectedElementsInfo.wrappedStartIndex() != -1) { out.addAll(combinedList.subList(affectedElementsInfo.wrappedStartIndex(), combinedList.size())); out.addAll(combinedList.subList(0, affectedElementsInfo.wrappedEndIndex())); } for (var affectedRange : affectedElementsInfo.affectedMiddleRangeList()) { out.addAll(combinedList.subList(affectedRange.startInclusive(), affectedRange.endExclusive())); } return out; } private <T> void flipSublists(List<FlipSublistAction> actions, MultipleDelegateList<T> combinedList, int shiftAmount) { // Apply all flip actions for (var move : actions) { move.execute(combinedList); } // Update the delegate sublists of the combined list combinedList.moveElementsOfDelegates(newEndIndices); Collections.rotate(combinedList, shiftAmount); } public String toString() { return descriptor.toString(); } static <Solution_> MultipleDelegateList<?> computeCombinedList(ListVariableDescriptor<Solution_> listVariableDescriptor, Object[] entities) { @SuppressWarnings("unchecked") List<Object>[] delegates = new List[entities.length]; for (var i = 0; i < entities.length; i++) { delegates[i] = listVariableDescriptor.getUnpinnedSubList(entities[i]); } return new MultipleDelegateList<>(entities, delegates); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.Arrays; import java.util.Iterator; import java.util.Random; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked final class KOptListMoveIterator<Solution_, Node_> extends UpcomingSelectionIterator<Move<Solution_>> { private final Random workingRandom; private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final IterableValueSelector<Node_> originSelector; private final IterableValueSelector<Node_> valueSelector; private final int minK; private final int[] pickedKDistribution; private final int pickedKDistributionSum; private final int maxCyclesPatchedInInfeasibleMove; public KOptListMoveIterator(Random workingRandom, ListVariableDescriptor<Solution_> listVariableDescriptor, ListVariableStateSupply<Solution_> listVariableStateSupply, IterableValueSelector<Node_> originSelector, IterableValueSelector<Node_> valueSelector, int minK, int maxK, int[] pickedKDistribution) { this.workingRandom = workingRandom; this.listVariableDescriptor = listVariableDescriptor; this.listVariableStateSupply = listVariableStateSupply; this.originSelector = originSelector; this.valueSelector = valueSelector; this.minK = minK; this.pickedKDistribution = pickedKDistribution; var tmpPickedKDistributionSum = 0; for (var relativeDistributionAmount : pickedKDistribution) { tmpPickedKDistributionSum += relativeDistributionAmount; } this.pickedKDistributionSum = tmpPickedKDistributionSum; this.maxCyclesPatchedInInfeasibleMove = maxK; } @Override protected Move<Solution_> createUpcomingSelection() { var locationInDistribution = workingRandom.nextInt(pickedKDistributionSum); var indexInDistribution = 0; while (locationInDistribution >= pickedKDistribution[indexInDistribution]) { locationInDistribution -= pickedKDistribution[indexInDistribution]; indexInDistribution++; } var k = minK + indexInDistribution; if (k == 2) { return pickTwoOptMove(); } var descriptor = pickKOptMove(k); if (descriptor == null) { // Was unable to find a K-Opt move return NoChangeMove.getInstance(); } return descriptor.getKOptListMove(listVariableStateSupply); } private Move<Solution_> pickTwoOptMove() { @SuppressWarnings("unchecked") var originIterator = (Iterator<Node_>) originSelector.iterator(); if (!originIterator.hasNext()) { return NoChangeMove.getInstance(); } @SuppressWarnings("unchecked") var valueIterator = (Iterator<Node_>) valueSelector.iterator(); if (!valueIterator.hasNext()) { return NoChangeMove.getInstance(); } Object firstValue = originIterator.next(); Object secondValue = valueIterator.next(); var firstElementPosition = listVariableStateSupply.getElementPosition(firstValue) .ensureAssigned(); var secondElementPosition = listVariableStateSupply.getElementPosition(secondValue) .ensureAssigned(); return new TwoOptListMove<>(listVariableDescriptor, firstElementPosition.entity(), secondElementPosition.entity(), firstElementPosition.index(), secondElementPosition.index()); } @SuppressWarnings("unchecked") private Iterator<Node_> getValuesOnSelectedEntitiesIterator(Node_[] pickedValues) { var entityOrderInfo = EntityOrderInfo.of(pickedValues, listVariableStateSupply); return (Iterator<Node_>) workingRandom.ints(0, entityOrderInfo.entities().length) .mapToObj(index -> { var entity = entityOrderInfo.entities()[index]; return listVariableDescriptor.getRandomUnpinnedElement(entity, workingRandom); }) .iterator(); } @SuppressWarnings("unchecked") private @Nullable KOptDescriptor<Node_> pickKOptMove(int k) { // The code in the paper used 1-index arrays var pickedValues = (Node_[]) new Object[2 * k + 1]; var originIterator = (Iterator<Node_>) originSelector.iterator(); pickedValues[1] = originIterator.next(); if (pickedValues[1] == null) { return null; } var remainingAttempts = 20; while (remainingAttempts > 0 && listVariableDescriptor .getUnpinnedSubListSize(listVariableStateSupply.getInverseSingleton(pickedValues[1])) < 2) { do { if (!originIterator.hasNext()) { return null; } pickedValues[1] = originIterator.next(); remainingAttempts--; } while ((pickedValues[1] == null)); } if (remainingAttempts == 0) { // could not find a value in a list with more than 1 element return null; } var entityOrderInfo = EntityOrderInfo.of(pickedValues, listVariableStateSupply); pickedValues[2] = workingRandom.nextBoolean() ? getNodeSuccessor(entityOrderInfo, pickedValues[1]) : getNodePredecessor(entityOrderInfo, pickedValues[1]); if (isNodeEndpointOfList(pickedValues[1]) || isNodeEndpointOfList(pickedValues[2])) { return pickKOptMoveRec(getValuesOnSelectedEntitiesIterator(pickedValues), entityOrderInfo, pickedValues, 2, k, false); } else { return pickKOptMoveRec((Iterator<Node_>) valueSelector.iterator(), entityOrderInfo, pickedValues, 2, k, true); } } private @Nullable KOptDescriptor<Node_> pickKOptMoveRec(Iterator<Node_> valueIterator, EntityOrderInfo entityOrderInfo, Node_[] pickedValues, int pickedSoFar, int k, boolean canSelectNewEntities) { var previousRemovedEdgeEndpoint = pickedValues[2 * pickedSoFar - 2]; Node_ nextRemovedEdgePoint, nextRemovedEdgeOppositePoint; var remainingAttempts = (k - pickedSoFar + 3) * 2; while (remainingAttempts > 0) { nextRemovedEdgePoint = getNextNodeOrNull(valueIterator); if (nextRemovedEdgePoint == null) { return null; } var newEntityOrderInfo = entityOrderInfo.withNewNode(nextRemovedEdgePoint, listVariableStateSupply); while (nextRemovedEdgePoint == getNodePredecessor(newEntityOrderInfo, previousRemovedEdgeEndpoint) || nextRemovedEdgePoint == getNodeSuccessor(newEntityOrderInfo, previousRemovedEdgeEndpoint) || isEdgeAlreadyAdded(pickedValues, previousRemovedEdgeEndpoint, nextRemovedEdgePoint, pickedSoFar - 2) || (isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint, getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint), pickedSoFar - 2) && isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint, getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint), pickedSoFar - 2))) { if (remainingAttempts == 0) { return null; } nextRemovedEdgePoint = getNextNodeOrNull(valueIterator); if (nextRemovedEdgePoint == null) { return null; } newEntityOrderInfo = entityOrderInfo.withNewNode(nextRemovedEdgePoint, listVariableStateSupply); remainingAttempts--; } remainingAttempts--; pickedValues[2 * pickedSoFar - 1] = nextRemovedEdgePoint; if (isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint, getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint), pickedSoFar - 2)) { nextRemovedEdgeOppositePoint = getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint); } else if (isEdgeAlreadyDeleted(pickedValues, nextRemovedEdgePoint, getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint), pickedSoFar - 2)) { nextRemovedEdgeOppositePoint = getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint); } else { nextRemovedEdgeOppositePoint = workingRandom.nextBoolean() ? getNodeSuccessor(newEntityOrderInfo, nextRemovedEdgePoint) : getNodePredecessor(newEntityOrderInfo, nextRemovedEdgePoint); } pickedValues[2 * pickedSoFar] = nextRemovedEdgeOppositePoint; if (canSelectNewEntities && isNodeEndpointOfList(nextRemovedEdgePoint) || isNodeEndpointOfList(nextRemovedEdgeOppositePoint)) { valueIterator = getValuesOnSelectedEntitiesIterator(pickedValues); canSelectNewEntities = false; } if (pickedSoFar < k) { var descriptor = pickKOptMoveRec(valueIterator, newEntityOrderInfo, pickedValues, pickedSoFar + 1, k, canSelectNewEntities); if (descriptor != null && descriptor.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) { return descriptor; } } else { var descriptor = new KOptDescriptor<>(pickedValues, KOptUtils.getMultiEntitySuccessorFunction(pickedValues, listVariableStateSupply), KOptUtils.getMultiEntityBetweenPredicate(pickedValues, listVariableStateSupply)); if (descriptor.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) { return descriptor; } else { descriptor = patchCycles(descriptor, newEntityOrderInfo, pickedValues, pickedSoFar); if (descriptor.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) { return descriptor; } } } } return null; } private @Nullable Node_ getNextNodeOrNull(Iterator<Node_> iterator) { if (!iterator.hasNext()) { return null; } // This may still be null. // Either due to filtering the underlying iterator, // or due to the underlying iterator returning null. return iterator.next(); } KOptDescriptor<Node_> patchCycles(KOptDescriptor<Node_> descriptor, EntityOrderInfo entityOrderInfo, Node_[] oldRemovedEdges, int k) { Node_ s1, s2; var removedEdgeIndexToTourOrder = descriptor.removedEdgeIndexToTourOrder(); var valueIterator = getValuesOnSelectedEntitiesIterator(oldRemovedEdges); var cycleInfo = KOptUtils.getCyclesForPermutation(descriptor); var cycleCount = cycleInfo.cycleCount(); var cycle = cycleInfo.indexToCycleIdentifier(); // If cycleCount != 1, // we are changing an infeasible k-opt move that results in cycleCount cycles // into a (k+cycleCount) move. // If the k+cycleCount > maxK, we should ignore generating the move // Note: maxCyclesPatchedInInfeasibleMove = maxK if (cycleCount == 1 || k + cycleCount > maxCyclesPatchedInInfeasibleMove) { return descriptor; } var currentCycle = getShortestCycleIdentifier(entityOrderInfo, oldRemovedEdges, cycle, removedEdgeIndexToTourOrder, cycleCount, k); for (var i = 0; i < k; i++) { if (cycle[removedEdgeIndexToTourOrder[2 * i]] == currentCycle) { var sStart = oldRemovedEdges[removedEdgeIndexToTourOrder[2 * i]]; var sStop = oldRemovedEdges[removedEdgeIndexToTourOrder[2 * i + 1]]; var attemptRemaining = k; for (s1 = sStart; s1 != sStop; s1 = s2) { attemptRemaining--; if (attemptRemaining == 0) { break; } var removedEdges = Arrays.copyOf(oldRemovedEdges, oldRemovedEdges.length + 2); removedEdges[2 * k + 1] = s1; s2 = getNodeSuccessor(entityOrderInfo, s1); removedEdges[2 * k + 2] = s2; var addedEdgeToOtherEndpoint = Arrays.copyOf(KOptDescriptor.computeInEdgesForSequentialMove(oldRemovedEdges), removedEdges.length + 2 + (2 * cycleCount)); for (var newEdge = removedEdges.length; newEdge < addedEdgeToOtherEndpoint.length - 2; newEdge++) { addedEdgeToOtherEndpoint[newEdge] = newEdge + 2; } addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint.length - 1] = addedEdgeToOtherEndpoint.length - 3; addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint.length - 2] = addedEdgeToOtherEndpoint.length - 4; var newMove = patchCyclesRec(valueIterator, descriptor, entityOrderInfo, removedEdges, addedEdgeToOtherEndpoint, cycle, currentCycle, k, 2, cycleCount); if (newMove.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) { return newMove; } } } } return descriptor; } KOptDescriptor<Node_> patchCyclesRec(Iterator<Node_> valueIterator, KOptDescriptor<Node_> originalMove, EntityOrderInfo entityOrderInfo, Node_[] oldRemovedEdges, int[] addedEdgeToOtherEndpoint, int[] cycle, int currentCycle, int k, int patchedCycleCount, int cycleCount) { Node_ s1, s2, s3, s4; int NewCycle, i; var cycleSaved = new Integer[1 + 2 * k]; var removedEdges = Arrays.copyOf(oldRemovedEdges, oldRemovedEdges.length + 2); s1 = removedEdges[2 * k + 1]; s2 = removedEdges[i = 2 * (k + patchedCycleCount) - 2]; addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint[i] = i + 1] = i; for (i = 1; i <= 2 * k; i++) { cycleSaved[i] = cycle[i]; } s3 = valueIterator.next(); var remainingAttempts = cycleCount * 2; while (s3 == getNodePredecessor(entityOrderInfo, s2) || s3 == getNodeSuccessor(entityOrderInfo, s2) || ((NewCycle = findCycleIdentifierForNode(entityOrderInfo, s3, removedEdges, originalMove.removedEdgeIndexToTourOrder(), cycle)) == currentCycle) || (isEdgeAlreadyDeleted(removedEdges, s3, getNodePredecessor(entityOrderInfo, s3), k) && isEdgeAlreadyDeleted(removedEdges, s3, getNodeSuccessor(entityOrderInfo, s3), k))) { if (remainingAttempts == 0) { return originalMove; } s3 = valueIterator.next(); remainingAttempts--; } removedEdges[2 * (k + patchedCycleCount) - 1] = s3; if (isEdgeAlreadyDeleted(removedEdges, s3, getNodePredecessor(entityOrderInfo, s3), k)) { s4 = getNodeSuccessor(entityOrderInfo, s3); } else if (isEdgeAlreadyDeleted(removedEdges, s3, getNodeSuccessor(entityOrderInfo, s3), k)) { s4 = getNodePredecessor(entityOrderInfo, s3); } else { s4 = workingRandom.nextBoolean() ? getNodeSuccessor(entityOrderInfo, s3) : getNodePredecessor(entityOrderInfo, s3); } removedEdges[2 * (k + patchedCycleCount)] = s4; if (cycleCount > 2) { for (i = 1; i <= 2 * k; i++) { if (cycle[i] == NewCycle) { cycle[i] = currentCycle; } } var recursiveCall = patchCyclesRec(valueIterator, originalMove, entityOrderInfo, removedEdges, addedEdgeToOtherEndpoint, cycle, currentCycle, k, patchedCycleCount + 1, cycleCount - 1); if (recursiveCall.isFeasible(minK, maxCyclesPatchedInInfeasibleMove)) { return recursiveCall; } for (i = 1; i <= 2 * k; i++) { cycle[i] = cycleSaved[i]; } } else if (s4 != s1) { addedEdgeToOtherEndpoint[addedEdgeToOtherEndpoint[2 * k + 1] = 2 * (k + patchedCycleCount)] = 2 * k + 1; return new KOptDescriptor<>(removedEdges, addedEdgeToOtherEndpoint, KOptUtils.getMultiEntitySuccessorFunction(removedEdges, listVariableStateSupply), KOptUtils.getMultiEntityBetweenPredicate(removedEdges, listVariableStateSupply)); } return originalMove; } int findCycleIdentifierForNode(EntityOrderInfo entityOrderInfo, Node_ value, Node_[] pickedValues, int[] permutation, int[] indexToCycle) { for (var i = 1; i < pickedValues.length; i++) { if (isMiddleNodeBetween(entityOrderInfo, pickedValues[permutation[i - 1]], value, pickedValues[permutation[i]])) { return indexToCycle[permutation[i]]; } } throw new IllegalStateException("Cannot find cycle the " + value + " belongs to"); } int getShortestCycleIdentifier(EntityOrderInfo entityOrderInfo, Object[] removeEdgeEndpoints, int[] endpointIndexToCycle, int[] removeEdgeEndpointIndexToTourOrder, int cycleCount, int k) { int i; var minCycleIdentifier = 0; var minSize = Integer.MAX_VALUE; var size = new int[cycleCount + 1]; for (i = 1; i <= cycleCount; i++) { size[i] = 0; } removeEdgeEndpointIndexToTourOrder[0] = removeEdgeEndpointIndexToTourOrder[2 * k]; for (i = 0; i < 2 * k; i += 2) { size[endpointIndexToCycle[removeEdgeEndpointIndexToTourOrder[i]]] += getSegmentSize(entityOrderInfo, removeEdgeEndpoints[removeEdgeEndpointIndexToTourOrder[i]], removeEdgeEndpoints[removeEdgeEndpointIndexToTourOrder[i + 1]]); } for (i = 1; i <= cycleCount; i++) { if (size[i] < minSize) { minSize = size[i]; minCycleIdentifier = i - 1; } } return minCycleIdentifier; } private int getSegmentSize(EntityOrderInfo entityOrderInfo, Object from, Object to) { var entityToEntityIndex = entityOrderInfo.entityToEntityIndex(); var startElementPosition = listVariableStateSupply.getElementPosition(from) .ensureAssigned(); var endElementPosition = listVariableStateSupply.getElementPosition(to) .ensureAssigned(); var startEntityIndex = entityToEntityIndex.get(startElementPosition.entity()); var endEntityIndex = entityToEntityIndex.get(endElementPosition.entity()); var offsets = entityOrderInfo.offsets(); var startIndex = offsets[startEntityIndex] + startElementPosition.index(); var endIndex = offsets[endEntityIndex] + endElementPosition.index(); if (startIndex <= endIndex) { return endIndex - startIndex; } else { var entities = entityOrderInfo.entities(); var totalRouteSize = offsets[offsets.length - 1] + listVariableDescriptor.getListSize(entities[entities.length - 1]); return totalRouteSize - startIndex + endIndex; } } private boolean isEdgeAlreadyAdded(Object[] pickedValues, Object ta, Object tb, int k) { var i = 2 * k; while ((i -= 2) > 0) { if ((ta == pickedValues[i] && tb == pickedValues[i + 1]) || (ta == pickedValues[i + 1] && tb == pickedValues[i])) { return true; } } return false; } private boolean isEdgeAlreadyDeleted(Object[] pickedValues, Object ta, Object tb, int k) { var i = 2 * k + 2; while ((i -= 2) > 0) { if ((ta == pickedValues[i - 1] && tb == pickedValues[i]) || (ta == pickedValues[i] && tb == pickedValues[i - 1])) { return true; } } return false; } private boolean isNodeEndpointOfList(Object node) { var elementPosition = listVariableStateSupply.getElementPosition(node) .ensureAssigned(); var index = elementPosition.index(); var firstUnpinnedIndex = listVariableDescriptor.getFirstUnpinnedIndex(elementPosition.entity()); if (index == firstUnpinnedIndex) { return true; } var size = listVariableDescriptor.getListSize(elementPosition.entity()); return index == size - 1; } private Node_ getNodeSuccessor(EntityOrderInfo entityOrderInfo, Node_ node) { return entityOrderInfo.successor(node, listVariableStateSupply); } private Node_ getNodePredecessor(EntityOrderInfo entityOrderInfo, Node_ node) { return entityOrderInfo.predecessor(node, listVariableStateSupply); } private boolean isMiddleNodeBetween(EntityOrderInfo entityOrderInfo, Node_ start, Node_ middle, Node_ end) { return entityOrderInfo.between(start, middle, end, listVariableStateSupply); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex; import java.util.Iterator; import java.util.Objects; import java.util.function.Supplier; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.apache.commons.math3.util.CombinatoricsUtils; final class KOptListMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final IterableValueSelector<Solution_> originSelector; private final IterableValueSelector<Solution_> valueSelector; private final int minK; private final int maxK; private final int[] pickedKDistribution; private ListVariableStateSupply<Solution_> listVariableStateSupply; public KOptListMoveSelector(ListVariableDescriptor<Solution_> listVariableDescriptor, IterableValueSelector<Solution_> originSelector, IterableValueSelector<Solution_> valueSelector, int minK, int maxK, int[] pickedKDistribution) { this.listVariableDescriptor = listVariableDescriptor; this.originSelector = createEffectiveValueSelector(originSelector, this::getListVariableStateSupply); this.valueSelector = createEffectiveValueSelector(valueSelector, this::getListVariableStateSupply); this.minK = minK; this.maxK = maxK; this.pickedKDistribution = pickedKDistribution; phaseLifecycleSupport.addEventListener(this.originSelector); phaseLifecycleSupport.addEventListener(this.valueSelector); } private IterableValueSelector<Solution_> createEffectiveValueSelector( IterableValueSelector<Solution_> iterableValueSelector, Supplier<ListVariableStateSupply<Solution_>> listVariableStateSupplier) { var filteredValueSelector = filterPinnedListPlanningVariableValuesWithIndex(iterableValueSelector, listVariableStateSupplier); return FilteringValueSelector.ofAssigned(filteredValueSelector, listVariableStateSupplier); } 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); 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() { long total = 0; long valueSelectorSize = valueSelector.getSize(); for (int i = minK; i < Math.min(valueSelectorSize, maxK); i++) { if (valueSelectorSize > i) { // need more than k nodes in order to perform a k-opt long kOptMoveTypes = KOptUtils.getPureKOptMoveTypes(i); // A tour with n nodes have n - 1 edges // And we chose k of them to remove in a k-opt final long edgeChoices; if (valueSelectorSize <= Integer.MAX_VALUE) { edgeChoices = CombinatoricsUtils.binomialCoefficient((int) (valueSelectorSize - 1), i); } else { edgeChoices = Long.MAX_VALUE; } total += kOptMoveTypes * edgeChoices; } } return total; } @Override public Iterator<Move<Solution_>> iterator() { return new KOptListMoveIterator<>(workingRandom, listVariableDescriptor, listVariableStateSupply, originSelector, valueSelector, minK, maxK, pickedKDistribution); } @Override public boolean isCountable() { return false; } @Override public boolean isNeverEnding() { return true; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptListMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.Objects; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public final class KOptListMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, KOptListMoveSelectorConfig> { private static final int DEFAULT_MINIMUM_K = 2; private static final int DEFAULT_MAXIMUM_K = 2; public KOptListMoveSelectorFactory(KOptListMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var listVariableDescriptor = configPolicy.getSolutionDescriptor().getListVariableDescriptor(); if (listVariableDescriptor == null) { throw new IllegalArgumentException(""" The kOptListMoveSelector (%s) can only be used when the domain model has a list variable. Check your @%s and make sure it has a @%s.""" .formatted(config, PlanningEntity.class.getSimpleName(), PlanningListVariable.class.getSimpleName())); } var originSelectorConfig = Objects.requireNonNullElseGet(config.getOriginSelectorConfig(), ValueSelectorConfig::new); var valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); var entityDescriptor = getTheOnlyEntityDescriptorWithListVariable(configPolicy.getSolutionDescriptor()); if (originSelectorConfig.getVariableName() == null) { originSelectorConfig.setVariableName(listVariableDescriptor.getVariableName()); } if (valueSelectorConfig.getVariableName() == null) { valueSelectorConfig.setVariableName(listVariableDescriptor.getVariableName()); } var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); var originSelector = buildIterableValueSelector(configPolicy, entityDescriptor, originSelectorConfig, minimumCacheType, selectionOrder); var valueSelector = buildIterableValueSelector(configPolicy, entityDescriptor, valueSelectorConfig, minimumCacheType, selectionOrder); int minimumK = Objects.requireNonNullElse(config.getMinimumK(), DEFAULT_MINIMUM_K); if (minimumK < 2) { throw new IllegalArgumentException("minimumK (%d) must be at least 2." .formatted(minimumK)); } int maximumK = Objects.requireNonNullElse(config.getMaximumK(), DEFAULT_MAXIMUM_K); if (maximumK < minimumK) { throw new IllegalArgumentException("maximumK (%d) must be at least minimumK (%d)." .formatted(maximumK, minimumK)); } var pickedKDistribution = new int[maximumK - minimumK + 1]; // Each prior k is 8 times more likely to be picked than the subsequent k var total = 1; for (var i = minimumK; i < maximumK; i++) { total *= 8; } for (var i = 0; i < pickedKDistribution.length - 1; i++) { int remainder = total / 8; pickedKDistribution[i] = total - remainder; total = remainder; } pickedKDistribution[pickedKDistribution.length - 1] = total; return new KOptListMoveSelector<>(listVariableDescriptor, originSelector, valueSelector, minimumK, maximumK, pickedKDistribution); } private IterableValueSelector<Solution_> buildIterableValueSelector( HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, ValueSelectorConfig valueSelectorConfig, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { var valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder); if (valueSelector instanceof IterableValueSelector<Solution_> iterableValueSelector) { return iterableValueSelector; } throw new IllegalArgumentException(""" The kOptListMoveSelector (%s) for a list variable needs to be based on an %s (%s). Check your valueSelectorConfig.""" .formatted(config, IterableValueSelector.class.getSimpleName(), valueSelector)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/KOptUtils.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.function.Function; import ai.timefold.solver.core.api.function.TriPredicate; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.index.IndexVariableSupply; import ai.timefold.solver.core.impl.util.Pair; import org.apache.commons.math3.util.CombinatoricsUtils; final class KOptUtils { private KOptUtils() { } /** * Calculate the disjoint k-cycles for {@link KOptDescriptor#removedEdgeIndexToTourOrder()}. <br /> * <br /> * Any permutation can be expressed as combination of k-cycles. A k-cycle is a sequence of * unique elements (p_1, p_2, ..., p_k) where * <ul> * <li>p_1 maps to p_2 in the permutation</li> * <li>p_2 maps to p_3 in the permutation</li> * <li>p_(k-1) maps to p_k in the permutation</li> * <li>p_k maps to p_1 in the permutation</li> * <li>In general: p_i maps to p_(i+1) in the permutation</li> * </ul> * For instance, the permutation * <ul> * <li>1 -> 2</li> * <li>2 -> 3</li> * <li>3 -> 1</li> * <li>4 -> 5</li> * <li>5 -> 4</li> * </ul> * can be expressed as `(1, 2, 3)(4, 5)`. * * @return The {@link KOptCycle} corresponding to the permutation described by * {@link KOptDescriptor#removedEdgeIndexToTourOrder()}. * @param kOptDescriptor The descriptor to calculate cycles for */ static KOptCycle getCyclesForPermutation(KOptDescriptor<?> kOptDescriptor) { var cycleCount = 0; var removedEdgeIndexToTourOrder = kOptDescriptor.removedEdgeIndexToTourOrder(); var addedEdgeToOtherEndpoint = kOptDescriptor.addedEdgeToOtherEndpoint(); var inverseRemovedEdgeIndexToTourOrder = kOptDescriptor.inverseRemovedEdgeIndexToTourOrder(); var indexToCycle = new int[removedEdgeIndexToTourOrder.length]; var remaining = new BitSet(removedEdgeIndexToTourOrder.length); remaining.set(1, removedEdgeIndexToTourOrder.length, true); while (!remaining.isEmpty()) { var currentEndpoint = remaining.nextSetBit(0); while (remaining.get(currentEndpoint)) { indexToCycle[currentEndpoint] = cycleCount; remaining.clear(currentEndpoint); // Go to the endpoint connected to this one by an added edge var currentEndpointTourIndex = removedEdgeIndexToTourOrder[currentEndpoint]; var nextEndpointTourIndex = addedEdgeToOtherEndpoint[currentEndpointTourIndex]; currentEndpoint = inverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex]; indexToCycle[currentEndpoint] = cycleCount; remaining.clear(currentEndpoint); // Go to the endpoint after the added edge currentEndpoint = currentEndpoint ^ 1; } cycleCount++; } return new KOptCycle(cycleCount, indexToCycle); } static <Node_> List<Pair<Node_, Node_>> getAddedEdgeList(KOptDescriptor<Node_> kOptDescriptor) { var k = kOptDescriptor.k(); List<Pair<Node_, Node_>> out = new ArrayList<>(2 * k); var currentEndpoint = 1; var removedEdges = kOptDescriptor.removedEdges(); var addedEdgeToOtherEndpoint = kOptDescriptor.addedEdgeToOtherEndpoint(); var removedEdgeIndexToTourOrder = kOptDescriptor.removedEdgeIndexToTourOrder(); var inverseRemovedEdgeIndexToTourOrder = kOptDescriptor.inverseRemovedEdgeIndexToTourOrder(); // This loop iterates through the new tour created while (currentEndpoint != 2 * k + 1) { out.add(new Pair<>(removedEdges[currentEndpoint], removedEdges[addedEdgeToOtherEndpoint[currentEndpoint]])); var tourIndex = removedEdgeIndexToTourOrder[currentEndpoint]; var nextEndpointTourIndex = addedEdgeToOtherEndpoint[tourIndex]; currentEndpoint = inverseRemovedEdgeIndexToTourOrder[nextEndpointTourIndex] ^ 1; } return out; } static <Node_> List<Pair<Node_, Node_>> getRemovedEdgeList(KOptDescriptor<Node_> kOptDescriptor) { var k = kOptDescriptor.k(); var removedEdges = kOptDescriptor.removedEdges(); List<Pair<Node_, Node_>> out = new ArrayList<>(2 * k); for (var i = 1; i <= k; i++) { out.add(new Pair<>(removedEdges[2 * i - 1], removedEdges[2 * i])); } return out; } @SuppressWarnings("unchecked") public static <Node_> Function<Node_, Node_> getMultiEntitySuccessorFunction(Node_[] pickedValues, ListVariableStateSupply<?> listVariableStateSupply) { var entityOrderInfo = EntityOrderInfo.of(pickedValues, listVariableStateSupply); return node -> entityOrderInfo.successor(node, listVariableStateSupply); } public static <Node_> TriPredicate<Node_, Node_, Node_> getBetweenPredicate(IndexVariableSupply indexVariableSupply) { return (start, middle, end) -> { int startIndex = indexVariableSupply.getIndex(start); int middleIndex = indexVariableSupply.getIndex(middle); int endIndex = indexVariableSupply.getIndex(end); if (startIndex <= endIndex) { // test middleIndex in [startIndex, endIndex] return startIndex <= middleIndex && middleIndex <= endIndex; } else { // test middleIndex in [0, endIndex] or middleIndex in [startIndex, listSize) return middleIndex >= startIndex || middleIndex <= endIndex; } }; } public static <Node_> TriPredicate<Node_, Node_, Node_> getMultiEntityBetweenPredicate(Node_[] pickedValues, ListVariableStateSupply<?> listVariableStateSupply) { var entityOrderInfo = EntityOrderInfo.of(pickedValues, listVariableStateSupply); return (start, middle, end) -> entityOrderInfo.between(start, middle, end, listVariableStateSupply); } public static void flipSubarray(int[] array, int fromIndexInclusive, int toIndexExclusive) { if (fromIndexInclusive < toIndexExclusive) { final var halfwayPoint = (toIndexExclusive - fromIndexInclusive) >> 1; for (var i = 0; i < halfwayPoint; i++) { var saved = array[fromIndexInclusive + i]; array[fromIndexInclusive + i] = array[toIndexExclusive - i - 1]; array[toIndexExclusive - i - 1] = saved; } } else { var firstHalfSize = array.length - fromIndexInclusive; var secondHalfSize = toIndexExclusive; // Reverse the combined list firstHalfReversedPath + secondHalfReversedPath // For instance, (1, 2, 3)(4, 5, 6, 7, 8, 9) becomes // (9, 8, 7)(6, 5, 4, 3, 2, 1) var totalLength = firstHalfSize + secondHalfSize; // Used to rotate the list to put the first element back in its original position for (var i = 0; (i < totalLength >> 1); i++) { int firstHalfIndex; int secondHalfIndex; if (i < firstHalfSize) { if (i < secondHalfSize) { firstHalfIndex = fromIndexInclusive + i; secondHalfIndex = secondHalfSize - i - 1; } else { firstHalfIndex = fromIndexInclusive + i; secondHalfIndex = array.length - (i - secondHalfSize) - 1; } } else { firstHalfIndex = i - firstHalfSize; secondHalfIndex = secondHalfSize - i - 1; } var saved = array[firstHalfIndex]; array[firstHalfIndex] = array[secondHalfIndex]; array[secondHalfIndex] = saved; } } } /** * Returns the number of unique ways a K-Opt can add K edges without reinserting a removed edge. * * @param k How many edges were removed/will be added * @return the number of unique ways a K-Opt can add K edges without reinserting a removed edge. */ public static long getPureKOptMoveTypes(int k) { // This calculates the item at index k for the sequence https://oeis.org/A061714 long totalTypes = 0; for (var i = 1; i < k; i++) { for (var j = 0; j <= i; j++) { var sign = ((k + j - 1) % 2 == 0) ? 1 : -1; totalTypes += sign * CombinatoricsUtils.binomialCoefficient(i, j) * CombinatoricsUtils.factorial(j) * (1L << j); } } return totalTypes; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/MultipleDelegateList.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.RandomAccess; import java.util.stream.Stream; import ai.timefold.solver.core.api.function.TriConsumer; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.ValueRangeManager; /** * A list that delegates get and set operations to multiple delegates. * Add and removal operations are not supported. * * @param <T> */ final class MultipleDelegateList<T> implements List<T>, RandomAccess { final Object[] delegateEntities; final List<T>[] delegates; final int[] delegateSizes; final int[] offsets; final int totalSize; @SafeVarargs public MultipleDelegateList(Object[] delegateEntities, List<T>... delegates) { this.delegates = delegates; this.delegateEntities = delegateEntities; this.delegateSizes = new int[delegates.length]; this.offsets = new int[delegates.length]; var sizeSoFar = 0; for (var i = 0; i < delegates.length; i++) { delegateSizes[i] = delegates[i].size(); offsets[i] = sizeSoFar; sizeSoFar += delegateSizes[i]; } this.totalSize = sizeSoFar; } @SafeVarargs MultipleDelegateList(List<T>... delegates) { this(new Object[delegates.length], delegates); } @SuppressWarnings("unchecked") public MultipleDelegateList<T> copy() { List<T>[] delegateClones = new List[delegates.length]; for (var i = 0; i < delegates.length; i++) { delegateClones[i] = new ArrayList<>(delegates[i]); } return new MultipleDelegateList<>(delegateEntities, delegateClones); } @SuppressWarnings("unchecked") public void applyChangesFromCopy(MultipleDelegateList<?> copy) { for (var i = 0; i < delegates.length; i++) { delegates[i].clear(); delegates[i].addAll((List<T>) copy.delegates[i]); } } public int getIndexOfValue(ListVariableStateSupply<?> listVariableStateSupply, Object value) { var elementPosition = listVariableStateSupply.getElementPosition(value) .ensureAssigned(() -> "Value (" + value + ") is not contained in any entity list"); var entity = elementPosition.entity(); var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); for (var i = 0; i < delegateEntities.length; i++) { if (delegateEntities[i] == entity) { var firstUnpinnedIndex = listVariableDescriptor.getFirstUnpinnedIndex(delegateEntities[i]); return offsets[i] + (elementPosition.index() - firstUnpinnedIndex); } } throw new IllegalArgumentException("Impossible state: value (%s) not found" .formatted(value)); } public void actOnAffectedElements(ListVariableDescriptor<?> listVariableDescriptor, Object[] originalEntities, TriConsumer<Object, Integer, Integer> action) { for (Object originalEntity : originalEntities) { action.accept(originalEntity, listVariableDescriptor.getFirstUnpinnedIndex(originalEntity), listVariableDescriptor.getListSize(originalEntity)); } } public void moveElementsOfDelegates(int[] newDelegateEndIndices) { List<T>[] newDelegateData = new List[delegates.length]; var start = 0; for (var i = 0; i < newDelegateData.length; i++) { newDelegateData[i] = List.copyOf(subList(start, newDelegateEndIndices[i] + 1)); start = newDelegateEndIndices[i] + 1; } for (var i = 0; i < delegates.length; i++) { delegates[i].clear(); delegates[i].addAll(newDelegateData[i]); } var sizeSoFar = 0; for (var i = 0; i < delegates.length; i++) { delegateSizes[i] = delegates[i].size(); offsets[i] = sizeSoFar; sizeSoFar += delegateSizes[i]; } } /** * When the value range is assigned to the entity, * we must verify whether the new arrangement of the elements conforms to the entity's value range. * As a result, * each sublist generated after applying all changes is validated against the related value ranges. */ public <S> boolean isElementsFromDelegateInEntityValueRange(ListVariableDescriptor<S> listVariableDescriptor, ValueRangeManager<S> valueRangeManager) { if (listVariableDescriptor.getValueRangeDescriptor().canExtractValueRangeFromSolution()) { // When the value range can be extracted from the solution, // there is no need to check if the new arrangement corresponds to the value list. // However, this is not the case when the value range is associated with the entity. // In such instances, // we must ensure that the value list for each delegated entity aligns with the related value range. return true; } for (var i = 0; i < delegateEntities.length; i++) { var entity = delegateEntities[i]; var valueRange = valueRangeManager.getFromEntity(listVariableDescriptor.getValueRangeDescriptor(), entity); var containsAll = delegates[i].stream().allMatch(valueRange::contains); if (!containsAll) { return false; } } return true; } @Override public int size() { return totalSize; } @Override public boolean isEmpty() { return totalSize == 0; } @Override public boolean contains(Object o) { for (var delegate : delegates) { if (delegate.contains(o)) { return true; } } return false; } @Override public Iterator<T> iterator() { return Stream.of(delegates).flatMap(Collection::stream).iterator(); } @Override public Object[] toArray() { return Stream.of(delegates).flatMap(Collection::stream).toArray(); } @Override @SuppressWarnings("unchecked") public <T1> T1[] toArray(T1[] t1s) { var out = Stream.of(delegates).flatMap(Collection::stream).toArray(size -> { if (size <= t1s.length) { return t1s; } else { return (T1[]) Array.newInstance(t1s.getClass().getComponentType(), size); } }); if (out.length > totalSize) { out[totalSize] = null; } return out; } @Override public boolean containsAll(Collection<?> collection) { return collection.stream().allMatch(this::contains); } private int getDelegateIndex(int actualIndex) { var delegateIndex = 0; while (delegateSizes[delegateIndex] <= actualIndex) { actualIndex -= delegateSizes[delegateIndex]; delegateIndex++; } return delegateIndex; } @Override public T get(int i) { if (i < 0 || i >= totalSize) { throw new IndexOutOfBoundsException("Index (" + i + ") out of bounds for a list of size (" + totalSize + ")"); } var delegateIndex = getDelegateIndex(i); return delegates[delegateIndex].get(i - offsets[delegateIndex]); } @Override public T set(int i, T t) { if (i < 0 || i >= totalSize) { throw new IndexOutOfBoundsException("Index (" + i + ") out of bounds for a list of size (" + totalSize + ")"); } var delegateIndex = getDelegateIndex(i); return delegates[delegateIndex].set(i - offsets[delegateIndex], t); } @Override public int indexOf(Object o) { if (delegates.length == 0) { return -1; } var delegateIndex = 0; var objectIndex = -1; var offset = 0; while (delegateIndex < delegates.length && (objectIndex = delegates[delegateIndex].indexOf(o)) == -1) { // We do the indexOf in the while condition so offset is not updated // for the list that contains the element // (ex: [1, 2, 3].indexOf(2) should return 1, not 4) offset += delegateSizes[delegateIndex]; delegateIndex++; } if (objectIndex == -1) { return -1; } return offset + objectIndex; } @Override public int lastIndexOf(Object o) { if (delegates.length == 0) { return -1; } var delegateIndex = delegates.length - 1; var objectIndex = -1; var offset = 0; while (delegateIndex >= 0 && objectIndex == -1) { // We update index here so offset is updated with the containing // list size (since totalSize is subtracted from it) // (ex: [1, 2, 3].lastIndexOf(2) should return 1, not 4) objectIndex = delegates[delegateIndex].lastIndexOf(o); offset += delegateSizes[delegateIndex]; delegateIndex--; } if (objectIndex == -1) { return -1; } return (totalSize - offset) + objectIndex; } @Override public ListIterator<T> listIterator() { return new MultipleDelegateListIterator<>(this, 0); } @Override public ListIterator<T> listIterator(int i) { return new MultipleDelegateListIterator<>(this, i); } @Override public MultipleDelegateList<T> subList(int startInclusive, int endExclusive) { if (startInclusive < 0) { throw new IndexOutOfBoundsException("Sublist start index (" + startInclusive + ") out of range"); } if (endExclusive > totalSize) { throw new IndexOutOfBoundsException("Sublist end index (" + endExclusive + ") out of range"); } var startDelegateIndex = 0; var endDelegateIndex = 0; while (startInclusive >= delegateSizes[startDelegateIndex]) { startInclusive -= delegateSizes[startDelegateIndex]; startDelegateIndex++; } while (endExclusive > delegateSizes[endDelegateIndex]) { endExclusive -= delegateSizes[endDelegateIndex]; endDelegateIndex++; } @SuppressWarnings("unchecked") List<T>[] out = new List[endDelegateIndex - startDelegateIndex + 1]; if (out.length == 0) { return new MultipleDelegateList<>(delegateEntities); } if (startDelegateIndex == endDelegateIndex) { out[0] = delegates[startDelegateIndex].subList(startInclusive, endExclusive); } else { out[0] = delegates[startDelegateIndex].subList(startInclusive, delegateSizes[startDelegateIndex]); out[out.length - 1] = delegates[endDelegateIndex].subList(0, endExclusive); System.arraycopy(delegates, startDelegateIndex + 1, out, 1, out.length - 2); } return new MultipleDelegateList<>(delegateEntities, out); } @Override public boolean add(T t) { throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list"); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list"); } @Override public void add(int i, T t) { throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list"); } @Override public T remove(int i) { throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list"); } @Override public boolean addAll(Collection<? extends T> collection) { throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list"); } @Override public boolean addAll(int i, Collection<? extends T> collection) { throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list"); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list"); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list"); } @Override public void clear() { throw new UnsupportedOperationException("Cannot remove elements from a multiple delegate list"); } @Override public String toString() { return Arrays.toString(delegates); } @Override public boolean equals(Object o) { if (o instanceof List other) { if (other.size() != totalSize) { return false; } for (var i = 0; i < totalSize; i++) { if (!Objects.equals(other.get(i), get(i))) { return false; } } return true; } else { return false; } } @Override public int hashCode() { return Arrays.hashCode(delegates); } private static final class MultipleDelegateListIterator<T> implements ListIterator<T> { final MultipleDelegateList<T> parent; int currentIndex; public MultipleDelegateListIterator(MultipleDelegateList<T> parent, int currentIndex) { this.parent = parent; this.currentIndex = currentIndex; } @Override public boolean hasNext() { return currentIndex < parent.totalSize; } @Override public T next() { var out = parent.get(currentIndex); currentIndex++; return out; } @Override public boolean hasPrevious() { return currentIndex > 0; } @Override public T previous() { currentIndex--; return parent.get(currentIndex); } @Override public int nextIndex() { return currentIndex + 1; } @Override public int previousIndex() { return currentIndex - 1; } @Override public void set(T t) { parent.set(currentIndex, t); } @Override public void add(T t) { throw new UnsupportedOperationException("Cannot add new elements to a multiple delegate list"); } @Override public void remove() { throw new UnsupportedOperationException("Cannot remove elements to a multiple delegate list"); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/TwoOptListMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Set; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.ValueRangeManager; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * A 2-opt move for list variables, which takes two edges and swap their endpoints. * For instance, let [A, B, E, D, C, F, G, H] be the route assigned to an entity. * Select (B, E) and (C, F) as the edges to swap. * Then the resulting route after this operation would be [A, B, C, D, E, F, G, H]. * The edge (B, E) became (B, C), and the edge (C, F) became (E, F) * (the first edge end point became the second edge start point and vice versa). * It is used to fix crossings; for instance, it can change: * * <pre>{@code * ... -> A B <- ... * ....... x ....... * ... <- C D -> ... * }</pre> * * to * * <pre>{@code * ... -> A -> B -> ... * ... <- C <- D <- ... * }</pre> * * Note the sub-path D...B was reversed. * The 2-opt works by reversing the path between the two edges being removed. * <p> * When the edges are assigned to different entities, * it results in a tail swap. * For instance, let r1 = [A, B, C, D], and r2 = [E, F, G, H]. * Doing a 2-opt on (B, C) + (F, G) will result in r1 = [A, B, G, H] and r2 = [E, F, C, D]. * * @param <Solution_> */ public final class TwoOptListMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> variableDescriptor; private final Object firstEntity; private final Object secondEntity; private final int firstEdgeEndpoint; private final int secondEdgeEndpoint; private final int shift; private final int entityFirstUnpinnedIndex; public TwoOptListMove(ListVariableDescriptor<Solution_> variableDescriptor, Object firstEntity, Object secondEntity, int firstEdgeEndpoint, int secondEdgeEndpoint) { this.variableDescriptor = variableDescriptor; this.firstEntity = firstEntity; this.secondEntity = secondEntity; this.firstEdgeEndpoint = firstEdgeEndpoint; this.secondEdgeEndpoint = secondEdgeEndpoint; if (firstEntity == secondEntity) { entityFirstUnpinnedIndex = variableDescriptor.getFirstUnpinnedIndex(firstEntity); if (firstEdgeEndpoint == 0) { shift = -secondEdgeEndpoint; } else if (secondEdgeEndpoint < firstEdgeEndpoint) { var listSize = variableDescriptor.getListSize(firstEntity); var flippedSectionSize = listSize - firstEdgeEndpoint + secondEdgeEndpoint; var firstElementIndexInFlipped = listSize - firstEdgeEndpoint; var firstElementMirroredIndex = flippedSectionSize - firstElementIndexInFlipped; shift = -(firstEdgeEndpoint + firstElementMirroredIndex - 1); } else { shift = 0; } } else { // This is a tail swap move, so entityFirstUnpinnedIndex is unused as no // flipping will be done entityFirstUnpinnedIndex = 0; shift = 0; } } private TwoOptListMove(ListVariableDescriptor<Solution_> variableDescriptor, Object firstEntity, Object secondEntity, int firstEdgeEndpoint, int secondEdgeEndpoint, int entityFirstUnpinnedIndex, int shift) { this.variableDescriptor = variableDescriptor; this.firstEntity = firstEntity; this.secondEntity = secondEntity; this.firstEdgeEndpoint = firstEdgeEndpoint; this.secondEdgeEndpoint = secondEdgeEndpoint; this.entityFirstUnpinnedIndex = entityFirstUnpinnedIndex; this.shift = shift; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { if (firstEntity == secondEntity) { doSublistReversal(scoreDirector); } else { doTailSwap(scoreDirector); } } private void doTailSwap(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var firstListVariable = variableDescriptor.getValue(firstEntity); var secondListVariable = variableDescriptor.getValue(secondEntity); var firstOriginalSize = firstListVariable.size(); var secondOriginalSize = secondListVariable.size(); castScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity, firstEdgeEndpoint, firstOriginalSize); castScoreDirector.beforeListVariableChanged(variableDescriptor, secondEntity, secondEdgeEndpoint, secondOriginalSize); var firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstOriginalSize); var secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondOriginalSize); var tailSizeDifference = secondListVariableTail.size() - firstListVariableTail.size(); var firstListVariableTailCopy = new ArrayList<>(firstListVariableTail); firstListVariableTail.clear(); firstListVariable.addAll(secondListVariableTail); secondListVariableTail.clear(); secondListVariable.addAll(firstListVariableTailCopy); castScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity, firstEdgeEndpoint, firstOriginalSize + tailSizeDifference); castScoreDirector.afterListVariableChanged(variableDescriptor, secondEntity, secondEdgeEndpoint, secondOriginalSize - tailSizeDifference); } private void doSublistReversal(ScoreDirector<Solution_> scoreDirector) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; var listVariable = variableDescriptor.getValue(firstEntity); if (firstEdgeEndpoint < secondEdgeEndpoint) { if (firstEdgeEndpoint > 0) { castScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity, firstEdgeEndpoint, secondEdgeEndpoint); } else { castScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity, entityFirstUnpinnedIndex, listVariable.size()); } if (firstEdgeEndpoint == 0 && shift > 0) { if (entityFirstUnpinnedIndex == 0) { Collections.rotate(listVariable, shift); } else { Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()), shift); } } FlipSublistAction.flipSublist(listVariable, entityFirstUnpinnedIndex, firstEdgeEndpoint, secondEdgeEndpoint); if (firstEdgeEndpoint == 0 && shift < 0) { if (entityFirstUnpinnedIndex == 0) { Collections.rotate(listVariable, shift); } else { Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()), shift); } } if (firstEdgeEndpoint > 0) { castScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity, firstEdgeEndpoint, secondEdgeEndpoint); } else { castScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity, entityFirstUnpinnedIndex, listVariable.size()); } } else { castScoreDirector.beforeListVariableChanged(variableDescriptor, firstEntity, entityFirstUnpinnedIndex, listVariable.size()); if (shift > 0) { if (entityFirstUnpinnedIndex == 0) { Collections.rotate(listVariable, shift); } else { Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()), shift); } } FlipSublistAction.flipSublist(listVariable, entityFirstUnpinnedIndex, firstEdgeEndpoint, secondEdgeEndpoint); if (shift < 0) { if (entityFirstUnpinnedIndex == 0) { Collections.rotate(listVariable, shift); } else { Collections.rotate(listVariable.subList(entityFirstUnpinnedIndex, listVariable.size()), shift); } } castScoreDirector.afterListVariableChanged(variableDescriptor, firstEntity, entityFirstUnpinnedIndex, listVariable.size()); } } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { var sameEntity = firstEntity == secondEntity; var doable = !sameEntity || // A shift will rotate the entire list, changing the visiting order shift != 0 || // The chain flipped by a K-Opt only changes if there are at least 2 values // in the chain Math.abs(secondEdgeEndpoint - firstEdgeEndpoint) >= 2; if (!doable || sameEntity || variableDescriptor.canExtractValueRangeFromSolution()) { return doable; } // When the first and second elements are different, // and the value range is located at the entity, // we need to check if the destination's value range accepts the upcoming values ValueRangeManager<Solution_> valueRangeManager = ((VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector).getValueRangeManager(); var firstValueRange = valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), firstEntity); var firstListVariable = variableDescriptor.getValue(firstEntity); var firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstListVariable.size()); var secondValueRange = valueRangeManager.getFromEntity(variableDescriptor.getValueRangeDescriptor(), secondEntity); var secondListVariable = variableDescriptor.getValue(secondEntity); var secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondListVariable.size()); return firstListVariableTail.stream().allMatch(secondValueRange::contains) && secondListVariableTail.stream().allMatch(firstValueRange::contains); } @Override public TwoOptListMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new TwoOptListMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(firstEntity), destinationScoreDirector.lookUpWorkingObject(secondEntity), firstEdgeEndpoint, secondEdgeEndpoint, entityFirstUnpinnedIndex, shift); } @Override public String getSimpleMoveTypeDescription() { return "2-Opt(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<?> getPlanningEntities() { if (firstEntity == secondEntity) { return Collections.singleton(firstEntity); } return Set.of(firstEntity, secondEntity); } @Override public Collection<?> getPlanningValues() { if (firstEntity == secondEntity) { var listVariable = variableDescriptor.getValue(firstEntity); if (firstEdgeEndpoint < secondEdgeEndpoint) { return new ArrayList<>(listVariable.subList(firstEdgeEndpoint, secondEdgeEndpoint)); } else { var firstHalfReversedPath = listVariable.subList(firstEdgeEndpoint, listVariable.size()); var secondHalfReversedPath = listVariable.subList(entityFirstUnpinnedIndex, secondEdgeEndpoint); return CollectionUtils.concat(firstHalfReversedPath, secondHalfReversedPath); } } else { var firstListVariable = variableDescriptor.getValue(firstEntity); var secondListVariable = variableDescriptor.getValue(secondEntity); var firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstListVariable.size()); var secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondListVariable.size()); var out = new ArrayList<>(firstListVariableTail.size() + secondListVariableTail.size()); out.addAll(firstListVariableTail); out.addAll(secondListVariableTail); return out; } } public Object getFirstEntity() { return firstEntity; } public Object getSecondEntity() { return secondEntity; } public Object getFirstEdgeEndpoint() { return firstEdgeEndpoint; } public Object getSecondEdgeEndpoint() { return secondEdgeEndpoint; } @Override public String toString() { return "2-Opt(firstEntity=" + firstEntity + ", secondEntity=" + secondEntity + ", firstEndpointIndex=" + firstEdgeEndpoint + ", secondEndpointIndex=" + secondEdgeEndpoint + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/kopt/package-info.java
/** * Contains classes relevant to K-Opt moves. * A K-Opt move is a move that removes K edges and adds K new edges that are composed of the removal edges endpoints. * The classes in this package implement the algorithms described in * <a href="http://webhotel4.ruc.dk/~keld/research/LKH/KoptReport.pdf"> * "An Effective Implementation of K-opt Moves for the Lin-Kernighan TSP Heuristic" * </a>. * <br /> * The paper changes the problem of performing a K-Opt * to the problem of transforming a signed permutation that consists of a single K-cycle to the identity permutation. * A signed permutation is a permutation where each element has a sign. * Let the removed edges be (t_1, t_2), (t_3, t_4), ..., (t_(2k - 1), t_2k). * Let s_1, s_2, ..., s_k be segments from the original tour that starts and end at two different endpoints of two different * removed edges. * Additionally, let s_1, s_2, ..., s_k be sorted such that * <ul> * <li>s_1 starts at t_2</li> * <li>s_2 starts at the successor of the end of s_1</li> * <li>in general s_i starts at the successor of s_(i-1)</li> * <li>s_k ends at t_1</li> * </ul> * For example, if the original tour was [t_1, t_2, t_4, t_3, t_8, t_7, t_5, t_6], * then * <ul> * <li>s_1 = t_2...t_4</li> * <li>s_2 = t_3...t_8</li> * <li>s_3 = t_7...t_5</li> * <li>s_4 = t_6...t_1</li> * </ul> * These segments will still be in the tour after the K-Opt move is performed, but may be reversed and in a different order. * To construct the signed permutation P corresponding to the K-Opt, create a list of K elements where * <ul> * <li> * abs(P[i]) = starting from t_2, he number of segments needed to be transversed to encounter s[i] + 1 * (after the K-Opt move been applied) * </li> * <li> * sign(P[i]) = +1 if s[i] has the same orientation in the tour after the K-Opt move been applied, * -1 if it been reversed * </li> * </ul> * For example, if the original tour was <br /> * [t_2, t_4, t_3, t_8, t_7, t_5, t_6, t_1] <br /> * and the 4-Opt move changes it to <br /> * [t2, t_4, t_5, t_7, t_6, t_1, t_8, t_3] <br /> * Then * <ul> * <li>s_1 = (t_2...t_4), s_2 = (t_3...t_8), s_3 = (t_7...t_5), s_4 = (t_6...t_1)</li> * <li>P_1 = +1 (first segment encountered, same orientation as original</li> * <li>P_2 = -4 ((t_8...t_3) is encountered last in the new tour, and it was reversed from (t_3...t_8))</li> * <li>P_3 = -2 ((t_5...t_7) is second segment encountered in the new tour, and it was reversed from (t_7...t_5)</li> * <li>P_4 = +3 ((t_6...t_1) is the third segment encountered in the new tour, and has the same orientation.</li> * </ul> * Thus, for this example, P = (+1, -4, -2, +3). * The goal is to transform P into the identity permutation (+1, +2, +3, +4) using the minimal amount of signed reversals. * For the above example, it can be achieved using three signed reversals: * * <ol> * <li>(+1 -4 [-2 +3])</li> * <li>(+1 [-4 -3 +2])</li> * <li>(+1 [-2] +3 +4)</li> * <li>(+1, +2, +3, +4)</li> * </ol> * * Each signed reversal directly corresponds to a 2-opt move (which reverses a sub-path of the tour). * For the signed reversals above, they are: * * <ol> * <li>2-opt(t2, t1, t8, t7)</li> * <li>2-opt(t4, t3, t2, t7)</li> * <li>2-opt(t7, t4, t5, t6)</li> * </ol> * * Where 2-opt(a, b, c, d) remove edges (a, b) and (c, d) and add edges (b, c), (a, d). * The series of signed reversals can be found by the algorithm described in * <a href="https://dl.acm.org/doi/pdf/10.1145/300515.300516"> * "Transforming Cabbage into Turnip: Polynomial Algorithm for Sorting Signed Permutations by Reversals" * </a>. */ package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt;
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ruin/ListRuinRecreateMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateConstructionHeuristicPhase; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateConstructionHeuristicPhaseBuilder; import ai.timefold.solver.core.impl.move.director.VariableChangeRecordingScoreDirector; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.util.CollectionUtils; public final class ListRuinRecreateMove<Solution_> extends AbstractMove<Solution_> { private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final List<Object> ruinedValueList; private final Set<Object> affectedEntitySet; private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; private final SolverScope<Solution_> solverScope; private final Map<Object, NavigableSet<RuinedPosition>> entityToNewPositionMap; public ListRuinRecreateMove(ListVariableDescriptor<Solution_> listVariableDescriptor, RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, SolverScope<Solution_> solverScope, List<Object> ruinedValueList, Set<Object> affectedEntitySet) { this.listVariableDescriptor = listVariableDescriptor; this.constructionHeuristicPhaseBuilder = constructionHeuristicPhaseBuilder; this.solverScope = solverScope; this.ruinedValueList = ruinedValueList; this.affectedEntitySet = affectedEntitySet; this.entityToNewPositionMap = CollectionUtils.newIdentityHashMap(affectedEntitySet.size()); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { entityToNewPositionMap.clear(); var variableChangeRecordingScoreDirector = (VariableChangeRecordingScoreDirector<Solution_, ?>) scoreDirector; try (var listVariableStateSupply = variableChangeRecordingScoreDirector.getBacking().getSupplyManager() .demand(listVariableDescriptor.getStateDemand())) { var entityToOriginalPositionMap = CollectionUtils.<Object, NavigableSet<RuinedPosition>> newIdentityHashMap(affectedEntitySet.size()); for (var valueToRuin : ruinedValueList) { var position = listVariableStateSupply.getElementPosition(valueToRuin) .ensureAssigned(); entityToOriginalPositionMap.computeIfAbsent(position.entity(), ignored -> new TreeSet<>()).add(new RuinedPosition(valueToRuin, position.index())); } var nonRecordingScoreDirector = variableChangeRecordingScoreDirector.getBacking(); for (var entry : entityToOriginalPositionMap.entrySet()) { var entity = entry.getKey(); var originalPositionSet = entry.getValue(); // Only record before(), so we can restore the state. // The after() is sent straight to the real score director. variableChangeRecordingScoreDirector.beforeListVariableChanged(listVariableDescriptor, entity, listVariableDescriptor.getFirstUnpinnedIndex(entity), listVariableDescriptor.getListSize(entity)); for (var position : originalPositionSet.descendingSet()) { variableChangeRecordingScoreDirector.beforeListVariableElementUnassigned(listVariableDescriptor, position.ruinedValue()); listVariableDescriptor.removeElement(entity, position.index()); variableChangeRecordingScoreDirector.afterListVariableElementUnassigned(listVariableDescriptor, position.ruinedValue()); } nonRecordingScoreDirector.afterListVariableChanged(listVariableDescriptor, entity, listVariableDescriptor.getFirstUnpinnedIndex(entity), listVariableDescriptor.getListSize(entity)); } scoreDirector.triggerVariableListeners(); var constructionHeuristicPhase = (RuinRecreateConstructionHeuristicPhase<Solution_>) constructionHeuristicPhaseBuilder .ensureThreadSafe(variableChangeRecordingScoreDirector.getBacking()) .withElementsToRuin(entityToOriginalPositionMap.keySet()) .withElementsToRecreate(ruinedValueList) .build(); var nestedSolverScope = new SolverScope<Solution_>(solverScope.getClock()); nestedSolverScope.setSolver(solverScope.getSolver()); nestedSolverScope.setScoreDirector(variableChangeRecordingScoreDirector.getBacking()); constructionHeuristicPhase.solvingStarted(nestedSolverScope); constructionHeuristicPhase.solve(nestedSolverScope); constructionHeuristicPhase.solvingEnded(nestedSolverScope); scoreDirector.triggerVariableListeners(); var entityToInsertedValuesMap = CollectionUtils.<Object, List<Object>> newIdentityHashMap(0); for (var entity : entityToOriginalPositionMap.keySet()) { entityToInsertedValuesMap.put(entity, new ArrayList<>()); } for (var ruinedValue : ruinedValueList) { var position = listVariableStateSupply.getElementPosition(ruinedValue) .ensureAssigned(); entityToNewPositionMap.computeIfAbsent(position.entity(), ignored -> new TreeSet<>()) .add(new RuinedPosition(ruinedValue, position.index())); entityToInsertedValuesMap.computeIfAbsent(position.entity(), ignored -> new ArrayList<>()).add(ruinedValue); } var onlyRecordingChangesScoreDirector = variableChangeRecordingScoreDirector.getNonDelegating(); for (var entry : entityToInsertedValuesMap.entrySet()) { if (!entityToOriginalPositionMap.containsKey(entry.getKey())) { // The entity has not been evaluated while creating the entityToOriginalPositionMap, // meaning it is a new destination entity without a ListVariableBeforeChangeAction // to restore the original elements. // We need to ensure the before action is executed in order to restore the original elements. var originalElementList = constructionHeuristicPhase.getMissingUpdatedElementsMap().get(entry.getKey()); var currentElementList = List.copyOf(listVariableDescriptor.getValue(entry.getKey())); // We need to first update the entity element list before tracking changes // and set it back to the one from the generated solution listVariableDescriptor.getValue(entry.getKey()).clear(); listVariableDescriptor.getValue(entry.getKey()).addAll(originalElementList); onlyRecordingChangesScoreDirector.beforeListVariableChanged(listVariableDescriptor, entry.getKey(), 0, originalElementList.size()); listVariableDescriptor.getValue(entry.getKey()).clear(); listVariableDescriptor.getValue(entry.getKey()).addAll(currentElementList); } // Since the solution was generated through a nested phase, // all actions taken to produce the solution are not accessible. // Therefore, we need to replicate all the actions required to generate the solution // while also allowing for restoring the original state. for (var element : entry.getValue()) { onlyRecordingChangesScoreDirector.beforeListVariableElementAssigned(listVariableDescriptor, element); } onlyRecordingChangesScoreDirector.afterListVariableChanged(listVariableDescriptor, entry.getKey(), listVariableDescriptor.getFirstUnpinnedIndex(entry.getKey()), listVariableDescriptor.getListSize(entry.getKey())); for (var element : entry.getValue()) { onlyRecordingChangesScoreDirector.afterListVariableElementAssigned(listVariableDescriptor, element); } } variableChangeRecordingScoreDirector.getBacking().getSupplyManager() .cancel(listVariableDescriptor.getStateDemand()); } } @Override public Collection<?> getPlanningEntities() { return affectedEntitySet; } @Override public Collection<?> getPlanningValues() { return ruinedValueList; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return true; } @Override public Move<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { var rebasedRuinedValueList = AbstractMove.rebaseList(ruinedValueList, destinationScoreDirector); var rebasedAffectedEntitySet = AbstractMove.rebaseSet(affectedEntitySet, destinationScoreDirector); var rebasedListVariableDescriptor = ((InnerScoreDirector<Solution_, ?>) destinationScoreDirector) .getSolutionDescriptor().getListVariableDescriptor(); return new ListRuinRecreateMove<>(rebasedListVariableDescriptor, constructionHeuristicPhaseBuilder, solverScope, rebasedRuinedValueList, rebasedAffectedEntitySet); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ListRuinRecreateMove<?> that)) return false; return Objects.equals(listVariableDescriptor, that.listVariableDescriptor) && Objects.equals(ruinedValueList, that.ruinedValueList) && Objects.equals(affectedEntitySet, that.affectedEntitySet); } @Override public int hashCode() { return Objects.hash(listVariableDescriptor, ruinedValueList, affectedEntitySet); } @Override public String toString() { return "ListRuinMove{" + "values=" + ruinedValueList + ", newPositionsByEntity=" + (!entityToNewPositionMap.isEmpty() ? entityToNewPositionMap : "?") + '}'; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ruin/ListRuinRecreateMoveIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateConstructionHeuristicPhaseBuilder; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.util.CollectionUtils; final class ListRuinRecreateMoveIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { private final IterableValueSelector<Solution_> valueSelector; private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; private final SolverScope<Solution_> solverScope; private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final int minimumRuinedCount; private final int maximumRuinedCount; private final Random workingRandom; public ListRuinRecreateMoveIterator(IterableValueSelector<Solution_> valueSelector, RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, SolverScope<Solution_> solverScope, ListVariableStateSupply<Solution_> listVariableStateSupply, int minimumRuinedCount, int maximumRuinedCount, Random workingRandom) { this.valueSelector = valueSelector; this.constructionHeuristicPhaseBuilder = constructionHeuristicPhaseBuilder; this.solverScope = solverScope; this.listVariableStateSupply = listVariableStateSupply; this.minimumRuinedCount = minimumRuinedCount; this.maximumRuinedCount = maximumRuinedCount; this.workingRandom = workingRandom; } @Override protected Move<Solution_> createUpcomingSelection() { var valueIterator = valueSelector.iterator(); var ruinedCount = workingRandom.nextInt(minimumRuinedCount, maximumRuinedCount + 1); var selectedValueList = new ArrayList<>(ruinedCount); var affectedEntitySet = CollectionUtils.newLinkedHashSet(ruinedCount); var selectedValueSet = Collections.newSetFromMap(CollectionUtils.newIdentityHashMap(ruinedCount)); for (var i = 0; i < ruinedCount; i++) { var remainingAttempts = ruinedCount; while (true) { if (!valueIterator.hasNext()) { // Bail out; cannot select enough unique elements. return NoChangeMove.getInstance(); } var selectedValue = valueIterator.next(); if (selectedValueSet.add(selectedValue)) { selectedValueList.add(selectedValue); var affectedEntity = listVariableStateSupply.getInverseSingleton(selectedValue); if (affectedEntity != null) { affectedEntitySet.add(affectedEntity); } break; } else { remainingAttempts--; } if (remainingAttempts == 0) { // Bail out; cannot select enough unique elements. return NoChangeMove.getInstance(); } } } return new ListRuinRecreateMove<>(listVariableStateSupply.getSourceVariableDescriptor(), constructionHeuristicPhaseBuilder, solverScope, selectedValueList, affectedEntitySet); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ruin/ListRuinRecreateMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; 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.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.CountSupplier; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.GenericMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateConstructionHeuristicPhaseBuilder; 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 org.apache.commons.math3.util.CombinatoricsUtils; final class ListRuinRecreateMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { private final IterableValueSelector<Solution_> valueSelector; private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; private final CountSupplier minimumSelectedCountSupplier; private final CountSupplier maximumSelectedCountSupplier; private SolverScope<Solution_> solverScope; private ListVariableStateSupply<Solution_> listVariableStateSupply; public ListRuinRecreateMoveSelector(IterableValueSelector<Solution_> valueSelector, ListVariableDescriptor<Solution_> listVariableDescriptor, RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, CountSupplier minimumSelectedCountSupplier, CountSupplier maximumSelectedCountSupplier) { super(); this.valueSelector = FilteringValueSelector.ofAssigned(valueSelector, this::getListVariableStateSupply); this.listVariableDescriptor = listVariableDescriptor; this.constructionHeuristicPhaseBuilder = constructionHeuristicPhaseBuilder; this.minimumSelectedCountSupplier = minimumSelectedCountSupplier; this.maximumSelectedCountSupplier = maximumSelectedCountSupplier; phaseLifecycleSupport.addEventListener(this.valueSelector); } private ListVariableStateSupply<Solution_> getListVariableStateSupply() { return Objects.requireNonNull(listVariableStateSupply, "Impossible state: The listVariableStateSupply is not initialized yet."); } @Override public long getSize() { var totalSize = 0L; var valueCount = valueSelector.getSize(); var minimumSelectedCount = minimumSelectedCountSupplier.applyAsInt(valueCount); var maximumSelectedCount = maximumSelectedCountSupplier.applyAsInt(valueCount); for (var selectedCount = minimumSelectedCount; selectedCount <= maximumSelectedCount; selectedCount++) { // Order is significant, and each entity can only be picked once totalSize += CombinatoricsUtils.factorial((int) valueCount) / CombinatoricsUtils.factorial(selectedCount); } return totalSize; } @Override public boolean isCountable() { return valueSelector.isCountable(); } @Override public boolean isNeverEnding() { return valueSelector.isNeverEnding(); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); this.solverScope = solverScope; this.listVariableStateSupply = solverScope.getScoreDirector() .getSupplyManager() .demand(listVariableDescriptor.getStateDemand()); this.workingRandom = solverScope.getWorkingRandom(); } @Override public Iterator<Move<Solution_>> iterator() { var valueSelectorSize = valueSelector.getSize(); return new ListRuinRecreateMoveIterator<>(valueSelector, constructionHeuristicPhaseBuilder, solverScope, listVariableStateSupply, minimumSelectedCountSupplier.applyAsInt(valueSelectorSize), maximumSelectedCountSupplier.applyAsInt(valueSelectorSize), workingRandom); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ruin/ListRuinRecreateMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListRuinRecreateMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory; 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.generic.CountSupplier; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateConstructionHeuristicPhaseBuilder; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public final class ListRuinRecreateMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, ListRuinRecreateMoveSelectorConfig> { private final ListRuinRecreateMoveSelectorConfig ruinMoveSelectorConfig; public ListRuinRecreateMoveSelectorFactory(ListRuinRecreateMoveSelectorConfig ruinMoveSelectorConfig) { super(ruinMoveSelectorConfig); this.ruinMoveSelectorConfig = ruinMoveSelectorConfig; } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { CountSupplier minimumSelectedSupplier = ruinMoveSelectorConfig::determineMinimumRuinedCount; CountSupplier maximumSelectedSupplier = ruinMoveSelectorConfig::determineMaximumRuinedCount; this.getTheOnlyEntityDescriptorWithListVariable(configPolicy.getSolutionDescriptor()); var listVariableDescriptor = configPolicy.getSolutionDescriptor().getListVariableDescriptor(); var entityDescriptor = listVariableDescriptor.getEntityDescriptor(); var valueSelector = (IterableValueSelector<Solution_>) ValueSelectorFactory .<Solution_> create( new ValueSelectorConfig().withVariableName(listVariableDescriptor.getVariableName())) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, SelectionOrder.RANDOM, false, ValueSelectorFactory.ListValueFilteringType.ACCEPT_ASSIGNED); var entityPlacerConfig = DefaultConstructionHeuristicPhaseFactory.buildListVariableQueuedValuePlacerConfig(configPolicy, listVariableDescriptor); var constructionHeuristicPhaseConfig = new ConstructionHeuristicPhaseConfig().withEntityPlacerConfig(entityPlacerConfig); var constructionHeuristicPhaseBuilder = RuinRecreateConstructionHeuristicPhaseBuilder.create(configPolicy, constructionHeuristicPhaseConfig); return new ListRuinRecreateMoveSelector<>(valueSelector, listVariableDescriptor, constructionHeuristicPhaseBuilder, minimumSelectedSupplier, maximumSelectedSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/list/ruin/RuinedPosition.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; record RuinedPosition(Object ruinedValue, int index) implements Comparable<RuinedPosition> { @Override public int compareTo(RuinedPosition other) { return index - other.index; } }
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/value/FromEntityPropertyValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * This is the common {@link ValueSelector} implementation. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class FromEntityPropertyValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueSelector<Solution_> { private final ValueRangeDescriptor<Solution_> valueRangeDescriptor; private final boolean randomSelection; private CountableValueRange<Object> countableValueRange; private InnerScoreDirector<Solution_, ?> scoreDirector; public FromEntityPropertyValueSelector(ValueRangeDescriptor<Solution_> valueRangeDescriptor, boolean randomSelection) { this.valueRangeDescriptor = valueRangeDescriptor; this.randomSelection = randomSelection; } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); this.scoreDirector = solverScope.getScoreDirector(); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); this.scoreDirector = null; } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); this.countableValueRange = scoreDirector.getValueRangeManager().getFromSolution(valueRangeDescriptor); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); this.countableValueRange = null; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return valueRangeDescriptor.getVariableDescriptor(); } @Override public boolean isCountable() { return valueRangeDescriptor.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || !isCountable(); } @Override public long getSize(Object entity) { if (entity == null) { // When the entity is null, the size of the complete list of values is returned // This logic aligns with the requirements for Nearby in the enterprise repository return Objects.requireNonNull(countableValueRange).getSize(); } else { return scoreDirector.getValueRangeManager().countOnEntity(valueRangeDescriptor, entity); } } @Override public Iterator<Object> iterator(Object entity) { var valueRange = scoreDirector.getValueRangeManager().getFromEntity(valueRangeDescriptor, entity); if (!randomSelection) { return valueRange.createOriginalIterator(); } else { return valueRange.createRandomIterator(workingRandom); } } @Override public Iterator<Object> endingIterator(Object entity) { if (entity == null) { // When the entity is null, the complete list of values is returned // This logic aligns with the requirements for Nearby in the enterprise repository return countableValueRange.createOriginalIterator(); } else { var valueRange = scoreDirector.getValueRangeManager().getFromEntity(valueRangeDescriptor, entity); return valueRange.createOriginalIterator(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FromEntityPropertyValueSelector<?> that = (FromEntityPropertyValueSelector<?>) o; return randomSelection == that.randomSelection && Objects.equals(valueRangeDescriptor, that.valueRangeDescriptor); } @Override public int hashCode() { return Objects.hash(valueRangeDescriptor, randomSelection); } @Override public String toString() { return getClass().getSimpleName() + "(" + getVariableDescriptor().getVariableName() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/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/value/IterableFromSolutionPropertyValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange; import ai.timefold.solver.core.api.domain.valuerange.ValueRange; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; /** * This is the common {@link ValueSelector} implementation. */ public final class IterableFromSolutionPropertyValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_> { private final ValueRangeDescriptor<Solution_> valueRangeDescriptor; private final SelectionCacheType minimumCacheType; private final boolean randomSelection; private final boolean valueRangeMightContainEntity; private ValueRange<Object> cachedValueRange = null; private Long cachedEntityListRevision = null; private boolean cachedEntityListIsDirty = false; public IterableFromSolutionPropertyValueSelector(ValueRangeDescriptor<Solution_> valueRangeDescriptor, SelectionCacheType minimumCacheType, boolean randomSelection) { this.valueRangeDescriptor = valueRangeDescriptor; this.minimumCacheType = minimumCacheType; this.randomSelection = randomSelection; valueRangeMightContainEntity = valueRangeDescriptor.mightContainEntity(); } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return valueRangeDescriptor.getVariableDescriptor(); } @Override public SelectionCacheType getCacheType() { var intrinsicCacheType = valueRangeMightContainEntity ? SelectionCacheType.STEP : SelectionCacheType.PHASE; return (intrinsicCacheType.compareTo(minimumCacheType) > 0) ? intrinsicCacheType : minimumCacheType; } // ************************************************************************ // Cache lifecycle methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); var scoreDirector = phaseScope.getScoreDirector(); cachedValueRange = scoreDirector.getValueRangeManager().getFromSolution(valueRangeDescriptor, scoreDirector.getWorkingSolution()); if (valueRangeMightContainEntity) { cachedEntityListRevision = scoreDirector.getWorkingEntityListRevision(); cachedEntityListIsDirty = false; } } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { super.stepStarted(stepScope); if (valueRangeMightContainEntity) { var scoreDirector = stepScope.getScoreDirector(); if (scoreDirector.isWorkingEntityListDirty(cachedEntityListRevision)) { if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) { cachedEntityListIsDirty = true; } else { cachedValueRange = scoreDirector.getValueRangeManager().getFromSolution(valueRangeDescriptor, scoreDirector.getWorkingSolution()); cachedEntityListRevision = scoreDirector.getWorkingEntityListRevision(); } } } } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); cachedValueRange = null; if (valueRangeMightContainEntity) { cachedEntityListRevision = null; cachedEntityListIsDirty = false; } } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return valueRangeDescriptor.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || !isCountable(); } @Override public long getSize(Object entity) { return getSize(); } @Override public long getSize() { return ((CountableValueRange<?>) cachedValueRange).getSize(); } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } @Override public Iterator<Object> iterator() { checkCachedEntityListIsDirty(); if (randomSelection) { return cachedValueRange.createRandomIterator(workingRandom); } if (cachedValueRange instanceof CountableValueRange<Object> range) { return range.createOriginalIterator(); } throw new IllegalStateException("Value range's class (" + cachedValueRange.getClass().getCanonicalName() + ") " + "does not implement " + CountableValueRange.class + ", " + "yet selectionOrder is not " + SelectionOrder.RANDOM + ".\n" + "Maybe switch selectors' selectionOrder to " + SelectionOrder.RANDOM + "?\n" + "Maybe switch selectors' cacheType to " + SelectionCacheType.JUST_IN_TIME + "?"); } @Override public Iterator<Object> endingIterator(Object entity) { return endingIterator(); } public Iterator<Object> endingIterator() { return ((CountableValueRange<Object>) cachedValueRange).createOriginalIterator(); } private void checkCachedEntityListIsDirty() { if (cachedEntityListIsDirty) { throw new IllegalStateException("The selector (" + this + ") with minimumCacheType (" + minimumCacheType + ")'s workingEntityList became dirty between steps but is still used afterwards."); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; var that = (IterableFromSolutionPropertyValueSelector<?>) other; return randomSelection == that.randomSelection && Objects.equals(valueRangeDescriptor, that.valueRangeDescriptor) && minimumCacheType == that.minimumCacheType; } @Override public int hashCode() { return Objects.hash(valueRangeDescriptor, minimumCacheType, randomSelection); } @Override public String toString() { return getClass().getSimpleName() + "(" + getVariableDescriptor().getVariableName() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/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/value/IterableValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value; import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.IterableFromEntityPropertyValueSelector; /** * @see IterableFromSolutionPropertyValueSelector * @see IterableFromEntityPropertyValueSelector */ public interface IterableValueSelector<Solution_> extends ValueSelector<Solution_>, IterableSelector<Solution_, Object> { }
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/value/ValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value; import java.util.Iterator; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector; import ai.timefold.solver.core.impl.heuristic.selector.Selector; /** * Selects values from the {@link ValueRangeProvider} for a {@link PlanningVariable} annotated property. * * @see AbstractDemandEnabledSelector */ public interface ValueSelector<Solution_> extends Selector<Solution_> { /** * @return never null */ GenuineVariableDescriptor<Solution_> getVariableDescriptor(); /** * Similar to {@link IterableSelector#getSize()}, but requires an entity. * * @param entity never null * @return the approximate number of elements generated by this {@link Selector}, always {@code >= 0} * @throws IllegalStateException if {@link #isCountable} returns false, * but not if only {@link #isNeverEnding()} returns true */ long getSize(Object entity); /** * Similar to {@link IterableSelector#iterator()}, but requires an entity. * * @param entity never null * @return never null */ Iterator<Object> iterator(Object entity); /** * If {@link #isNeverEnding()} is true, then {@link #iterator(Object)} will never end. * This returns an ending {@link Iterator}, that tries to match {@link #iterator(Object)} as much as possible, * but return each distinct element only once * and therefore it might not respect the configuration of this {@link ValueSelector} entirely. * * @param entity never null * @return never null * @see #iterator(Object) */ Iterator<Object> endingIterator(Object entity); }
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/value/ValueSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.value; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Function; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.WeightFactorySelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.AssignedListValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.CachingValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.DowncastingValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueRangeSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FromEntitySortingValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.InitializedValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.IterableFromEntityPropertyValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.ProbabilityValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.ReinitializeVariableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.SelectedCountLimitValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.ShufflingValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.SortingValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.UnassignedListValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.mimic.MimicRecordingValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.mimic.MimicReplayingValueSelector; import ai.timefold.solver.core.impl.solver.ClassInstanceCache; public class ValueSelectorFactory<Solution_> extends AbstractSelectorFactory<Solution_, ValueSelectorConfig> { public static <Solution_> ValueSelectorFactory<Solution_> create(ValueSelectorConfig valueSelectorConfig) { return new ValueSelectorFactory<>(valueSelectorConfig); } public ValueSelectorFactory(ValueSelectorConfig valueSelectorConfig) { super(valueSelectorConfig); } public GenuineVariableDescriptor<Solution_> extractVariableDescriptor(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor) { var variableName = config.getVariableName(); var mimicSelectorRef = config.getMimicSelectorRef(); if (variableName != null) { return getVariableDescriptorForName(downcastEntityDescriptor(configPolicy, entityDescriptor), variableName); } else if (mimicSelectorRef != null) { return configPolicy.getValueMimicRecorder(mimicSelectorRef).getVariableDescriptor(); } else { return null; } } public ValueSelector<Solution_> buildValueSelector(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { return buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder, configPolicy.isReinitializeVariableFilterEnabled(), ListValueFilteringType.NONE); } public ValueSelector<Solution_> buildValueSelector(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, boolean applyReinitializeVariableFiltering, ListValueFilteringType listValueFilteringType) { return buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder, applyReinitializeVariableFiltering, listValueFilteringType, null, false); } /** * @param configPolicy never null * @param entityDescriptor never null * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching * and less would be pointless. * @param inheritedSelectionOrder never null * @param applyReinitializeVariableFiltering the reinitialization flag * @param listValueFilteringType the list filtering type * @param entityValueRangeRecorderId the recorder id to be used to create a replaying selector when enabling entity value * range * @param assertBothSides a flag used by the entity value range filtering select to enable different types of validations * @return never null */ public ValueSelector<Solution_> buildValueSelector(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, boolean applyReinitializeVariableFiltering, ListValueFilteringType listValueFilteringType, String entityValueRangeRecorderId, boolean assertBothSides) { var variableDescriptor = deduceGenuineVariableDescriptor(downcastEntityDescriptor(configPolicy, entityDescriptor), config.getVariableName()); if (config.getMimicSelectorRef() != null) { var valueSelector = buildMimicReplaying(configPolicy); valueSelector = applyReinitializeVariableFiltering(applyReinitializeVariableFiltering, variableDescriptor, valueSelector); valueSelector = applyDowncasting(valueSelector); return valueSelector; } 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); // baseValueSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely var randomSelection = determineBaseRandomSelection(variableDescriptor, resolvedCacheType, resolvedSelectionOrder); var valueSelector = buildBaseValueSelector(variableDescriptor, SelectionCacheType.max(minimumCacheType, resolvedCacheType), randomSelection); var instanceCache = configPolicy.getClassInstanceCache(); if (nearbySelectionConfig != null) { // TODO Static filtering (such as movableEntitySelectionFilter) should affect nearbySelection too valueSelector = applyNearbySelection(configPolicy, entityDescriptor, minimumCacheType, resolvedSelectionOrder, valueSelector); } 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. valueSelector = applyValueRangeFiltering(configPolicy, valueSelector, entityDescriptor, minimumCacheType, inheritedSelectionOrder, randomSelection, entityValueRangeRecorderId, assertBothSides); } valueSelector = applyFiltering(valueSelector, instanceCache); valueSelector = applyInitializedChainedValueFilter(configPolicy, variableDescriptor, valueSelector); valueSelector = applySorting(resolvedCacheType, resolvedSelectionOrder, valueSelector, instanceCache); valueSelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, valueSelector, instanceCache); valueSelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, valueSelector); valueSelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, valueSelector); valueSelector = applySelectedLimit(valueSelector); valueSelector = applyListValueFiltering(configPolicy, listValueFilteringType, variableDescriptor, valueSelector); valueSelector = applyMimicRecording(configPolicy, valueSelector); valueSelector = applyReinitializeVariableFiltering(applyReinitializeVariableFiltering, variableDescriptor, valueSelector); valueSelector = applyDowncasting(valueSelector); return valueSelector; } protected ValueSelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy) { if (config.getId() != null || config.getCacheType() != null || config.getSelectionOrder() != null || config.getNearbySelectionConfig() != null || config.getFilterClass() != null || config.getSorterManner() != null || config.getSorterComparatorClass() != null || config.getSorterWeightFactoryClass() != null || config.getSorterOrder() != null || config.getSorterClass() != null || config.getProbabilityWeightFactoryClass() != null || config.getSelectedCountLimit() != null) { throw new IllegalArgumentException( "The valueSelectorConfig (%s) with mimicSelectorRef (%s) has another property that is not null." .formatted(config, config.getMimicSelectorRef())); } var valueMimicRecorder = configPolicy.getValueMimicRecorder(config.getMimicSelectorRef()); if (valueMimicRecorder == null) { throw new IllegalArgumentException( "The valueSelectorConfig (%s) has a mimicSelectorRef (%s) for which no valueSelector with that id exists (in its solver phase)." .formatted(config, config.getMimicSelectorRef())); } return new MimicReplayingValueSelector<>(valueMimicRecorder); } protected EntityDescriptor<Solution_> downcastEntityDescriptor(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor) { var downcastEntityClass = config.getDowncastEntityClass(); if (downcastEntityClass != null) { var parentEntityClass = entityDescriptor.getEntityClass(); if (!parentEntityClass.isAssignableFrom(downcastEntityClass)) { throw new IllegalStateException( "The downcastEntityClass (%s) is not a subclass of the parentEntityClass (%s) configured by the %s." .formatted(downcastEntityClass, parentEntityClass, EntitySelector.class.getSimpleName())); } var solutionDescriptor = configPolicy.getSolutionDescriptor(); entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(downcastEntityClass); if (entityDescriptor == null) { throw new IllegalArgumentException(""" The selectorConfig (%s) has an downcastEntityClass (%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, downcastEntityClass, downcastEntityClass.getSimpleName(), solutionDescriptor.getEntityClassSet(), PlanningSolution.class.getSimpleName())); } } return entityDescriptor; } protected boolean determineBaseRandomSelection(GenuineVariableDescriptor<Solution_> variableDescriptor, 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() || !hasFiltering(variableDescriptor); default -> throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder + ") is not implemented."); }; } private ValueSelector<Solution_> buildBaseValueSelector(GenuineVariableDescriptor<Solution_> variableDescriptor, SelectionCacheType minimumCacheType, boolean randomSelection) { var valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); // TODO minimumCacheType SOLVER is only a problem if the valueRange includes entities or custom weird cloning if (minimumCacheType == SelectionCacheType.SOLVER) { // TODO Solver cached entities are not compatible with ConstraintStreams and IncrementalScoreDirector // because between phases the entities get cloned throw new IllegalArgumentException("The minimumCacheType (" + minimumCacheType + ") is not yet supported. Please use " + SelectionCacheType.PHASE + " instead."); } if (valueRangeDescriptor.canExtractValueRangeFromSolution()) { return new IterableFromSolutionPropertyValueSelector<>(valueRangeDescriptor, minimumCacheType, randomSelection); } else { // TODO Do not allow PHASE cache on FromEntityPropertyValueSelector, except if the moveSelector is PHASE cached too. var fromEntityPropertySelector = new FromEntityPropertyValueSelector<>(valueRangeDescriptor, randomSelection); return new IterableFromEntityPropertyValueSelector<>(fromEntityPropertySelector, randomSelection); } } private boolean hasFiltering(GenuineVariableDescriptor<Solution_> variableDescriptor) { return config.getFilterClass() != null || (variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.hasMovableChainedTrailingValueFilter()); } protected ValueSelector<Solution_> applyFiltering(ValueSelector<Solution_> valueSelector, ClassInstanceCache instanceCache) { var variableDescriptor = valueSelector.getVariableDescriptor(); if (hasFiltering(variableDescriptor)) { List<SelectionFilter<Solution_, Object>> filterList = new ArrayList<>(config.getFilterClass() == null ? 1 : 2); if (config.getFilterClass() != null) { filterList.add(instanceCache.newInstance(config, "filterClass", config.getFilterClass())); } // Filter out pinned entities if (variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.hasMovableChainedTrailingValueFilter()) { filterList.add(basicVariableDescriptor.getMovableChainedTrailingValueFilter()); } valueSelector = FilteringValueSelector.of(valueSelector, SelectionFilter.compose(filterList)); } return valueSelector; } protected ValueSelector<Solution_> applyInitializedChainedValueFilter(HeuristicConfigPolicy<Solution_> configPolicy, GenuineVariableDescriptor<Solution_> variableDescriptor, ValueSelector<Solution_> valueSelector) { var isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (configPolicy.isInitializedChainedValueFilterEnabled() && isChained) { valueSelector = InitializedValueSelector.create(valueSelector); } return valueSelector; } 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 valueSelectorConfig (%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", ValueSelectorConfig::getSorterComparatorClass); assertNotSorterMannerAnd(config, "sorterWeightFactoryClass", ValueSelectorConfig::getSorterWeightFactoryClass); assertNotSorterMannerAnd(config, "sorterClass", ValueSelectorConfig::getSorterClass); assertNotSorterMannerAnd(config, "sorterOrder", ValueSelectorConfig::getSorterOrder); assertNotSorterClassAnd(config, "sorterComparatorClass", ValueSelectorConfig::getSorterComparatorClass); assertNotSorterClassAnd(config, "sorterWeightFactoryClass", ValueSelectorConfig::getSorterWeightFactoryClass); assertNotSorterClassAnd(config, "sorterOrder", ValueSelectorConfig::getSorterOrder); if (sorterComparatorClass != null && sorterWeightFactoryClass != null) { throw new IllegalArgumentException( "The valueSelectorConfig (%s) has both a sorterComparatorClass (%s) and a sorterWeightFactoryClass (%s)." .formatted(config, sorterComparatorClass, sorterWeightFactoryClass)); } } private static void assertNotSorterMannerAnd(ValueSelectorConfig config, String propertyName, Function<ValueSelectorConfig, 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(ValueSelectorConfig config, String propertyName, Function<ValueSelectorConfig, 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 ValueSelector<Solution_> applySorting(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector, ClassInstanceCache instanceCache) { if (resolvedSelectionOrder == SelectionOrder.SORTED) { SelectionSorter<Solution_, Object> sorter; var sorterManner = config.getSorterManner(); if (sorterManner != null) { var variableDescriptor = valueSelector.getVariableDescriptor(); if (!ValueSelectorConfig.hasSorter(sorterManner, variableDescriptor)) { return valueSelector; } sorter = ValueSelectorConfig.determineSorter(sorterManner, variableDescriptor); } else if (config.getSorterComparatorClass() != null) { Comparator<Object> sorterComparator = instanceCache.newInstance(config, "sorterComparatorClass", config.getSorterComparatorClass()); sorter = new ComparatorSelectionSorter<>(sorterComparator, SelectionSorterOrder.resolve(config.getSorterOrder())); } else if (config.getSorterWeightFactoryClass() != null) { SelectionSorterWeightFactory<Solution_, Object> sorterWeightFactory = instanceCache.newInstance(config, "sorterWeightFactoryClass", config.getSorterWeightFactoryClass()); sorter = new WeightFactorySelectionSorter<>(sorterWeightFactory, SelectionSorterOrder.resolve(config.getSorterOrder())); } else if (config.getSorterClass() != null) { sorter = instanceCache.newInstance(config, "sorterClass", config.getSorterClass()); } else { throw new IllegalArgumentException(""" The valueSelectorConfig (%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())); } if (!valueSelector.getVariableDescriptor().canExtractValueRangeFromSolution() && resolvedCacheType == SelectionCacheType.STEP) { valueSelector = new FromEntitySortingValueSelector<>(valueSelector, resolvedCacheType, sorter); } else { if (!(valueSelector instanceof IterableValueSelector)) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with resolvedCacheType (" + resolvedCacheType + ") and resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs to be based on an " + IterableValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } valueSelector = new SortingValueSelector<>((IterableValueSelector<Solution_>) valueSelector, resolvedCacheType, sorter); } } return valueSelector; } protected void validateProbability(SelectionOrder resolvedSelectionOrder) { if (config.getProbabilityWeightFactoryClass() != null && resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass() + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") that is not " + SelectionOrder.PROBABILISTIC + "."); } } protected ValueSelector<Solution_> applyProbability(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector, ClassInstanceCache instanceCache) { if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) { if (config.getProbabilityWeightFactoryClass() == null) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs a probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass() + ")."); } SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory = instanceCache.newInstance(config, "probabilityWeightFactoryClass", config.getProbabilityWeightFactoryClass()); if (!(valueSelector instanceof IterableValueSelector)) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with resolvedCacheType (" + resolvedCacheType + ") and resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs to be based on an " + IterableValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } valueSelector = new ProbabilityValueSelector<>((IterableValueSelector<Solution_>) valueSelector, resolvedCacheType, probabilityWeightFactory); } return valueSelector; } private ValueSelector<Solution_> applyShuffling(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector) { if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) { if (!(valueSelector instanceof IterableValueSelector)) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with resolvedCacheType (" + resolvedCacheType + ") and resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs to be based on an " + IterableValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } valueSelector = new ShufflingValueSelector<>((IterableValueSelector<Solution_>) valueSelector, resolvedCacheType); } return valueSelector; } private ValueSelector<Solution_> applyCaching(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector) { if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(valueSelector.getCacheType()) > 0) { if (!(valueSelector instanceof IterableValueSelector)) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with resolvedCacheType (" + resolvedCacheType + ") and resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs to be based on an " + IterableValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } valueSelector = new CachingValueSelector<>((IterableValueSelector<Solution_>) valueSelector, resolvedCacheType, resolvedSelectionOrder.toRandomSelectionBoolean()); } return valueSelector; } private void validateSelectedLimit(SelectionCacheType minimumCacheType) { if (config.getSelectedCountLimit() != null && minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with selectedCountLimit (" + config.getSelectedCountLimit() + ") has a minimumCacheType (" + minimumCacheType + ") that is higher than " + SelectionCacheType.JUST_IN_TIME + "."); } } private ValueSelector<Solution_> applySelectedLimit(ValueSelector<Solution_> valueSelector) { if (config.getSelectedCountLimit() != null) { valueSelector = new SelectedCountLimitValueSelector<>(valueSelector, config.getSelectedCountLimit()); } return valueSelector; } private ValueSelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector) { return TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION) .applyNearbySelection(config, configPolicy, entityDescriptor, minimumCacheType, resolvedSelectionOrder, valueSelector); } private ValueSelector<Solution_> applyMimicRecording(HeuristicConfigPolicy<Solution_> configPolicy, ValueSelector<Solution_> valueSelector) { var id = config.getId(); if (id != null) { if (id.isEmpty()) { throw new IllegalArgumentException("The valueSelectorConfig (%s) has an empty id (%s).".formatted(config, id)); } if (!(valueSelector instanceof IterableValueSelector)) { throw new IllegalArgumentException(""" The valueSelectorConfig (%s) with id (%s) needs to be based on an %s (%s). Check your @%s annotations.""" .formatted(config, id, IterableValueSelector.class.getSimpleName(), valueSelector, ValueRangeProvider.class.getSimpleName())); } var mimicRecordingValueSelector = new MimicRecordingValueSelector<>((IterableValueSelector<Solution_>) valueSelector); configPolicy.addValueMimicRecorder(id, mimicRecordingValueSelector); valueSelector = mimicRecordingValueSelector; } return valueSelector; } ValueSelector<Solution_> applyListValueFiltering(HeuristicConfigPolicy<?> configPolicy, ListValueFilteringType listValueFilteringType, GenuineVariableDescriptor<Solution_> variableDescriptor, ValueSelector<Solution_> valueSelector) { if (variableDescriptor.isListVariable() && configPolicy.isUnassignedValuesAllowed() && listValueFilteringType != ListValueFilteringType.NONE) { if (!(valueSelector instanceof IterableValueSelector)) { throw new IllegalArgumentException("The valueSelectorConfig (" + config + ") with id (" + config.getId() + ") needs to be based on an " + IterableValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } valueSelector = listValueFilteringType == ListValueFilteringType.ACCEPT_ASSIGNED ? new AssignedListValueSelector<>(((IterableValueSelector<Solution_>) valueSelector)) : new UnassignedListValueSelector<>(((IterableValueSelector<Solution_>) valueSelector)); } return valueSelector; } private ValueSelector<Solution_> applyReinitializeVariableFiltering(boolean applyReinitializeVariableFiltering, GenuineVariableDescriptor<Solution_> variableDescriptor, ValueSelector<Solution_> valueSelector) { if (applyReinitializeVariableFiltering && !variableDescriptor.isListVariable()) { valueSelector = new ReinitializeVariableValueSelector<>(valueSelector); } return valueSelector; } private ValueSelector<Solution_> applyDowncasting(ValueSelector<Solution_> valueSelector) { if (config.getDowncastEntityClass() != null) { valueSelector = new DowncastingValueSelector<>(valueSelector, config.getDowncastEntityClass()); } return valueSelector; } public static <Solution_> ValueSelector<Solution_> applyValueRangeFiltering( HeuristicConfigPolicy<Solution_> configPolicy, ValueSelector<Solution_> valueSelector, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder selectionOrder, boolean randomSelection, String entityValueRangeRecorderId, boolean assertBothSides) { if (entityValueRangeRecorderId == null) { return valueSelector; } var valueSelectorConfig = new ValueSelectorConfig() .withMimicSelectorRef(entityValueRangeRecorderId); var replayingValueSelector = (IterableValueSelector<Solution_>) ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, selectionOrder); return new FilteringValueRangeSelector<>((IterableValueSelector<Solution_>) valueSelector, replayingValueSelector, randomSelection, assertBothSides); } public enum ListValueFilteringType { NONE, ACCEPT_ASSIGNED, ACCEPT_UNASSIGNED, } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/chained/DefaultSubChainSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.chained; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.solver.random.RandomUtils; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * This is the common {@link SubChainSelector} implementation. */ public class DefaultSubChainSelector<Solution_> extends AbstractSelector<Solution_> implements SubChainSelector<Solution_>, SelectionCacheLifecycleListener<Solution_> { protected static final SelectionCacheType CACHE_TYPE = SelectionCacheType.STEP; protected final IterableValueSelector<Solution_> valueSelector; protected final boolean randomSelection; protected SingletonInverseVariableSupply inverseVariableSupply; // The sub selection here is a sequence. For example from ABCDE, it can select BCD, but not ACD. protected final int minimumSubChainSize; protected final int maximumSubChainSize; protected List<SubChain> anchorTrailingChainList = null; public DefaultSubChainSelector(IterableValueSelector<Solution_> valueSelector, boolean randomSelection, int minimumSubChainSize, int maximumSubChainSize) { this.valueSelector = valueSelector; this.randomSelection = randomSelection; boolean isChained = valueSelector.getVariableDescriptor() instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (!isChained) { throw new IllegalArgumentException( "The selector (%s)'s valueSelector (%s) must have a chained variableDescriptor chained (%s)." .formatted(this, valueSelector, isChained)); } if (valueSelector.isNeverEnding()) { throw new IllegalStateException( "The selector (%s) has a valueSelector (%s) with neverEnding (%s)." .formatted(this, valueSelector, valueSelector.isNeverEnding())); } phaseLifecycleSupport.addEventListener(valueSelector); phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(CACHE_TYPE, this)); this.minimumSubChainSize = minimumSubChainSize; this.maximumSubChainSize = maximumSubChainSize; if (minimumSubChainSize < 1) { throw new IllegalStateException("The selector (%s)'s minimumSubChainSize (%d) must be at least 1." .formatted(this, minimumSubChainSize)); } if (minimumSubChainSize > maximumSubChainSize) { throw new IllegalStateException("The minimumSubChainSize (%d) must be less than maximumSubChainSize (%d)." .formatted(minimumSubChainSize, maximumSubChainSize)); } } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return valueSelector.getVariableDescriptor(); } @Override public SelectionCacheType getCacheType() { return CACHE_TYPE; } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); SupplyManager supplyManager = solverScope.getScoreDirector().getSupplyManager(); GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor(); inverseVariableSupply = supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor)); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); inverseVariableSupply = null; } // ************************************************************************ // Cache lifecycle methods // ************************************************************************ @Override public void constructCache(SolverScope<Solution_> solverScope) { GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor(); long valueSize = valueSelector.getSize(); // Fail-fast when anchorTrailingChainList.size() could ever be too big if (valueSize > Integer.MAX_VALUE) { throw new IllegalStateException( "The selector (%s) has a valueSelector (%s) with valueSize (%d) which is higher than Integer.MAX_VALUE." .formatted(this, valueSelector, valueSize)); } List<Object> anchorList = new ArrayList<>(); for (Object value : valueSelector) { if (variableDescriptor.isValuePotentialAnchor(value)) { anchorList.add(value); } } int anchorListSize = Math.max(anchorList.size(), 1); anchorTrailingChainList = new ArrayList<>(anchorListSize); int anchorChainInitialCapacity = ((int) valueSize / anchorListSize) + 1; for (Object anchor : anchorList) { List<Object> anchorChain = new ArrayList<>(anchorChainInitialCapacity); Object trailingEntity = inverseVariableSupply.getInverseSingleton(anchor); while (trailingEntity != null) { anchorChain.add(trailingEntity); trailingEntity = inverseVariableSupply.getInverseSingleton(trailingEntity); } if (anchorChain.size() >= minimumSubChainSize) { anchorTrailingChainList.add(new SubChain(anchorChain)); } } } @Override public void disposeCache(SolverScope<Solution_> solverScope) { anchorTrailingChainList = null; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return randomSelection; } @Override public long getSize() { long selectionSize = 0L; for (SubChain anchorTrailingChain : anchorTrailingChainList) { selectionSize += calculateSubChainSelectionSize(anchorTrailingChain); } return selectionSize; } protected long calculateSubChainSelectionSize(SubChain anchorTrailingChain) { long anchorTrailingChainSize = anchorTrailingChain.getSize(); long n = anchorTrailingChainSize - minimumSubChainSize + 1L; long m = (maximumSubChainSize >= anchorTrailingChainSize) ? 0L : anchorTrailingChainSize - maximumSubChainSize; return (n * (n + 1L) / 2L) - (m * (m + 1L) / 2L); } @Override public Iterator<SubChain> iterator() { if (!randomSelection) { return new OriginalSubChainIterator(anchorTrailingChainList.listIterator()); } else { return new RandomSubChainIterator(); } } @Override public ListIterator<SubChain> listIterator() { if (!randomSelection) { return new OriginalSubChainIterator(anchorTrailingChainList.listIterator()); } else { throw new IllegalStateException("The selector (%s) does not support a ListIterator with randomSelection (%s)." .formatted(this, randomSelection)); } } @Override public ListIterator<SubChain> listIterator(int index) { if (!randomSelection) { // TODO Implement more efficient ListIterator https://issues.redhat.com/browse/PLANNER-37 OriginalSubChainIterator it = new OriginalSubChainIterator(anchorTrailingChainList.listIterator()); for (int i = 0; i < index; i++) { it.next(); } return it; } else { throw new IllegalStateException("The selector (%s) does not support a ListIterator with randomSelection (%s)." .formatted(this, randomSelection)); } } private class OriginalSubChainIterator extends UpcomingSelectionIterator<SubChain> implements ListIterator<SubChain> { private final ListIterator<SubChain> anchorTrailingChainIterator; private List<Object> anchorTrailingChain; private int fromIndex; // Inclusive private int toIndex; // Exclusive private int nextListIteratorIndex; public OriginalSubChainIterator(ListIterator<SubChain> anchorTrailingChainIterator) { this.anchorTrailingChainIterator = anchorTrailingChainIterator; fromIndex = 0; toIndex = 1; anchorTrailingChain = Collections.emptyList(); nextListIteratorIndex = 0; } @Override protected SubChain createUpcomingSelection() { toIndex++; if (toIndex - fromIndex > maximumSubChainSize || toIndex > anchorTrailingChain.size()) { fromIndex++; toIndex = fromIndex + minimumSubChainSize; // minimumSubChainSize <= maximumSubChainSize so (toIndex - fromIndex > maximumSubChainSize) is true while (toIndex > anchorTrailingChain.size()) { if (!anchorTrailingChainIterator.hasNext()) { return noUpcomingSelection(); } anchorTrailingChain = anchorTrailingChainIterator.next().getEntityList(); fromIndex = 0; toIndex = fromIndex + minimumSubChainSize; } } return new SubChain(anchorTrailingChain.subList(fromIndex, toIndex)); } @Override public SubChain next() { nextListIteratorIndex++; return super.next(); } @Override public int nextIndex() { return nextListIteratorIndex; } @Override public boolean hasPrevious() { throw new UnsupportedOperationException(); } @Override public SubChain previous() { throw new UnsupportedOperationException(); } @Override public int previousIndex() { throw new UnsupportedOperationException(); } @Override public void set(SubChain subChain) { throw new UnsupportedOperationException("The optional operation set() is not supported."); } @Override public void add(SubChain subChain) { throw new UnsupportedOperationException("The optional operation add() is not supported."); } } private class RandomSubChainIterator extends UpcomingSelectionIterator<SubChain> { private RandomSubChainIterator() { if (anchorTrailingChainList.isEmpty()) { upcomingSelection = noUpcomingSelection(); upcomingCreated = true; } } @Override protected SubChain createUpcomingSelection() { SubChain anchorTrailingChain = selectAnchorTrailingChain(); // Every SubChain has the same probability (from this point on at least). // A random fromIndex and random toIndex would not be fair. long selectionSize = calculateSubChainSelectionSize(anchorTrailingChain); // Black magic to translate selectionIndex into fromIndex and toIndex long fromIndex = RandomUtils.nextLong(workingRandom, selectionSize); long subChainSize = minimumSubChainSize; long countInThatSize = anchorTrailingChain.getSize() - subChainSize + 1; while (fromIndex >= countInThatSize) { fromIndex -= countInThatSize; subChainSize++; countInThatSize--; if (countInThatSize <= 0) { throw new IllegalStateException("Impossible if calculateSubChainSelectionSize() works correctly."); } } return anchorTrailingChain.subChain((int) fromIndex, (int) (fromIndex + subChainSize)); } private SubChain selectAnchorTrailingChain() { // Known issue/compromise: Every SubChain should have same probability, but doesn't. // Instead, every anchorTrailingChain has the same probability. int anchorTrailingChainListIndex = workingRandom.nextInt(anchorTrailingChainList.size()); return anchorTrailingChainList.get(anchorTrailingChainListIndex); } } @Override public String toString() { return getClass().getSimpleName() + "(" + valueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/chained/SubChain.java
package ai.timefold.solver.core.impl.heuristic.selector.value.chained; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * A subList out of a single chain. * <p> * Never includes an anchor. */ public final class SubChain { private final List<Object> entityList; public SubChain(List<Object> entityList) { this.entityList = entityList; } public List<Object> getEntityList() { return entityList; } // ************************************************************************ // Worker methods // ************************************************************************ public Object getFirstEntity() { if (entityList.isEmpty()) { return null; } return entityList.get(0); } public Object getLastEntity() { if (entityList.isEmpty()) { return null; } return entityList.get(entityList.size() - 1); } public int getSize() { return entityList.size(); } public SubChain reverse() { return new SubChain(CollectionUtils.copy(entityList, true)); } public SubChain subChain(int fromIndex, int toIndex) { return new SubChain(entityList.subList(fromIndex, toIndex)); } public SubChain rebase(ScoreDirector<?> destinationScoreDirector) { return new SubChain(AbstractMove.rebaseList(entityList, destinationScoreDirector)); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } SubChain subChain = (SubChain) other; return Objects.equals(entityList, subChain.entityList); } @Override public int hashCode() { return Objects.hash(entityList); } @Override public String toString() { return entityList.toString(); } public String toDottedString() { return "[" + getFirstEntity() + ".." + getLastEntity() + "]"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/chained/SubChainSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.chained; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.ListIterableSelector; public interface SubChainSelector<Solution_> extends ListIterableSelector<Solution_, SubChain> { /** * @return never null */ GenuineVariableDescriptor<Solution_> getVariableDescriptor(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/chained/SubChainSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.value.chained; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.chained.SubChainSelectorConfig; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class SubChainSelectorFactory<Solution_> { /** * Defaults to 1, even if it partially duplicates {@link ChangeMoveSelectorConfig}, * because otherwise the default would not include * swapping a pillar of size 1 with another pillar of size 2 or greater. */ private static final int DEFAULT_MINIMUM_SUB_CHAIN_SIZE = 1; private static final int DEFAULT_MAXIMUM_SUB_CHAIN_SIZE = Integer.MAX_VALUE; public static <Solution_> SubChainSelectorFactory<Solution_> create(SubChainSelectorConfig subChainSelectorConfig) { return new SubChainSelectorFactory<>(subChainSelectorConfig); } private final SubChainSelectorConfig config; public SubChainSelectorFactory(SubChainSelectorConfig subChainSelectorConfig) { this.config = subChainSelectorConfig; } /** * @param configPolicy never null * @param entityDescriptor never null * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching * and less would be pointless. * @param inheritedSelectionOrder never null * @return never null */ public SubChainSelector<Solution_> buildSubChainSelector(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) { throw new IllegalArgumentException("The subChainSelectorConfig (" + config + ")'s minimumCacheType (" + minimumCacheType + ") must not be higher than " + SelectionCacheType.STEP + " because the chains change every step."); } ValueSelectorConfig valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); // ValueSelector uses SelectionOrder.ORIGINAL because a SubChainSelector STEP caches the values ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, SelectionOrder.ORIGINAL); return new DefaultSubChainSelector<>((IterableValueSelector<Solution_>) valueSelector, inheritedSelectionOrder.toRandomSelectionBoolean(), Objects.requireNonNullElse(config.getMinimumSubChainSize(), DEFAULT_MINIMUM_SUB_CHAIN_SIZE), Objects.requireNonNullElse(config.getMaximumSubChainSize(), DEFAULT_MAXIMUM_SUB_CHAIN_SIZE)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/AbstractCachingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public abstract class AbstractCachingValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements SelectionCacheLifecycleListener<Solution_>, ValueSelector<Solution_> { protected final IterableValueSelector<Solution_> childValueSelector; protected final SelectionCacheType cacheType; protected List<Object> cachedValueList = null; protected AbstractCachingValueSelector(IterableValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType) { this.childValueSelector = childValueSelector; this.cacheType = cacheType; if (childValueSelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with neverEnding (" + childValueSelector.isNeverEnding() + ")."); } phaseLifecycleSupport.addEventListener(childValueSelector); if (cacheType.isNotCached()) { throw new IllegalArgumentException("The selector (" + this + ") does not support the cacheType (" + cacheType + ")."); } phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this)); } public ValueSelector<Solution_> getChildValueSelector() { return childValueSelector; } @Override public SelectionCacheType getCacheType() { return cacheType; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void constructCache(SolverScope<Solution_> solverScope) { long childSize = childValueSelector.getSize(); if (childSize > Integer.MAX_VALUE) { throw new IllegalStateException("The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with childSize (" + childSize + ") which is higher than Integer.MAX_VALUE."); } cachedValueList = new ArrayList<>((int) childSize); // TODO Fail-faster if a non FromSolutionPropertyValueSelector is used childValueSelector.iterator().forEachRemaining(cachedValueList::add); logger.trace(" Created cachedValueList: size ({}), valueSelector ({}).", cachedValueList.size(), this); } @Override public void disposeCache(SolverScope<Solution_> solverScope) { cachedValueList = null; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return true; } @Override public long getSize(Object entity) { return getSize(); } public long getSize() { return cachedValueList.size(); } @Override public Iterator<Object> endingIterator(Object entity) { return endingIterator(); } public Iterator<Object> endingIterator() { return cachedValueList.iterator(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; AbstractCachingValueSelector<?> that = (AbstractCachingValueSelector<?>) other; return Objects.equals(childValueSelector, that.childValueSelector) && cacheType == that.cacheType; } @Override public int hashCode() { return Objects.hash(childValueSelector, cacheType); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/AbstractInverseEntityFilteringValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.Objects; import java.util.stream.Stream; import java.util.stream.StreamSupport; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; /** * Filters planning values based on their assigned status. The assigned status is determined using the inverse supply. * If the inverse entity is not null, the value is assigned, otherwise it is unassigned. * A subclass must implement the {@link #valueFilter(Object)} to decide whether assigned or unassigned values will be selected. * <p> * Does implement {@link IterableValueSelector} because the question whether a value is assigned or not does not depend * on a specific entity. */ abstract class AbstractInverseEntityFilteringValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_> { protected final IterableValueSelector<Solution_> childValueSelector; protected ListVariableStateSupply<Solution_> listVariableStateSupply; protected AbstractInverseEntityFilteringValueSelector(IterableValueSelector<Solution_> childValueSelector) { if (childValueSelector.isNeverEnding()) { throw new IllegalArgumentException("The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with neverEnding (" + childValueSelector.isNeverEnding() + ").\n" + "This is not allowed because " + AbstractInverseEntityFilteringValueSelector.class.getSimpleName() + " cannot decorate a never-ending child value selector.\n" + "This could be a result of using random selection order (which is often the default)."); } this.childValueSelector = childValueSelector; phaseLifecycleSupport.addEventListener(childValueSelector); } protected abstract boolean valueFilter(Object value); // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); ListVariableDescriptor<Solution_> variableDescriptor = (ListVariableDescriptor<Solution_>) childValueSelector.getVariableDescriptor(); listVariableStateSupply = phaseScope.getScoreDirector().getSupplyManager() .demand(variableDescriptor.getStateDemand()); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); listVariableStateSupply = null; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { // Because !neverEnding => countable. return true; } @Override public boolean isNeverEnding() { // Because the childValueSelector is not never-ending. return false; } @Override public long getSize(Object entity) { return getSize(); } @Override public long getSize() { return streamUnassignedValues().count(); } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } @Override public Iterator<Object> iterator() { return streamUnassignedValues().iterator(); } @Override public Iterator<Object> endingIterator(Object entity) { return iterator(); } private Stream<Object> streamUnassignedValues() { return StreamSupport.stream(childValueSelector.spliterator(), false) // Accept either assigned or unassigned values. .filter(this::valueFilter); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; AbstractInverseEntityFilteringValueSelector<?> that = (AbstractInverseEntityFilteringValueSelector<?>) other; return Objects.equals(childValueSelector, that.childValueSelector); } @Override public int hashCode() { return Objects.hash(childValueSelector); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/AssignedListValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import ai.timefold.solver.core.impl.heuristic.selector.list.ElementDestinationSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList; /** * Only selects values from the child value selector that are initialized. * This is used for {@link ElementDestinationSelector}’s child value selector during Construction Heuristic phase * to filter out values which cannot be used to build a destination {@link PositionInList}. */ public final class AssignedListValueSelector<Solution_> extends AbstractInverseEntityFilteringValueSelector<Solution_> { public AssignedListValueSelector(IterableValueSelector<Solution_> childValueSelector) { super(childValueSelector); } @Override protected boolean valueFilter(Object value) { if (listVariableStateSupply.getUnassignedCount() == 0) { return true; // Avoid hash lookup. } return listVariableStateSupply.isAssigned(value); } @Override public String toString() { return "Assigned(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/CachingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator; import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.CachingEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.CachingMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; /** * A {@link ValueSelector} that caches the result of its child {@link ValueSelector}. * <p> * Keep this code in sync with {@link CachingEntitySelector} and {@link CachingMoveSelector}. */ public final class CachingValueSelector<Solution_> extends AbstractCachingValueSelector<Solution_> implements IterableValueSelector<Solution_> { protected final boolean randomSelection; public CachingValueSelector(IterableValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType, boolean randomSelection) { super(childValueSelector, cacheType); this.randomSelection = randomSelection; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isNeverEnding() { // CachedListRandomIterator is neverEnding return randomSelection; } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } @Override public Iterator<Object> iterator() { if (!randomSelection) { return cachedValueList.iterator(); } else { return new CachedListRandomIterator<>(cachedValueList, workingRandom); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; if (!super.equals(other)) return false; CachingValueSelector<?> that = (CachingValueSelector<?>) other; return randomSelection == that.randomSelection; } @Override public int hashCode() { return Objects.hash(super.hashCode(), randomSelection); } @Override public String toString() { return "Caching(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/DowncastingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Collections; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; public final class DowncastingValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueSelector<Solution_> { private final ValueSelector<Solution_> childValueSelector; private final Class<?> downcastEntityClass; public DowncastingValueSelector(ValueSelector<Solution_> childValueSelector, Class<?> downcastEntityClass) { this.childValueSelector = childValueSelector; this.downcastEntityClass = downcastEntityClass; phaseLifecycleSupport.addEventListener(childValueSelector); } public ValueSelector<Solution_> getChildValueSelector() { return childValueSelector; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return childValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return childValueSelector.isNeverEnding(); } @Override public long getSize(Object entity) { if (!downcastEntityClass.isInstance(entity)) { return 0L; } return childValueSelector.getSize(entity); } @Override public Iterator<Object> iterator(Object entity) { if (!downcastEntityClass.isInstance(entity)) { return Collections.emptyIterator(); } return childValueSelector.iterator(entity); } @Override public Iterator<Object> endingIterator(Object entity) { if (!downcastEntityClass.isInstance(entity)) { return Collections.emptyIterator(); } return childValueSelector.endingIterator(entity); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; DowncastingValueSelector<?> that = (DowncastingValueSelector<?>) other; return Objects.equals(childValueSelector, that.childValueSelector) && Objects.equals(downcastEntityClass, that.downcastEntityClass); } @Override public int hashCode() { return Objects.hash(childValueSelector, downcastEntityClass); } @Override public String toString() { return "Downcasting(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/FilteringValueRangeSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.function.Supplier; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.ReachableValues; import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListSwapMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListSwapMoveSelectorFactory; 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.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * The decorator returns a list of reachable values for a specific value. * It enables the creation of a filtering tier when using entity-provided value ranges, * ensuring only valid and reachable values are returned. * A value is considered reachable to another value if both exist within their respective entity value ranges. * <p> * The decorator can only be applied to list variables. * <p> * <code> * * e1 = entity_range[v1, v2, v3] * * e2 = entity_range[v1, v4] * * v1 = [v2, v3, v4] * * v2 = [v1, v3] * * v3 = [v1, v2] * * v4 = [v1] * * </code> * <p> * This node is currently used by the {@link ListChangeMoveSelector} and {@link ListSwapMoveSelector} selectors. * To illustrate its usage, let’s assume how moves are generated for the list swap type. * Initially, the swap move selector used a left value selector to choose a value. * After that, it uses a right value selector to choose another value to swap them. * <p> * Based on the previously described process and the current goal of this node, * we can observe that once a value is selected using the left value selector, * the right node can filter out all non-reachable values and generate a valid move. * A move is considered valid only if both entities accept each other's values. * The filtering process of invalid values allows the solver to explore the solution space more efficiently. * * @see ListChangeMoveSelectorFactory * @see DestinationSelectorFactory * @see ListSwapMoveSelectorFactory * @see ValueSelectorFactory * * @param <Solution_> the solution type */ public final class FilteringValueRangeSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_> { private final IterableValueSelector<Solution_> nonReplayingValueSelector; private final IterableValueSelector<Solution_> replayingValueSelector; private final boolean randomSelection; private Object replayedValue = null; private long valuesSize; private ListVariableStateSupply<Solution_> listVariableStateSupply; private ReachableValues reachableValues; private final boolean checkSourceAndDestination; public FilteringValueRangeSelector(IterableValueSelector<Solution_> nonReplayingValueSelector, IterableValueSelector<Solution_> replayingValueSelector, boolean randomSelection, boolean checkSourceAndDestination) { this.nonReplayingValueSelector = nonReplayingValueSelector; this.replayingValueSelector = replayingValueSelector; this.randomSelection = randomSelection; this.checkSourceAndDestination = checkSourceAndDestination; } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); this.nonReplayingValueSelector.solvingStarted(solverScope); this.replayingValueSelector.solvingStarted(solverScope); this.listVariableStateSupply = solverScope.getScoreDirector().getListVariableStateSupply( (ListVariableDescriptor<Solution_>) nonReplayingValueSelector.getVariableDescriptor()); } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); this.nonReplayingValueSelector.phaseStarted(phaseScope); this.replayingValueSelector.phaseStarted(phaseScope); this.reachableValues = phaseScope.getScoreDirector().getValueRangeManager() .getReachableValues(listVariableStateSupply.getSourceVariableDescriptor()); valuesSize = reachableValues.getSize(); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); this.nonReplayingValueSelector.phaseEnded(phaseScope); this.replayingValueSelector.phaseEnded(phaseScope); this.reachableValues = null; } // ************************************************************************ // Worker methods // ************************************************************************ public IterableValueSelector<Solution_> getChildValueSelector() { return nonReplayingValueSelector; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return nonReplayingValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return nonReplayingValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return nonReplayingValueSelector.isNeverEnding(); } @Override public long getSize(Object entity) { return getSize(); } @Override public long getSize() { return valuesSize; } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } /** * 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> iterator() { if (randomSelection) { return new RandomFilteringValueRangeIterator(this::selectReplayedValue, reachableValues, listVariableStateSupply, workingRandom, checkSourceAndDestination); } else { return new OriginalFilteringValueRangeIterator(this::selectReplayedValue, reachableValues, listVariableStateSupply, checkSourceAndDestination); } } @Override public Iterator<Object> endingIterator(Object entity) { return new OriginalFilteringValueRangeIterator(this::selectReplayedValue, reachableValues, listVariableStateSupply, checkSourceAndDestination); } @Override public boolean equals(Object other) { return other instanceof FilteringValueRangeSelector<?> that && Objects.equals(nonReplayingValueSelector, that.nonReplayingValueSelector) && Objects.equals(replayingValueSelector, that.replayingValueSelector); } @Override public int hashCode() { return Objects.hash(nonReplayingValueSelector, replayingValueSelector); } @NullMarked private abstract class AbstractFilteringValueRangeIterator implements Iterator<Object> { private final Supplier<Object> upcomingValueSupplier; private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final ReachableValues reachableValues; private final boolean checkSourceAndDestination; private boolean initialized = false; private boolean hasData = false; @Nullable private Object currentUpcomingValue; @Nullable private Object currentUpcomingEntity; @Nullable private List<Object> currentUpcomingList; AbstractFilteringValueRangeIterator(Supplier<Object> upcomingValueSupplier, ReachableValues reachableValues, ListVariableStateSupply<Solution_> listVariableStateSupply, boolean checkSourceAndDestination) { this.upcomingValueSupplier = upcomingValueSupplier; this.reachableValues = Objects.requireNonNull(reachableValues); this.listVariableStateSupply = listVariableStateSupply; this.checkSourceAndDestination = checkSourceAndDestination; } void initialize() { if (initialized) { return; } checkUpcomingValue(); } void checkUpcomingValue() { if (currentUpcomingValue != null) { var updatedUpcomingValue = upcomingValueSupplier.get(); if (updatedUpcomingValue != currentUpcomingValue) { // The iterator may be reused // like in the ElementPositionRandomIterator, // even if the entity has changed. // Therefore, // we need to update the value list to ensure it is consistent. loadValues(updatedUpcomingValue); } } else { loadValues(upcomingValueSupplier.get()); } } /** * This method initializes the basic structure required for the child iterators, * including the upcoming entity and the upcoming list. * * @param upcomingValue the upcoming value */ private void loadValues(@Nullable Object upcomingValue) { if (upcomingValue == null) { noData(); return; } if (upcomingValue == currentUpcomingValue) { return; } currentUpcomingValue = upcomingValue; currentUpcomingEntity = null; currentUpcomingList = null; if (checkSourceAndDestination) { // Load the current assigned entity of the selected value var position = listVariableStateSupply.getElementPosition(currentUpcomingValue); if (position instanceof PositionInList positionInList) { currentUpcomingEntity = positionInList.entity(); } } currentUpcomingList = reachableValues.extractValuesAsList(currentUpcomingValue); processUpcomingValue(currentUpcomingValue, currentUpcomingList); this.hasData = !currentUpcomingList.isEmpty(); this.initialized = true; } abstract void processUpcomingValue(Object upcomingValue, List<Object> upcomingList); boolean hasNoData() { return !hasData; } private void noData() { this.currentUpcomingEntity = null; this.hasData = false; this.initialized = true; this.currentUpcomingList = Collections.emptyList(); } boolean isReachable(Object destinationValue) { Object destinationEntity = null; var assignedDestinationPosition = listVariableStateSupply.getElementPosition(destinationValue); if (assignedDestinationPosition instanceof PositionInList elementPosition) { destinationEntity = elementPosition.entity(); } if (checkSourceAndDestination) { return reachableValues.isEntityReachable(Objects.requireNonNull(currentUpcomingValue), destinationEntity) && reachableValues.isEntityReachable(Objects.requireNonNull(destinationValue), currentUpcomingEntity); } else { return reachableValues.isEntityReachable(Objects.requireNonNull(currentUpcomingValue), destinationEntity); } } } private class OriginalFilteringValueRangeIterator extends AbstractFilteringValueRangeIterator { // The value iterator returns all reachable values private Iterator<Object> reachableValueIterator; private Object selected = null; private OriginalFilteringValueRangeIterator(Supplier<Object> upcomingValueSupplier, ReachableValues reachableValues, ListVariableStateSupply<Solution_> listVariableStateSupply, boolean checkSourceAndDestination) { super(upcomingValueSupplier, reachableValues, listVariableStateSupply, checkSourceAndDestination); } @Override void processUpcomingValue(Object upcomingValue, List<Object> upcomingList) { reachableValueIterator = Objects.requireNonNull(upcomingList).iterator(); 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 (reachableValueIterator.hasNext()) { var value = reachableValueIterator.next(); if (isReachable(value)) { return value; } } return null; } @Override public Object next() { if (selected == null) { throw new NoSuchElementException(); } var result = selected; this.selected = null; return result; } } private class RandomFilteringValueRangeIterator extends AbstractFilteringValueRangeIterator { private final Random workingRandom; private int maxBailoutSize; private Object replayedValue; private List<Object> reachableValueList = null; private RandomFilteringValueRangeIterator(Supplier<Object> upcomingValueSupplier, ReachableValues reachableValues, ListVariableStateSupply<Solution_> listVariableStateSupply, Random workingRandom, boolean checkSourceAndDestination) { super(upcomingValueSupplier, reachableValues, listVariableStateSupply, checkSourceAndDestination); this.workingRandom = workingRandom; } @Override void processUpcomingValue(Object upcomingValue, List<Object> upcomingList) { this.replayedValue = upcomingValue; this.reachableValueList = Objects.requireNonNull(upcomingList); this.maxBailoutSize = reachableValueList.size(); } @Override public boolean hasNext() { checkUpcomingValue(); return reachableValues != null && !reachableValueList.isEmpty(); } @Override public Object next() { if (hasNoData()) { throw new NoSuchElementException(); } var bailoutSize = maxBailoutSize; do { bailoutSize--; var index = workingRandom.nextInt(reachableValueList.size()); var next = reachableValueList.get(index); if (isReachable(next)) { return next; } } while (bailoutSize > 0); // if a valid move is not found with the given bailout size, // we assign the same value to the left side, which will result in a non-doable move return replayedValue; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/FilteringValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.Objects; import java.util.function.Supplier; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; 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.phase.scope.AbstractPhaseScope; public class FilteringValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueSelector<Solution_> { public static <Solution_> ValueSelector<Solution_> of(ValueSelector<Solution_> valueSelector, SelectionFilter<Solution_, Object> filter) { if (valueSelector instanceof IterableFilteringValueSelector<Solution_> filteringValueSelector) { return new IterableFilteringValueSelector<>( (IterableValueSelector<Solution_>) filteringValueSelector.childValueSelector, SelectionFilter.compose(filteringValueSelector.selectionFilter, filter)); } else if (valueSelector instanceof FilteringValueSelector<Solution_> filteringValueSelector) { return new FilteringValueSelector<>(filteringValueSelector.childValueSelector, SelectionFilter.compose(filteringValueSelector.selectionFilter, filter)); } else if (valueSelector instanceof IterableValueSelector<Solution_> iterableValueSelector) { return new IterableFilteringValueSelector<>(iterableValueSelector, filter); } else { return new FilteringValueSelector<>(valueSelector, filter); } } public static <Solution_> ValueSelector<Solution_> ofAssigned(ValueSelector<Solution_> valueSelector, Supplier<ListVariableStateSupply<Solution_>> listVariableStateSupplier) { var listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor(); if (!listVariableDescriptor.allowsUnassignedValues()) { return valueSelector; } // We need to filter out unassigned vars. return FilteringValueSelector.of(valueSelector, (scoreDirector, selection) -> { var listVariableStateSupply = listVariableStateSupplier.get(); if (listVariableStateSupply.getUnassignedCount() == 0) { return true; } return listVariableStateSupply.isAssigned(selection); }); } public static <Solution_> IterableValueSelector<Solution_> ofAssigned( IterableValueSelector<Solution_> iterableValueSelector, Supplier<ListVariableStateSupply<Solution_>> listVariableStateSupplier) { return (IterableValueSelector<Solution_>) ofAssigned((ValueSelector<Solution_>) iterableValueSelector, listVariableStateSupplier); } protected final ValueSelector<Solution_> childValueSelector; final SelectionFilter<Solution_, Object> selectionFilter; protected final boolean bailOutEnabled; private ScoreDirector<Solution_> scoreDirector = null; protected FilteringValueSelector(ValueSelector<Solution_> childValueSelector, SelectionFilter<Solution_, Object> filter) { this.childValueSelector = Objects.requireNonNull(childValueSelector); this.selectionFilter = Objects.requireNonNull(filter); bailOutEnabled = childValueSelector.isNeverEnding(); phaseLifecycleSupport.addEventListener(childValueSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); scoreDirector = phaseScope.getScoreDirector(); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); scoreDirector = null; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return childValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return childValueSelector.isNeverEnding(); } @Override public long getSize(Object entity) { return childValueSelector.getSize(entity); } @Override public Iterator<Object> iterator(Object entity) { return new JustInTimeFilteringValueIterator(childValueSelector.iterator(entity), determineBailOutSize(entity)); } protected class JustInTimeFilteringValueIterator extends UpcomingSelectionIterator<Object> { private final Iterator<Object> childValueIterator; private final long bailOutSize; public JustInTimeFilteringValueIterator(Iterator<Object> childValueIterator, long bailOutSize) { this.childValueIterator = childValueIterator; this.bailOutSize = bailOutSize; } @Override protected Object createUpcomingSelection() { Object next; long attemptsBeforeBailOut = bailOutSize; do { if (!childValueIterator.hasNext()) { return noUpcomingSelection(); } if (bailOutEnabled) { // if childValueIterator is neverEnding and nothing is accepted, bail out of the infinite loop if (attemptsBeforeBailOut <= 0L) { logger.trace("Bailing out of neverEnding selector ({}) to avoid infinite loop.", FilteringValueSelector.this); return noUpcomingSelection(); } attemptsBeforeBailOut--; } next = childValueIterator.next(); } while (!selectionFilter.accept(scoreDirector, next)); return next; } } @Override public Iterator<Object> endingIterator(Object entity) { return new JustInTimeFilteringValueIterator(childValueSelector.endingIterator(entity), determineBailOutSize(entity)); } protected long determineBailOutSize(Object entity) { if (!bailOutEnabled) { return -1L; } return childValueSelector.getSize(entity) * 10L; } @Override public boolean equals(Object o) { return o instanceof FilteringValueSelector<?> that && Objects.equals(childValueSelector, that.childValueSelector) && Objects.equals(selectionFilter, that.selectionFilter); } @Override public int hashCode() { return Objects.hash(childValueSelector, selectionFilter); } @Override public String toString() { return "Filtering(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/FromEntitySortingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; public final class FromEntitySortingValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueSelector<Solution_> { private final ValueSelector<Solution_> childValueSelector; private final SelectionCacheType cacheType; private final SelectionSorter<Solution_, Object> sorter; private ScoreDirector<Solution_> scoreDirector = null; public FromEntitySortingValueSelector(ValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType, SelectionSorter<Solution_, Object> sorter) { this.childValueSelector = childValueSelector; this.cacheType = cacheType; this.sorter = sorter; if (childValueSelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with neverEnding (" + childValueSelector.isNeverEnding() + ")."); } if (cacheType != SelectionCacheType.STEP) { throw new IllegalArgumentException("The selector (" + this + ") does not support the cacheType (" + cacheType + ")."); } phaseLifecycleSupport.addEventListener(childValueSelector); } public ValueSelector<Solution_> getChildValueSelector() { return childValueSelector; } @Override public SelectionCacheType getCacheType() { return cacheType; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); scoreDirector = phaseScope.getScoreDirector(); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); scoreDirector = null; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public long getSize(Object entity) { return childValueSelector.getSize(entity); } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return false; } @Override public Iterator<Object> iterator(Object entity) { long childSize = childValueSelector.getSize(entity); if (childSize > Integer.MAX_VALUE) { throw new IllegalStateException("The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with childSize (" + childSize + ") which is higher than Integer.MAX_VALUE."); } List<Object> cachedValueList = new ArrayList<>((int) childSize); childValueSelector.iterator(entity).forEachRemaining(cachedValueList::add); logger.trace(" Created cachedValueList: size ({}), valueSelector ({}).", cachedValueList.size(), this); sorter.sort(scoreDirector, cachedValueList); logger.trace(" Sorted cachedValueList: size ({}), valueSelector ({}).", cachedValueList.size(), this); return cachedValueList.iterator(); } @Override public Iterator<Object> endingIterator(Object entity) { return iterator(entity); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; var that = (FromEntitySortingValueSelector<?>) other; return Objects.equals(childValueSelector, that.childValueSelector) && cacheType == that.cacheType && Objects.equals(sorter, that.sorter); } @Override public int hashCode() { return Objects.hash(childValueSelector, cacheType, sorter); } @Override public String toString() { return "Sorting(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/InitializedValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; /** * Prevents creating chains without an anchor. * <p> * Filters out every value that is a planning entity for which the {@link PlanningVariable} * (on which this {@link ValueSelector} applies to) is uninitialized. * <p> * Mainly used for chained planning variables, but supports other planning variables too. */ public class InitializedValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueSelector<Solution_> { public static <Solution_> ValueSelector<Solution_> create(ValueSelector<Solution_> valueSelector) { if (valueSelector instanceof IterableValueSelector) { return new IterableInitializedValueSelector<>((IterableValueSelector<Solution_>) valueSelector); } else { return new InitializedValueSelector<>(valueSelector); } } private final GenuineVariableDescriptor<Solution_> variableDescriptor; final ValueSelector<Solution_> childValueSelector; final boolean bailOutEnabled; InitializedValueSelector(ValueSelector<Solution_> childValueSelector) { this.variableDescriptor = childValueSelector.getVariableDescriptor(); this.childValueSelector = childValueSelector; bailOutEnabled = childValueSelector.isNeverEnding(); phaseLifecycleSupport.addEventListener(childValueSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return childValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return childValueSelector.isNeverEnding(); } @Override public long getSize(Object entity) { // TODO use cached results return childValueSelector.getSize(entity); } @Override public Iterator<Object> iterator(Object entity) { return new JustInTimeInitializedValueIterator(entity, childValueSelector.iterator(entity)); } @Override public Iterator<Object> endingIterator(Object entity) { return new JustInTimeInitializedValueIterator(entity, childValueSelector.endingIterator(entity)); } protected class JustInTimeInitializedValueIterator extends UpcomingSelectionIterator<Object> { private final Iterator<Object> childValueIterator; private final long bailOutSize; public JustInTimeInitializedValueIterator(Object entity, Iterator<Object> childValueIterator) { this(childValueIterator, determineBailOutSize(entity)); } public JustInTimeInitializedValueIterator(Iterator<Object> childValueIterator, long bailOutSize) { this.childValueIterator = childValueIterator; this.bailOutSize = bailOutSize; } @Override protected Object createUpcomingSelection() { Object next; long attemptsBeforeBailOut = bailOutSize; do { if (!childValueIterator.hasNext()) { return noUpcomingSelection(); } if (bailOutEnabled) { // if childValueIterator is neverEnding and nothing is accepted, bail out of the infinite loop if (attemptsBeforeBailOut <= 0L) { logger.trace("Bailing out of neverEnding selector ({}) to avoid infinite loop.", InitializedValueSelector.this); return noUpcomingSelection(); } attemptsBeforeBailOut--; } next = childValueIterator.next(); } while (!accept(next)); return next; } } protected long determineBailOutSize(Object entity) { if (!bailOutEnabled) { return -1L; } return childValueSelector.getSize(entity) * 10L; } protected boolean accept(Object value) { return value == null || !variableDescriptor.getEntityDescriptor().getEntityClass().isAssignableFrom(value.getClass()) || variableDescriptor.isInitialized(value); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; InitializedValueSelector<?> that = (InitializedValueSelector<?>) other; return Objects.equals(variableDescriptor, that.variableDescriptor) && Objects.equals(childValueSelector, that.childValueSelector); } @Override public int hashCode() { return Objects.hash(variableDescriptor, childValueSelector); } @Override public String toString() { return "Initialized(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/IterableFilteringValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; public final class IterableFilteringValueSelector<Solution_> extends FilteringValueSelector<Solution_> implements IterableValueSelector<Solution_> { IterableFilteringValueSelector(IterableValueSelector<Solution_> childValueSelector, SelectionFilter<Solution_, Object> filter) { super(childValueSelector, filter); } @Override public long getSize() { return ((IterableValueSelector<Solution_>) childValueSelector).getSize(); } @Override public Iterator<Object> iterator() { return new JustInTimeFilteringValueIterator(((IterableValueSelector<Solution_>) childValueSelector).iterator(), determineBailOutSize()); } private long determineBailOutSize() { if (!bailOutEnabled) { return -1L; } return ((IterableValueSelector<Solution_>) childValueSelector).getSize() * 10L; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/IterableFromEntityPropertyValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.FromEntityPropertyValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.FromEntityPropertyValueSelector; 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.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * The value range for list variables requires the selector to be entity-independent, * as it needs to fetch the entire list of values. * Fetching the list of values is not a problem when the value range is located within the solution class, * serving as a single source of truth. * In cases where it is entity-dependent, * the list of entities must be read to generate the corresponding list of values. * <p> * This selector adapts {@link FromEntityPropertyValueSelector} to behave like an entity-independent selector * and meets the requirement to retrieve the complete list of values. * * @param <Solution_> the solution type */ public final class IterableFromEntityPropertyValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_> { private final FromEntityPropertyValueSelector<Solution_> childValueSelector; private final boolean randomSelection; private final FromEntityPropertyValueRangeDescriptor<Solution_> valueRangeDescriptor; private InnerScoreDirector<Solution_, ?> innerScoreDirector = null; public IterableFromEntityPropertyValueSelector(FromEntityPropertyValueSelector<Solution_> childValueSelector, boolean randomSelection) { this.childValueSelector = childValueSelector; this.randomSelection = randomSelection; this.valueRangeDescriptor = (FromEntityPropertyValueRangeDescriptor<Solution_>) childValueSelector .getVariableDescriptor().getValueRangeDescriptor(); } // ************************************************************************ // Life-cycle methods // ************************************************************************ @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); this.childValueSelector.solvingStarted(solverScope); this.innerScoreDirector = solverScope.getScoreDirector(); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); childValueSelector.solvingEnded(solverScope); this.innerScoreDirector = null; } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); childValueSelector.phaseStarted(phaseScope); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); childValueSelector.phaseEnded(phaseScope); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public long getSize(Object entity) { return childValueSelector.getSize(entity); } @Override public Iterator<Object> iterator(Object entity) { return childValueSelector.iterator(entity); } @Override public Iterator<Object> endingIterator(Object entity) { return childValueSelector.endingIterator(entity); } @Override public boolean isCountable() { return valueRangeDescriptor.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || !isCountable(); } @Override public long getSize() { return innerScoreDirector.getValueRangeManager().countOnSolution(valueRangeDescriptor, innerScoreDirector.getWorkingSolution()); } @Override public Iterator<Object> iterator() { var valueRange = innerScoreDirector.getValueRangeManager() .getFromSolution(valueRangeDescriptor, innerScoreDirector.getWorkingSolution()); if (randomSelection) { return valueRange.createRandomIterator(workingRandom); } else { return valueRange.createOriginalIterator(); } } @Override public boolean equals(Object other) { return childValueSelector.equals(other); } @Override public int hashCode() { return childValueSelector.hashCode(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/IterableInitializedValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; public final class IterableInitializedValueSelector<Solution_> extends InitializedValueSelector<Solution_> implements IterableValueSelector<Solution_> { public IterableInitializedValueSelector(IterableValueSelector<Solution_> childValueSelector) { super(childValueSelector); } @Override public long getSize() { return ((IterableValueSelector<Solution_>) childValueSelector).getSize(); } @Override public Iterator<Object> iterator() { return new JustInTimeInitializedValueIterator( ((IterableValueSelector<Solution_>) childValueSelector).iterator(), determineBailOutSize()); } private long determineBailOutSize() { if (!bailOutEnabled) { return -1L; } return ((IterableValueSelector<Solution_>) childValueSelector).getSize() * 10L; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/MovableChainedTrailingValueFilter.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class MovableChainedTrailingValueFilter<Solution_> implements SelectionFilter<Solution_, Object> { private final GenuineVariableDescriptor<Solution_> variableDescriptor; public MovableChainedTrailingValueFilter(GenuineVariableDescriptor<Solution_> variableDescriptor) { this.variableDescriptor = variableDescriptor; } @Override public boolean accept(ScoreDirector<Solution_> scoreDirector, Object value) { if (value == null) { return true; } SingletonInverseVariableSupply supply = retrieveSingletonInverseVariableSupply(scoreDirector); Object trailingEntity = supply.getInverseSingleton(value); EntityDescriptor<Solution_> entityDescriptor = variableDescriptor.getEntityDescriptor(); if (trailingEntity == null || !entityDescriptor.matchesEntity(trailingEntity)) { return true; } return entityDescriptor.getEffectiveMovableEntityFilter().test(scoreDirector.getWorkingSolution(), trailingEntity); } private SingletonInverseVariableSupply retrieveSingletonInverseVariableSupply(ScoreDirector<Solution_> scoreDirector) { // TODO Performance loss because the supply is retrieved for every accept // A SelectionFilter should be optionally made aware of lifecycle events, so it can cache the supply SupplyManager supplyManager = ((InnerScoreDirector<Solution_, ?>) scoreDirector).getSupplyManager(); return supplyManager.demand(new SingletonInverseVariableDemand<>(variableDescriptor)); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; MovableChainedTrailingValueFilter<?> that = (MovableChainedTrailingValueFilter<?>) other; return Objects.equals(variableDescriptor, that.variableDescriptor); } @Override public int hashCode() { return Objects.hash(variableDescriptor); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/ProbabilityValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.NavigableMap; import java.util.Objects; import java.util.TreeMap; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.solver.random.RandomUtils; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public final class ProbabilityValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_>, SelectionCacheLifecycleListener<Solution_> { private final IterableValueSelector<Solution_> childValueSelector; private final SelectionCacheType cacheType; private final SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory; private NavigableMap<Double, Object> cachedEntityMap = null; private double probabilityWeightTotal = -1.0; public ProbabilityValueSelector(IterableValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType, SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory) { this.childValueSelector = childValueSelector; this.cacheType = cacheType; this.probabilityWeightFactory = probabilityWeightFactory; if (childValueSelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a childValueSelector (" + childValueSelector + ") with neverEnding (" + childValueSelector.isNeverEnding() + ")."); } phaseLifecycleSupport.addEventListener(childValueSelector); if (cacheType.isNotCached()) { throw new IllegalArgumentException("The selector (" + this + ") does not support the cacheType (" + cacheType + ")."); } phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this)); } @Override public SelectionCacheType getCacheType() { return cacheType; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void constructCache(SolverScope<Solution_> solverScope) { cachedEntityMap = new TreeMap<>(); ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector(); double probabilityWeightOffset = 0L; // TODO Fail-faster if a non FromSolutionPropertyValueSelector is used for (Object value : childValueSelector) { double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(scoreDirector, value); cachedEntityMap.put(probabilityWeightOffset, value); probabilityWeightOffset += probabilityWeight; } probabilityWeightTotal = probabilityWeightOffset; } @Override public void disposeCache(SolverScope<Solution_> solverScope) { probabilityWeightTotal = -1.0; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return false; } @Override public long getSize(Object entity) { return getSize(); } @Override public long getSize() { return cachedEntityMap.size(); } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } @Override public Iterator<Object> iterator() { return new Iterator<Object>() { @Override public boolean hasNext() { return true; } @Override public Object next() { double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal); // 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 Iterator<Object> endingIterator(Object entity) { return childValueSelector.endingIterator(entity); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ProbabilityValueSelector<?> that = (ProbabilityValueSelector<?>) other; return Objects.equals(childValueSelector, that.childValueSelector) && cacheType == that.cacheType && Objects.equals(probabilityWeightFactory, that.probabilityWeightFactory); } @Override public int hashCode() { return Objects.hash(childValueSelector, cacheType, probabilityWeightFactory); } @Override public String toString() { return "Probability(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/ReinitializeVariableValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Collections; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; /** * Prevents reassigning of already initialized variables during Construction Heuristics and Exhaustive Search. * <p> * Returns no values for an entity's variable if the variable is not reinitializable. * <p> * Does not implement {@link IterableValueSelector} because if used like that, * it shouldn't be added during configuration in the first place. */ public final class ReinitializeVariableValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueSelector<Solution_> { private final ValueSelector<Solution_> childValueSelector; public ReinitializeVariableValueSelector(ValueSelector<Solution_> childValueSelector) { this.childValueSelector = childValueSelector; phaseLifecycleSupport.addEventListener(childValueSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return childValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return childValueSelector.isNeverEnding(); } @Override public long getSize(Object entity) { if (isReinitializable(entity)) { return childValueSelector.getSize(entity); } return 0L; } @Override public Iterator<Object> iterator(Object entity) { if (isReinitializable(entity)) { return childValueSelector.iterator(entity); } return Collections.emptyIterator(); } @Override public Iterator<Object> endingIterator(Object entity) { if (isReinitializable(entity)) { return childValueSelector.endingIterator(entity); } return Collections.emptyIterator(); } private boolean isReinitializable(Object entity) { return childValueSelector.getVariableDescriptor().isReinitializable(entity); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ReinitializeVariableValueSelector<?> that = (ReinitializeVariableValueSelector<?>) other; return Objects.equals(childValueSelector, that.childValueSelector); } @Override public int hashCode() { return Objects.hash(childValueSelector); } @Override public String toString() { return "Reinitialize(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/SelectedCountLimitValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; public final class SelectedCountLimitValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_> { private final ValueSelector<Solution_> childValueSelector; private final long selectedCountLimit; /** * Unlike most of the other {@link ValueSelector} decorations, * this one works for an entity dependent {@link ValueSelector} too. * * @param childValueSelector never null, if any of the {@link IterableValueSelector} specific methods * are going to be used, this parameter must also implement that interface * @param selectedCountLimit at least 0 */ public SelectedCountLimitValueSelector(ValueSelector<Solution_> childValueSelector, long selectedCountLimit) { this.childValueSelector = childValueSelector; this.selectedCountLimit = selectedCountLimit; if (selectedCountLimit < 0L) { throw new IllegalArgumentException("The selector (" + this + ") has a negative selectedCountLimit (" + selectedCountLimit + ")."); } phaseLifecycleSupport.addEventListener(childValueSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return false; } @Override public long getSize(Object entity) { long childSize = childValueSelector.getSize(entity); return Math.min(selectedCountLimit, childSize); } @Override public long getSize() { long childSize = ((IterableValueSelector<Solution_>) childValueSelector).getSize(); return Math.min(selectedCountLimit, childSize); } @Override public Iterator<Object> iterator(Object entity) { return new SelectedCountLimitValueIterator(childValueSelector.iterator(entity)); } @Override public Iterator<Object> iterator() { return new SelectedCountLimitValueIterator(((IterableValueSelector<Solution_>) childValueSelector).iterator()); } @Override public Iterator<Object> endingIterator(Object entity) { return new SelectedCountLimitValueIterator(childValueSelector.endingIterator(entity)); } private class SelectedCountLimitValueIterator extends SelectionIterator<Object> { private final Iterator<Object> childValueIterator; private long selectedSize; public SelectedCountLimitValueIterator(Iterator<Object> childValueIterator) { this.childValueIterator = childValueIterator; selectedSize = 0L; } @Override public boolean hasNext() { return selectedSize < selectedCountLimit && childValueIterator.hasNext(); } @Override public Object next() { if (selectedSize >= selectedCountLimit) { throw new NoSuchElementException(); } selectedSize++; return childValueIterator.next(); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; SelectedCountLimitValueSelector<?> that = (SelectedCountLimitValueSelector<?>) other; return selectedCountLimit == that.selectedCountLimit && Objects.equals(childValueSelector, that.childValueSelector); } @Override public int hashCode() { return Objects.hash(childValueSelector, selectedCountLimit); } @Override public String toString() { return "SelectedCountLimit(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/ShufflingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Collections; import java.util.Iterator; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; public final class ShufflingValueSelector<Solution_> extends AbstractCachingValueSelector<Solution_> implements IterableValueSelector<Solution_> { public ShufflingValueSelector(IterableValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType) { super(childValueSelector, cacheType); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isNeverEnding() { return false; } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } @Override public Iterator<Object> iterator() { Collections.shuffle(cachedValueList, workingRandom); logger.trace(" Shuffled cachedValueList with size ({}) in valueSelector({}).", cachedValueList.size(), this); return cachedValueList.iterator(); } @Override public String toString() { return "Shuffling(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/SortingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import java.util.Iterator; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public final class SortingValueSelector<Solution_> extends AbstractCachingValueSelector<Solution_> implements IterableValueSelector<Solution_> { protected final SelectionSorter<Solution_, Object> sorter; public SortingValueSelector(IterableValueSelector<Solution_> childValueSelector, SelectionCacheType cacheType, SelectionSorter<Solution_, Object> sorter) { super(childValueSelector, cacheType); this.sorter = sorter; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void constructCache(SolverScope<Solution_> solverScope) { super.constructCache(solverScope); sorter.sort(solverScope.getScoreDirector(), cachedValueList); logger.trace(" Sorted cachedValueList: size ({}), valueSelector ({}).", cachedValueList.size(), this); } @Override public boolean isNeverEnding() { return false; } @Override public Iterator<Object> iterator(Object entity) { return iterator(); } @Override public Iterator<Object> iterator() { return cachedValueList.iterator(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; if (!super.equals(other)) return false; SortingValueSelector<?> that = (SortingValueSelector<?>) other; return Objects.equals(sorter, that.sorter); } @Override public int hashCode() { return Objects.hash(super.hashCode(), sorter); } @Override public String toString() { return "Sorting(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/decorator/UnassignedListValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.decorator; import ai.timefold.solver.core.impl.constructionheuristic.placer.QueuedValuePlacer; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; /** * Only selects values from the child value selector that are uninitialized. * This used for {@link QueuedValuePlacer}’s recording value selector during Construction Heuristic phase * to prevent reinitializing values. */ public final class UnassignedListValueSelector<Solution_> extends AbstractInverseEntityFilteringValueSelector<Solution_> { public UnassignedListValueSelector(IterableValueSelector<Solution_> childValueSelector) { super(childValueSelector); } @Override protected boolean valueFilter(Object value) { if (listVariableStateSupply.getUnassignedCount() == 0) { return false; // Avoid hash lookup. } return !listVariableStateSupply.isAssigned(value); } @Override public String toString() { return "Unassigned(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/mimic/MimicRecordingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.mimic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; public class MimicRecordingValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements ValueMimicRecorder<Solution_>, IterableValueSelector<Solution_> { protected final IterableValueSelector<Solution_> childValueSelector; protected final List<MimicReplayingValueSelector<Solution_>> replayingValueSelectorList; public MimicRecordingValueSelector(IterableValueSelector<Solution_> childValueSelector) { this.childValueSelector = childValueSelector; phaseLifecycleSupport.addEventListener(childValueSelector); replayingValueSelectorList = new ArrayList<>(); } @Override public void addMimicReplayingValueSelector(MimicReplayingValueSelector<Solution_> replayingValueSelector) { replayingValueSelectorList.add(replayingValueSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return childValueSelector.getVariableDescriptor(); } @Override public boolean isCountable() { return childValueSelector.isCountable(); } @Override public boolean isNeverEnding() { return childValueSelector.isNeverEnding(); } @Override public long getSize(Object entity) { return childValueSelector.getSize(entity); } @Override public long getSize() { return childValueSelector.getSize(); } @Override public Iterator<Object> iterator(Object entity) { return new RecordingValueIterator(childValueSelector.iterator(entity)); } @Override public Iterator<Object> iterator() { return new RecordingValueIterator(childValueSelector.iterator()); } private class RecordingValueIterator extends SelectionIterator<Object> { private final Iterator<Object> childValueIterator; public RecordingValueIterator(Iterator<Object> childValueIterator) { this.childValueIterator = childValueIterator; } @Override public boolean hasNext() { boolean hasNext = childValueIterator.hasNext(); for (MimicReplayingValueSelector<Solution_> replayingValueSelector : replayingValueSelectorList) { replayingValueSelector.recordedHasNext(hasNext); } return hasNext; } @Override public Object next() { Object next = childValueIterator.next(); for (MimicReplayingValueSelector<Solution_> replayingValueSelector : replayingValueSelectorList) { replayingValueSelector.recordedNext(next); } return next; } } @Override public Iterator<Object> endingIterator(Object entity) { // No recording, because the endingIterator() is used for determining size return childValueSelector.endingIterator(entity); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; MimicRecordingValueSelector<?> that = (MimicRecordingValueSelector<?>) other; /* * Using list size in order to prevent recursion in equals/hashcode. * Since the replaying selector will always point back to this instance, * we only need to know if the lists are the same * in order to be able to tell if two instances are equal. */ return Objects.equals(childValueSelector, that.childValueSelector) && Objects.equals(replayingValueSelectorList.size(), that.replayingValueSelectorList.size()); } @Override public int hashCode() { return Objects.hash(childValueSelector, replayingValueSelectorList.size()); } @Override public String toString() { return "Recording(" + childValueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/mimic/MimicReplayingValueSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.value.mimic; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; public class MimicReplayingValueSelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements IterableValueSelector<Solution_> { protected final ValueMimicRecorder<Solution_> valueMimicRecorder; protected boolean hasRecordingCreated; protected boolean hasRecording; protected boolean recordingCreated; protected Object recording; protected boolean recordingAlreadyReturned; public MimicReplayingValueSelector(ValueMimicRecorder<Solution_> valueMimicRecorder) { this.valueMimicRecorder = valueMimicRecorder; // No PhaseLifecycleSupport because the MimicRecordingValueSelector is hooked up elsewhere too valueMimicRecorder.addMimicReplayingValueSelector(this); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); // Doing this in phaseStarted instead of stepStarted due to QueuedValuePlacer compatibility hasRecordingCreated = false; recordingCreated = false; } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); // Doing this in phaseEnded instead of stepEnded due to QueuedValuePlacer compatibility hasRecordingCreated = false; hasRecording = false; recordingCreated = false; recording = null; } @Override public GenuineVariableDescriptor<Solution_> getVariableDescriptor() { return valueMimicRecorder.getVariableDescriptor(); } @Override public boolean isCountable() { return valueMimicRecorder.isCountable(); } @Override public boolean isNeverEnding() { return valueMimicRecorder.isNeverEnding(); } @Override public long getSize(Object entity) { return valueMimicRecorder.getSize(entity); } @Override public long getSize() { return valueMimicRecorder.getSize(); } @Override public Iterator<Object> iterator(Object entity) { // Ignores the entity, but the constructor of this class guarantees that the valueRange is entity independent return new ReplayingValueIterator(); } @Override public Iterator<Object> iterator() { return new ReplayingValueIterator(); } public void recordedHasNext(boolean hasNext) { hasRecordingCreated = true; hasRecording = hasNext; recordingCreated = false; recording = null; recordingAlreadyReturned = false; } public void recordedNext(Object next) { hasRecordingCreated = true; hasRecording = true; recordingCreated = true; recording = next; recordingAlreadyReturned = false; } private class ReplayingValueIterator extends SelectionIterator<Object> { private ReplayingValueIterator() { // Reset so the last recording plays again even if it has already played recordingAlreadyReturned = false; } @Override public boolean hasNext() { if (!hasRecordingCreated) { throw new IllegalStateException("Replay must occur after record." + " The recordingValueSelector (" + valueMimicRecorder + ")'s hasNext() has not been called yet. "); } return hasRecording && !recordingAlreadyReturned; } @Override public Object next() { if (!recordingCreated) { throw new IllegalStateException("Replay must occur after record." + " The recordingValueSelector (" + valueMimicRecorder + ")'s next() has not been called yet. "); } if (recordingAlreadyReturned) { throw new NoSuchElementException("The recordingAlreadyReturned (" + recordingAlreadyReturned + ") is impossible. Check if hasNext() returns true before this call."); } // Until the recorder records something, this iterator has no next. recordingAlreadyReturned = true; return recording; } @Override public String toString() { if (hasRecordingCreated && !hasRecording) { return "No next replay"; } return "Next replay (" + (recordingCreated ? recording : "?") + ")"; } } @Override public Iterator<Object> endingIterator(Object entity) { // No replaying, because the endingIterator() is used for determining size return valueMimicRecorder.endingIterator(entity); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; MimicReplayingValueSelector<?> that = (MimicReplayingValueSelector<?>) other; return Objects.equals(valueMimicRecorder, that.valueMimicRecorder); } @Override public int hashCode() { return Objects.hash(valueMimicRecorder); } @Override public String toString() { return "Replaying(" + valueMimicRecorder + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/value/mimic/ValueMimicRecorder.java
package ai.timefold.solver.core.impl.heuristic.selector.value.mimic; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.value.IterableValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; public interface ValueMimicRecorder<Solution_> { /** * @param replayingValueSelector never null */ void addMimicReplayingValueSelector(MimicReplayingValueSelector<Solution_> replayingValueSelector); /** * @return As defined by {@link ValueSelector#getVariableDescriptor()} * @see ValueSelector#getVariableDescriptor() */ GenuineVariableDescriptor<Solution_> getVariableDescriptor(); /** * @return As defined by {@link ValueSelector#isCountable()} * @see ValueSelector#isCountable() */ boolean isCountable(); /** * @return As defined by {@link ValueSelector#isNeverEnding()} * @see ValueSelector#isNeverEnding() */ boolean isNeverEnding(); /** * @return As defined by {@link IterableValueSelector#getSize()} * @see IterableValueSelector#getSize() */ long getSize(); /** * @return As defined by {@link ValueSelector#getSize(Object)} * @see ValueSelector#getSize(Object) */ long getSize(Object entity); /** * @return As defined by {@link ValueSelector#endingIterator(Object)} * @see ValueSelector#endingIterator(Object) */ Iterator<Object> endingIterator(Object entity); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/io
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/io/jaxb/ElementNamespaceOverride.java
package ai.timefold.solver.core.impl.io.jaxb; public class ElementNamespaceOverride { public static ElementNamespaceOverride of(String elementLocalName, String namespaceOverride) { return new ElementNamespaceOverride(elementLocalName, namespaceOverride); } private final String elementLocalName; private final String namespaceOverride; private ElementNamespaceOverride(String elementLocalName, String namespaceOverride) { this.elementLocalName = elementLocalName; this.namespaceOverride = namespaceOverride; } public String getElementLocalName() { return elementLocalName; } public String getNamespaceOverride() { return namespaceOverride; } @Override public String toString() { return "ElementNamespaceOverride{" + "elementLocalName='" + elementLocalName + '\'' + ", namespaceOverride='" + namespaceOverride + '\'' + '}'; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/io
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/io/jaxb/GenericJaxbIO.java
package ai.timefold.solver.core.impl.io.jaxb; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.util.ValidationEventCollector; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; public final class GenericJaxbIO<T> implements JaxbIO<T> { private static final Logger LOGGER = LoggerFactory.getLogger(GenericJaxbIO.class); private static final int DEFAULT_INDENTATION = 2; private static final String ERR_MSG_WRITE = "Failed to marshall a root element class (%s) to XML."; private static final String ERR_MSG_READ = "Failed to unmarshall a root element class (%s) from XML."; private static final String ERR_MSG_READ_OVERRIDE_NAMESPACE = "Failed to unmarshall a root element class (%s) from XML with overriding elements' namespaces: (%s)."; private final JAXBContext jaxbContext; private final Marshaller marshaller; private final Class<T> rootClass; private final int indentation; public GenericJaxbIO(Class<T> rootClass) { this(rootClass, DEFAULT_INDENTATION); } public GenericJaxbIO(Class<T> rootClass, int indentation) { Objects.requireNonNull(rootClass); this.rootClass = rootClass; this.indentation = indentation; try { jaxbContext = JAXBContext.newInstance(rootClass); marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.toString()); } catch (JAXBException jaxbException) { String errorMessage = String.format("Failed to create JAXB Marshaller for a root element class (%s).", rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, jaxbException); } } @Override public T read(Reader reader) { Objects.requireNonNull(reader); try { return (T) createUnmarshaller().unmarshal(reader); } catch (JAXBException jaxbException) { String errorMessage = String.format(ERR_MSG_READ, rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, jaxbException); } } public T readAndValidate(Reader reader, String schemaResource) { Objects.requireNonNull(reader); Schema schema = readSchemaResource(schemaResource); return readAndValidate(reader, schema); } public T readAndValidate(Document document, String schemaResource) { return readAndValidate(document, readSchemaResource(schemaResource)); } private Schema readSchemaResource(String schemaResource) { String nonNullSchemaResource = Objects.requireNonNull(schemaResource); URL schemaResourceUrl = GenericJaxbIO.class.getResource(nonNullSchemaResource); if (schemaResourceUrl == null) { throw new IllegalArgumentException("The XML schema (" + nonNullSchemaResource + ") does not exist.\n" + "Maybe build the sources with Maven first?"); } SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); } catch (SAXNotSupportedException | SAXNotRecognizedException saxException) { String errorMessage = String.format( "Failed to configure the %s to validate an XML for a root class (%s) using the (%s) XML Schema.", SchemaFactory.class.getSimpleName(), rootClass.getName(), schemaResource); throw new TimefoldXmlSerializationException(errorMessage, saxException); } try { return schemaFactory.newSchema(schemaResourceUrl); } catch (SAXException saxException) { String errorMessage = String.format("Failed to read an XML Schema resource (%s) to validate an XML for a root class (%s).", nonNullSchemaResource, rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, saxException); } } public T readAndValidate(Reader reader, Schema schema) { Document document = parseXml(Objects.requireNonNull(reader)); return readAndValidate(document, Objects.requireNonNull(schema)); } public T readAndValidate(Document document, Schema schema) { Document nonNullDocument = Objects.requireNonNull(document); Schema nonNullSchema = Objects.requireNonNull(schema); Unmarshaller unmarshaller = createUnmarshaller(); unmarshaller.setSchema(nonNullSchema); ValidationEventCollector validationEventCollector = new ValidationEventCollector(); try { unmarshaller.setEventHandler(validationEventCollector); } catch (JAXBException jaxbException) { String errorMessage = String.format("Failed to set a validation event handler to the %s for " + "a root element class (%s).", Unmarshaller.class.getSimpleName(), rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, jaxbException); } try { return (T) unmarshaller.unmarshal(nonNullDocument); } catch (JAXBException jaxbException) { if (validationEventCollector.hasEvents()) { String errorMessage = String.format("XML validation failed for a root element class (%s).", rootClass.getName()); String validationErrors = Stream.of(validationEventCollector.getEvents()) .map(validationEvent -> validationEvent.getMessage() + "\nNode: " + validationEvent.getLocator().getNode().getNodeName()) .collect(Collectors.joining("\n")); String errorMessageWithValidationEvents = errorMessage + "\n" + validationErrors; throw new TimefoldXmlSerializationException(errorMessageWithValidationEvents, jaxbException); } else { String errorMessage = String.format(ERR_MSG_READ, rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, jaxbException); } } } /** * Reads the input XML using the {@link Reader} overriding elements namespaces. If an element already has a namespace and * a {@link ElementNamespaceOverride} is defined for this element, its namespace is overridden. In case the element has no * namespace, new namespace defined in the {@link ElementNamespaceOverride} is added. * * @param reader input XML {@link Reader}; never null * @param elementNamespaceOverrides never null * @return deserialized object representation of the XML. */ public T readOverridingNamespace(Reader reader, ElementNamespaceOverride... elementNamespaceOverrides) { Objects.requireNonNull(reader); Objects.requireNonNull(elementNamespaceOverrides); return readOverridingNamespace(parseXml(reader), elementNamespaceOverrides); } /** * Reads the input XML {@link Document} overriding namespaces. If an element already has a namespace and * a {@link ElementNamespaceOverride} is defined for this element, its namespace is overridden. In case the element has no * namespace a new namespace defined in the {@link ElementNamespaceOverride} is added. * * @param document input XML {@link Document}; never null * @param elementNamespaceOverrides never null * @return deserialized object representation of the XML. */ public T readOverridingNamespace(Document document, ElementNamespaceOverride... elementNamespaceOverrides) { Document translatedDocument = overrideNamespaces(Objects.requireNonNull(document), Objects.requireNonNull(elementNamespaceOverrides)); try { return (T) createUnmarshaller().unmarshal(translatedDocument); } catch (JAXBException e) { final String errorMessage = String.format(ERR_MSG_READ_OVERRIDE_NAMESPACE, rootClass.getName(), Arrays.toString(elementNamespaceOverrides)); throw new TimefoldXmlSerializationException(errorMessage, e); } } public Document parseXml(Reader reader) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder builder; try { builder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { String errorMessage = String.format("Failed to create a %s instance to parse an XML for a root class (%s).", DocumentBuilder.class.getSimpleName(), rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, e); } try (Reader nonNullReader = Objects.requireNonNull(reader)) { return builder.parse(new InputSource(nonNullReader)); } catch (SAXException saxException) { String errorMessage = String.format("Failed to parse an XML for a root class (%s).", rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, saxException); } catch (IOException ioException) { String errorMessage = String.format("Failed to read an XML for a root class (%s).", rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, ioException); } } private Unmarshaller createUnmarshaller() { try { return jaxbContext.createUnmarshaller(); } catch (JAXBException e) { String errorMessage = String.format("Failed to create a JAXB %s for a root element class (%s).", Unmarshaller.class.getSimpleName(), rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, e); } } public void validate(Document document, String schemaResource) { Schema schema = readSchemaResource(Objects.requireNonNull(schemaResource)); validate(Objects.requireNonNull(document), schema); } public void validate(Document document, Schema schema) { Validator validator = Objects.requireNonNull(schema).newValidator(); try { validator.validate(new DOMSource(Objects.requireNonNull(document))); } catch (SAXException saxException) { String errorMessage = String.format("XML validation failed for a root element class (%s).", rootClass.getName()) + "\n" + saxException.getMessage(); throw new TimefoldXmlSerializationException(errorMessage, saxException); } catch (IOException ioException) { String errorMessage = String.format("Failed to read an XML for a root element class (%s) during validation.", rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, ioException); } } @Override public void write(T root, Writer writer) { write(root, writer, null); } private void write(T root, Writer writer, StreamSource xslt) { DOMResult domResult = marshall(Objects.requireNonNull(root)); Writer nonNullWriter = Objects.requireNonNull(writer); formatXml(domResult, xslt, nonNullWriter); } public void writeWithoutNamespaces(T root, Writer writer) { try (InputStream xsltInputStream = getClass().getResourceAsStream("removeNamespaces.xslt")) { if (xsltInputStream == null) { throw new IllegalStateException("Impossible state: Failed to load XSLT stylesheet to remove namespaces."); } write(root, writer, new StreamSource(xsltInputStream)); } catch (Exception e) { throw new TimefoldXmlSerializationException(String.format(ERR_MSG_WRITE, rootClass.getName()), e); } } private DOMResult marshall(T root) { Objects.requireNonNull(root); DOMResult domResult = new DOMResult(); try { marshaller.marshal(root, domResult); } catch (JAXBException jaxbException) { throw new TimefoldXmlSerializationException(String.format(ERR_MSG_WRITE, rootClass.getName()), jaxbException); } return domResult; } private void formatXml(DOMResult domResult, Source transformationTemplate, Writer writer) { /* * The code is not vulnerable to XXE-based attacks as it does not process any external XML nor XSL input. * Should the transformerFactory be used for such purposes, it has to be appropriately secured: * https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A4-XML_External_Entities_(XXE) */ @SuppressWarnings({ "java:S2755", "java:S4435" }) TransformerFactory transformerFactory = TransformerFactory.newInstance(); try { Transformer transformer = transformationTemplate == null ? transformerFactory.newTransformer() : transformerFactory.newTransformer(transformationTemplate); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation)); transformer.transform(new DOMSource(domResult.getNode()), new StreamResult(writer)); } catch (TransformerException transformerException) { String errorMessage = String.format("Failed to format XML for a root element class (%s).", rootClass.getName()); throw new TimefoldXmlSerializationException(errorMessage, transformerException); } } private Document overrideNamespaces(Document document, ElementNamespaceOverride... elementNamespaceOverrides) { Document nonNullDocument = Objects.requireNonNull(document); final Map<String, String> elementNamespaceOverridesMap = new HashMap<>(); for (ElementNamespaceOverride namespaceOverride : Objects.requireNonNull(elementNamespaceOverrides)) { elementNamespaceOverridesMap.put(namespaceOverride.getElementLocalName(), namespaceOverride.getNamespaceOverride()); } final Deque<NamespaceOverride> preOrderNodes = new LinkedList<>(); preOrderNodes.push(new NamespaceOverride(nonNullDocument.getDocumentElement(), null)); while (!preOrderNodes.isEmpty()) { NamespaceOverride currentNodeOverride = preOrderNodes.pop(); Node currentNode = currentNodeOverride.node; final String elementLocalName = currentNode.getLocalName() == null ? currentNode.getNodeName() : currentNode.getLocalName(); // Is there any override defined for the current node? String detectedNamespaceOverride = elementNamespaceOverridesMap.get(elementLocalName); String effectiveNamespaceOverride = detectedNamespaceOverride != null ? detectedNamespaceOverride : currentNodeOverride.namespace; if (effectiveNamespaceOverride != null) { nonNullDocument.renameNode(currentNode, effectiveNamespaceOverride, elementLocalName); } processChildNodes(currentNode, (childNode -> { if (childNode.getNodeType() == Node.ELEMENT_NODE) { preOrderNodes.push(new NamespaceOverride(childNode, effectiveNamespaceOverride)); } })); } return nonNullDocument; } private void processChildNodes(Node node, Consumer<Node> nodeConsumer) { NodeList childNodes = node.getChildNodes(); if (childNodes != null) { for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode != null) { nodeConsumer.accept(childNode); } } } } private static final class NamespaceOverride { private final Node node; private final String namespace; private NamespaceOverride(Node node, String namespace) { this.node = node; this.namespace = namespace; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/io
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/io/jaxb/JaxbIO.java
package ai.timefold.solver.core.impl.io.jaxb; import java.io.Reader; import java.io.Writer; public interface JaxbIO<T> { T read(Reader reader); void write(T root, Writer writer); }