index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/descriptor/BasicVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariableGraphType; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.MovableChainedTrailingValueFilter; public final class BasicVariableDescriptor<Solution_> extends GenuineVariableDescriptor<Solution_> { private SelectionFilter<Solution_, Object> movableChainedTrailingValueFilter; private boolean chained; private boolean allowsUnassigned; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public BasicVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } public boolean isChained() { return chained; } public boolean allowsUnassigned() { return allowsUnassigned; } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override protected void processPropertyAnnotations(DescriptorPolicy descriptorPolicy) { PlanningVariable planningVariableAnnotation = variableMemberAccessor.getAnnotation(PlanningVariable.class); processAllowsUnassigned(planningVariableAnnotation); processChained(planningVariableAnnotation); processValueRangeRefs(descriptorPolicy, planningVariableAnnotation.valueRangeProviderRefs()); processStrength(planningVariableAnnotation.strengthComparatorClass(), planningVariableAnnotation.strengthWeightFactoryClass()); } private void processAllowsUnassigned(PlanningVariable planningVariableAnnotation) { var deprecatedNullable = planningVariableAnnotation.nullable(); if (planningVariableAnnotation.allowsUnassigned()) { // If the user has specified allowsUnassigned = true, it takes precedence. if (deprecatedNullable) { throw new IllegalArgumentException( "The entityClass (%s) has a @%s-annotated property (%s) with allowsUnassigned (%s) and nullable (%s) which are mutually exclusive." .formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(), variableMemberAccessor.getName(), true, true)); } this.allowsUnassigned = true; } else { // If the user has not specified allowsUnassigned = true, nullable is taken. this.allowsUnassigned = deprecatedNullable; } if (this.allowsUnassigned && variableMemberAccessor.getType().isPrimitive()) { throw new IllegalArgumentException( "The entityClass (%s) has a @%s-annotated property (%s) with allowsUnassigned (%s) which is not compatible with the primitive propertyType (%s)." .formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(), variableMemberAccessor.getName(), this.allowsUnassigned, variableMemberAccessor.getType())); } } private void processChained(PlanningVariable planningVariableAnnotation) { chained = planningVariableAnnotation.graphType() == PlanningVariableGraphType.CHAINED; if (!chained) { return; } if (!acceptsValueType(entityDescriptor.getEntityClass())) { throw new IllegalArgumentException( """ The entityClass (%s) has a @%s-annotated property (%s) with chained (%s) and propertyType (%s) which is not a superclass/interface of or the same as the entityClass (%s). If an entity's chained planning variable cannot point to another entity of the same class, then it is impossible to make a chain longer than 1 entity and therefore chaining is useless.""" .formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(), variableMemberAccessor.getName(), chained, getVariablePropertyType(), entityDescriptor.getEntityClass())); } if (allowsUnassigned) { throw new IllegalArgumentException( "The entityClass (%s) has a @%s-annotated property (%s) with chained (%s), which is not compatible with nullable (%s)." .formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(), variableMemberAccessor.getName(), chained, allowsUnassigned)); } } @Override public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { super.linkVariableDescriptors(descriptorPolicy); if (chained && entityDescriptor.hasEffectiveMovableEntitySelectionFilter()) { movableChainedTrailingValueFilter = new MovableChainedTrailingValueFilter<>(this); } else { movableChainedTrailingValueFilter = null; } } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean acceptsValueType(Class<?> valueType) { return getVariablePropertyType().isAssignableFrom(valueType); } @Override public boolean isInitialized(Object entity) { return allowsUnassigned || getValue(entity) != null; } public boolean hasMovableChainedTrailingValueFilter() { return movableChainedTrailingValueFilter != null; } public SelectionFilter<Solution_, Object> getMovableChainedTrailingValueFilter() { return movableChainedTrailingValueFilter; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/descriptor/GenuineVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.stream.Stream; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.valuerange.ValueRange; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.CompositeValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.FromEntityPropertyValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.FromSolutionPropertyValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter; 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; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class GenuineVariableDescriptor<Solution_> extends VariableDescriptor<Solution_> { private ValueRangeDescriptor<Solution_> valueRangeDescriptor; private SelectionSorter<Solution_, Object> increasingStrengthSorter; private SelectionSorter<Solution_, Object> decreasingStrengthSorter; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ protected GenuineVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } // ************************************************************************ // Lifecycle methods // ************************************************************************ public void processAnnotations(DescriptorPolicy descriptorPolicy) { processPropertyAnnotations(descriptorPolicy); } protected abstract void processPropertyAnnotations(DescriptorPolicy descriptorPolicy); protected void processValueRangeRefs(DescriptorPolicy descriptorPolicy, String[] valueRangeProviderRefs) { MemberAccessor[] valueRangeProviderMemberAccessors; if (valueRangeProviderRefs == null || valueRangeProviderRefs.length == 0) { valueRangeProviderMemberAccessors = findAnonymousValueRangeMemberAccessors(descriptorPolicy); if (valueRangeProviderMemberAccessors.length == 0) { throw new IllegalArgumentException(""" The entityClass (%s) has a @%s annotated property (%s) that has no valueRangeProviderRefs (%s) \ and no matching anonymous value range providers were found.""" .formatted(entityDescriptor.getEntityClass().getSimpleName(), PlanningVariable.class.getSimpleName(), variableMemberAccessor.getName(), Arrays.toString(valueRangeProviderRefs))); } } else { valueRangeProviderMemberAccessors = Arrays.stream(valueRangeProviderRefs) .map(ref -> findValueRangeMemberAccessor(descriptorPolicy, ref)) .toArray(MemberAccessor[]::new); } var valueRangeDescriptorList = new ArrayList<ValueRangeDescriptor<Solution_>>(valueRangeProviderMemberAccessors.length); var addNullInValueRange = this instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.allowsUnassigned() && valueRangeProviderMemberAccessors.length == 1; for (var valueRangeProviderMemberAccessor : valueRangeProviderMemberAccessors) { valueRangeDescriptorList .add(buildValueRangeDescriptor(descriptorPolicy, valueRangeProviderMemberAccessor, addNullInValueRange)); } if (valueRangeDescriptorList.size() == 1) { valueRangeDescriptor = valueRangeDescriptorList.get(0); } else { valueRangeDescriptor = new CompositeValueRangeDescriptor<>(this, addNullInValueRange, valueRangeDescriptorList); } } private MemberAccessor[] findAnonymousValueRangeMemberAccessors(DescriptorPolicy descriptorPolicy) { boolean supportsValueRangeProviderFromEntity = !isListVariable(); Stream<MemberAccessor> applicableValueRangeProviderAccessors = supportsValueRangeProviderFromEntity ? Stream.concat( descriptorPolicy.getAnonymousFromEntityValueRangeProviderSet().stream(), descriptorPolicy.getAnonymousFromSolutionValueRangeProviderSet().stream()) : descriptorPolicy.getAnonymousFromSolutionValueRangeProviderSet().stream(); return applicableValueRangeProviderAccessors .filter(valueRangeProviderAccessor -> { /* * For basic variable, the type is the type of the variable. * For list variable, the type is List<X>, and we need to know X. */ Class<?> variableType = isListVariable() ? (Class<?>) ((ParameterizedType) variableMemberAccessor.getGenericType()) .getActualTypeArguments()[0] : variableMemberAccessor.getType(); // We expect either ValueRange, Collection or an array. Type valueRangeType = valueRangeProviderAccessor.getGenericType(); if (valueRangeType instanceof ParameterizedType parameterizedValueRangeType) { Class<?> rawType = (Class<?>) parameterizedValueRangeType.getRawType(); if (!ValueRange.class.isAssignableFrom(rawType) && !Collection.class.isAssignableFrom(rawType)) { return false; } Type[] generics = parameterizedValueRangeType.getActualTypeArguments(); if (generics.length != 1) { return false; } Class<?> valueRangeGenericType = (Class<?>) generics[0]; return variableType.isAssignableFrom(valueRangeGenericType); } else { Class<?> clz = (Class<?>) valueRangeType; if (clz.isArray()) { Class<?> componentType = clz.getComponentType(); return variableType.isAssignableFrom(componentType); } return false; } }) .toArray(MemberAccessor[]::new); } private MemberAccessor findValueRangeMemberAccessor(DescriptorPolicy descriptorPolicy, String valueRangeProviderRef) { if (descriptorPolicy.hasFromSolutionValueRangeProvider(valueRangeProviderRef)) { return descriptorPolicy.getFromSolutionValueRangeProvider(valueRangeProviderRef); } else if (descriptorPolicy.hasFromEntityValueRangeProvider(valueRangeProviderRef)) { return descriptorPolicy.getFromEntityValueRangeProvider(valueRangeProviderRef); } else { Collection<String> providerIds = descriptorPolicy.getValueRangeProviderIds(); throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has a @" + PlanningVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") with a valueRangeProviderRef (" + valueRangeProviderRef + ") that does not exist in a @" + ValueRangeProvider.class.getSimpleName() + " on the solution class (" + entityDescriptor.getSolutionDescriptor().getSolutionClass().getSimpleName() + ") or on that entityClass.\n" + "The valueRangeProviderRef (" + valueRangeProviderRef + ") does not appear in the valueRangeProvideIds (" + providerIds + ")." + (!providerIds.isEmpty() ? "" : "\nMaybe a @" + ValueRangeProvider.class.getSimpleName() + " annotation is missing on a method in the solution class (" + entityDescriptor.getSolutionDescriptor().getSolutionClass().getSimpleName() + ").")); } } private ValueRangeDescriptor<Solution_> buildValueRangeDescriptor(DescriptorPolicy descriptorPolicy, MemberAccessor valueRangeProviderMemberAccessor, boolean addNullInValueRange) { if (descriptorPolicy.isFromSolutionValueRangeProvider(valueRangeProviderMemberAccessor)) { return new FromSolutionPropertyValueRangeDescriptor<>(this, addNullInValueRange, valueRangeProviderMemberAccessor); } else if (descriptorPolicy.isFromEntityValueRangeProvider(valueRangeProviderMemberAccessor)) { return new FromEntityPropertyValueRangeDescriptor<>(this, addNullInValueRange, valueRangeProviderMemberAccessor); } else { throw new IllegalStateException("Impossible state: member accessor (" + valueRangeProviderMemberAccessor + ") is not a value range provider."); } } protected void processStrength(Class<? extends Comparator> strengthComparatorClass, Class<? extends SelectionSorterWeightFactory> strengthWeightFactoryClass) { if (strengthComparatorClass == PlanningVariable.NullStrengthComparator.class) { strengthComparatorClass = null; } if (strengthWeightFactoryClass == PlanningVariable.NullStrengthWeightFactory.class) { strengthWeightFactoryClass = null; } if (strengthComparatorClass != null && strengthWeightFactoryClass != null) { throw new IllegalStateException("The entityClass (" + entityDescriptor.getEntityClass() + ") property (" + variableMemberAccessor.getName() + ") cannot have a strengthComparatorClass (" + strengthComparatorClass.getName() + ") and a strengthWeightFactoryClass (" + strengthWeightFactoryClass.getName() + ") at the same time."); } if (strengthComparatorClass != null) { Comparator<Object> strengthComparator = ConfigUtils.newInstance(this::toString, "strengthComparatorClass", strengthComparatorClass); increasingStrengthSorter = new ComparatorSelectionSorter<>(strengthComparator, SelectionSorterOrder.ASCENDING); decreasingStrengthSorter = new ComparatorSelectionSorter<>(strengthComparator, SelectionSorterOrder.DESCENDING); } if (strengthWeightFactoryClass != null) { SelectionSorterWeightFactory<Solution_, Object> strengthWeightFactory = ConfigUtils.newInstance(this::toString, "strengthWeightFactoryClass", strengthWeightFactoryClass); increasingStrengthSorter = new WeightFactorySelectionSorter<>(strengthWeightFactory, SelectionSorterOrder.ASCENDING); decreasingStrengthSorter = new WeightFactorySelectionSorter<>(strengthWeightFactory, SelectionSorterOrder.DESCENDING); } } @Override public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { // Overriding this method so that subclasses can override it too and call super. // This way, if this method ever gets any content, it will be called by all subclasses, preventing bugs. } // ************************************************************************ // Worker methods // ************************************************************************ public abstract boolean acceptsValueType(Class<?> valueType); public ValueRangeDescriptor<Solution_> getValueRangeDescriptor() { return valueRangeDescriptor; } public boolean isValueRangeEntityIndependent() { return valueRangeDescriptor.isEntityIndependent(); } // ************************************************************************ // Extraction methods // ************************************************************************ /** * A basic planning variable {@link PlanningVariable#allowsUnassigned() allowing unassigned} * and @{@link PlanningListVariable} are always considered initialized. * * @param entity never null * @return true if the variable on that entity is initialized */ public abstract boolean isInitialized(Object entity); /** * Decides whether an entity is eligible for initialization. * This is not an opposite of {@code isInitialized()} because * even a {@link PlanningVariable#allowsUnassigned() variable that allows unassigned}, * which is always considered initialized, * is reinitializable if its value is {@code null}. */ public boolean isReinitializable(Object entity) { Object value = getValue(entity); return value == null; } public SelectionSorter<Solution_, Object> getIncreasingStrengthSorter() { return increasingStrengthSorter; } public SelectionSorter<Solution_, Object> getDecreasingStrengthSorter() { return decreasingStrengthSorter; } public long getValueRangeSize(Solution_ solution, Object entity) { return valueRangeDescriptor.extractValueRangeSize(solution, entity); } @Override public String toString() { return getSimpleEntityAndVariableName() + " variable"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/descriptor/ListVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.function.BiPredicate; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateDemand; import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor; import ai.timefold.solver.core.impl.util.MutableLong; public final class ListVariableDescriptor<Solution_> extends GenuineVariableDescriptor<Solution_> { private final ListVariableStateDemand<Solution_> stateDemand = new ListVariableStateDemand<>(this); private final BiPredicate inListPredicate = (element, entity) -> { var list = getValue(entity); return list.contains(element); }; private boolean allowsUnassignedValues = true; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public ListVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } public ListVariableStateDemand<Solution_> getStateDemand() { return stateDemand; } public <A> BiPredicate<A, Object> getInListPredicate() { return inListPredicate; } public boolean allowsUnassignedValues() { return allowsUnassignedValues; } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override protected void processPropertyAnnotations(DescriptorPolicy descriptorPolicy) { PlanningListVariable planningVariableAnnotation = variableMemberAccessor.getAnnotation(PlanningListVariable.class); allowsUnassignedValues = planningVariableAnnotation.allowsUnassignedValues(); processValueRangeRefs(descriptorPolicy, planningVariableAnnotation.valueRangeProviderRefs()); } @Override protected void processValueRangeRefs(DescriptorPolicy descriptorPolicy, String[] valueRangeProviderRefs) { var fromEntityValueRangeProviderRefs = Arrays.stream(valueRangeProviderRefs) .filter(descriptorPolicy::hasFromEntityValueRangeProvider) .toList(); if (!fromEntityValueRangeProviderRefs.isEmpty()) { throw new IllegalArgumentException("@" + ValueRangeProvider.class.getSimpleName() + " on a @" + PlanningEntity.class.getSimpleName() + " is not supported with a list variable (" + this + ").\n" + "Maybe move the valueRangeProvider" + (fromEntityValueRangeProviderRefs.size() > 1 ? "s" : "") + " (" + fromEntityValueRangeProviderRefs + ") from the entity class to the @" + PlanningSolution.class.getSimpleName() + " class."); } super.processValueRangeRefs(descriptorPolicy, valueRangeProviderRefs); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean acceptsValueType(Class<?> valueType) { return getElementType().isAssignableFrom(valueType); } @Override public boolean isInitialized(Object entity) { return true; // List variable itself can never be null and is always initialized. } public Class<?> getElementType() { return ConfigUtils.extractCollectionGenericTypeParameterStrictly( "entityClass", entityDescriptor.getEntityClass(), variableMemberAccessor.getType(), variableMemberAccessor.getGenericType(), PlanningListVariable.class, variableMemberAccessor.getName()); } public int countUnassigned(Solution_ solution) { var valueCount = new MutableLong(getValueRangeSize(solution, null)); var entityDescriptor = getEntityDescriptor(); var solutionDescriptor = entityDescriptor.getSolutionDescriptor(); solutionDescriptor.visitEntitiesByEntityClass(solution, entityDescriptor.getEntityClass(), entity -> { var assignedValues = getValue(entity); valueCount.subtract(assignedValues.size()); return false; }); return valueCount.intValue(); } public InverseRelationShadowVariableDescriptor<Solution_> getInverseRelationShadowVariableDescriptor() { var entityDescriptor = getEntityDescriptor().getSolutionDescriptor().findEntityDescriptor(getElementType()); if (entityDescriptor == null) { return null; } var applicableShadowDescriptors = entityDescriptor.getShadowVariableDescriptors() .stream() .filter(f -> f instanceof InverseRelationShadowVariableDescriptor<Solution_> inverseRelationShadowVariableDescriptor && Objects.equals(inverseRelationShadowVariableDescriptor.getSourceVariableDescriptorList().get(0), this)) .toList(); if (applicableShadowDescriptors.isEmpty()) { return null; } else if (applicableShadowDescriptors.size() > 1) { // This state may be impossible. throw new IllegalStateException( """ Instances of entityClass (%s) may be used in list variable (%s), but the class has more than one @%s-annotated field (%s). Remove the annotations from all but one field.""" .formatted(entityDescriptor.getEntityClass().getCanonicalName(), getSimpleEntityAndVariableName(), InverseRelationShadowVariable.class.getSimpleName(), applicableShadowDescriptors.stream() .map(ShadowVariableDescriptor::getSimpleEntityAndVariableName) .collect(Collectors.joining(", ", "[", "]")))); } else { return (InverseRelationShadowVariableDescriptor<Solution_>) applicableShadowDescriptors.get(0); } } // ************************************************************************ // Extraction methods // ************************************************************************ @Override public List<Object> getValue(Object entity) { Object value = super.getValue(entity); if (value == null) { throw new IllegalStateException("The planning list variable (" + this + ") of entity (" + entity + ") is null."); } return (List<Object>) value; } public Object removeElement(Object entity, int index) { return getValue(entity).remove(index); } public void addElement(Object entity, int index, Object element) { getValue(entity).add(index, element); } public Object getElement(Object entity, int index) { var values = getValue(entity); if (index >= values.size()) { throw new IndexOutOfBoundsException( "Impossible state: The index (%s) must be less than the size (%s) of the planning list variable (%s) of entity (%s)." .formatted(index, values.size(), this, entity)); } return getValue(entity).get(index); } public Object setElement(Object entity, int index, Object element) { return getValue(entity).set(index, element); } public int getListSize(Object entity) { return getValue(entity).size(); } // ************************************************************************ // Pinning support // ************************************************************************ public boolean supportsPinning() { return entityDescriptor.supportsPinning(); } public boolean isElementPinned(ScoreDirector<Solution_> scoreDirector, Object entity, int index) { if (!supportsPinning()) { return false; } else if (!entityDescriptor.isMovable(scoreDirector, entity)) { // Skipping due to @PlanningPin. return true; } else { return index < getFirstUnpinnedIndex(entity); } } public Object getRandomUnpinnedElement(Object entity, Random workingRandom) { var listVariable = getValue(entity); var firstUnpinnedIndex = getFirstUnpinnedIndex(entity); return listVariable.get(workingRandom.nextInt(listVariable.size() - firstUnpinnedIndex) + firstUnpinnedIndex); } public int getUnpinnedSubListSize(Object entity) { var listSize = getListSize(entity); var firstUnpinnedIndex = getFirstUnpinnedIndex(entity); return listSize - firstUnpinnedIndex; } public List<Object> getUnpinnedSubList(Object entity) { var firstUnpinnedIndex = getFirstUnpinnedIndex(entity); var entityList = getValue(entity); if (firstUnpinnedIndex == 0) { return entityList; } return entityList.subList(firstUnpinnedIndex, entityList.size()); } public int getFirstUnpinnedIndex(Object entity) { var effectivePlanningPinToIndexReader = entityDescriptor.getEffectivePlanningPinToIndexReader(); if (effectivePlanningPinToIndexReader == null) { // There is no @PlanningPinToIndex. return 0; } else { return effectivePlanningPinToIndexReader.applyAsInt(null, entity); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/descriptor/ShadowVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; import java.util.Collection; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class ShadowVariableDescriptor<Solution_> extends VariableDescriptor<Solution_> { private int globalShadowOrder = Integer.MAX_VALUE; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ protected ShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } public int getGlobalShadowOrder() { return globalShadowOrder; } public void setGlobalShadowOrder(int globalShadowOrder) { this.globalShadowOrder = globalShadowOrder; } // ************************************************************************ // Lifecycle methods // ************************************************************************ public abstract void processAnnotations(DescriptorPolicy descriptorPolicy); // ************************************************************************ // Worker methods // ************************************************************************ /** * Inverse of {@link #getSinkVariableDescriptorList()}. * * @return never null, only variables affect this shadow variable directly */ public abstract List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList(); public abstract Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses(); /** * @return never null */ public abstract Demand<?> getProvidedDemand(); public boolean hasVariableListener() { return true; } /** * @param supplyManager never null * @return never null */ public abstract Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager); // ************************************************************************ // Extraction methods // ************************************************************************ @Override public String toString() { return getSimpleEntityAndVariableName() + " shadow"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/descriptor/VariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class VariableDescriptor<Solution_> { protected final int ordinal; protected final EntityDescriptor<Solution_> entityDescriptor; protected final MemberAccessor variableMemberAccessor; protected final String variableName; protected final String simpleEntityAndVariableName; protected List<ShadowVariableDescriptor<Solution_>> sinkVariableDescriptorList = new ArrayList<>(4); // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ protected VariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { if (variableMemberAccessor.getType().isPrimitive()) { throw new IllegalStateException(""" The entityClass (%s) has a @%s annotated member (%s) that returns a primitive type (%s). This means it cannot represent an uninitialized variable as null \ and the Construction Heuristics think it's already initialized. Maybe let the member (%s) return its primitive wrapper type instead.""" .formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(), variableMemberAccessor, variableMemberAccessor.getType(), getSimpleEntityAndVariableName())); } this.ordinal = ordinal; this.entityDescriptor = entityDescriptor; this.variableMemberAccessor = variableMemberAccessor; this.variableName = variableMemberAccessor.getName(); this.simpleEntityAndVariableName = entityDescriptor.getEntityClass().getSimpleName() + "." + variableName; } /** * A number unique within an {@link EntityDescriptor}, increasing sequentially from zero. * Used for indexing in arrays to avoid object hash lookups in maps. * * @return zero or higher */ public int getOrdinal() { return ordinal; } public EntityDescriptor<Solution_> getEntityDescriptor() { return entityDescriptor; } public String getVariableName() { return variableName; } // ************************************************************************ // Worker methods // ************************************************************************ public String getSimpleEntityAndVariableName() { return simpleEntityAndVariableName; } public Class<?> getVariablePropertyType() { return variableMemberAccessor.getType(); } public abstract void linkVariableDescriptors(DescriptorPolicy descriptorPolicy); public final boolean isListVariable() { return this instanceof ListVariableDescriptor; } // ************************************************************************ // Shadows // ************************************************************************ public void registerSinkVariableDescriptor(ShadowVariableDescriptor<Solution_> shadowVariableDescriptor) { sinkVariableDescriptorList.add(shadowVariableDescriptor); } /** * Inverse of {@link ShadowVariableDescriptor#getSourceVariableDescriptorList()}. * * @return never null, only direct shadow variables that are affected by this variable */ public List<ShadowVariableDescriptor<Solution_>> getSinkVariableDescriptorList() { return sinkVariableDescriptorList; } /** * @param value never null * @return true if it might be an anchor, false if it is definitely not an anchor */ public boolean isValuePotentialAnchor(Object value) { return !entityDescriptor.getEntityClass().isAssignableFrom(value.getClass()); } // ************************************************************************ // Extraction methods // ************************************************************************ public Object getValue(Object entity) { return variableMemberAccessor.executeGetter(entity); } public void setValue(Object entity, Object value) { variableMemberAccessor.executeSetter(entity, value); } public String getMemberAccessorSpeedNote() { return variableMemberAccessor.getSpeedNote(); } public final boolean isGenuineAndUninitialized(Object entity) { return this instanceof GenuineVariableDescriptor<Solution_> genuineVariableDescriptor && !genuineVariableDescriptor.isInitialized(entity); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/index/IndexShadowVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.index; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.domain.variable.IndexShadowVariable; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class IndexShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { private ListVariableDescriptor<Solution_> sourceVariableDescriptor; public IndexShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); if (!variableMemberAccessor.getType().equals(Integer.class) && !variableMemberAccessor.getType().equals(Long.class)) { throw new IllegalStateException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + IndexShadowVariable.class.getSimpleName() + " annotated member (" + variableMemberAccessor + ") of type (" + variableMemberAccessor.getType() + ") which cannot represent an index in a list.\n" + "The @" + IndexShadowVariable.class.getSimpleName() + " annotated member type must be " + Integer.class + " or " + Long.class + "."); } } @Override public void processAnnotations(DescriptorPolicy descriptorPolicy) { // Do nothing } @Override public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { linkShadowSources(descriptorPolicy); } private void linkShadowSources(DescriptorPolicy descriptorPolicy) { String sourceVariableName = variableMemberAccessor.getAnnotation(IndexShadowVariable.class).sourceVariableName(); List<EntityDescriptor<Solution_>> entitiesWithSourceVariable = entityDescriptor.getSolutionDescriptor().getEntityDescriptors().stream() .filter(entityDescriptor -> entityDescriptor.hasVariableDescriptor(sourceVariableName)) .collect(Collectors.toList()); if (entitiesWithSourceVariable.isEmpty()) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + IndexShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a valid planning variable on any of the entity classes (" + entityDescriptor.getSolutionDescriptor().getEntityDescriptors() + ")."); } if (entitiesWithSourceVariable.size() > 1) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + IndexShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a unique planning variable." + " A planning variable with the name (" + sourceVariableName + ") exists on multiple entity classes (" + entitiesWithSourceVariable + ")."); } VariableDescriptor<Solution_> variableDescriptor = entitiesWithSourceVariable.get(0).getVariableDescriptor(sourceVariableName); if (variableDescriptor == null) { throw new IllegalStateException( "Impossible state: variableDescriptor (" + variableDescriptor + ") is null" + " but previous checks indicate that the entityClass (" + entitiesWithSourceVariable.get(0) + ") has a planning variable with sourceVariableName (" + sourceVariableName + ")."); } if (!(variableDescriptor instanceof ListVariableDescriptor)) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + IndexShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a @" + PlanningListVariable.class.getSimpleName() + "."); } sourceVariableDescriptor = (ListVariableDescriptor<Solution_>) variableDescriptor; sourceVariableDescriptor.registerSinkVariableDescriptor(this); } @Override public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() { return Collections.singletonList(sourceVariableDescriptor); } @Override public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() { return Collections.singleton(IndexVariableListener.class); } @Override public IndexVariableDemand<Solution_> getProvidedDemand() { return new IndexVariableDemand<>(sourceVariableDescriptor); } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { return new VariableListenerWithSources<>(new IndexVariableListener<>(this, sourceVariableDescriptor), sourceVariableDescriptor).toCollection(); } @Override public Integer getValue(Object entity) { return (Integer) super.getValue(entity); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/index/IndexVariableDemand.java
package ai.timefold.solver.core.impl.domain.variable.index; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.AbstractVariableDescriptorBasedDemand; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class IndexVariableDemand<Solution_> extends AbstractVariableDescriptorBasedDemand<Solution_, IndexVariableSupply> { public IndexVariableDemand(ListVariableDescriptor<Solution_> sourceVariableDescriptor) { super(sourceVariableDescriptor); } // ************************************************************************ // Creation method // ************************************************************************ @Override public IndexVariableSupply createExternalizedSupply(SupplyManager supplyManager) { return supplyManager.demand(((ListVariableDescriptor<Solution_>) variableDescriptor).getStateDemand()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/index/IndexVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.index; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; 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.score.director.InnerScoreDirector; public class IndexVariableListener<Solution_> implements ListVariableListener<Solution_, Object, Object>, IndexVariableSupply { protected final IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor; protected final ListVariableDescriptor<Solution_> sourceVariableDescriptor; private static final int NEVER_QUIT_EARLY = Integer.MAX_VALUE; public IndexVariableListener( IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor, ListVariableDescriptor<Solution_> sourceVariableDescriptor) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { updateIndexes((InnerScoreDirector<Solution_, ?>) scoreDirector, entity, 0, NEVER_QUIT_EARLY); } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); for (Object element : listVariable) { innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } } @Override public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } @Override public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { // Do nothing } @Override public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; updateIndexes(innerScoreDirector, entity, fromIndex, toIndex); } private void updateIndexes(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, int fromIndex, int toIndex) { List<Object> listVariable = sourceVariableDescriptor.getValue(entity); for (int i = fromIndex; i < listVariable.size(); i++) { Object element = listVariable.get(i); Integer oldIndex = shadowVariableDescriptor.getValue(element); if (!Objects.equals(oldIndex, i)) { scoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, i); scoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } else if (i >= toIndex) { // Do not quit early while inside the affected subList range. // Example 1. When X is moved from Ann[3] to Beth[3], we need to start updating Beth's elements at index 3 // where X already has the expected index, but quitting there would be incorrect because all the elements // above X need their indexes incremented. // Example 2. After ListSwapMove(Ann, 5, 9), the listener must not quit at index 6, but it can quit at index 10. return; } } } @Override public Integer getIndex(Object planningValue) { return shadowVariableDescriptor.getValue(planningValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/index/IndexVariableSupply.java
package ai.timefold.solver.core.impl.domain.variable.index; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * Only supported for {@link PlanningListVariable list variables}. * <p> * To get an instance, demand an {@link IndexVariableDemand} from {@link InnerScoreDirector#getSupplyManager()}. */ public interface IndexVariableSupply extends Supply { /** * Get {@code planningValue}'s index in the {@link PlanningListVariable list variable} it is an element of. * * @param planningValue never null * @return {@code planningValue}'s index in the list variable it is an element of or {@code null} if the value is unassigned */ Integer getIndex(Object planningValue); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/CollectionInverseVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import java.util.Collection; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; public class CollectionInverseVariableListener<Solution_> implements VariableListener<Solution_, Object>, CollectionInverseVariableSupply { protected final InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor; protected final VariableDescriptor<Solution_> sourceVariableDescriptor; public CollectionInverseVariableListener(InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor, VariableDescriptor<Solution_> sourceVariableDescriptor) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } protected void insert(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) { Object shadowEntity = sourceVariableDescriptor.getValue(entity); if (shadowEntity != null) { Collection shadowCollection = (Collection) shadowVariableDescriptor.getValue(shadowEntity); if (scoreDirector.expectShadowVariablesInCorrectState() && shadowCollection == null) { throw new IllegalStateException("The entity (" + entity + ") has a variable (" + sourceVariableDescriptor.getVariableName() + ") with value (" + shadowEntity + ") which has a sourceVariableName variable (" + shadowVariableDescriptor.getVariableName() + ") with a value (" + shadowCollection + ") which is null.\n" + "Verify the consistency of your input problem for that bi-directional relationship.\n" + "Every non-singleton inverse variable can never be null. It should at least be an empty " + Collection.class.getSimpleName() + " instead."); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, shadowEntity); boolean added = shadowCollection.add(entity); if (scoreDirector.expectShadowVariablesInCorrectState() && !added) { throw new IllegalStateException("The entity (" + entity + ") has a variable (" + sourceVariableDescriptor.getVariableName() + ") with value (" + shadowEntity + ") which has a sourceVariableName variable (" + shadowVariableDescriptor.getVariableName() + ") with a value (" + shadowCollection + ") which already contained the entity (" + entity + ").\n" + "Verify the consistency of your input problem for that bi-directional relationship."); } scoreDirector.afterVariableChanged(shadowVariableDescriptor, shadowEntity); } } protected void retract(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) { Object shadowEntity = sourceVariableDescriptor.getValue(entity); if (shadowEntity != null) { Collection shadowCollection = (Collection) shadowVariableDescriptor.getValue(shadowEntity); if (scoreDirector.expectShadowVariablesInCorrectState() && shadowCollection == null) { throw new IllegalStateException("The entity (" + entity + ") has a variable (" + sourceVariableDescriptor.getVariableName() + ") with value (" + shadowEntity + ") which has a sourceVariableName variable (" + shadowVariableDescriptor.getVariableName() + ") with a value (" + shadowCollection + ") which is null.\n" + "Verify the consistency of your input problem for that bi-directional relationship.\n" + "Every non-singleton inverse variable can never be null. It should at least be an empty " + Collection.class.getSimpleName() + " instead."); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, shadowEntity); boolean removed = shadowCollection.remove(entity); if (scoreDirector.expectShadowVariablesInCorrectState() && !removed) { throw new IllegalStateException("The entity (" + entity + ") has a variable (" + sourceVariableDescriptor.getVariableName() + ") with value (" + shadowEntity + ") which has a sourceVariableName variable (" + shadowVariableDescriptor.getVariableName() + ") with a value (" + shadowCollection + ") which did not contain the entity (" + entity + ").\n" + "Verify the consistency of your input problem for that bi-directional relationship."); } scoreDirector.afterVariableChanged(shadowVariableDescriptor, shadowEntity); } } @Override public Collection<?> getInverseCollection(Object planningValue) { return (Collection<?>) shadowVariableDescriptor.getValue(planningValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/ExternalizedCollectionInverseVariableSupply.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener; /** * Alternative to {@link CollectionInverseVariableListener}. */ public class ExternalizedCollectionInverseVariableSupply<Solution_> implements SourcedVariableListener<Solution_>, VariableListener<Solution_, Object>, CollectionInverseVariableSupply { protected final VariableDescriptor<Solution_> sourceVariableDescriptor; protected Map<Object, Set<Object>> inverseEntitySetMap = null; public ExternalizedCollectionInverseVariableSupply(VariableDescriptor<Solution_> sourceVariableDescriptor) { this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public VariableDescriptor<Solution_> getSourceVariableDescriptor() { return sourceVariableDescriptor; } @Override public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) { inverseEntitySetMap = new IdentityHashMap<>(); sourceVariableDescriptor.getEntityDescriptor().visitAllEntities(scoreDirector.getWorkingSolution(), this::insert); } @Override public void close() { inverseEntitySetMap = null; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { insert(entity); } @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { retract(entity); } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { insert(entity); } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { retract(entity); } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } protected void insert(Object entity) { Object value = sourceVariableDescriptor.getValue(entity); if (value == null) { return; } Set<Object> inverseEntitySet = inverseEntitySetMap.computeIfAbsent(value, k -> Collections.newSetFromMap(new IdentityHashMap<>())); boolean addSucceeded = inverseEntitySet.add(entity); if (!addSucceeded) { throw new IllegalStateException("The supply (" + this + ") is corrupted," + " because the entity (" + entity + ") for sourceVariable (" + sourceVariableDescriptor.getVariableName() + ") cannot be inserted: it was already inserted."); } } protected void retract(Object entity) { Object value = sourceVariableDescriptor.getValue(entity); if (value == null) { return; } Set<Object> inverseEntitySet = inverseEntitySetMap.get(value); boolean removeSucceeded = inverseEntitySet.remove(entity); if (!removeSucceeded) { throw new IllegalStateException("The supply (" + this + ") is corrupted," + " because the entity (" + entity + ") for sourceVariable (" + sourceVariableDescriptor.getVariableName() + ") cannot be retracted: it was never inserted."); } if (inverseEntitySet.isEmpty()) { inverseEntitySetMap.put(value, null); } } @Override public Collection<?> getInverseCollection(Object value) { Set<Object> inverseEntitySet = inverseEntitySetMap.get(value); if (inverseEntitySet == null) { return Collections.emptySet(); } return inverseEntitySet; } @Override public String toString() { return getClass().getSimpleName() + "(" + sourceVariableDescriptor.getVariableName() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/ExternalizedSingletonInverseVariableSupply.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import java.util.IdentityHashMap; import java.util.Map; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener; /** * Alternative to {@link SingletonInverseVariableListener}. */ public class ExternalizedSingletonInverseVariableSupply<Solution_> implements SourcedVariableListener<Solution_>, VariableListener<Solution_, Object>, SingletonInverseVariableSupply { protected final VariableDescriptor<Solution_> sourceVariableDescriptor; protected Map<Object, Object> inverseEntityMap = null; public ExternalizedSingletonInverseVariableSupply(VariableDescriptor<Solution_> sourceVariableDescriptor) { this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public VariableDescriptor<Solution_> getSourceVariableDescriptor() { return sourceVariableDescriptor; } @Override public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) { inverseEntityMap = new IdentityHashMap<>(); sourceVariableDescriptor.getEntityDescriptor().visitAllEntities(scoreDirector.getWorkingSolution(), this::insert); } @Override public void close() { inverseEntityMap = null; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { insert(entity); } @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { retract(entity); } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { insert(entity); } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { retract(entity); } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } protected void insert(Object entity) { Object value = sourceVariableDescriptor.getValue(entity); if (value == null) { return; } Object oldInverseEntity = inverseEntityMap.put(value, entity); if (oldInverseEntity != null) { throw new IllegalStateException("The supply (" + this + ") is corrupted," + " because the entity (" + entity + ") for sourceVariable (" + sourceVariableDescriptor.getVariableName() + ") cannot be inserted: another entity (" + oldInverseEntity + ") already has that value (" + value + ")."); } } protected void retract(Object entity) { Object value = sourceVariableDescriptor.getValue(entity); if (value == null) { return; } Object oldInverseEntity = inverseEntityMap.remove(value); if (oldInverseEntity != entity) { throw new IllegalStateException("The supply (" + this + ") is corrupted," + " because the entity (" + entity + ") for sourceVariable (" + sourceVariableDescriptor.getVariableName() + ") cannot be retracted: the entity was never inserted for that value (" + value + ")."); } } @Override public Object getInverseSingleton(Object value) { return inverseEntityMap.get(value); } @Override public String toString() { return getClass().getSimpleName() + "(" + sourceVariableDescriptor.getVariableName() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/InverseRelationShadowVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import java.lang.reflect.Type; 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.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariableGraphType; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class InverseRelationShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { private VariableDescriptor<Solution_> sourceVariableDescriptor; private boolean singleton; private boolean chained; public InverseRelationShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } @Override public void processAnnotations(DescriptorPolicy descriptorPolicy) { // Do nothing } @Override public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { linkShadowSources(descriptorPolicy); } /** * Sourced on a basic genuine planning variable, the shadow type is a Collection (such as List or Set). * Sourced on a list or chained planning variable, the shadow variable type is a single instance. * * @param descriptorPolicy descriptor policy */ private void linkShadowSources(DescriptorPolicy descriptorPolicy) { InverseRelationShadowVariable shadowVariableAnnotation = variableMemberAccessor .getAnnotation(InverseRelationShadowVariable.class); Class<?> variablePropertyType = getVariablePropertyType(); Class<?> sourceClass; if (Collection.class.isAssignableFrom(variablePropertyType)) { Type genericType = variableMemberAccessor.getGenericType(); sourceClass = ConfigUtils.extractCollectionGenericTypeParameterLeniently( "entityClass", entityDescriptor.getEntityClass(), variablePropertyType, genericType, InverseRelationShadowVariable.class, variableMemberAccessor.getName()).orElse(Object.class); singleton = false; } else { sourceClass = variablePropertyType; singleton = true; } EntityDescriptor<Solution_> sourceEntityDescriptor = getEntityDescriptor().getSolutionDescriptor() .findEntityDescriptor(sourceClass); if (sourceEntityDescriptor == null) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + InverseRelationShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") with a sourceClass (" + sourceClass + ") which is not a valid planning entity." + "\nMaybe check the annotations of the class (" + sourceClass + ")." + "\nMaybe add the class (" + sourceClass + ") among planning entities in the solver configuration."); } String sourceVariableName = shadowVariableAnnotation.sourceVariableName(); // TODO can we getGenuineVariableDescriptor()? sourceVariableDescriptor = sourceEntityDescriptor.getVariableDescriptor(sourceVariableName); if (sourceVariableDescriptor == null) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + InverseRelationShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a valid planning variable on entityClass (" + sourceEntityDescriptor.getEntityClass() + ").\n" + sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName)); } chained = sourceVariableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); boolean list = sourceVariableDescriptor.isListVariable(); if (singleton) { if (!chained && !list) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + InverseRelationShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") which does not return a " + Collection.class.getSimpleName() + " with sourceVariableName (" + sourceVariableName + ") which is neither a list variable @" + PlanningListVariable.class.getSimpleName() + " nor a chained variable @" + PlanningVariable.class.getSimpleName() + "(graphType=" + PlanningVariableGraphType.CHAINED + ")." + " Only list and chained variables support a singleton inverse."); } } else { if (chained || list) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has an @" + InverseRelationShadowVariable.class.getSimpleName() + " annotated property (" + variableMemberAccessor.getName() + ") which returns a " + Collection.class.getSimpleName() + " (" + variablePropertyType + ") with sourceVariableName (" + sourceVariableName + ") which is a" + (chained ? " chained variable @" + PlanningVariable.class.getSimpleName() + "(graphType=" + PlanningVariableGraphType.CHAINED + "). A chained variable supports only a singleton inverse." : " list variable @" + PlanningListVariable.class.getSimpleName() + ". A list variable supports only a singleton inverse.")); } } sourceVariableDescriptor.registerSinkVariableDescriptor(this); } @Override public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() { return Collections.singletonList(sourceVariableDescriptor); } @Override public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() { if (singleton) { if (chained) { return Collections.singleton(SingletonInverseVariableListener.class); } else { return Collections.singleton(SingletonListInverseVariableListener.class); } } else { return Collections.singleton(CollectionInverseVariableListener.class); } } // ************************************************************************ // Worker methods // ************************************************************************ @Override public Demand<?> getProvidedDemand() { if (singleton) { if (chained) { return new SingletonInverseVariableDemand<>(sourceVariableDescriptor); } else { return new SingletonListInverseVariableDemand<>((ListVariableDescriptor<Solution_>) sourceVariableDescriptor); } } else { return new CollectionInverseVariableDemand<>(sourceVariableDescriptor); } } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { return new VariableListenerWithSources<>(buildVariableListener(), sourceVariableDescriptor).toCollection(); } private AbstractVariableListener<Solution_, Object> buildVariableListener() { if (singleton) { if (chained) { return new SingletonInverseVariableListener<>(this, sourceVariableDescriptor); } else { return new SingletonListInverseVariableListener<>( this, (ListVariableDescriptor<Solution_>) sourceVariableDescriptor); } } else { return new CollectionInverseVariableListener<>(this, sourceVariableDescriptor); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/SingletonInverseVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; public class SingletonInverseVariableListener<Solution_> implements VariableListener<Solution_, Object>, SingletonInverseVariableSupply { protected final InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor; protected final VariableDescriptor<Solution_> sourceVariableDescriptor; public SingletonInverseVariableListener(InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor, VariableDescriptor<Solution_> sourceVariableDescriptor) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } protected void insert(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) { Object shadowEntity = sourceVariableDescriptor.getValue(entity); if (shadowEntity != null) { Object shadowValue = shadowVariableDescriptor.getValue(shadowEntity); if (scoreDirector.expectShadowVariablesInCorrectState() && shadowValue != null) { throw new IllegalStateException("The entity (" + entity + ") has a variable (" + sourceVariableDescriptor.getVariableName() + ") with value (" + shadowEntity + ") which has a sourceVariableName variable (" + shadowVariableDescriptor.getVariableName() + ") with a value (" + shadowValue + ") which is not null.\n" + "Verify the consistency of your input problem for that sourceVariableName variable."); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, shadowEntity); shadowVariableDescriptor.setValue(shadowEntity, entity); scoreDirector.afterVariableChanged(shadowVariableDescriptor, shadowEntity); } } protected void retract(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) { Object shadowEntity = sourceVariableDescriptor.getValue(entity); if (shadowEntity != null) { Object shadowValue = shadowVariableDescriptor.getValue(shadowEntity); if (scoreDirector.expectShadowVariablesInCorrectState() && shadowValue != entity) { throw new IllegalStateException("The entity (" + entity + ") has a variable (" + sourceVariableDescriptor.getVariableName() + ") with value (" + shadowEntity + ") which has a sourceVariableName variable (" + shadowVariableDescriptor.getVariableName() + ") with a value (" + shadowValue + ") which is not that entity.\n" + "Verify the consistency of your input problem for that sourceVariableName variable."); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, shadowEntity); shadowVariableDescriptor.setValue(shadowEntity, null); scoreDirector.afterVariableChanged(shadowVariableDescriptor, shadowEntity); } } @Override public Object getInverseSingleton(Object planningValue) { return shadowVariableDescriptor.getValue(planningValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/SingletonInverseVariableSupply.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * Currently only supported for chained variables and {@link PlanningListVariable list variables}, * which guarantee that no 2 entities use the same planningValue. * <p> * To get an instance, demand a {@link SingletonInverseVariableDemand} (for a chained variable) * or a {@link SingletonListInverseVariableDemand} (for a list variable) from {@link InnerScoreDirector#getSupplyManager()}. */ public interface SingletonInverseVariableSupply extends Supply { /** * If entity1.varA = x then the inverse of x is entity1. * * @param planningValue never null * @return sometimes null, an entity for which the planning variable is the planningValue. */ Object getInverseSingleton(Object planningValue); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/SingletonListInverseVariableDemand.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.AbstractVariableDescriptorBasedDemand; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class SingletonListInverseVariableDemand<Solution_> extends AbstractVariableDescriptorBasedDemand<Solution_, SingletonInverseVariableSupply> { public SingletonListInverseVariableDemand(ListVariableDescriptor<Solution_> sourceVariableDescriptor) { super(sourceVariableDescriptor); } // ************************************************************************ // Creation method // ************************************************************************ @Override public SingletonInverseVariableSupply createExternalizedSupply(SupplyManager supplyManager) { return supplyManager.demand(((ListVariableDescriptor<Solution_>) variableDescriptor).getStateDemand()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/SingletonListInverseVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; 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.score.director.InnerScoreDirector; public class SingletonListInverseVariableListener<Solution_> implements ListVariableListener<Solution_, Object, Object>, SingletonInverseVariableSupply { protected final InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor; protected final ListVariableDescriptor<Solution_> sourceVariableDescriptor; public SingletonListInverseVariableListener( InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor, ListVariableDescriptor<Solution_> sourceVariableDescriptor) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) { if (sourceVariableDescriptor.supportsPinning()) { // Required for variable pinning, otherwise pinned values have their inverse set to null. var entityDescriptor = sourceVariableDescriptor.getEntityDescriptor(); entityDescriptor.getSolutionDescriptor() .visitEntitiesByEntityClass(scoreDirector.getWorkingSolution(), entityDescriptor.getEntityClass(), entity -> { beforeEntityAdded(scoreDirector, entity); afterEntityAdded(scoreDirector, entity); return false; }); } } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { for (var element : sourceVariableDescriptor.getValue(entity)) { setInverse((InnerScoreDirector<Solution_, ?>) scoreDirector, element, entity, null); } } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; for (var element : sourceVariableDescriptor.getValue(entity)) { setInverse(innerScoreDirector, element, null, entity); } } @Override public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) { var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } @Override public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { // Do nothing } @Override public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; var listVariable = sourceVariableDescriptor.getValue(entity); for (var i = fromIndex; i < toIndex; i++) { var element = listVariable.get(i); if (getInverseSingleton(element) != entity) { innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, entity); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } } } private void setInverse(InnerScoreDirector<Solution_, ?> scoreDirector, Object element, Object inverseEntity, Object expectedOldInverseEntity) { var oldInverseEntity = getInverseSingleton(element); if (oldInverseEntity == inverseEntity) { return; } if (scoreDirector.expectShadowVariablesInCorrectState() && oldInverseEntity != expectedOldInverseEntity) { throw new IllegalStateException("The entity (" + inverseEntity + ") has a list variable (" + sourceVariableDescriptor.getVariableName() + ") and one of its elements (" + element + ") which has a shadow variable (" + shadowVariableDescriptor.getVariableName() + ") has an oldInverseEntity (" + oldInverseEntity + ") which is not that entity.\n" + "Verify the consistency of your input problem for that shadow variable."); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, inverseEntity); scoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } @Override public Object getInverseSingleton(Object planningValue) { return shadowVariableDescriptor.getValue(planningValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/AbstractNotifiable.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import java.util.ArrayDeque; import java.util.Collection; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.util.ListBasedScalingOrderedSet; /** * Generic notifiable that receives and triggers {@link Notification}s for a specific variable listener of the type {@code T}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <T> the variable listener type */ abstract class AbstractNotifiable<Solution_, T extends AbstractVariableListener<Solution_, Object>> implements EntityNotifiable<Solution_> { private final ScoreDirector<Solution_> scoreDirector; private final T variableListener; private final Collection<Notification<Solution_, ? super T>> notificationQueue; private final int globalOrder; static <Solution_> EntityNotifiable<Solution_> buildNotifiable( ScoreDirector<Solution_> scoreDirector, AbstractVariableListener<Solution_, Object> variableListener, int globalOrder) { if (variableListener instanceof ListVariableListener) { return new ListVariableListenerNotifiable<>( scoreDirector, ((ListVariableListener<Solution_, Object, Object>) variableListener), new ArrayDeque<>(), globalOrder); } else { VariableListener<Solution_, Object> basicVariableListener = (VariableListener<Solution_, Object>) variableListener; return new VariableListenerNotifiable<>( scoreDirector, basicVariableListener, basicVariableListener.requiresUniqueEntityEvents() ? new ListBasedScalingOrderedSet<>() : new ArrayDeque<>(), globalOrder); } } AbstractNotifiable(ScoreDirector<Solution_> scoreDirector, T variableListener, Collection<Notification<Solution_, ? super T>> notificationQueue, int globalOrder) { this.scoreDirector = scoreDirector; this.variableListener = variableListener; this.notificationQueue = notificationQueue; this.globalOrder = globalOrder; } @Override public void notifyBefore(EntityNotification<Solution_> notification) { if (notificationQueue.add(notification)) { notification.triggerBefore(variableListener, scoreDirector); } } protected boolean storeForLater(Notification<Solution_, T> notification) { return notificationQueue.add(notification); } protected void triggerBefore(Notification<Solution_, T> notification) { notification.triggerBefore(variableListener, scoreDirector); } @Override public void resetWorkingSolution() { variableListener.resetWorkingSolution(scoreDirector); } @Override public void closeVariableListener() { variableListener.close(); } @Override public void triggerAllNotifications() { int notifiedCount = 0; for (Notification<Solution_, ? super T> notification : notificationQueue) { notification.triggerAfter(variableListener, scoreDirector); notifiedCount++; } if (notifiedCount != notificationQueue.size()) { throw new IllegalStateException("The variableListener (" + variableListener.getClass() + ") has been notified with notifiedCount (" + notifiedCount + ") but after being triggered, its notificationCount (" + notificationQueue.size() + ") is different.\n" + "Maybe that variableListener (" + variableListener.getClass() + ") changed an upstream shadow variable (which is illegal)."); } notificationQueue.clear(); } @Override public String toString() { return "(" + globalOrder + ") " + variableListener; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/AbstractNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import java.util.Objects; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; abstract class AbstractNotification { protected final Object entity; protected AbstractNotification(Object entity) { this.entity = entity; } /** * Warning: do not test equality of {@link AbstractNotification}s for different {@link VariableListener}s * (so {@link ShadowVariableDescriptor}s) because equality does not take those into account (for performance)! * * @param o sometimes null * @return true if same entity instance and the same type */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractNotification that = (AbstractNotification) o; return entity.equals(that.entity); } @Override public int hashCode() { return Objects.hash(System.identityHashCode(entity), getClass()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/ListVariableChangedNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; final class ListVariableChangedNotification<Solution_> extends AbstractNotification implements ListVariableNotification<Solution_> { private final int fromIndex; private final int toIndex; ListVariableChangedNotification(Object entity, int fromIndex, int toIndex) { super(entity); this.fromIndex = fromIndex; this.toIndex = toIndex; } @Override public void triggerBefore(ListVariableListener<Solution_, Object, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.beforeListVariableChanged(scoreDirector, entity, fromIndex, toIndex); } @Override public void triggerAfter(ListVariableListener<Solution_, Object, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.afterListVariableChanged(scoreDirector, entity, fromIndex, toIndex); } @Override public String toString() { return "ListVariableChangedNotification(" + entity + "[" + fromIndex + ".." + toIndex + "])"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/Notifiable.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; /** * A notifiable’s purpose is to execute variable listener methods. This interface is the most * generalized form of a notifiable. It covers variable listener methods that are executed immediately * ({@link AbstractVariableListener#resetWorkingSolution} and {@link AbstractVariableListener#close}. * * <p> * Specialized notifiables use {@link Notification}s to record planing variable changes and defer triggering of "after" methods * so that dependent variable listeners can be executed in the correct order. */ public interface Notifiable { /** * Notify the variable listener about working solution reset. */ void resetWorkingSolution(); /** * Trigger all queued notifications. */ void triggerAllNotifications(); /** * Close the variable listener. */ void closeVariableListener(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/Notification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * A notification represents some kind of change of a planning variable. When a score director is notified about a change, * one notification is created for each {@link Notifiable} registered for the subject of the change. * * <p> * Each implementation is tailored to a specific {@link AbstractVariableListener} and triggers on the listener * the pair of "before/after" methods corresponding to the type of change it represents. * * <p> * For example, if there is a shadow variable sourced on the {@code Process.computer} genuine planning variable, * then there is a notifiable {@code F} registered for the {@code Process.computer} planning variable, and it holds a basic * variable listener {@code L}. * When {@code Process X} is moved from {@code Computer A} to {@code Computer B}, a notification {@code N} is created and added * to notifiable {@code F}'s queue. The notification {@code N} triggers * {@link VariableListener#beforeVariableChanged L.beforeVariableChanged(scoreDirector, Process X)} immediately. * Later, when {@link Notifiable#triggerAllNotifications() F.triggerAllNotifications()} is called, {@code N} is taken from * the queue and triggers {@link VariableListener#afterVariableChanged}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <T> the variable listener type */ public interface Notification<Solution_, T extends AbstractVariableListener<Solution_, Object>> { /** * The {@code entity} was added. */ static <Solution_> EntityNotification<Solution_> entityAdded(Object entity) { return new EntityAddedNotification<>(entity); } /** * The {@code entity} was removed. */ static <Solution_> EntityNotification<Solution_> entityRemoved(Object entity) { return new EntityRemovedNotification<>(entity); } /** * Basic genuine or shadow planning variable changed on {@code entity}. */ static <Solution_> BasicVariableNotification<Solution_> variableChanged(Object entity) { return new VariableChangedNotification<>(entity); } /** * An element was unassigned from a list variable. */ static <Solution_> ListVariableNotification<Solution_> elementUnassigned(Object element) { return new ElementUnassignedNotification<>(element); } /** * A list variable change occurs on {@code entity} between {@code fromIndex} and {@code toIndex}. */ static <Solution_> ListVariableNotification<Solution_> listVariableChanged(Object entity, int fromIndex, int toIndex) { return new ListVariableChangedNotification<>(entity, fromIndex, toIndex); } /** * Trigger {@code variableListener}'s before method corresponding to this notification. */ void triggerBefore(T variableListener, ScoreDirector<Solution_> scoreDirector); /** * Trigger {@code variableListener}'s after method corresponding to this notification. */ void triggerAfter(T variableListener, ScoreDirector<Solution_> scoreDirector); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/VariableListenerSupport.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Map; 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.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener; import ai.timefold.solver.core.impl.domain.variable.listener.support.violation.ShadowVariablesAssert; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * This class is not thread-safe. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class VariableListenerSupport<Solution_> implements SupplyManager { public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDirector<Solution_, ?> scoreDirector) { return new VariableListenerSupport<>(scoreDirector, new NotifiableRegistry<>(scoreDirector.getSolutionDescriptor())); } private final InnerScoreDirector<Solution_, ?> scoreDirector; private final NotifiableRegistry<Solution_> notifiableRegistry; private final Map<Demand<?>, SupplyWithDemandCount> supplyMap = new HashMap<>(); private boolean notificationQueuesAreEmpty = true; private int nextGlobalOrder = 0; VariableListenerSupport(InnerScoreDirector<Solution_, ?> scoreDirector, NotifiableRegistry<Solution_> notifiableRegistry) { this.scoreDirector = scoreDirector; this.notifiableRegistry = notifiableRegistry; } public void linkVariableListeners() { scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream() .map(EntityDescriptor::getDeclaredShadowVariableDescriptors) .flatMap(Collection::stream) .filter(ShadowVariableDescriptor::hasVariableListener) .sorted(Comparator.comparingInt(ShadowVariableDescriptor::getGlobalShadowOrder)) .forEach(this::processShadowVariableDescriptor); } private void processShadowVariableDescriptor(ShadowVariableDescriptor<Solution_> shadowVariableDescriptor) { for (var listenerWithSources : shadowVariableDescriptor.buildVariableListeners(this)) { var variableListener = listenerWithSources.getVariableListener(); if (variableListener instanceof Supply supply) { // Non-sourced variable listeners (ie. ones provided by the user) can never be a supply. var demand = shadowVariableDescriptor.getProvidedDemand(); supplyMap.put(demand, new SupplyWithDemandCount(supply, 1L)); } var globalOrder = shadowVariableDescriptor.getGlobalShadowOrder(); notifiableRegistry.registerNotifiable( listenerWithSources.getSourceVariableDescriptors(), AbstractNotifiable.buildNotifiable(scoreDirector, variableListener, globalOrder)); nextGlobalOrder = globalOrder + 1; } } @Override public <Supply_ extends Supply> Supply_ demand(Demand<Supply_> demand) { var supplyWithDemandCount = supplyMap.get(demand); if (supplyWithDemandCount == null) { var newSupplyWithDemandCount = new SupplyWithDemandCount(createSupply(demand), 1L); supplyMap.put(demand, newSupplyWithDemandCount); return (Supply_) newSupplyWithDemandCount.supply; } else { var supply = supplyWithDemandCount.supply; var newSupplyWithDemandCount = new SupplyWithDemandCount(supply, supplyWithDemandCount.demandCount + 1L); supplyMap.put(demand, newSupplyWithDemandCount); return (Supply_) supply; } } private Supply createSupply(Demand<?> demand) { var supply = demand.createExternalizedSupply(this); if (supply instanceof SourcedVariableListener) { var variableListener = (SourcedVariableListener<Solution_>) supply; // An external ScoreDirector can be created before the working solution is set if (scoreDirector.getWorkingSolution() != null) { variableListener.resetWorkingSolution(scoreDirector); } notifiableRegistry.registerNotifiable( variableListener.getSourceVariableDescriptor(), AbstractNotifiable.buildNotifiable(scoreDirector, variableListener, nextGlobalOrder++)); } return supply; } @Override public <Supply_ extends Supply> boolean cancel(Demand<Supply_> demand) { var supplyWithDemandCount = supplyMap.get(demand); if (supplyWithDemandCount == null) { return false; } if (supplyWithDemandCount.demandCount == 1L) { supplyMap.remove(demand); } else { supplyMap.put(demand, new SupplyWithDemandCount(supplyWithDemandCount.supply, supplyWithDemandCount.demandCount - 1L)); } return true; } @Override public <Supply_ extends Supply> long getActiveCount(Demand<Supply_> demand) { var supplyAndDemandCounter = supplyMap.get(demand); if (supplyAndDemandCounter == null) { return 0L; } else { return supplyAndDemandCounter.demandCount; } } // ************************************************************************ // Lifecycle methods // ************************************************************************ public void resetWorkingSolution() { for (Notifiable notifiable : notifiableRegistry.getAll()) { notifiable.resetWorkingSolution(); } } public void close() { for (Notifiable notifiable : notifiableRegistry.getAll()) { notifiable.closeVariableListener(); } } public void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) { Collection<EntityNotifiable<Solution_>> notifiables = notifiableRegistry.get(entityDescriptor); if (!notifiables.isEmpty()) { EntityNotification<Solution_> notification = Notification.entityAdded(entity); for (EntityNotifiable<Solution_> notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) { Collection<EntityNotifiable<Solution_>> notifiables = notifiableRegistry.get(entityDescriptor); if (!notifiables.isEmpty()) { EntityNotification<Solution_> notification = Notification.entityRemoved(entity); for (EntityNotifiable<Solution_> notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { Collection<VariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { BasicVariableNotification<Solution_> notification = Notification.variableChanged(entity); for (VariableListenerNotifiable<Solution_> notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void afterElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { Collection<ListVariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.elementUnassigned(element); for (ListVariableListenerNotifiable<Solution_> notifiable : notifiables) { notifiable.notifyAfter(notification); } notificationQueuesAreEmpty = false; } } public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { Collection<ListVariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex); for (ListVariableListenerNotifiable<Solution_> notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { Collection<ListVariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex); for (ListVariableListenerNotifiable<Solution_> notifiable : notifiables) { notifiable.notifyAfter(notification); } notificationQueuesAreEmpty = false; } } public void triggerVariableListenersInNotificationQueues() { for (Notifiable notifiable : notifiableRegistry.getAll()) { notifiable.triggerAllNotifications(); } notificationQueuesAreEmpty = true; } /** * @return null if there are no violations */ public String createShadowVariablesViolationMessage() { Solution_ workingSolution = scoreDirector.getWorkingSolution(); ShadowVariablesAssert snapshot = ShadowVariablesAssert.takeSnapshot(scoreDirector.getSolutionDescriptor(), workingSolution); forceTriggerAllVariableListeners(workingSolution); final int SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT = 3; return snapshot.createShadowVariablesViolationMessage(SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT); } /** * Triggers all variable listeners even though the notification queue is empty. * * <p> * To ensure each listener is triggered, * an artificial notification is created for each genuine variable without doing any change on the working solution. * If everything works correctly, * triggering listeners at this point must not change any shadow variables either. * * @param workingSolution working solution */ public void forceTriggerAllVariableListeners(Solution_ workingSolution) { scoreDirector.getSolutionDescriptor().visitAllEntities(workingSolution, this::simulateGenuineVariableChange); triggerVariableListenersInNotificationQueues(); } private void simulateGenuineVariableChange(Object entity) { var entityDescriptor = scoreDirector.getSolutionDescriptor() .findEntityDescriptorOrFail(entity.getClass()); if (!entityDescriptor.isGenuine()) { return; } for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) { if (variableDescriptor.isListVariable()) { var listVariableDescriptor = (ListVariableDescriptor<Solution_>) variableDescriptor; int size = listVariableDescriptor.getValue(entity).size(); beforeListVariableChanged(listVariableDescriptor, entity, 0, size); afterListVariableChanged(listVariableDescriptor, entity, 0, size); } else { // Triggering before...() is enough, as that will add the after...() call to the queue automatically. beforeVariableChanged(variableDescriptor, entity); } } } public void assertNotificationQueuesAreEmpty() { if (!notificationQueuesAreEmpty) { throw new IllegalStateException("The notificationQueues might not be empty (" + notificationQueuesAreEmpty + ") so any shadow variables might be stale so score calculation is unreliable.\n" + "Maybe a " + ScoreDirector.class.getSimpleName() + ".before*() method was called" + " without calling " + ScoreDirector.class.getSimpleName() + ".triggerVariableListeners()," + " before calling " + ScoreDirector.class.getSimpleName() + ".calculateScore()."); } } private record SupplyWithDemandCount(Supply supply, long demandCount) { } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/ListVariableTracker.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; 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.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * Tracks variable listener events for a given {@link ai.timefold.solver.core.api.domain.variable.PlanningListVariable}. */ public class ListVariableTracker<Solution_> implements SourcedVariableListener<Solution_>, ListVariableListener<Solution_, Object, Object>, Supply { private final ListVariableDescriptor<Solution_> variableDescriptor; private final List<Object> beforeVariableChangedEntityList; private final List<Object> afterVariableChangedEntityList; public ListVariableTracker(ListVariableDescriptor<Solution_> variableDescriptor) { this.variableDescriptor = variableDescriptor; beforeVariableChangedEntityList = new ArrayList<>(); afterVariableChangedEntityList = new ArrayList<>(); } @Override public VariableDescriptor<Solution_> getSourceVariableDescriptor() { return variableDescriptor; } @Override public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) { beforeVariableChangedEntityList.clear(); afterVariableChangedEntityList.clear(); } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { } @Override public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) { } @Override public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { beforeVariableChangedEntityList.add(entity); } @Override public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { afterVariableChangedEntityList.add(entity); } public List<String> getEntitiesMissingBeforeAfterEvents( List<VariableId<Solution_>> changedVariables) { List<String> out = new ArrayList<>(); for (var changedVariable : changedVariables) { if (!variableDescriptor.equals(changedVariable.variableDescriptor())) { continue; } Object entity = changedVariable.entity(); if (!beforeVariableChangedEntityList.contains(entity)) { out.add("Entity (" + entity + ") is missing a beforeListVariableChanged call for list variable (" + variableDescriptor.getVariableName() + ")."); } if (!afterVariableChangedEntityList.contains(entity)) { out.add("Entity (" + entity + ") is missing a afterListVariableChanged call for list variable (" + variableDescriptor.getVariableName() + ")."); } } beforeVariableChangedEntityList.clear(); afterVariableChangedEntityList.clear(); return out; } public TrackerDemand demand() { return new TrackerDemand(); } /** * In order for the {@link ListVariableTracker} to be registered as a variable listener, * it needs to be passed to the {@link InnerScoreDirector#getSupplyManager()}, which requires a {@link Demand}. * <p> * Unlike most other {@link Demand}s, there will only be one instance of * {@link ListVariableTracker} in the {@link InnerScoreDirector} for each list variable. */ public class TrackerDemand implements Demand<ListVariableTracker<Solution_>> { @Override public ListVariableTracker<Solution_> createExternalizedSupply(SupplyManager supplyManager) { return ListVariableTracker.this; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/SolutionTracker.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class SolutionTracker<Solution_> { private final SolutionDescriptor<Solution_> solutionDescriptor; private final List<VariableTracker<Solution_>> normalVariableTrackers; private final List<ListVariableTracker<Solution_>> listVariableTrackers; private List<String> missingEventsForward; private List<String> missingEventsBackward; Solution_ beforeMoveSolution; VariableSnapshotTotal<Solution_> beforeVariables; Solution_ afterMoveSolution; VariableSnapshotTotal<Solution_> afterVariables; Solution_ afterUndoSolution; VariableSnapshotTotal<Solution_> undoVariables; VariableSnapshotTotal<Solution_> undoFromScratchVariables; VariableSnapshotTotal<Solution_> beforeFromScratchVariables; public SolutionTracker(SolutionDescriptor<Solution_> solutionDescriptor, SupplyManager supplyManager) { this.solutionDescriptor = solutionDescriptor; normalVariableTrackers = new ArrayList<>(); listVariableTrackers = new ArrayList<>(); for (EntityDescriptor<Solution_> entityDescriptor : solutionDescriptor.getEntityDescriptors()) { for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) { if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) { listVariableTrackers.add(new ListVariableTracker<>(listVariableDescriptor)); } else { normalVariableTrackers.add(new VariableTracker<>(variableDescriptor)); } } } normalVariableTrackers.forEach(tracker -> supplyManager.demand(tracker.demand())); listVariableTrackers.forEach(tracker -> supplyManager.demand(tracker.demand())); } public Solution_ getBeforeMoveSolution() { return beforeMoveSolution; } public Solution_ getAfterMoveSolution() { return afterMoveSolution; } public Solution_ getAfterUndoSolution() { return afterUndoSolution; } public void setBeforeMoveSolution(Solution_ workingSolution) { beforeVariables = VariableSnapshotTotal.takeSnapshot(solutionDescriptor, workingSolution); beforeMoveSolution = cloneSolution(workingSolution); } public void setAfterMoveSolution(Solution_ workingSolution) { afterVariables = VariableSnapshotTotal.takeSnapshot(solutionDescriptor, workingSolution); afterMoveSolution = cloneSolution(workingSolution); if (beforeVariables != null) { missingEventsForward = getEntitiesMissingBeforeAfterEvents(beforeVariables, afterVariables); } else { missingEventsBackward = Collections.emptyList(); } } public void setAfterUndoSolution(Solution_ workingSolution) { undoVariables = VariableSnapshotTotal.takeSnapshot(solutionDescriptor, workingSolution); afterUndoSolution = cloneSolution(workingSolution); if (beforeVariables != null) { missingEventsBackward = getEntitiesMissingBeforeAfterEvents(undoVariables, afterVariables); } else { missingEventsBackward = Collections.emptyList(); } } public void setUndoFromScratchSolution(Solution_ workingSolution) { undoFromScratchVariables = VariableSnapshotTotal.takeSnapshot(solutionDescriptor, workingSolution); } public void setBeforeFromScratchSolution(Solution_ workingSolution) { beforeFromScratchVariables = VariableSnapshotTotal.takeSnapshot(solutionDescriptor, workingSolution); } private Solution_ cloneSolution(Solution_ workingSolution) { return solutionDescriptor.getSolutionCloner().cloneSolution(workingSolution); } public void restoreBeforeSolution() { beforeVariables.restore(); } private List<String> getEntitiesMissingBeforeAfterEvents(VariableSnapshotTotal<Solution_> beforeSolution, VariableSnapshotTotal<Solution_> afterSolution) { List<String> out = new ArrayList<>(); var changes = afterSolution.changedVariablesFrom(beforeSolution); for (VariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) { out.addAll(normalVariableTracker.getEntitiesMissingBeforeAfterEvents(changes)); } for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) { out.addAll(listVariableTracker.getEntitiesMissingBeforeAfterEvents(changes)); } return out; } public String buildScoreCorruptionMessage() { if (beforeMoveSolution == null) { return ""; } StringBuilder out = new StringBuilder(); var changedBetweenBeforeAndUndo = getVariableChangedViolations(beforeVariables, undoVariables); var changedBetweenBeforeAndScratch = getVariableChangedViolations(beforeFromScratchVariables, beforeVariables); var changedBetweenUndoAndScratch = getVariableChangedViolations(undoFromScratchVariables, undoVariables); if (!changedBetweenBeforeAndUndo.isEmpty()) { out.append(""" Variables that are different between before and undo: %s """.formatted(formatList(changedBetweenBeforeAndUndo))); } if (!changedBetweenBeforeAndScratch.isEmpty()) { out.append(""" Variables that are different between from scratch and before: %s """.formatted(formatList(changedBetweenBeforeAndScratch))); } if (!changedBetweenUndoAndScratch.isEmpty()) { out.append(""" Variables that are different between from scratch and undo: %s """.formatted(formatList(changedBetweenUndoAndScratch))); } if (!missingEventsForward.isEmpty()) { out.append(""" Missing variable listener events for actual move: %s """.formatted(formatList(missingEventsForward))); } if (!missingEventsBackward.isEmpty()) { out.append(""" Missing variable listener events for undo move:") %s """.formatted(formatList(missingEventsBackward))); } if (out.isEmpty()) { return "Genuine and shadow variables agree with from scratch calculation after the undo move and match the state prior to the move."; } return out.toString(); } static <Solution_> List<String> getVariableChangedViolations( VariableSnapshotTotal<Solution_> expectedSnapshot, VariableSnapshotTotal<Solution_> actualSnapshot) { List<String> out = new ArrayList<>(); var changedVariables = expectedSnapshot.changedVariablesFrom(actualSnapshot); for (var changedVariable : changedVariables) { var expectedSnapshotVariable = expectedSnapshot.getVariableSnapshot(changedVariable); var actualSnapshotVariable = actualSnapshot.getVariableSnapshot(changedVariable); out.add("Actual value (%s) of variable %s on %s entity (%s) differs from expected (%s)" .formatted(actualSnapshotVariable.getValue(), expectedSnapshotVariable.getVariableDescriptor().getVariableName(), expectedSnapshotVariable.getVariableDescriptor().getEntityDescriptor().getEntityClass() .getSimpleName(), expectedSnapshotVariable.getEntity(), expectedSnapshotVariable.getValue())); } return out; } static String formatList(List<String> messages) { final int LIMIT = 5; if (messages.isEmpty()) { return ""; } if (messages.size() <= LIMIT) { return messages.stream() .collect(Collectors.joining("\n - ", " - ", "\n")); } return messages.stream() .limit(LIMIT) .collect(Collectors.joining("\n - ", " - ", "\n ...(" + (messages.size() - LIMIT) + " more)\n")); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/VariableTracker.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * Tracks variable listener events for a given genuine or shadow variable * (except {@link ai.timefold.solver.core.api.domain.variable.PlanningListVariable}). */ public class VariableTracker<Solution_> implements SourcedVariableListener<Solution_>, VariableListener<Solution_, Object>, Supply { private final VariableDescriptor<Solution_> variableDescriptor; private final List<Object> beforeVariableChangedEntityList; private final List<Object> afterVariableChangedEntityList; public VariableTracker(VariableDescriptor<Solution_> variableDescriptor) { this.variableDescriptor = variableDescriptor; beforeVariableChangedEntityList = new ArrayList<>(); afterVariableChangedEntityList = new ArrayList<>(); } @Override public VariableDescriptor<Solution_> getSourceVariableDescriptor() { return variableDescriptor; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object object) { } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object object) { } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object object) { } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object object) { } @Override public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) { beforeVariableChangedEntityList.clear(); afterVariableChangedEntityList.clear(); } @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { beforeVariableChangedEntityList.add(entity); } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { afterVariableChangedEntityList.add(entity); } public List<String> getEntitiesMissingBeforeAfterEvents( List<VariableId<Solution_>> changedVariables) { List<String> out = new ArrayList<>(); for (var changedVariable : changedVariables) { if (!variableDescriptor.equals(changedVariable.variableDescriptor())) { continue; } Object entity = changedVariable.entity(); if (!beforeVariableChangedEntityList.contains(entity)) { out.add("Entity (" + entity + ") is missing a beforeVariableChanged call for variable (" + variableDescriptor.getVariableName() + ")."); } if (!afterVariableChangedEntityList.contains(entity)) { out.add("Entity (" + entity + ") is missing a afterVariableChanged call for variable (" + variableDescriptor.getVariableName() + ")."); } } beforeVariableChangedEntityList.clear(); afterVariableChangedEntityList.clear(); return out; } public TrackerDemand demand() { return new TrackerDemand(); } /** * In order for the {@link VariableTracker} to be registered as a variable listener, * it needs to be passed to the {@link InnerScoreDirector#getSupplyManager()}, which requires a {@link Demand}. * <p> * Unlike most other {@link Demand}s, there will only be one instance of * {@link VariableTracker} in the {@link InnerScoreDirector} for each variable. */ public class TrackerDemand implements Demand<VariableTracker<Solution_>> { @Override public VariableTracker<Solution_> createExternalizedSupply(SupplyManager supplyManager) { return VariableTracker.this; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/nextprev/AbstractNextPrevElementShadowVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.nextprev; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; abstract class AbstractNextPrevElementShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { protected ListVariableDescriptor<Solution_> sourceVariableDescriptor; protected AbstractNextPrevElementShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } abstract String getSourceVariableName(); abstract String getAnnotationName(); @Override public void processAnnotations(DescriptorPolicy descriptorPolicy) { // Do nothing } @Override public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { linkShadowSources(descriptorPolicy); } private void linkShadowSources(DescriptorPolicy descriptorPolicy) { String sourceVariableName = getSourceVariableName(); List<EntityDescriptor<Solution_>> entitiesWithSourceVariable = entityDescriptor.getSolutionDescriptor().getEntityDescriptors().stream() .filter(entityDescriptor -> entityDescriptor.hasVariableDescriptor(sourceVariableName)) .collect(Collectors.toList()); if (entitiesWithSourceVariable.isEmpty()) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has a @" + getAnnotationName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a valid planning variable on any of the entity classes (" + entityDescriptor.getSolutionDescriptor().getEntityDescriptors() + ")."); } if (entitiesWithSourceVariable.size() > 1) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has a @" + getAnnotationName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a unique planning variable." + " A planning variable with the name (" + sourceVariableName + ") exists on multiple entity classes (" + entitiesWithSourceVariable + ")."); } VariableDescriptor<Solution_> variableDescriptor = entitiesWithSourceVariable.get(0).getVariableDescriptor(sourceVariableName); if (variableDescriptor == null) { throw new IllegalStateException( "Impossible state: variableDescriptor (" + variableDescriptor + ") is null" + " but previous checks indicate that the entityClass (" + entitiesWithSourceVariable.get(0) + ") has a planning variable with sourceVariableName (" + sourceVariableName + ")."); } if (!(variableDescriptor instanceof ListVariableDescriptor)) { throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() + ") has a @" + getAnnotationName() + " annotated property (" + variableMemberAccessor.getName() + ") with sourceVariableName (" + sourceVariableName + ") which is not a @" + PlanningListVariable.class.getSimpleName() + "."); } sourceVariableDescriptor = (ListVariableDescriptor<Solution_>) variableDescriptor; if (!variableMemberAccessor.getType().equals(sourceVariableDescriptor.getElementType())) { throw new IllegalStateException("The entityClass (" + entityDescriptor.getEntityClass() + ") has a @" + getAnnotationName() + " annotated property (" + variableMemberAccessor.getName() + ") of type (" + variableMemberAccessor.getType() + ") which is not the type of elements (" + sourceVariableDescriptor.getElementType() + ") of the source list variable (" + sourceVariableDescriptor + ")."); } sourceVariableDescriptor.registerSinkVariableDescriptor(this); } @Override public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() { return Collections.singletonList(sourceVariableDescriptor); } @Override public Demand<?> getProvidedDemand() { throw new UnsupportedOperationException( "Not implemented because no subsystems demand previous or next shadow variables."); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/nextprev/NextElementShadowVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.nextprev; import java.util.Collection; import java.util.Collections; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class NextElementShadowVariableDescriptor<Solution_> extends AbstractNextPrevElementShadowVariableDescriptor<Solution_> { public NextElementShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } @Override String getSourceVariableName() { return variableMemberAccessor.getAnnotation(NextElementShadowVariable.class).sourceVariableName(); } @Override String getAnnotationName() { return NextElementShadowVariable.class.getSimpleName(); } @Override public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() { return Collections.singleton(NextElementVariableListener.class); } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { return new VariableListenerWithSources<>(new NextElementVariableListener<>(this, sourceVariableDescriptor), sourceVariableDescriptor).toCollection(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/nextprev/NextElementVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.nextprev; import java.util.List; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; 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.score.director.InnerScoreDirector; public class NextElementVariableListener<Solution_> implements ListVariableListener<Solution_, Object, Object> { protected final NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor; protected final ListVariableDescriptor<Solution_> sourceVariableDescriptor; public NextElementVariableListener( NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor, ListVariableDescriptor<Solution_> sourceVariableDescriptor) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); for (int i = 0; i < listVariable.size() - 1; i++) { Object element = listVariable.get(i); Object next = listVariable.get(i + 1); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, next); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); } } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); for (int i = 0; i < listVariable.size() - 1; i++) { Object element = listVariable.get(i); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); } } @Override public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; if (shadowVariableDescriptor.getValue(element) != null) { innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } } @Override public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { // Do nothing } @Override public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); Object next = toIndex < listVariable.size() ? listVariable.get(toIndex) : null; for (int i = toIndex - 1; i >= fromIndex - 1 && i >= 0; i--) { Object element = listVariable.get(i); if (next != shadowVariableDescriptor.getValue(element)) { innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, next); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } next = element; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/nextprev/PreviousElementShadowVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.nextprev; import java.util.Collection; import java.util.Collections; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class PreviousElementShadowVariableDescriptor<Solution_> extends AbstractNextPrevElementShadowVariableDescriptor<Solution_> { public PreviousElementShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } @Override String getSourceVariableName() { return variableMemberAccessor.getAnnotation(PreviousElementShadowVariable.class).sourceVariableName(); } @Override String getAnnotationName() { return PreviousElementShadowVariable.class.getSimpleName(); } @Override public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() { return Collections.singleton(PreviousElementVariableListener.class); } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { return new VariableListenerWithSources<>(new PreviousElementVariableListener<>(this, sourceVariableDescriptor), sourceVariableDescriptor).toCollection(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/nextprev/PreviousElementVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.nextprev; import java.util.List; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; 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.score.director.InnerScoreDirector; public class PreviousElementVariableListener<Solution_> implements ListVariableListener<Solution_, Object, Object> { protected final PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor; protected final ListVariableDescriptor<Solution_> sourceVariableDescriptor; public PreviousElementVariableListener( PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor, ListVariableDescriptor<Solution_> sourceVariableDescriptor) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.sourceVariableDescriptor = sourceVariableDescriptor; } @Override public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); for (int i = 1; i < listVariable.size(); i++) { Object element = listVariable.get(i); Object previous = listVariable.get(i - 1); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, previous); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); } } @Override public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); for (int i = 1; i < listVariable.size(); i++) { Object element = listVariable.get(i); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); } } @Override public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; if (shadowVariableDescriptor.getValue(element) != null) { innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, null); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } } @Override public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { // Do nothing } @Override public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; List<Object> listVariable = sourceVariableDescriptor.getValue(entity); Object previous = fromIndex > 0 ? listVariable.get(fromIndex - 1) : null; for (int i = fromIndex; i <= toIndex && i < listVariable.size(); i++) { Object element = listVariable.get(i); if (previous != shadowVariableDescriptor.getValue(element)) { innerScoreDirector.beforeVariableChanged(shadowVariableDescriptor, element); shadowVariableDescriptor.setValue(element, previous); innerScoreDirector.afterVariableChanged(shadowVariableDescriptor, element); } previous = element; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/DefaultExhaustiveSearchPhase.java
package ai.timefold.solver.core.impl.exhaustivesearch; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.exhaustivesearch.decider.ExhaustiveSearchDecider; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchLayer; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; import ai.timefold.solver.core.impl.exhaustivesearch.node.bounder.ScoreBounder; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchPhaseScope; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchStepScope; 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.phase.AbstractPhase; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.Termination; /** * Default implementation of {@link ExhaustiveSearchPhase}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class DefaultExhaustiveSearchPhase<Solution_> extends AbstractPhase<Solution_> implements ExhaustiveSearchPhase<Solution_> { protected final Comparator<ExhaustiveSearchNode> nodeComparator; protected final EntitySelector<Solution_> entitySelector; protected final ExhaustiveSearchDecider<Solution_> decider; protected final boolean assertWorkingSolutionScoreFromScratch; protected final boolean assertExpectedWorkingSolutionScore; private DefaultExhaustiveSearchPhase(Builder<Solution_> builder) { super(builder); nodeComparator = builder.nodeComparator; entitySelector = builder.entitySelector; decider = builder.decider; assertWorkingSolutionScoreFromScratch = builder.assertWorkingSolutionScoreFromScratch; assertExpectedWorkingSolutionScore = builder.assertExpectedWorkingSolutionScore; } @Override public String getPhaseTypeString() { return "Exhaustive Search"; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void solve(SolverScope<Solution_> solverScope) { SortedSet<ExhaustiveSearchNode> expandableNodeQueue = new TreeSet<>(nodeComparator); ExhaustiveSearchPhaseScope<Solution_> phaseScope = new ExhaustiveSearchPhaseScope<>(solverScope); phaseScope.setExpandableNodeQueue(expandableNodeQueue); phaseStarted(phaseScope); while (!expandableNodeQueue.isEmpty() && !phaseTermination.isPhaseTerminated(phaseScope)) { ExhaustiveSearchStepScope<Solution_> stepScope = new ExhaustiveSearchStepScope<>(phaseScope); ExhaustiveSearchNode node = expandableNodeQueue.last(); expandableNodeQueue.remove(node); stepScope.setExpandingNode(node); stepStarted(stepScope); restoreWorkingSolution(stepScope); decider.expandNode(stepScope); stepEnded(stepScope); phaseScope.setLastCompletedStepScope(stepScope); } phaseEnded(phaseScope); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); entitySelector.solvingStarted(solverScope); decider.solvingStarted(solverScope); } public void phaseStarted(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); entitySelector.phaseStarted(phaseScope); decider.phaseStarted(phaseScope); fillLayerList(phaseScope); initStartNode(phaseScope); } private void fillLayerList(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { ExhaustiveSearchStepScope<Solution_> stepScope = new ExhaustiveSearchStepScope<>(phaseScope); entitySelector.stepStarted(stepScope); long entitySize = entitySelector.getSize(); if (entitySize > Integer.MAX_VALUE) { throw new IllegalStateException("The entitySelector (" + entitySelector + ") has an entitySize (" + entitySize + ") which is higher than Integer.MAX_VALUE."); } List<ExhaustiveSearchLayer> layerList = new ArrayList<>((int) entitySize); int depth = 0; for (Object entity : entitySelector) { ExhaustiveSearchLayer layer = new ExhaustiveSearchLayer(depth, entity); // Keep in sync with ExhaustiveSearchPhaseConfig.buildMoveSelectorConfig() // which includes all genuineVariableDescriptors int reinitializeVariableCount = entitySelector.getEntityDescriptor().countReinitializableVariables(entity); // Ignore entities with only initialized variables to avoid confusing bound decisions if (reinitializeVariableCount == 0) { continue; } depth++; layerList.add(layer); } ExhaustiveSearchLayer lastLayer = new ExhaustiveSearchLayer(depth, null); layerList.add(lastLayer); entitySelector.stepEnded(stepScope); phaseScope.setLayerList(layerList); } private void initStartNode(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { ExhaustiveSearchLayer startLayer = phaseScope.getLayerList().get(0); ExhaustiveSearchNode startNode = new ExhaustiveSearchNode(startLayer, null); if (decider.isScoreBounderEnabled()) { InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector(); Score score = scoreDirector.calculateScore(); startNode.setScore(score); ScoreBounder scoreBounder = decider.getScoreBounder(); phaseScope.setBestPessimisticBound(startLayer.isLastLayer() ? score : scoreBounder.calculatePessimisticBound(scoreDirector, score)); startNode.setOptimisticBound(startLayer.isLastLayer() ? score : scoreBounder.calculateOptimisticBound(scoreDirector, score)); } if (!startLayer.isLastLayer()) { phaseScope.addExpandableNode(startNode); } phaseScope.getLastCompletedStepScope().setExpandingNode(startNode); } public void stepStarted(ExhaustiveSearchStepScope<Solution_> stepScope) { super.stepStarted(stepScope); // Skip entitySelector.stepStarted(stepScope) decider.stepStarted(stepScope); } protected void restoreWorkingSolution(ExhaustiveSearchStepScope<Solution_> stepScope) { ExhaustiveSearchPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope(); ExhaustiveSearchNode oldNode = phaseScope.getLastCompletedStepScope().getExpandingNode(); ExhaustiveSearchNode newNode = stepScope.getExpandingNode(); List<Move<Solution_>> oldMoveList = new ArrayList<>(oldNode.getDepth()); List<Move<Solution_>> newMoveList = new ArrayList<>(newNode.getDepth()); while (oldNode != newNode) { int oldDepth = oldNode.getDepth(); int newDepth = newNode.getDepth(); if (oldDepth < newDepth) { newMoveList.add(newNode.getMove()); newNode = newNode.getParent(); } else { oldMoveList.add(oldNode.getUndoMove()); oldNode = oldNode.getParent(); } } List<Move<Solution_>> restoreMoveList = new ArrayList<>(oldMoveList.size() + newMoveList.size()); restoreMoveList.addAll(oldMoveList); Collections.reverse(newMoveList); restoreMoveList.addAll(newMoveList); InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector(); restoreMoveList.forEach(restoreMove -> restoreMove.doMoveOnly(scoreDirector)); // There is no need to recalculate the score, but we still need to set it phaseScope.getSolutionDescriptor().setScore(phaseScope.getWorkingSolution(), stepScope.getStartingStepScore()); if (assertWorkingSolutionScoreFromScratch) { // In BRUTE_FORCE the stepScore can be null because it was not calculated if (stepScope.getStartingStepScore() != null) { phaseScope.assertPredictedScoreFromScratch(stepScope.getStartingStepScore(), restoreMoveList); } } if (assertExpectedWorkingSolutionScore) { // In BRUTE_FORCE the stepScore can be null because it was not calculated if (stepScope.getStartingStepScore() != null) { phaseScope.assertExpectedWorkingScore(stepScope.getStartingStepScore(), restoreMoveList); } } } public void stepEnded(ExhaustiveSearchStepScope<Solution_> stepScope) { super.stepEnded(stepScope); // Skip entitySelector.stepEnded(stepScope) decider.stepEnded(stepScope); if (logger.isDebugEnabled()) { ExhaustiveSearchPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope(); logger.debug("{} ES step ({}), time spent ({}), treeId ({}), {} best score ({}), selected move count ({}).", logIndentation, stepScope.getStepIndex(), phaseScope.calculateSolverTimeMillisSpentUpToNow(), stepScope.getTreeId(), (stepScope.getBestScoreImproved() ? "new" : " "), phaseScope.getBestScore(), stepScope.getSelectedMoveCount()); } } public void phaseEnded(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); entitySelector.phaseEnded(phaseScope); decider.phaseEnded(phaseScope); phaseScope.endingNow(); logger.info("{}Exhaustive Search phase ({}) ended: time spent ({}), best score ({})," + " score calculation speed ({}/sec), step total ({}).", logIndentation, phaseIndex, phaseScope.calculateSolverTimeMillisSpentUpToNow(), phaseScope.getBestScore(), phaseScope.getPhaseScoreCalculationSpeed(), phaseScope.getNextStepIndex()); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); entitySelector.solvingEnded(solverScope); decider.solvingEnded(solverScope); } public static class Builder<Solution_> extends AbstractPhase.Builder<Solution_> { private final Comparator<ExhaustiveSearchNode> nodeComparator; private final EntitySelector<Solution_> entitySelector; private final ExhaustiveSearchDecider<Solution_> decider; private boolean assertWorkingSolutionScoreFromScratch = false; private boolean assertExpectedWorkingSolutionScore = false; public Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination, Comparator<ExhaustiveSearchNode> nodeComparator, EntitySelector<Solution_> entitySelector, ExhaustiveSearchDecider<Solution_> decider) { super(phaseIndex, logIndentation, phaseTermination); this.nodeComparator = nodeComparator; this.entitySelector = entitySelector; this.decider = decider; } public void setAssertWorkingSolutionScoreFromScratch(boolean assertWorkingSolutionScoreFromScratch) { this.assertWorkingSolutionScoreFromScratch = assertWorkingSolutionScoreFromScratch; } public void setAssertExpectedWorkingSolutionScore(boolean assertExpectedWorkingSolutionScore) { this.assertExpectedWorkingSolutionScore = assertExpectedWorkingSolutionScore; } @Override public DefaultExhaustiveSearchPhase<Solution_> build() { return new DefaultExhaustiveSearchPhase<>(this); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/DefaultExhaustiveSearchPhaseFactory.java
package ai.timefold.solver.core.impl.exhaustivesearch; import static ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType.STEP; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.config.exhaustivesearch.ExhaustiveSearchPhaseConfig; import ai.timefold.solver.core.config.exhaustivesearch.ExhaustiveSearchType; import ai.timefold.solver.core.config.exhaustivesearch.NodeExplorationType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySorterManner; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSorterManner; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.exhaustivesearch.decider.ExhaustiveSearchDecider; import ai.timefold.solver.core.impl.exhaustivesearch.node.bounder.ScoreBounder; import ai.timefold.solver.core.impl.exhaustivesearch.node.bounder.TrendBasedScoreBounder; 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.entity.mimic.ManualEntityMimicRecorder; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelectorFactory; import ai.timefold.solver.core.impl.phase.AbstractPhaseFactory; import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller; import ai.timefold.solver.core.impl.solver.termination.Termination; public class DefaultExhaustiveSearchPhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, ExhaustiveSearchPhaseConfig> { public DefaultExhaustiveSearchPhaseFactory(ExhaustiveSearchPhaseConfig phaseConfig) { super(phaseConfig); } @Override public ExhaustiveSearchPhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) { ExhaustiveSearchType exhaustiveSearchType_ = Objects.requireNonNullElse( phaseConfig.getExhaustiveSearchType(), ExhaustiveSearchType.BRANCH_AND_BOUND); EntitySorterManner entitySorterManner = Objects.requireNonNullElse( phaseConfig.getEntitySorterManner(), exhaustiveSearchType_.getDefaultEntitySorterManner()); ValueSorterManner valueSorterManner = Objects.requireNonNullElse( phaseConfig.getValueSorterManner(), exhaustiveSearchType_.getDefaultValueSorterManner()); HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.cloneBuilder() .withReinitializeVariableFilterEnabled(true) .withInitializedChainedValueFilterEnabled(true) .withEntitySorterManner(entitySorterManner) .withValueSorterManner(valueSorterManner) .build(); Termination<Solution_> phaseTermination = buildPhaseTermination(phaseConfigPolicy, solverTermination); boolean scoreBounderEnabled = exhaustiveSearchType_.isScoreBounderEnabled(); NodeExplorationType nodeExplorationType_; if (exhaustiveSearchType_ == ExhaustiveSearchType.BRUTE_FORCE) { nodeExplorationType_ = Objects.requireNonNullElse(phaseConfig.getNodeExplorationType(), NodeExplorationType.ORIGINAL_ORDER); if (nodeExplorationType_ != NodeExplorationType.ORIGINAL_ORDER) { throw new IllegalArgumentException("The phaseConfig (" + phaseConfig + ") has an nodeExplorationType (" + phaseConfig.getNodeExplorationType() + ") which is not compatible with its exhaustiveSearchType (" + phaseConfig.getExhaustiveSearchType() + ")."); } } else { nodeExplorationType_ = Objects.requireNonNullElse(phaseConfig.getNodeExplorationType(), NodeExplorationType.DEPTH_FIRST); } EntitySelectorConfig entitySelectorConfig_ = buildEntitySelectorConfig(phaseConfigPolicy); EntitySelector<Solution_> entitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig_) .buildEntitySelector(phaseConfigPolicy, SelectionCacheType.PHASE, SelectionOrder.ORIGINAL); DefaultExhaustiveSearchPhase.Builder<Solution_> builder = new DefaultExhaustiveSearchPhase.Builder<>(phaseIndex, solverConfigPolicy.getLogIndentation(), phaseTermination, nodeExplorationType_.buildNodeComparator(scoreBounderEnabled), entitySelector, buildDecider(phaseConfigPolicy, entitySelector, bestSolutionRecaller, phaseTermination, scoreBounderEnabled)); EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode(); if (environmentMode.isNonIntrusiveFullAsserted()) { builder.setAssertWorkingSolutionScoreFromScratch(true); builder.setAssertStepScoreFromScratch(true); // Does nothing because ES doesn't use predictStepScore() } if (environmentMode.isIntrusiveFastAsserted()) { builder.setAssertExpectedWorkingSolutionScore(true); builder.setAssertExpectedStepScore(true); // Does nothing because ES doesn't use predictStepScore() builder.setAssertShadowVariablesAreNotStaleAfterStep(true); // Does nothing because ES doesn't use predictStepScore() } return builder.build(); } private EntitySelectorConfig buildEntitySelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { EntitySelectorConfig entitySelectorConfig_; if (phaseConfig.getEntitySelectorConfig() == null) { EntityDescriptor<Solution_> entityDescriptor = deduceEntityDescriptor(configPolicy.getSolutionDescriptor()); entitySelectorConfig_ = new EntitySelectorConfig() .withEntityClass(entityDescriptor.getEntityClass()); if (EntitySelectorConfig.hasSorter(configPolicy.getEntitySorterManner(), entityDescriptor)) { entitySelectorConfig_ = entitySelectorConfig_.withCacheType(SelectionCacheType.PHASE) .withSelectionOrder(SelectionOrder.SORTED) .withSorterManner(configPolicy.getEntitySorterManner()); } } else { entitySelectorConfig_ = phaseConfig.getEntitySelectorConfig(); } if (entitySelectorConfig_.getCacheType() != null && entitySelectorConfig_.getCacheType().compareTo(SelectionCacheType.PHASE) < 0) { throw new IllegalArgumentException("The phaseConfig (" + phaseConfig + ") cannot have an entitySelectorConfig (" + entitySelectorConfig_ + ") with a cacheType (" + entitySelectorConfig_.getCacheType() + ") lower than " + SelectionCacheType.PHASE + "."); } return entitySelectorConfig_; } protected EntityDescriptor<Solution_> deduceEntityDescriptor(SolutionDescriptor<Solution_> solutionDescriptor) { Collection<EntityDescriptor<Solution_>> entityDescriptors = solutionDescriptor.getGenuineEntityDescriptors(); if (entityDescriptors.size() != 1) { throw new IllegalArgumentException("The phaseConfig (" + phaseConfig + ") has no entitySelector configured" + " and because there are multiple in the entityClassSet (" + solutionDescriptor.getEntityClassSet() + "), it cannot be deduced automatically."); } return entityDescriptors.iterator().next(); } private ExhaustiveSearchDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy, EntitySelector<Solution_> sourceEntitySelector, BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> termination, boolean scoreBounderEnabled) { ManualEntityMimicRecorder<Solution_> manualEntityMimicRecorder = new ManualEntityMimicRecorder<>(sourceEntitySelector); String mimicSelectorId = sourceEntitySelector.getEntityDescriptor().getEntityClass().getName(); // TODO mimicSelectorId must be a field configPolicy.addEntityMimicRecorder(mimicSelectorId, manualEntityMimicRecorder); MoveSelectorConfig<?> moveSelectorConfig_ = buildMoveSelectorConfig(configPolicy, sourceEntitySelector, mimicSelectorId); MoveSelector<Solution_> moveSelector = MoveSelectorFactory.<Solution_> create(moveSelectorConfig_) .buildMoveSelector(configPolicy, SelectionCacheType.JUST_IN_TIME, SelectionOrder.ORIGINAL, false); ScoreBounder scoreBounder = scoreBounderEnabled ? new TrendBasedScoreBounder(configPolicy.getScoreDefinition(), configPolicy.getInitializingScoreTrend()) : null; ExhaustiveSearchDecider<Solution_> decider = new ExhaustiveSearchDecider<>(configPolicy.getLogIndentation(), bestSolutionRecaller, termination, manualEntityMimicRecorder, moveSelector, scoreBounderEnabled, scoreBounder); EnvironmentMode environmentMode = configPolicy.getEnvironmentMode(); if (environmentMode.isNonIntrusiveFullAsserted()) { decider.setAssertMoveScoreFromScratch(true); } if (environmentMode.isIntrusiveFastAsserted()) { decider.setAssertExpectedUndoMoveScore(true); } return decider; } private MoveSelectorConfig<?> buildMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy, EntitySelector<Solution_> entitySelector, String mimicSelectorId) { MoveSelectorConfig<?> moveSelectorConfig_; if (phaseConfig.getMoveSelectorConfig() == null) { EntityDescriptor<Solution_> entityDescriptor = entitySelector.getEntityDescriptor(); // Keep in sync with DefaultExhaustiveSearchPhase.fillLayerList() // which includes all genuineVariableDescriptors List<GenuineVariableDescriptor<Solution_>> variableDescriptorList = entityDescriptor.getGenuineVariableDescriptorList(); if (entityDescriptor.hasAnyGenuineListVariables()) { throw new IllegalArgumentException( "Exhaustive Search does not support list variables (" + variableDescriptorList + ")."); } List<MoveSelectorConfig> subMoveSelectorConfigList = new ArrayList<>(variableDescriptorList.size()); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { ChangeMoveSelectorConfig changeMoveSelectorConfig = new ChangeMoveSelectorConfig(); changeMoveSelectorConfig.setEntitySelectorConfig( EntitySelectorConfig.newMimicSelectorConfig(mimicSelectorId)); ValueSelectorConfig changeValueSelectorConfig = new ValueSelectorConfig() .withVariableName(variableDescriptor.getVariableName()); if (ValueSelectorConfig.hasSorter(configPolicy.getValueSorterManner(), variableDescriptor)) { changeValueSelectorConfig = changeValueSelectorConfig .withCacheType(variableDescriptor.isValueRangeEntityIndependent() ? SelectionCacheType.PHASE : STEP) .withSelectionOrder(SelectionOrder.SORTED) .withSorterManner(configPolicy.getValueSorterManner()); } changeMoveSelectorConfig.setValueSelectorConfig(changeValueSelectorConfig); subMoveSelectorConfigList.add(changeMoveSelectorConfig); } if (subMoveSelectorConfigList.size() > 1) { moveSelectorConfig_ = new CartesianProductMoveSelectorConfig(subMoveSelectorConfigList); } else { moveSelectorConfig_ = subMoveSelectorConfigList.get(0); } } else { moveSelectorConfig_ = phaseConfig.getMoveSelectorConfig(); // TODO Fail fast if it does not include all genuineVariableDescriptors as expected by DefaultExhaustiveSearchPhase.fillLayerList() } return moveSelectorConfig_; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/decider/ExhaustiveSearchDecider.java
package ai.timefold.solver.core.impl.exhaustivesearch.decider; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.exhaustivesearch.event.ExhaustiveSearchPhaseLifecycleListener; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchLayer; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; import ai.timefold.solver.core.impl.exhaustivesearch.node.bounder.ScoreBounder; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchPhaseScope; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchStepScope; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.ManualEntityMimicRecorder; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.Termination; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class ExhaustiveSearchDecider<Solution_> implements ExhaustiveSearchPhaseLifecycleListener<Solution_> { private static final Logger LOGGER = LoggerFactory.getLogger(ExhaustiveSearchDecider.class); private final String logIndentation; private final BestSolutionRecaller<Solution_> bestSolutionRecaller; private final Termination<Solution_> termination; private final ManualEntityMimicRecorder<Solution_> manualEntityMimicRecorder; private final MoveSelector<Solution_> moveSelector; private final boolean scoreBounderEnabled; private final ScoreBounder scoreBounder; private boolean assertMoveScoreFromScratch = false; private boolean assertExpectedUndoMoveScore = false; public ExhaustiveSearchDecider(String logIndentation, BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> termination, ManualEntityMimicRecorder<Solution_> manualEntityMimicRecorder, MoveSelector<Solution_> moveSelector, boolean scoreBounderEnabled, ScoreBounder scoreBounder) { this.logIndentation = logIndentation; this.bestSolutionRecaller = bestSolutionRecaller; this.termination = termination; this.manualEntityMimicRecorder = manualEntityMimicRecorder; this.moveSelector = moveSelector; this.scoreBounderEnabled = scoreBounderEnabled; this.scoreBounder = scoreBounder; } public MoveSelector<Solution_> getMoveSelector() { return moveSelector; } public boolean isScoreBounderEnabled() { return scoreBounderEnabled; } public ScoreBounder getScoreBounder() { return scoreBounder; } public void setAssertMoveScoreFromScratch(boolean assertMoveScoreFromScratch) { this.assertMoveScoreFromScratch = assertMoveScoreFromScratch; } public void setAssertExpectedUndoMoveScore(boolean assertExpectedUndoMoveScore) { this.assertExpectedUndoMoveScore = assertExpectedUndoMoveScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void solvingStarted(SolverScope<Solution_> solverScope) { moveSelector.solvingStarted(solverScope); } @Override public void phaseStarted(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { moveSelector.phaseStarted(phaseScope); } @Override public void stepStarted(ExhaustiveSearchStepScope<Solution_> stepScope) { moveSelector.stepStarted(stepScope); } @Override public void stepEnded(ExhaustiveSearchStepScope<Solution_> stepScope) { moveSelector.stepEnded(stepScope); } @Override public void phaseEnded(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { moveSelector.phaseEnded(phaseScope); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { moveSelector.solvingEnded(solverScope); } public void expandNode(ExhaustiveSearchStepScope<Solution_> stepScope) { ExhaustiveSearchNode expandingNode = stepScope.getExpandingNode(); manualEntityMimicRecorder.setRecordedEntity(expandingNode.getEntity()); int moveIndex = 0; ExhaustiveSearchLayer moveLayer = stepScope.getPhaseScope().getLayerList().get(expandingNode.getDepth() + 1); for (Move<?> move : moveSelector) { ExhaustiveSearchNode moveNode = new ExhaustiveSearchNode(moveLayer, expandingNode); moveIndex++; moveNode.setMove(move); // Do not filter out pointless moves, because the original value of the entity(s) is irrelevant. // If the original value is null and the variable allows unassigned values, // the move to null must be done too. doMove(stepScope, moveNode); // TODO in the lowest level (and only in that level) QuitEarly can be useful // No QuitEarly because lower layers might be promising stepScope.getPhaseScope().getSolverScope().checkYielding(); if (termination.isPhaseTerminated(stepScope.getPhaseScope())) { break; } } stepScope.setSelectedMoveCount((long) moveIndex); } private <Score_ extends Score<Score_>> void doMove(ExhaustiveSearchStepScope<Solution_> stepScope, ExhaustiveSearchNode moveNode) { InnerScoreDirector<Solution_, Score_> scoreDirector = stepScope.getScoreDirector(); // TODO reuse scoreDirector.doAndProcessMove() unless it's an expandableNode Move<Solution_> move = moveNode.getMove(); Move<Solution_> undoMove = move.doMove(scoreDirector); moveNode.setUndoMove(undoMove); processMove(stepScope, moveNode); undoMove.doMoveOnly(scoreDirector); if (assertExpectedUndoMoveScore) { // In BRUTE_FORCE a stepScore can be null because it was not calculated if (stepScope.getStartingStepScore() != null) { scoreDirector.assertExpectedUndoMoveScore(move, (Score_) stepScope.getStartingStepScore()); } } LOGGER.trace("{} Move treeId ({}), score ({}), expandable ({}), move ({}).", logIndentation, moveNode.getTreeId(), moveNode.getScore(), moveNode.isExpandable(), moveNode.getMove()); } private <Score_ extends Score<Score_>> void processMove(ExhaustiveSearchStepScope<Solution_> stepScope, ExhaustiveSearchNode moveNode) { ExhaustiveSearchPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope(); boolean lastLayer = moveNode.isLastLayer(); if (!scoreBounderEnabled) { if (lastLayer) { Score_ score = phaseScope.calculateScore(); moveNode.setScore(score); if (assertMoveScoreFromScratch) { phaseScope.assertWorkingScoreFromScratch(score, moveNode.getMove()); } bestSolutionRecaller.processWorkingSolutionDuringMove(score, stepScope); } else { phaseScope.addExpandableNode(moveNode); } } else { Score_ score = phaseScope.calculateScore(); moveNode.setScore(score); if (assertMoveScoreFromScratch) { phaseScope.assertWorkingScoreFromScratch(score, moveNode.getMove()); } if (lastLayer) { // There is no point in bounding a fully initialized score phaseScope.registerPessimisticBound(score); bestSolutionRecaller.processWorkingSolutionDuringMove(score, stepScope); } else { InnerScoreDirector<Solution_, Score_> scoreDirector = phaseScope.getScoreDirector(); Score_ optimisticBound = (Score_) scoreBounder.calculateOptimisticBound(scoreDirector, score); moveNode.setOptimisticBound(optimisticBound); Score_ bestPessimisticBound = (Score_) phaseScope.getBestPessimisticBound(); if (optimisticBound.compareTo(bestPessimisticBound) > 0) { // It's still worth investigating this node further (no need to prune it) phaseScope.addExpandableNode(moveNode); Score_ pessimisticBound = (Score_) scoreBounder.calculatePessimisticBound(scoreDirector, score); phaseScope.registerPessimisticBound(pessimisticBound); } } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/ExhaustiveSearchNode.java
package ai.timefold.solver.core.impl.exhaustivesearch.node; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.exhaustivesearch.node.bounder.ScoreBounder; import ai.timefold.solver.core.impl.heuristic.move.Move; public class ExhaustiveSearchNode { private final ExhaustiveSearchLayer layer; private final ExhaustiveSearchNode parent; private final long breadth; // The move to get from the parent to this node private Move move; private Move undoMove; private Score score; /** * Never worse than the best possible score a leaf node below this node might lead to. * * @see ScoreBounder#calculateOptimisticBound(ScoreDirector, Score) */ private Score optimisticBound; private boolean expandable = false; public ExhaustiveSearchNode(ExhaustiveSearchLayer layer, ExhaustiveSearchNode parent) { this.layer = layer; this.parent = parent; this.breadth = layer.assignBreadth(); } public ExhaustiveSearchLayer getLayer() { return layer; } public ExhaustiveSearchNode getParent() { return parent; } public long getBreadth() { return breadth; } public Move getMove() { return move; } public void setMove(Move move) { this.move = move; } public Move getUndoMove() { return undoMove; } public void setUndoMove(Move undoMove) { this.undoMove = undoMove; } public Score getScore() { return score; } public void setScore(Score score) { this.score = score; } public Score getOptimisticBound() { return optimisticBound; } public void setOptimisticBound(Score optimisticBound) { this.optimisticBound = optimisticBound; } public boolean isExpandable() { return expandable; } public void setExpandable(boolean expandable) { this.expandable = expandable; } // ************************************************************************ // Calculated methods // ************************************************************************ public int getDepth() { return layer.getDepth(); } public String getTreeId() { return layer.getDepth() + "-" + breadth; } public Object getEntity() { return layer.getEntity(); } public boolean isLastLayer() { return layer.isLastLayer(); } public long getParentBreadth() { return parent == null ? -1 : parent.getBreadth(); } @Override public String toString() { return getTreeId() + " (" + layer.getEntity() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/bounder/ScoreBounder.java
package ai.timefold.solver.core.impl.exhaustivesearch.node.bounder; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public interface ScoreBounder { /** * In OR terms, this is called the lower bound if they minimize, and upper bound if they maximize. * Because we always maximize the {@link Score}, calling it lower bound would be a contradiction. * * @param scoreDirector never null, use {@link ScoreDirector#getWorkingSolution()} to get the working * {@link PlanningSolution} * @param score never null, the {@link Score} of the working {@link PlanningSolution} * @return never null, never worse than the best possible {@link Score} we can get * by initializing the uninitialized variables of the working {@link PlanningSolution}. * @see ScoreDefinition#buildOptimisticBound(InitializingScoreTrend, Score) */ Score calculateOptimisticBound(ScoreDirector scoreDirector, Score score); /** * In OR terms, this is called the upper bound if they minimize, and lower bound if they maximize. * Because we always maximize the {@link Score}, calling it upper bound would be a contradiction. * * @param scoreDirector never null, use {@link ScoreDirector#getWorkingSolution()} to get the working * {@link PlanningSolution} * @param score never null, the {@link Score} of the working {@link PlanningSolution} * @return never null, never better than the worst possible {@link Score} we can get * by initializing the uninitialized variables of the working {@link PlanningSolution}. * @see ScoreDefinition#buildPessimisticBound(InitializingScoreTrend, Score) */ Score calculatePessimisticBound(ScoreDirector scoreDirector, Score score); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/bounder/TrendBasedScoreBounder.java
package ai.timefold.solver.core.impl.exhaustivesearch.node.bounder; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class TrendBasedScoreBounder implements ScoreBounder { protected final ScoreDefinition scoreDefinition; protected final InitializingScoreTrend initializingScoreTrend; public TrendBasedScoreBounder(ScoreDefinition scoreDefinition, InitializingScoreTrend initializingScoreTrend) { this.scoreDefinition = scoreDefinition; this.initializingScoreTrend = initializingScoreTrend; } @Override public Score calculateOptimisticBound(ScoreDirector scoreDirector, Score score) { return scoreDefinition.buildOptimisticBound(initializingScoreTrend, score); } @Override public Score calculatePessimisticBound(ScoreDirector scoreDirector, Score score) { return scoreDefinition.buildPessimisticBound(initializingScoreTrend, score); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/comparator/BreadthFirstNodeComparator.java
package ai.timefold.solver.core.impl.exhaustivesearch.node.comparator; import java.util.Comparator; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; import ai.timefold.solver.core.impl.exhaustivesearch.node.bounder.ScoreBounder; /** * Investigate nodes layer by layer: investigate shallower nodes first. * This results in horrible memory scalability. * <p> * A typical {@link ScoreBounder}'s {@link ScoreBounder#calculateOptimisticBound(ScoreDirector, Score)} * will be weak, which results in horrible performance scalability too. */ public class BreadthFirstNodeComparator implements Comparator<ExhaustiveSearchNode> { private final boolean scoreBounderEnabled; public BreadthFirstNodeComparator(boolean scoreBounderEnabled) { this.scoreBounderEnabled = scoreBounderEnabled; } @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate shallower nodes first int aDepth = a.getDepth(); int bDepth = b.getDepth(); if (aDepth < bDepth) { return 1; } else if (aDepth > bDepth) { return -1; } // Investigate better score first (ignore initScore to avoid depth first ordering) int scoreComparison = a.getScore().withInitScore(0).compareTo(b.getScore().withInitScore(0)); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } if (scoreBounderEnabled) { // Investigate better optimistic bound first int optimisticBoundComparison = a.getOptimisticBound().compareTo(b.getOptimisticBound()); if (optimisticBoundComparison < 0) { return -1; } else if (optimisticBoundComparison > 0) { return 1; } } // No point to investigating higher parent breadth index first (no impact on the churn on workingSolution) // Investigate lower breadth index first (to respect ValueSortingManner) return Long.compare(b.getBreadth(), a.getBreadth()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/comparator/DepthFirstNodeComparator.java
package ai.timefold.solver.core.impl.exhaustivesearch.node.comparator; import java.util.Comparator; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; /** * Investigate deeper nodes first. */ public class DepthFirstNodeComparator implements Comparator<ExhaustiveSearchNode> { private final boolean scoreBounderEnabled; public DepthFirstNodeComparator(boolean scoreBounderEnabled) { this.scoreBounderEnabled = scoreBounderEnabled; } @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate deeper first int aDepth = a.getDepth(); int bDepth = b.getDepth(); if (aDepth < bDepth) { return -1; } else if (aDepth > bDepth) { return 1; } // Investigate better score first (ignore initScore as that's already done by investigate deeper first) int scoreComparison = a.getScore().withInitScore(0).compareTo(b.getScore().withInitScore(0)); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } // Pitfall: score is compared before optimisticBound, because of this mixed ONLY_UP and ONLY_DOWN cases: // - Node a has score 0hard/20medium/-50soft and optimisticBound 0hard/+(infinity)medium/-50soft // - Node b has score 0hard/0medium/0soft and optimisticBound 0hard/+(infinity)medium/0soft // In non-mixed cases, the comparison order is irrelevant. if (scoreBounderEnabled) { // Investigate better optimistic bound first int optimisticBoundComparison = a.getOptimisticBound().compareTo(b.getOptimisticBound()); if (optimisticBoundComparison < 0) { return -1; } else if (optimisticBoundComparison > 0) { return 1; } } // Investigate higher parent breadth index first (to reduce on the churn on workingSolution) long aParentBreadth = a.getParentBreadth(); long bParentBreadth = b.getParentBreadth(); if (aParentBreadth < bParentBreadth) { return -1; } else if (aParentBreadth > bParentBreadth) { return 1; } // Investigate lower breadth index first (to respect ValueSortingManner) return Long.compare(b.getBreadth(), a.getBreadth()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/comparator/OptimisticBoundFirstNodeComparator.java
package ai.timefold.solver.core.impl.exhaustivesearch.node.comparator; import java.util.Comparator; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; /** * Investigate the nodes with a better optimistic bound first, then deeper nodes. */ public class OptimisticBoundFirstNodeComparator implements Comparator<ExhaustiveSearchNode> { public OptimisticBoundFirstNodeComparator(boolean scoreBounderEnabled) { if (!scoreBounderEnabled) { throw new IllegalArgumentException("This " + getClass().getSimpleName() + " only works if scoreBounderEnabled (" + scoreBounderEnabled + ") is true."); } } @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate better optimistic bound first (ignore initScore to avoid depth first ordering) int optimisticBoundComparison = a.getOptimisticBound().compareTo(b.getOptimisticBound()); if (optimisticBoundComparison < 0) { return -1; } else if (optimisticBoundComparison > 0) { return 1; } // Investigate better score first int scoreComparison = a.getScore().withInitScore(0).compareTo(b.getScore().withInitScore(0)); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } // Investigate deeper first int aDepth = a.getDepth(); int bDepth = b.getDepth(); if (aDepth < bDepth) { return -1; } else if (aDepth > bDepth) { return 1; } // Investigate higher parent breadth index first (to reduce on the churn on workingSolution) long aParentBreadth = a.getParentBreadth(); long bParentBreadth = b.getParentBreadth(); if (aParentBreadth < bParentBreadth) { return -1; } else if (aParentBreadth > bParentBreadth) { return 1; } // Investigate lower breadth index first (to respect ValueSortingManner) return Long.compare(b.getBreadth(), a.getBreadth()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/node/comparator/ScoreFirstNodeComparator.java
package ai.timefold.solver.core.impl.exhaustivesearch.node.comparator; import java.util.Comparator; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; /** * Investigate the nodes with a better optimistic bound first, then deeper nodes. */ public class ScoreFirstNodeComparator implements Comparator<ExhaustiveSearchNode> { public ScoreFirstNodeComparator(boolean scoreBounderEnabled) { if (!scoreBounderEnabled) { throw new IllegalArgumentException("This " + getClass().getSimpleName() + " only works if scoreBounderEnabled (" + scoreBounderEnabled + ") is true."); } } @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate better score first (ignore initScore to avoid depth first ordering) int scoreComparison = a.getScore().withInitScore(0).compareTo(b.getScore().withInitScore(0)); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } // Investigate better optimistic bound first int optimisticBoundComparison = a.getOptimisticBound().compareTo(b.getOptimisticBound()); if (optimisticBoundComparison < 0) { return -1; } else if (optimisticBoundComparison > 0) { return 1; } // Investigate deeper first int aDepth = a.getDepth(); int bDepth = b.getDepth(); if (aDepth < bDepth) { return -1; } else if (aDepth > bDepth) { return 1; } // Investigate higher parent breadth index first (to reduce on the churn on workingSolution) long aParentBreadth = a.getParentBreadth(); long bParentBreadth = b.getParentBreadth(); if (aParentBreadth < bParentBreadth) { return -1; } else if (aParentBreadth > bParentBreadth) { return 1; } // Investigate lower breadth index first (to respect ValueSortingManner) return Long.compare(b.getBreadth(), a.getBreadth()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/scope/ExhaustiveSearchPhaseScope.java
package ai.timefold.solver.core.impl.exhaustivesearch.scope; import java.util.List; import java.util.SortedSet; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchLayer; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ExhaustiveSearchPhaseScope<Solution_> extends AbstractPhaseScope<Solution_> { private List<ExhaustiveSearchLayer> layerList; private SortedSet<ExhaustiveSearchNode> expandableNodeQueue; private Score bestPessimisticBound; private ExhaustiveSearchStepScope<Solution_> lastCompletedStepScope; public ExhaustiveSearchPhaseScope(SolverScope<Solution_> solverScope) { super(solverScope); lastCompletedStepScope = new ExhaustiveSearchStepScope<>(this, -1); } public List<ExhaustiveSearchLayer> getLayerList() { return layerList; } public void setLayerList(List<ExhaustiveSearchLayer> layerList) { this.layerList = layerList; } public SortedSet<ExhaustiveSearchNode> getExpandableNodeQueue() { return expandableNodeQueue; } public void setExpandableNodeQueue(SortedSet<ExhaustiveSearchNode> expandableNodeQueue) { this.expandableNodeQueue = expandableNodeQueue; } public Score getBestPessimisticBound() { return bestPessimisticBound; } public void setBestPessimisticBound(Score bestPessimisticBound) { this.bestPessimisticBound = bestPessimisticBound; } @Override public ExhaustiveSearchStepScope<Solution_> getLastCompletedStepScope() { return lastCompletedStepScope; } public void setLastCompletedStepScope(ExhaustiveSearchStepScope<Solution_> lastCompletedStepScope) { this.lastCompletedStepScope = lastCompletedStepScope; } // ************************************************************************ // Calculated methods // ************************************************************************ public int getDepthSize() { return layerList.size(); } public void registerPessimisticBound(Score pessimisticBound) { if (pessimisticBound.compareTo(bestPessimisticBound) > 0) { bestPessimisticBound = pessimisticBound; // Prune the queue // TODO optimize this because expandableNodeQueue is too long to iterate expandableNodeQueue.removeIf(node -> node.getOptimisticBound().compareTo(bestPessimisticBound) <= 0); } } public void addExpandableNode(ExhaustiveSearchNode moveNode) { expandableNodeQueue.add(moveNode); moveNode.setExpandable(true); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/exhaustivesearch/scope/ExhaustiveSearchStepScope.java
package ai.timefold.solver.core.impl.exhaustivesearch.scope; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ExhaustiveSearchStepScope<Solution_> extends AbstractStepScope<Solution_> { private final ExhaustiveSearchPhaseScope<Solution_> phaseScope; private ExhaustiveSearchNode expandingNode; private Long selectedMoveCount = null; public ExhaustiveSearchStepScope(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { this(phaseScope, phaseScope.getNextStepIndex()); } public ExhaustiveSearchStepScope(ExhaustiveSearchPhaseScope<Solution_> phaseScope, int stepIndex) { super(stepIndex); this.phaseScope = phaseScope; } @Override public ExhaustiveSearchPhaseScope<Solution_> getPhaseScope() { return phaseScope; } public ExhaustiveSearchNode getExpandingNode() { return expandingNode; } public void setExpandingNode(ExhaustiveSearchNode expandingNode) { this.expandingNode = expandingNode; } public Score getStartingStepScore() { return expandingNode.getScore(); } public Long getSelectedMoveCount() { return selectedMoveCount; } public void setSelectedMoveCount(Long selectedMoveCount) { this.selectedMoveCount = selectedMoveCount; } // ************************************************************************ // Calculated methods // ************************************************************************ public int getDepth() { return expandingNode.getDepth(); } public String getTreeId() { return expandingNode.getTreeId(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/HeuristicConfigPolicy.java
package ai.timefold.solver.core.impl.heuristic; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.ThreadFactory; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySorterManner; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSorterManner; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.common.nearby.NearbyDistanceMeter; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.EntityMimicRecorder; import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector; import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.SubListMimicRecorder; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.mimic.ValueMimicRecorder; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; import ai.timefold.solver.core.impl.solver.ClassInstanceCache; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import ai.timefold.solver.core.impl.solver.thread.DefaultSolverThreadFactory; public class HeuristicConfigPolicy<Solution_> { private final EnvironmentMode environmentMode; private final String logIndentation; private final Integer moveThreadCount; private final Integer moveThreadBufferSize; private final Class<? extends ThreadFactory> threadFactoryClass; private final InitializingScoreTrend initializingScoreTrend; private final SolutionDescriptor<Solution_> solutionDescriptor; private final EntitySorterManner entitySorterManner; private final ValueSorterManner valueSorterManner; private final ClassInstanceCache classInstanceCache; private final boolean reinitializeVariableFilterEnabled; private final boolean initializedChainedValueFilterEnabled; private final boolean unassignedValuesAllowed; private final Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass; private final Random random; private final Map<String, EntityMimicRecorder<Solution_>> entityMimicRecorderMap = new HashMap<>(); private final Map<String, SubListMimicRecorder<Solution_>> subListMimicRecorderMap = new HashMap<>(); private final Map<String, ValueMimicRecorder<Solution_>> valueMimicRecorderMap = new HashMap<>(); private HeuristicConfigPolicy(Builder<Solution_> builder) { this.environmentMode = builder.environmentMode; this.logIndentation = builder.logIndentation; this.moveThreadCount = builder.moveThreadCount; this.moveThreadBufferSize = builder.moveThreadBufferSize; this.threadFactoryClass = builder.threadFactoryClass; this.initializingScoreTrend = builder.initializingScoreTrend; this.solutionDescriptor = builder.solutionDescriptor; this.entitySorterManner = builder.entitySorterManner; this.valueSorterManner = builder.valueSorterManner; this.classInstanceCache = builder.classInstanceCache; this.reinitializeVariableFilterEnabled = builder.reinitializeVariableFilterEnabled; this.initializedChainedValueFilterEnabled = builder.initializedChainedValueFilterEnabled; this.unassignedValuesAllowed = builder.unassignedValuesAllowed; this.nearbyDistanceMeterClass = builder.nearbyDistanceMeterClass; this.random = builder.random; } public EnvironmentMode getEnvironmentMode() { return environmentMode; } public String getLogIndentation() { return logIndentation; } public Integer getMoveThreadCount() { return moveThreadCount; } public Integer getMoveThreadBufferSize() { return moveThreadBufferSize; } public InitializingScoreTrend getInitializingScoreTrend() { return initializingScoreTrend; } public SolutionDescriptor<Solution_> getSolutionDescriptor() { return solutionDescriptor; } public ScoreDefinition getScoreDefinition() { return solutionDescriptor.getScoreDefinition(); } public EntitySorterManner getEntitySorterManner() { return entitySorterManner; } public ValueSorterManner getValueSorterManner() { return valueSorterManner; } public ClassInstanceCache getClassInstanceCache() { return classInstanceCache; } public boolean isReinitializeVariableFilterEnabled() { return reinitializeVariableFilterEnabled; } public boolean isInitializedChainedValueFilterEnabled() { return initializedChainedValueFilterEnabled; } public boolean isUnassignedValuesAllowed() { return unassignedValuesAllowed; } public Class<? extends NearbyDistanceMeter> getNearbyDistanceMeterClass() { return nearbyDistanceMeterClass; } public Random getRandom() { return random; } // ************************************************************************ // Builder methods // ************************************************************************ public Builder<Solution_> cloneBuilder() { return new Builder<>(environmentMode, moveThreadCount, moveThreadBufferSize, threadFactoryClass, nearbyDistanceMeterClass, random, initializingScoreTrend, solutionDescriptor, classInstanceCache) .withLogIndentation(logIndentation); } public HeuristicConfigPolicy<Solution_> createPhaseConfigPolicy() { return cloneBuilder().build(); } public HeuristicConfigPolicy<Solution_> createChildThreadConfigPolicy(ChildThreadType childThreadType) { return cloneBuilder() .withLogIndentation(logIndentation + " ") .build(); } // ************************************************************************ // Worker methods // ************************************************************************ public void addEntityMimicRecorder(String id, EntityMimicRecorder<Solution_> mimicRecordingEntitySelector) { EntityMimicRecorder<Solution_> put = entityMimicRecorderMap.put(id, mimicRecordingEntitySelector); if (put != null) { throw new IllegalStateException("Multiple " + EntityMimicRecorder.class.getSimpleName() + "s (usually " + EntitySelector.class.getSimpleName() + "s) have the same id (" + id + ").\n" + "Maybe specify a variable name for the mimicking selector in situations with multiple variables on the same entity?"); } } public EntityMimicRecorder<Solution_> getEntityMimicRecorder(String id) { return entityMimicRecorderMap.get(id); } public void addSubListMimicRecorder(String id, SubListMimicRecorder<Solution_> mimicRecordingSubListSelector) { SubListMimicRecorder<Solution_> put = subListMimicRecorderMap.put(id, mimicRecordingSubListSelector); if (put != null) { throw new IllegalStateException("Multiple " + SubListMimicRecorder.class.getSimpleName() + "s (usually " + SubListSelector.class.getSimpleName() + "s) have the same id (" + id + ").\n" + "Maybe specify a variable name for the mimicking selector in situations with multiple variables on the same entity?"); } } public SubListMimicRecorder<Solution_> getSubListMimicRecorder(String id) { return subListMimicRecorderMap.get(id); } public void addValueMimicRecorder(String id, ValueMimicRecorder<Solution_> mimicRecordingValueSelector) { ValueMimicRecorder<Solution_> put = valueMimicRecorderMap.put(id, mimicRecordingValueSelector); if (put != null) { throw new IllegalStateException("Multiple " + ValueMimicRecorder.class.getSimpleName() + "s (usually " + ValueSelector.class.getSimpleName() + "s) have the same id (" + id + ").\n" + "Maybe specify a variable name for the mimicking selector in situations with multiple variables on the same entity?"); } } public ValueMimicRecorder<Solution_> getValueMimicRecorder(String id) { return valueMimicRecorderMap.get(id); } public ThreadFactory buildThreadFactory(ChildThreadType childThreadType) { if (threadFactoryClass != null) { return ConfigUtils.newInstance(this::toString, "threadFactoryClass", threadFactoryClass); } else { String threadPrefix; switch (childThreadType) { case MOVE_THREAD: threadPrefix = "MoveThread"; break; case PART_THREAD: threadPrefix = "PartThread"; break; default: throw new IllegalStateException("Unsupported childThreadType (" + childThreadType + ")."); } return new DefaultSolverThreadFactory(threadPrefix); } } @Override public String toString() { return getClass().getSimpleName() + "(" + environmentMode + ")"; } public static class Builder<Solution_> { private final EnvironmentMode environmentMode; private final Integer moveThreadCount; private final Integer moveThreadBufferSize; private final Class<? extends ThreadFactory> threadFactoryClass; private final InitializingScoreTrend initializingScoreTrend; private final SolutionDescriptor<Solution_> solutionDescriptor; private final ClassInstanceCache classInstanceCache; private String logIndentation = ""; private EntitySorterManner entitySorterManner = EntitySorterManner.NONE; private ValueSorterManner valueSorterManner = ValueSorterManner.NONE; private boolean reinitializeVariableFilterEnabled = false; private boolean initializedChainedValueFilterEnabled = false; private boolean unassignedValuesAllowed = false; private final Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass; private final Random random; public Builder(EnvironmentMode environmentMode, Integer moveThreadCount, Integer moveThreadBufferSize, Class<? extends ThreadFactory> threadFactoryClass, Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass, Random random, InitializingScoreTrend initializingScoreTrend, SolutionDescriptor<Solution_> solutionDescriptor, ClassInstanceCache classInstanceCache) { this.environmentMode = environmentMode; this.moveThreadCount = moveThreadCount; this.moveThreadBufferSize = moveThreadBufferSize; this.threadFactoryClass = threadFactoryClass; this.nearbyDistanceMeterClass = nearbyDistanceMeterClass; this.random = random; this.initializingScoreTrend = initializingScoreTrend; this.solutionDescriptor = solutionDescriptor; this.classInstanceCache = classInstanceCache; } public Builder<Solution_> withLogIndentation(String logIndentation) { this.logIndentation = logIndentation; return this; } public Builder<Solution_> withEntitySorterManner(EntitySorterManner entitySorterManner) { this.entitySorterManner = entitySorterManner; return this; } public Builder<Solution_> withValueSorterManner(ValueSorterManner valueSorterManner) { this.valueSorterManner = valueSorterManner; return this; } public Builder<Solution_> withReinitializeVariableFilterEnabled(boolean reinitializeVariableFilterEnabled) { this.reinitializeVariableFilterEnabled = reinitializeVariableFilterEnabled; return this; } public Builder<Solution_> withInitializedChainedValueFilterEnabled(boolean initializedChainedValueFilterEnabled) { this.initializedChainedValueFilterEnabled = initializedChainedValueFilterEnabled; return this; } public Builder<Solution_> withUnassignedValuesAllowed(boolean unassignedValuesAllowed) { this.unassignedValuesAllowed = unassignedValuesAllowed; return this; } public HeuristicConfigPolicy<Solution_> build() { return new HeuristicConfigPolicy<>(this); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/AbstractMove.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Abstract superclass for {@link Move}, requiring implementation of undo moves. * Unless raw performance is a concern, consider using {@link AbstractSimplifiedMove} instead. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see Move */ public abstract class AbstractMove<Solution_> implements Move<Solution_> { @Override public final Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { var undoMove = createUndoMove(scoreDirector); doMoveOnly(scoreDirector); return undoMove; } @Override public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { doMoveOnGenuineVariables(scoreDirector); scoreDirector.triggerVariableListeners(); } /** * Called before the move is done, so the move can be evaluated and then be undone * without resulting into a permanent change in the solution. * * @param scoreDirector the {@link ScoreDirector} not yet modified by the move. * @return an undoMove which does the exact opposite of this move. */ protected abstract Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector); /** * Like {@link #doMoveOnly(ScoreDirector)} but without the {@link ScoreDirector#triggerVariableListeners()} call * (because {@link #doMoveOnly(ScoreDirector)} already does that). * * @param scoreDirector never null */ protected abstract void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector); // ************************************************************************ // Util methods // ************************************************************************ public static <E> List<E> rebaseList(List<E> externalObjectList, ScoreDirector<?> destinationScoreDirector) { List<E> rebasedObjectList = new ArrayList<>(externalObjectList.size()); for (E entity : externalObjectList) { rebasedObjectList.add(destinationScoreDirector.lookUpWorkingObject(entity)); } return rebasedObjectList; } public static Object[] rebaseArray(Object[] externalObjects, ScoreDirector<?> destinationScoreDirector) { Object[] rebasedObjects = new Object[externalObjects.length]; for (int i = 0; i < externalObjects.length; i++) { rebasedObjects[i] = destinationScoreDirector.lookUpWorkingObject(externalObjects[i]); } return rebasedObjects; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/AbstractSimplifiedMove.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * This is an alternative to {@link AbstractMove}, * allowing to trade some performance for less boilerplate. * This move will record all events that change variables, * and replay them in the undo move, * therefore removing the need to implement the undo move. * * @param <Solution_> */ public abstract class AbstractSimplifiedMove<Solution_> implements Move<Solution_> { @Override public final Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { var recordingScoreDirector = new VariableChangeRecordingScoreDirector<>(scoreDirector); doMoveOnly(recordingScoreDirector); return new RecordedUndoMove<>(recordingScoreDirector.getVariableChanges(), this::toString); } @Override public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { doMoveOnGenuineVariables(scoreDirector); scoreDirector.triggerVariableListeners(); } protected abstract void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector); @Override public String toString() { return getSimpleMoveTypeDescription(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ChangeAction.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; sealed interface ChangeAction<Solution_> permits ListVariableAfterAssignmentAction, ListVariableAfterChangeAction, ListVariableAfterUnassignmentAction, ListVariableBeforeAssignmentAction, ListVariableBeforeChangeAction, ListVariableBeforeUnassignmentAction, VariableChangeAction { void undo(InnerScoreDirector<Solution_, ?> scoreDirector); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/CompositeMove.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * A CompositeMove is composed out of multiple other moves. * <p> * Warning: each of moves in the moveList must not rely on the effect of a previous move in the moveList * to create its undoMove correctly. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see Move */ public final class CompositeMove<Solution_> implements Move<Solution_> { /** * @param moves never null, sometimes empty. Do not modify this argument afterwards or the CompositeMove corrupts. * @return never null */ @SafeVarargs public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(Move_... moves) { return switch (moves.length) { case 0 -> NoChangeMove.getInstance(); case 1 -> moves[0]; default -> new CompositeMove<>(moves); }; } /** * @param moveList never null, sometimes empty * @return never null */ public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(List<Move_> moveList) { return buildMove(moveList.toArray(new Move[0])); } // ************************************************************************ // Non-static members // ************************************************************************ private final Move<Solution_>[] moves; /** * @param moves never null, never empty. Do not modify this argument afterwards or this CompositeMove corrupts. */ @SafeVarargs CompositeMove(Move<Solution_>... moves) { this.moves = moves; } public Move<Solution_>[] getMoves() { return moves; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { for (Move<Solution_> move : moves) { if (move.isMoveDoable(scoreDirector)) { return true; } } return false; } @Override public Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { Move<Solution_>[] undoMoves = new Move[moves.length]; int doableCount = 0; for (Move<Solution_> move : moves) { if (!move.isMoveDoable(scoreDirector)) { continue; } // Calls scoreDirector.triggerVariableListeners() between moves // because a later move can depend on the shadow variables changed by an earlier move Move<Solution_> undoMove = move.doMove(scoreDirector); // Undo in reverse order and each undoMove is created after previous moves have been done undoMoves[moves.length - 1 - doableCount] = undoMove; doableCount++; } if (doableCount < undoMoves.length) { undoMoves = Arrays.copyOfRange(undoMoves, undoMoves.length - doableCount, undoMoves.length); } // No need to call scoreDirector.triggerVariableListeners() because Move.doMove() already does it for every move. return CompositeMove.buildMove(undoMoves); } @Override public void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { for (Move<Solution_> move : moves) { if (!move.isMoveDoable(scoreDirector)) { continue; } // Calls scoreDirector.triggerVariableListeners() between moves // because a later move can depend on the shadow variables changed by an earlier move move.doMoveOnly(scoreDirector); } } @Override public CompositeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { Move<Solution_>[] rebasedMoves = new Move[moves.length]; for (int i = 0; i < moves.length; i++) { rebasedMoves[i] = moves[i].rebase(destinationScoreDirector); } return new CompositeMove<>(rebasedMoves); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + Arrays.stream(moves) .map(Move::getSimpleMoveTypeDescription) .sorted() .map(childMoveTypeDescription -> "* " + childMoveTypeDescription) .collect(Collectors.joining(",", "(", ")")); } @Override public Collection<?> getPlanningEntities() { Set<Object> entities = CollectionUtils.newLinkedHashSet(moves.length * 2); for (Move<Solution_> move : moves) { entities.addAll(move.getPlanningEntities()); } return entities; } @Override public Collection<?> getPlanningValues() { Set<Object> values = CollectionUtils.newLinkedHashSet(moves.length * 2); for (Move<Solution_> move : moves) { values.addAll(move.getPlanningValues()); } return values; } @Override public boolean equals(Object other) { return other instanceof CompositeMove<?> otherCompositeMove && Arrays.equals(moves, otherCompositeMove.moves); } @Override public int hashCode() { return Arrays.hashCode(moves); } @Override public String toString() { return Arrays.toString(moves); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ListVariableAfterAssignmentAction.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class ListVariableAfterAssignmentAction<Solution_> implements ChangeAction<Solution_> { private final Object element; private final ListVariableDescriptor<Solution_> variableDescriptor; ListVariableAfterAssignmentAction(Object element, ListVariableDescriptor<Solution_> variableDescriptor) { this.element = element; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { scoreDirector.beforeListVariableElementUnassigned(variableDescriptor, element); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ListVariableAfterChangeAction.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.List; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class ListVariableAfterChangeAction<Solution_, Entity_, Value_> implements ChangeAction<Solution_> { private final Entity_ entity; private final int fromIndex; private final int toIndex; private final ListVariableDescriptor<Solution_> variableDescriptor; ListVariableAfterChangeAction(Entity_ entity, int fromIndex, int toIndex, ListVariableDescriptor<Solution_> variableDescriptor) { this.entity = entity; this.fromIndex = fromIndex; this.toIndex = toIndex; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { scoreDirector.beforeListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); @SuppressWarnings("unchecked") var items = (List<Value_>) variableDescriptor.getValue(entity).subList(fromIndex, toIndex); items.clear(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ListVariableAfterUnassignmentAction.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class ListVariableAfterUnassignmentAction<Solution_> implements ChangeAction<Solution_> { private final Object element; private final ListVariableDescriptor<Solution_> variableDescriptor; ListVariableAfterUnassignmentAction(Object element, ListVariableDescriptor<Solution_> variableDescriptor) { this.element = element; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { scoreDirector.beforeListVariableElementAssigned(variableDescriptor, element); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ListVariableBeforeAssignmentAction.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class ListVariableBeforeAssignmentAction<Solution_> implements ChangeAction<Solution_> { private final Object element; private final ListVariableDescriptor<Solution_> variableDescriptor; ListVariableBeforeAssignmentAction(Object element, ListVariableDescriptor<Solution_> variableDescriptor) { this.element = element; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { scoreDirector.afterListVariableElementUnassigned(variableDescriptor, element); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ListVariableBeforeChangeAction.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.List; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class ListVariableBeforeChangeAction<Solution_, Entity_, Value_> implements ChangeAction<Solution_> { private final Entity_ entity; private final List<Value_> oldValue; private final int fromIndex; private final int toIndex; private final ListVariableDescriptor<Solution_> variableDescriptor; ListVariableBeforeChangeAction(Entity_ entity, List<Value_> oldValue, int fromIndex, int toIndex, ListVariableDescriptor<Solution_> variableDescriptor) { this.entity = entity; this.oldValue = oldValue; this.fromIndex = fromIndex; this.toIndex = toIndex; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { variableDescriptor.getValue(entity).addAll(fromIndex, oldValue); scoreDirector.afterListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); // List variable listeners get confused if there are two pairs of before/after calls // before variable listeners are triggered scoreDirector.triggerVariableListeners(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/ListVariableBeforeUnassignmentAction.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class ListVariableBeforeUnassignmentAction<Solution_> implements ChangeAction<Solution_> { private final Object element; private final ListVariableDescriptor<Solution_> variableDescriptor; ListVariableBeforeUnassignmentAction(Object element, ListVariableDescriptor<Solution_> variableDescriptor) { this.element = element; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { scoreDirector.afterListVariableElementAssigned(variableDescriptor, element); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/Move.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.lookup.PlanningId; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.config.localsearch.decider.acceptor.AcceptorType; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.factory.MoveListFactory; import ai.timefold.solver.core.impl.localsearch.decider.acceptor.tabu.MoveTabuAcceptor; /** * A Move represents a change of 1 or more {@link PlanningVariable}s of 1 or more {@link PlanningEntity}s * in the working {@link PlanningSolution}. * <p> * Usually the move holds a direct reference to each {@link PlanningEntity} of the {@link PlanningSolution} * which it will change when {@link #doMove(ScoreDirector)} is called. * On that change it should also notify the {@link ScoreDirector} accordingly. * <p> * A Move should implement {@link Object#equals(Object)} and {@link Object#hashCode()} for {@link MoveTabuAcceptor}. * <p> * An implementation must extend {@link AbstractMove} to ensure backwards compatibility in future versions. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see AbstractMove */ public interface Move<Solution_> { /** * Called before a move is evaluated to decide whether the move can be done and evaluated. * A Move is not doable if: * <ul> * <li>Either doing it would change nothing in the {@link PlanningSolution}.</li> * <li>Either it's simply not possible to do (for example due to built-in hard constraints).</li> * </ul> * <p> * It is recommended to keep this method implementation simple: do not use it in an attempt to satisfy normal * hard and soft constraints. * <p> * Although you could also filter out non-doable moves in for example the {@link MoveSelector} * or {@link MoveListFactory}, this is not needed as the {@link Solver} will do it for you. * * @param scoreDirector the {@link ScoreDirector} not yet modified by the move. * @return true if the move achieves a change in the solution and the move is possible to do on the solution. */ boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector); /** * Does the move (which indirectly affects the {@link ScoreDirector#getWorkingSolution()}). * When the {@link PlanningSolution working solution} is modified, the {@link ScoreDirector} must be correctly notified * (through {@link ScoreDirector#beforeVariableChanged(Object, String)} and * {@link ScoreDirector#afterVariableChanged(Object, String)}), * otherwise later calculated {@link Score}s will be corrupted. * <p> * This method must end with calling {@link ScoreDirector#triggerVariableListeners()} to ensure all shadow variables are * updated. * <p> * This method must return an undo move, so the move can be evaluated and then be undone * without resulting into a permanent change in the solution. * * @param scoreDirector never null, the {@link ScoreDirector} that needs to get notified of the changes * @return an undoMove which does the exact opposite of this move */ Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector); /** * As defined by {@link #doMove(ScoreDirector)}, but does not return an undo move. * * @param scoreDirector never null, the {@link ScoreDirector} that needs to get notified of the changes */ default void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { // For backwards compatibility, this method is default and calls doMove(...). // Normally, the relationship is inversed, as implemented in AbstractMove. doMove(scoreDirector); } /** * Rebases a move from an origin {@link ScoreDirector} to another destination {@link ScoreDirector} * which is usually on another {@link Thread} or JVM. * The new move returned by this method translates the entities and problem facts * to the destination {@link PlanningSolution} of the destination {@link ScoreDirector}, * That destination {@link PlanningSolution} is a deep planning clone (or an even deeper clone) * of the origin {@link PlanningSolution} that this move has been generated from. * <p> * That new move does the exact same change as this move, * resulting in the same {@link PlanningSolution} state, * presuming that destination {@link PlanningSolution} was in the same state * as the original {@link PlanningSolution} to begin with. * <p> * Generally speaking, an implementation of this method iterates through every entity and fact instance in this move, * translates each one to the destination {@link ScoreDirector} with {@link ScoreDirector#lookUpWorkingObject(Object)} * and creates a new move instance of the same move type, using those translated instances. * <p> * The destination {@link PlanningSolution} can be in a different state than the original {@link PlanningSolution}. * So, rebasing can only depend on the identity of {@link PlanningEntity planning entities} and planning facts, * which is usually declared by a {@link PlanningId} on those classes. * It must not depend on the state of the {@link PlanningVariable planning variables}. * One thread might rebase a move before, amid or after another thread does that same move instance. * <p> * This method is thread-safe. * * @param destinationScoreDirector never null, the {@link ScoreDirector#getWorkingSolution()} * that the new move should change the planning entity instances of. * @return never null, a new move that does the same change as this move on another solution instance */ default Move<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { throw new UnsupportedOperationException( "Move class (%s) doesn't implement the rebase() method, so multithreaded solving is impossible." .formatted(getClass())); } // ************************************************************************ // Introspection methods // ************************************************************************ /** * Describes the move type for statistical purposes. * For example "ChangeMove(Process.computer)". * <p> * The format is not formalized. Never parse the {@link String} returned by this method. * * @return never null */ default String getSimpleMoveTypeDescription() { return getClass().getSimpleName(); } /** * Returns all planning entities that are being changed by this move. * Required for {@link AcceptorType#ENTITY_TABU}. * <p> * This method is only called after {@link #doMove(ScoreDirector)} (which might affect the return values). * <p> * Duplicate entries in the returned {@link Collection} are best avoided. * The returned {@link Collection} is recommended to be in a stable order. * For example: use {@link List} or {@link LinkedHashSet}, but not {@link HashSet}. * * @return never null */ default Collection<? extends Object> getPlanningEntities() { throw new UnsupportedOperationException( "Move class (%s) doesn't implement the getPlanningEntities() method, so Entity Tabu Search is impossible." .formatted(getClass())); } /** * Returns all planning values that entities are being assigned to by this move. * Required for {@link AcceptorType#VALUE_TABU}. * <p> * This method is only called after {@link #doMove(ScoreDirector)} (which might affect the return values). * <p> * Duplicate entries in the returned {@link Collection} are best avoided. * The returned {@link Collection} is recommended to be in a stable order. * For example: use {@link List} or {@link LinkedHashSet}, but not {@link HashSet}. * * @return never null */ default Collection<? extends Object> getPlanningValues() { throw new UnsupportedOperationException( "Move class (%s) doesn't implement the getPlanningEntities() method, so Value Tabu Search is impossible." .formatted(getClass())); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/NoChangeMove.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Makes no changes. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class NoChangeMove<Solution_> extends AbstractSimplifiedMove<Solution_> { public static final NoChangeMove<?> INSTANCE = new NoChangeMove<>(); public static <Solution_> NoChangeMove<Solution_> getInstance() { return (NoChangeMove<Solution_>) INSTANCE; } private NoChangeMove() { // No external instances allowed. } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return false; } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { // Do nothing. } @Override public Move<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return (Move<Solution_>) INSTANCE; } @Override public String getSimpleMoveTypeDescription() { return "No change"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/RecordedUndoMove.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.List; import java.util.function.Supplier; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class RecordedUndoMove<Solution_> implements Move<Solution_> { private final List<ChangeAction<Solution_>> changeActions; private final Supplier<String> sourceToString; RecordedUndoMove(List<ChangeAction<Solution_>> changeActions, Supplier<String> sourceToString) { this.changeActions = changeActions; this.sourceToString = sourceToString; } @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return true; } @Override public Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { doMoveOnly(scoreDirector); return null; } @Override public void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; for (int i = changeActions.size() - 1; i >= 0; i--) { // Iterate in reverse. var changeAction = changeActions.get(i); changeAction.undo(innerScoreDirector); } scoreDirector.triggerVariableListeners(); } @Override public String getSimpleMoveTypeDescription() { return "Undo(" + sourceToString.get() + ")"; } @Override public String toString() { return getSimpleMoveTypeDescription(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/VariableChangeAction.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; final class VariableChangeAction<Solution_, Entity_, Value_> implements ChangeAction<Solution_> { private final Entity_ entity; private final Value_ oldValue; private final VariableDescriptor<Solution_> variableDescriptor; VariableChangeAction(Entity_ entity, Value_ oldValue, VariableDescriptor<Solution_> variableDescriptor) { this.entity = entity; this.oldValue = oldValue; this.variableDescriptor = variableDescriptor; } @Override public void undo(InnerScoreDirector<Solution_, ?> scoreDirector) { scoreDirector.beforeVariableChanged(variableDescriptor, entity); variableDescriptor.setValue(entity, oldValue); scoreDirector.afterVariableChanged(variableDescriptor, entity); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/move/VariableChangeRecordingScoreDirector.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; 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.score.director.AbstractScoreDirector; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; import ai.timefold.solver.core.impl.score.director.VariableDescriptorCache; final class VariableChangeRecordingScoreDirector<Solution_> implements VariableDescriptorAwareScoreDirector<Solution_> { private final AbstractScoreDirector<Solution_, ?, ?> delegate; private final List<ChangeAction<Solution_>> variableChanges; /* * The fromIndex of afterListVariableChanged must match the fromIndex of its beforeListVariableChanged call. * Otherwise this will happen in the undo move: * * // beforeListVariableChanged(0, 3); * [1, 2, 3, 4] * change * [1, 2, 3] * // afterListVariableChanged(2, 3) * // Start Undo * // Undo afterListVariableChanged(2, 3) * [1, 2, 3] -> [1, 2] * // Undo beforeListVariableChanged(0, 3); * [1, 2, 3, 4, 1, 2] * * This map exists to ensure that this is the case. */ private final Map<Object, Integer> cache = new IdentityHashMap<>(); VariableChangeRecordingScoreDirector(ScoreDirector<Solution_> delegate) { this.delegate = (AbstractScoreDirector<Solution_, ?, ?>) delegate; this.variableChanges = new ArrayList<>(); } public List<ChangeAction<Solution_>> getVariableChanges() { return variableChanges; } // For variable change operations, record the change then call the delegate @Override public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { variableChanges.add(new VariableChangeAction<>(entity, variableDescriptor.getValue(entity), variableDescriptor)); delegate.beforeVariableChanged(variableDescriptor, entity); } @Override public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { delegate.afterVariableChanged(variableDescriptor, entity); } @Override public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { // List is fromIndex, fromIndex, since the undo action for afterListVariableChange will clear the affected list cache.put(entity, fromIndex); variableChanges.add(new ListVariableBeforeChangeAction<>(entity, new ArrayList<>(variableDescriptor.getValue(entity).subList(fromIndex, toIndex)), fromIndex, toIndex, variableDescriptor)); delegate.beforeListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); } @Override public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { Integer requiredFromIndex = cache.remove(entity); if (requiredFromIndex != fromIndex) { throw new IllegalArgumentException( """ The fromIndex of afterListVariableChanged (%d) must match the fromIndex of its beforeListVariableChanged counterpart (%d). Maybe check implementation of your %s.""" .formatted(fromIndex, requiredFromIndex, AbstractSimplifiedMove.class.getSimpleName())); } variableChanges.add(new ListVariableAfterChangeAction<>(entity, fromIndex, toIndex, variableDescriptor)); delegate.afterListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); } @Override public void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { variableChanges.add(new ListVariableBeforeAssignmentAction<>(element, variableDescriptor)); delegate.beforeListVariableElementAssigned(variableDescriptor, element); } @Override public void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { variableChanges.add(new ListVariableAfterAssignmentAction<>(element, variableDescriptor)); delegate.afterListVariableElementAssigned(variableDescriptor, element); } @Override public void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { variableChanges.add(new ListVariableBeforeUnassignmentAction<>(element, variableDescriptor)); delegate.beforeListVariableElementUnassigned(variableDescriptor, element); } @Override public void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { variableChanges.add(new ListVariableAfterUnassignmentAction<>(element, variableDescriptor)); delegate.afterListVariableElementUnassigned(variableDescriptor, element); } // For other operations, call the delegate's method. @Override public SolutionDescriptor<Solution_> getSolutionDescriptor() { return delegate.getSolutionDescriptor(); } @Override public Solution_ getWorkingSolution() { return delegate.getWorkingSolution(); } @Override public VariableDescriptorCache<Solution_> getVariableDescriptorCache() { return delegate.getVariableDescriptorCache(); } @Override public void triggerVariableListeners() { delegate.triggerVariableListeners(); } @Override public <E> E lookUpWorkingObject(E externalObject) { return delegate.lookUpWorkingObject(externalObject); } @Override public <E> E lookUpWorkingObjectOrReturnNull(E externalObject) { return delegate.lookUpWorkingObjectOrReturnNull(externalObject); } @Override public void changeVariableFacade(VariableDescriptor<Solution_> variableDescriptor, Object entity, Object newValue) { delegate.changeVariableFacade(variableDescriptor, entity, newValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/common
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/common/decorator/SelectionFilter.java
package ai.timefold.solver.core.impl.heuristic.selector.common.decorator; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.Selector; /** * Decides on accepting or discarding a selection, * which is either a {@link PlanningEntity}, a planning value, a {@link Move} or a {@link Selector}). * For example, a pinned {@link PlanningEntity} is rejected and therefore never used in a {@link Move}. * <p> * A filtered selection is considered as not selected, it does not count as an unaccepted selection. * * <p> * Implementations are expected to be stateless. * The solver may choose to reuse instances. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <T> the selection type. * On problems using multiple planning variables on a single entity without specifying single variable name, * this needs to be {@link Object} as variables of both types will be tested. */ @FunctionalInterface public interface SelectionFilter<Solution_, T> { /** * Creates a {@link SelectionFilter} which applies all the provided filters one after another. * Once one filter in the sequence returns false, no subsequent filers are evaluated. * * @param filterArray filters to apply, never null * @return never null * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <T> the selection type */ static <Solution_, T> SelectionFilter<Solution_, T> compose(SelectionFilter<Solution_, T>... filterArray) { return compose(Arrays.asList(filterArray)); } /** * As defined by {@link #compose(SelectionFilter[])}. */ static <Solution_, T> SelectionFilter<Solution_, T> compose(List<SelectionFilter<Solution_, T>> filterList) { return switch (filterList.size()) { case 0 -> CompositeSelectionFilter.NOOP; case 1 -> filterList.get(0); default -> { var distinctFilterArray = filterList.stream() .flatMap(filter -> { if (filter == CompositeSelectionFilter.NOOP) { return Stream.empty(); } else if (filter instanceof CompositeSelectionFilter<Solution_, T> compositeSelectionFilter) { // Decompose composites if necessary; avoids needless recursion. return Arrays.stream(compositeSelectionFilter.selectionFilterArray()); } else { return Stream.of(filter); } }) .distinct() .toArray(SelectionFilter[]::new); yield switch (distinctFilterArray.length) { case 0 -> CompositeSelectionFilter.NOOP; case 1 -> distinctFilterArray[0]; default -> new CompositeSelectionFilter<>(distinctFilterArray); }; } }; } /** * @param scoreDirector never null, the {@link ScoreDirector} * which has the {@link ScoreDirector#getWorkingSolution()} to which the selection belongs or applies to * @param selection never null, a {@link PlanningEntity}, a planningValue, a {@link Move} or a {@link Selector} * @return true if the selection is accepted (for example it is movable), * false if the selection will be discarded (for example it is pinned) */ boolean accept(ScoreDirector<Solution_> scoreDirector, T selection); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/common
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/AbstractOriginalSwapIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.common.iterator; import java.util.Collections; import java.util.ListIterator; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.ListIterableSelector; public abstract class AbstractOriginalSwapIterator<Solution_, Move_ extends Move<Solution_>, SubSelection_> extends UpcomingSelectionIterator<Move_> { public static <Solution_, SubSelection_> long getSize(ListIterableSelector<Solution_, SubSelection_> leftSubSelector, ListIterableSelector<Solution_, SubSelection_> rightSubSelector) { if (leftSubSelector != rightSubSelector) { return leftSubSelector.getSize() * rightSubSelector.getSize(); } else { long leftSize = leftSubSelector.getSize(); return leftSize * (leftSize - 1L) / 2L; } } protected final ListIterable<SubSelection_> leftSubSelector; protected final ListIterable<SubSelection_> rightSubSelector; protected final boolean leftEqualsRight; private final ListIterator<SubSelection_> leftSubSelectionIterator; private ListIterator<SubSelection_> rightSubSelectionIterator; private SubSelection_ leftSubSelection; public AbstractOriginalSwapIterator(ListIterable<SubSelection_> leftSubSelector, ListIterable<SubSelection_> rightSubSelector) { this.leftSubSelector = leftSubSelector; this.rightSubSelector = rightSubSelector; leftEqualsRight = (leftSubSelector == rightSubSelector); leftSubSelectionIterator = leftSubSelector.listIterator(); rightSubSelectionIterator = Collections.<SubSelection_> emptyList().listIterator(); // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording) } @Override protected Move_ createUpcomingSelection() { if (!rightSubSelectionIterator.hasNext()) { if (!leftSubSelectionIterator.hasNext()) { return noUpcomingSelection(); } leftSubSelection = leftSubSelectionIterator.next(); if (!leftEqualsRight) { rightSubSelectionIterator = rightSubSelector.listIterator(); if (!rightSubSelectionIterator.hasNext()) { return noUpcomingSelection(); } } else { // Select A-B, A-C, B-C. Do not select B-A, C-A, C-B. Do not select A-A, B-B, C-C. if (!leftSubSelectionIterator.hasNext()) { return noUpcomingSelection(); } rightSubSelectionIterator = rightSubSelector.listIterator(leftSubSelectionIterator.nextIndex()); // rightEntityIterator's first hasNext() always returns true because of the nextIndex() } } SubSelection_ rightSubSelection = rightSubSelectionIterator.next(); return newSwapSelection(leftSubSelection, rightSubSelection); } protected abstract Move_ newSwapSelection(SubSelection_ leftSubSelection, SubSelection_ rightSubSelection); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/common
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/common/iterator/UpcomingSelectionIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.common.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.Selector; import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.MimicReplayingEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation; import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList; /** * IMPORTANT: The constructor of any subclass of this abstract class, should never call any of its child * {@link Selector}'s {@link Iterator#hasNext()} or {@link Iterator#next()} methods, * because that can cause descendant {@link Selector}s to be selected too early * (which breaks {@link MimicReplayingEntitySelector}). * * @param <S> Selection type, for example a {@link Move} class, an entity class or a value class. */ public abstract class UpcomingSelectionIterator<S> extends SelectionIterator<S> { protected boolean upcomingCreated = false; protected boolean hasUpcomingSelection = true; protected S upcomingSelection; @Override public boolean hasNext() { if (!upcomingCreated) { upcomingSelection = createUpcomingSelection(); upcomingCreated = true; } return hasUpcomingSelection; } @Override public S next() { if (!hasUpcomingSelection) { throw new NoSuchElementException(); } if (!upcomingCreated) { upcomingSelection = createUpcomingSelection(); } upcomingCreated = false; return upcomingSelection; } protected abstract S createUpcomingSelection(); protected S noUpcomingSelection() { hasUpcomingSelection = false; return null; } @Override public String toString() { if (!upcomingCreated) { return "Next upcoming (?)"; } else if (!hasUpcomingSelection) { return "No next upcoming"; } else { return "Next upcoming (" + upcomingSelection + ")"; } } /** * Some destination iterators, such as nearby destination iterators, may return even elements which are pinned. * This is because the nearby matrix always picks from all nearby elements, and is unaware of any pinning. * This means that later we need to filter out the pinned elements, so that moves aren't generated for them. * * @param destinationIterator never null * @param listVariableDescriptor never null * @return null if no unpinned destination was found, at which point the iterator is exhausted. */ public static ElementLocation findUnpinnedDestination(Iterator<ElementLocation> destinationIterator, ListVariableDescriptor<?> listVariableDescriptor) { while (destinationIterator.hasNext()) { var destination = destinationIterator.next(); if (destination instanceof LocationInList locationInList) { var isPinned = listVariableDescriptor.isElementPinned(null, locationInList.entity(), locationInList.index()); if (!isPinned) { return destination; } } else { // Unassigned location can not be pinned. return destination; } } return null; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity/EntitySelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.entity; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder; import ai.timefold.solver.core.config.heuristic.selector.common.nearby.NearbySelectionConfig; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.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.decorator.CachingEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.FilteringEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.ProbabilityEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.SelectedCountLimitEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.ShufflingEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.SortingEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.EntityMimicRecorder; import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.MimicRecordingEntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.mimic.MimicReplayingEntitySelector; import ai.timefold.solver.core.impl.solver.ClassInstanceCache; public class EntitySelectorFactory<Solution_> extends AbstractSelectorFactory<Solution_, EntitySelectorConfig> { public static <Solution_> EntitySelectorFactory<Solution_> create(EntitySelectorConfig entitySelectorConfig) { return new EntitySelectorFactory<>(entitySelectorConfig); } public EntitySelectorFactory(EntitySelectorConfig entitySelectorConfig) { super(entitySelectorConfig); } public EntityDescriptor<Solution_> extractEntityDescriptor(HeuristicConfigPolicy<Solution_> configPolicy) { if (config.getEntityClass() != null) { SolutionDescriptor<Solution_> solutionDescriptor = configPolicy.getSolutionDescriptor(); EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(config.getEntityClass()); if (entityDescriptor == null) { throw new IllegalArgumentException("The selectorConfig (" + config + ") has an entityClass (" + config.getEntityClass() + ") that is not a known planning entity.\n" + "Check your solver configuration. If that class (" + config.getEntityClass().getSimpleName() + ") is not in the entityClassSet (" + solutionDescriptor.getEntityClassSet() + "), check your @" + PlanningSolution.class.getSimpleName() + " implementation's annotated methods too."); } return entityDescriptor; } else if (config.getMimicSelectorRef() != null) { return configPolicy.getEntityMimicRecorder(config.getMimicSelectorRef()).getEntityDescriptor(); } else { return null; } } /** * @param configPolicy never null * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching * and less would be pointless. * @param inheritedSelectionOrder never null * @return never null */ public EntitySelector<Solution_> buildEntitySelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { if (config.getMimicSelectorRef() != null) { return buildMimicReplaying(configPolicy); } EntityDescriptor<Solution_> entityDescriptor = deduceEntityDescriptor(configPolicy, config.getEntityClass()); SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(config.getCacheType(), minimumCacheType); SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(config.getSelectionOrder(), inheritedSelectionOrder); if (config.getNearbySelectionConfig() != null) { config.getNearbySelectionConfig().validateNearby(resolvedCacheType, resolvedSelectionOrder); } validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder); validateSorting(resolvedSelectionOrder); validateProbability(resolvedSelectionOrder); validateSelectedLimit(minimumCacheType); // baseEntitySelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely boolean baseRandomSelection = determineBaseRandomSelection(entityDescriptor, resolvedCacheType, resolvedSelectionOrder); SelectionCacheType baseSelectionCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType); EntitySelector<Solution_> entitySelector = buildBaseEntitySelector(entityDescriptor, baseSelectionCacheType, baseRandomSelection); if (config.getNearbySelectionConfig() != null) { // TODO Static filtering (such as movableEntitySelectionFilter) should affect nearbySelection entitySelector = applyNearbySelection(configPolicy, config.getNearbySelectionConfig(), minimumCacheType, resolvedSelectionOrder, entitySelector); } ClassInstanceCache instanceCache = configPolicy.getClassInstanceCache(); entitySelector = applyFiltering(entitySelector, instanceCache); entitySelector = applySorting(resolvedCacheType, resolvedSelectionOrder, entitySelector, instanceCache); entitySelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, entitySelector, instanceCache); entitySelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, entitySelector); entitySelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, entitySelector); entitySelector = applySelectedLimit(resolvedSelectionOrder, entitySelector); entitySelector = applyMimicRecording(configPolicy, entitySelector); return entitySelector; } protected EntitySelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy) { final boolean anyConfigurationParameterDefined = Stream .of(config.getId(), config.getEntityClass(), config.getCacheType(), config.getSelectionOrder(), config.getNearbySelectionConfig(), config.getFilterClass(), config.getSorterManner(), config.getSorterComparatorClass(), config.getSorterWeightFactoryClass(), config.getSorterOrder(), config.getSorterClass(), config.getProbabilityWeightFactoryClass(), config.getSelectedCountLimit()) .anyMatch(Objects::nonNull); if (anyConfigurationParameterDefined) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with mimicSelectorRef (" + config.getMimicSelectorRef() + ") has another property that is not null."); } EntityMimicRecorder<Solution_> entityMimicRecorder = configPolicy.getEntityMimicRecorder(config.getMimicSelectorRef()); if (entityMimicRecorder == null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has a mimicSelectorRef (" + config.getMimicSelectorRef() + ") for which no entitySelector with that id exists (in its solver phase)."); } return new MimicReplayingEntitySelector<>(entityMimicRecorder); } protected boolean determineBaseRandomSelection(EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { switch (resolvedSelectionOrder) { case ORIGINAL: return false; case SORTED: case SHUFFLED: case PROBABILISTIC: // baseValueSelector and lower should be ORIGINAL if they are going to get cached completely return false; case RANDOM: // Predict if caching will occur return resolvedCacheType.isNotCached() || (isBaseInherentlyCached() && !hasFiltering(entityDescriptor)); default: throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder + ") is not implemented."); } } protected boolean isBaseInherentlyCached() { return true; } private EntitySelector<Solution_> buildBaseEntitySelector(EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, boolean randomSelection) { if (minimumCacheType == SelectionCacheType.SOLVER) { // TODO Solver cached entities are not compatible with ConstraintStreams and IncrementalScoreDirector // because between phases the entities get cloned throw new IllegalArgumentException("The minimumCacheType (" + minimumCacheType + ") is not yet supported. Please use " + SelectionCacheType.PHASE + " instead."); } // FromSolutionEntitySelector has an intrinsicCacheType STEP return new FromSolutionEntitySelector<>(entityDescriptor, minimumCacheType, randomSelection); } private boolean hasFiltering(EntityDescriptor<Solution_> entityDescriptor) { return config.getFilterClass() != null || entityDescriptor.hasEffectiveMovableEntitySelectionFilter(); } private EntitySelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy, NearbySelectionConfig nearbySelectionConfig, SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) { return TimefoldSolverEnterpriseService .loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION) .applyNearbySelection(config, configPolicy, nearbySelectionConfig, minimumCacheType, resolvedSelectionOrder, entitySelector); } private EntitySelector<Solution_> applyFiltering(EntitySelector<Solution_> entitySelector, ClassInstanceCache instanceCache) { EntityDescriptor<Solution_> entityDescriptor = entitySelector.getEntityDescriptor(); if (hasFiltering(entityDescriptor)) { List<SelectionFilter<Solution_, Object>> filterList = new ArrayList<>(config.getFilterClass() == null ? 1 : 2); if (config.getFilterClass() != null) { SelectionFilter<Solution_, Object> selectionFilter = instanceCache.newInstance(config, "filterClass", config.getFilterClass()); filterList.add(selectionFilter); } // Filter out pinned entities if (entityDescriptor.hasEffectiveMovableEntitySelectionFilter()) { filterList.add(entityDescriptor.getEffectiveMovableEntitySelectionFilter()); } // Do not filter out initialized entities here for CH and ES, because they can be partially initialized // Instead, ValueSelectorConfig.applyReinitializeVariableFiltering() does that. entitySelector = FilteringEntitySelector.of(entitySelector, SelectionFilter.compose(filterList)); } return entitySelector; } protected void validateSorting(SelectionOrder resolvedSelectionOrder) { if ((config.getSorterManner() != null || config.getSorterComparatorClass() != null || config.getSorterWeightFactoryClass() != null || config.getSorterOrder() != null || config.getSorterClass() != null) && resolvedSelectionOrder != SelectionOrder.SORTED) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with sorterManner (" + config.getSorterManner() + ") and sorterComparatorClass (" + config.getSorterComparatorClass() + ") and sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ") and sorterOrder (" + config.getSorterOrder() + ") and sorterClass (" + config.getSorterClass() + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") that is not " + SelectionOrder.SORTED + "."); } if (config.getSorterManner() != null && config.getSorterComparatorClass() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has both a sorterManner (" + config.getSorterManner() + ") and a sorterComparatorClass (" + config.getSorterComparatorClass() + ")."); } if (config.getSorterManner() != null && config.getSorterWeightFactoryClass() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has both a sorterManner (" + config.getSorterManner() + ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ")."); } if (config.getSorterManner() != null && config.getSorterClass() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has both a sorterManner (" + config.getSorterManner() + ") and a sorterClass (" + config.getSorterClass() + ")."); } if (config.getSorterManner() != null && config.getSorterOrder() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with sorterManner (" + config.getSorterManner() + ") has a non-null sorterOrder (" + config.getSorterOrder() + ")."); } if (config.getSorterComparatorClass() != null && config.getSorterWeightFactoryClass() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has both a sorterComparatorClass (" + config.getSorterComparatorClass() + ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ")."); } if (config.getSorterComparatorClass() != null && config.getSorterClass() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has both a sorterComparatorClass (" + config.getSorterComparatorClass() + ") and a sorterClass (" + config.getSorterClass() + ")."); } if (config.getSorterWeightFactoryClass() != null && config.getSorterClass() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has both a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ") and a sorterClass (" + config.getSorterClass() + ")."); } if (config.getSorterClass() != null && config.getSorterOrder() != null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with sorterClass (" + config.getSorterClass() + ") has a non-null sorterOrder (" + config.getSorterOrder() + ")."); } } protected EntitySelector<Solution_> applySorting(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector, ClassInstanceCache instanceCache) { if (resolvedSelectionOrder == SelectionOrder.SORTED) { SelectionSorter<Solution_, Object> sorter; if (config.getSorterManner() != null) { EntityDescriptor<Solution_> entityDescriptor = entitySelector.getEntityDescriptor(); if (!EntitySelectorConfig.hasSorter(config.getSorterManner(), entityDescriptor)) { return entitySelector; } sorter = EntitySelectorConfig.determineSorter(config.getSorterManner(), entityDescriptor); } else if (config.getSorterComparatorClass() != null) { Comparator<Object> sorterComparator = instanceCache.newInstance(config, "sorterComparatorClass", config.getSorterComparatorClass()); sorter = new ComparatorSelectionSorter<>(sorterComparator, SelectionSorterOrder.resolve(config.getSorterOrder())); } else if (config.getSorterWeightFactoryClass() != null) { SelectionSorterWeightFactory<Solution_, Object> sorterWeightFactory = instanceCache.newInstance(config, "sorterWeightFactoryClass", config.getSorterWeightFactoryClass()); sorter = new WeightFactorySelectionSorter<>(sorterWeightFactory, SelectionSorterOrder.resolve(config.getSorterOrder())); } else if (config.getSorterClass() != null) { sorter = instanceCache.newInstance(config, "sorterClass", config.getSorterClass()); } else { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs a sorterManner (" + config.getSorterManner() + ") or a sorterComparatorClass (" + config.getSorterComparatorClass() + ") or a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ") or a sorterClass (" + config.getSorterClass() + ")."); } entitySelector = new SortingEntitySelector<>(entitySelector, resolvedCacheType, sorter); } return entitySelector; } protected void validateProbability(SelectionOrder resolvedSelectionOrder) { if (config.getProbabilityWeightFactoryClass() != null && resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass() + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") that is not " + SelectionOrder.PROBABILISTIC + "."); } } protected EntitySelector<Solution_> applyProbability(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector, ClassInstanceCache instanceCache) { if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) { if (config.getProbabilityWeightFactoryClass() == null) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs a probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass() + ")."); } SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory = instanceCache.newInstance(config, "probabilityWeightFactoryClass", config.getProbabilityWeightFactoryClass()); entitySelector = new ProbabilityEntitySelector<>(entitySelector, resolvedCacheType, probabilityWeightFactory); } return entitySelector; } private EntitySelector<Solution_> applyShuffling(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) { if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) { entitySelector = new ShufflingEntitySelector<>(entitySelector, resolvedCacheType); } return entitySelector; } private EntitySelector<Solution_> applyCaching(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) { if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(entitySelector.getCacheType()) > 0) { entitySelector = new CachingEntitySelector<>(entitySelector, resolvedCacheType, resolvedSelectionOrder.toRandomSelectionBoolean()); } return entitySelector; } private void validateSelectedLimit(SelectionCacheType minimumCacheType) { if (config.getSelectedCountLimit() != null && minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") with selectedCountLimit (" + config.getSelectedCountLimit() + ") has a minimumCacheType (" + minimumCacheType + ") that is higher than " + SelectionCacheType.JUST_IN_TIME + "."); } } private EntitySelector<Solution_> applySelectedLimit(SelectionOrder resolvedSelectionOrder, EntitySelector<Solution_> entitySelector) { if (config.getSelectedCountLimit() != null) { entitySelector = new SelectedCountLimitEntitySelector<>(entitySelector, resolvedSelectionOrder.toRandomSelectionBoolean(), config.getSelectedCountLimit()); } return entitySelector; } private EntitySelector<Solution_> applyMimicRecording(HeuristicConfigPolicy<Solution_> configPolicy, EntitySelector<Solution_> entitySelector) { if (config.getId() != null) { if (config.getId().isEmpty()) { throw new IllegalArgumentException("The entitySelectorConfig (" + config + ") has an empty id (" + config.getId() + ")."); } MimicRecordingEntitySelector<Solution_> mimicRecordingEntitySelector = new MimicRecordingEntitySelector<>(entitySelector); configPolicy.addEntityMimicRecorder(config.getId(), mimicRecordingEntitySelector); entitySelector = mimicRecordingEntitySelector; } return entitySelector; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity/FromSolutionEntitySelector.java
package ai.timefold.solver.core.impl.heuristic.selector.entity; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * This is the common {@link EntitySelector} implementation. */ public final class FromSolutionEntitySelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements EntitySelector<Solution_> { private final EntityDescriptor<Solution_> entityDescriptor; private final SelectionCacheType minimumCacheType; private final boolean randomSelection; private List<Object> cachedEntityList = null; private Long cachedEntityListRevision = null; private boolean cachedEntityListIsDirty = false; public FromSolutionEntitySelector(EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, boolean randomSelection) { this.entityDescriptor = entityDescriptor; this.minimumCacheType = minimumCacheType; this.randomSelection = randomSelection; } @Override public EntityDescriptor<Solution_> getEntityDescriptor() { return entityDescriptor; } /** * @return never null, at least {@link SelectionCacheType#STEP} */ @Override public SelectionCacheType getCacheType() { SelectionCacheType intrinsicCacheType = SelectionCacheType.STEP; return (intrinsicCacheType.compareTo(minimumCacheType) > 0) ? intrinsicCacheType : minimumCacheType; } // ************************************************************************ // Cache lifecycle methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector(); reloadCachedEntityList(scoreDirector); } private void reloadCachedEntityList(InnerScoreDirector<Solution_, ?> scoreDirector) { cachedEntityList = entityDescriptor.extractEntities(scoreDirector.getWorkingSolution()); cachedEntityListRevision = scoreDirector.getWorkingEntityListRevision(); cachedEntityListIsDirty = false; } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { super.stepStarted(stepScope); InnerScoreDirector<Solution_, ?> scoreDirector = stepScope.getScoreDirector(); if (scoreDirector.isWorkingEntityListDirty(cachedEntityListRevision)) { if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) { cachedEntityListIsDirty = true; } else { reloadCachedEntityList(scoreDirector); } } } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); cachedEntityList = null; cachedEntityListRevision = null; cachedEntityListIsDirty = false; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { // CachedListRandomIterator is neverEnding return randomSelection; } @Override public long getSize() { return cachedEntityList.size(); } @Override public Iterator<Object> iterator() { checkCachedEntityListIsDirty(); if (!randomSelection) { return cachedEntityList.iterator(); } else { return new CachedListRandomIterator<>(cachedEntityList, workingRandom); } } @Override public ListIterator<Object> listIterator() { checkCachedEntityListIsDirty(); if (!randomSelection) { return cachedEntityList.listIterator(); } else { throw new IllegalStateException("The selector (" + this + ") does not support a ListIterator with randomSelection (" + randomSelection + ")."); } } @Override public ListIterator<Object> listIterator(int index) { checkCachedEntityListIsDirty(); if (!randomSelection) { return cachedEntityList.listIterator(index); } else { throw new IllegalStateException("The selector (" + this + ") does not support a ListIterator with randomSelection (" + randomSelection + ")."); } } @Override public Iterator<Object> endingIterator() { checkCachedEntityListIsDirty(); return cachedEntityList.iterator(); } private void checkCachedEntityListIsDirty() { if (cachedEntityListIsDirty) { throw new IllegalStateException("The selector (" + this + ") with minimumCacheType (" + minimumCacheType + ")'s workingEntityList became dirty between steps but is still used afterwards."); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; FromSolutionEntitySelector<?> that = (FromSolutionEntitySelector<?>) other; return randomSelection == that.randomSelection && Objects.equals(entityDescriptor, that.entityDescriptor) && minimumCacheType == that.minimumCacheType; } @Override public int hashCode() { return Objects.hash(entityDescriptor, minimumCacheType, randomSelection); } @Override public String toString() { return getClass().getSimpleName() + "(" + entityDescriptor.getEntityClass().getSimpleName() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/FilteringEntitySelector.java
package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator; import java.util.Iterator; import java.util.ListIterator; import java.util.Objects; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionListIterator; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; public final class FilteringEntitySelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements EntitySelector<Solution_> { public static <Solution_> FilteringEntitySelector<Solution_> of(EntitySelector<Solution_> childEntitySelector, SelectionFilter<Solution_, Object> filter) { if (childEntitySelector instanceof FilteringEntitySelector<Solution_> filteringEntitySelector) { return new FilteringEntitySelector<>(filteringEntitySelector.childEntitySelector, SelectionFilter.compose(filteringEntitySelector.selectionFilter, filter)); } return new FilteringEntitySelector<>(childEntitySelector, filter); } private final EntitySelector<Solution_> childEntitySelector; private final SelectionFilter<Solution_, Object> selectionFilter; private final boolean bailOutEnabled; private ScoreDirector<Solution_> scoreDirector = null; private FilteringEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionFilter<Solution_, Object> filter) { this.childEntitySelector = Objects.requireNonNull(childEntitySelector); this.selectionFilter = Objects.requireNonNull(filter); bailOutEnabled = childEntitySelector.isNeverEnding(); phaseLifecycleSupport.addEventListener(childEntitySelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); scoreDirector = phaseScope.getScoreDirector(); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); scoreDirector = null; } @Override public EntityDescriptor<Solution_> getEntityDescriptor() { return childEntitySelector.getEntityDescriptor(); } @Override public boolean isCountable() { return childEntitySelector.isCountable(); } @Override public boolean isNeverEnding() { return childEntitySelector.isNeverEnding(); } @Override public long getSize() { return childEntitySelector.getSize(); } @Override public Iterator<Object> iterator() { return new JustInTimeFilteringEntityIterator(childEntitySelector.iterator(), determineBailOutSize()); } protected class JustInTimeFilteringEntityIterator extends UpcomingSelectionIterator<Object> { private final Iterator<Object> childEntityIterator; private final long bailOutSize; public JustInTimeFilteringEntityIterator(Iterator<Object> childEntityIterator, long bailOutSize) { this.childEntityIterator = childEntityIterator; this.bailOutSize = bailOutSize; } @Override protected Object createUpcomingSelection() { Object next; long attemptsBeforeBailOut = bailOutSize; do { if (!childEntityIterator.hasNext()) { return noUpcomingSelection(); } if (bailOutEnabled) { // if childEntityIterator is neverEnding and nothing is accepted, bail out of the infinite loop if (attemptsBeforeBailOut <= 0L) { logger.debug("Bailing out of neverEnding selector ({}) to avoid infinite loop.", FilteringEntitySelector.this); return noUpcomingSelection(); } attemptsBeforeBailOut--; } next = childEntityIterator.next(); } while (!selectionFilter.accept(scoreDirector, next)); return next; } } protected class JustInTimeFilteringEntityListIterator extends UpcomingSelectionListIterator<Object> { private final ListIterator<Object> childEntityListIterator; public JustInTimeFilteringEntityListIterator(ListIterator<Object> childEntityListIterator) { this.childEntityListIterator = childEntityListIterator; } @Override protected Object createUpcomingSelection() { Object next; do { if (!childEntityListIterator.hasNext()) { return noUpcomingSelection(); } next = childEntityListIterator.next(); } while (!selectionFilter.accept(scoreDirector, next)); return next; } @Override protected Object createPreviousSelection() { Object previous; do { if (!childEntityListIterator.hasPrevious()) { return noPreviousSelection(); } previous = childEntityListIterator.previous(); } while (!selectionFilter.accept(scoreDirector, previous)); return previous; } } @Override public ListIterator<Object> listIterator() { return new JustInTimeFilteringEntityListIterator(childEntitySelector.listIterator()); } @Override public ListIterator<Object> listIterator(int index) { JustInTimeFilteringEntityListIterator listIterator = new JustInTimeFilteringEntityListIterator(childEntitySelector.listIterator()); for (int i = 0; i < index; i++) { listIterator.next(); } return listIterator; } @Override public Iterator<Object> endingIterator() { return new JustInTimeFilteringEntityIterator(childEntitySelector.endingIterator(), determineBailOutSize()); } private long determineBailOutSize() { if (!bailOutEnabled) { return -1L; } return childEntitySelector.getSize() * 10L; } @Override public boolean equals(Object other) { return other instanceof FilteringEntitySelector<?> that && Objects.equals(childEntitySelector, that.childEntitySelector) && Objects.equals(selectionFilter, that.selectionFilter); } @Override public int hashCode() { return Objects.hash(childEntitySelector, selectionFilter); } @Override public String toString() { return "Filtering(" + childEntitySelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/PinEntityFilter.java
package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator; import java.util.Objects; import ai.timefold.solver.core.api.domain.entity.PlanningPin; 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.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; /** * Filters out entities that return true for the {@link PlanningPin} annotated boolean member. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class PinEntityFilter<Solution_> implements SelectionFilter<Solution_, Object> { private final MemberAccessor memberAccessor; public PinEntityFilter(MemberAccessor memberAccessor) { this.memberAccessor = memberAccessor; } @Override public boolean accept(ScoreDirector<Solution_> scoreDirector, Object entity) { Boolean pinned = (Boolean) memberAccessor.executeGetter(entity); if (pinned == null) { throw new IllegalStateException("The entity (" + entity + ") has a @" + PlanningPin.class.getSimpleName() + " annotated property (" + memberAccessor.getName() + ") that returns null."); } return !pinned; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; PinEntityFilter<?> that = (PinEntityFilter<?>) other; return Objects.equals(memberAccessor, that.memberAccessor); } @Override public int hashCode() { return Objects.hash(memberAccessor); } @Override public String toString() { return "Non-pinned entities only"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/entity/decorator/ProbabilityEntitySelector.java
package ai.timefold.solver.core.impl.heuristic.selector.entity.decorator; import java.util.Iterator; import java.util.ListIterator; import java.util.Map; import java.util.NavigableMap; import java.util.Objects; import java.util.TreeMap; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractDemandEnabledSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.solver.random.RandomUtils; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public final class ProbabilityEntitySelector<Solution_> extends AbstractDemandEnabledSelector<Solution_> implements SelectionCacheLifecycleListener<Solution_>, EntitySelector<Solution_> { private final EntitySelector<Solution_> childEntitySelector; private final SelectionCacheType cacheType; private final SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory; private NavigableMap<Double, Object> cachedEntityMap = null; private double probabilityWeightTotal = -1.0; public ProbabilityEntitySelector(EntitySelector<Solution_> childEntitySelector, SelectionCacheType cacheType, SelectionProbabilityWeightFactory<Solution_, Object> probabilityWeightFactory) { this.childEntitySelector = childEntitySelector; this.cacheType = cacheType; this.probabilityWeightFactory = probabilityWeightFactory; if (childEntitySelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a childEntitySelector (" + childEntitySelector + ") with neverEnding (" + childEntitySelector.isNeverEnding() + ")."); } phaseLifecycleSupport.addEventListener(childEntitySelector); if (cacheType.isNotCached()) { throw new IllegalArgumentException("The selector (" + this + ") does not support the cacheType (" + cacheType + ")."); } phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge<>(cacheType, this)); } @Override public SelectionCacheType getCacheType() { return cacheType; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void constructCache(SolverScope<Solution_> solverScope) { cachedEntityMap = new TreeMap<>(); ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector(); double probabilityWeightOffset = 0L; for (Object entity : childEntitySelector) { double probabilityWeight = probabilityWeightFactory.createProbabilityWeight( scoreDirector, entity); cachedEntityMap.put(probabilityWeightOffset, entity); probabilityWeightOffset += probabilityWeight; } probabilityWeightTotal = probabilityWeightOffset; } @Override public void disposeCache(SolverScope<Solution_> solverScope) { probabilityWeightTotal = -1.0; } @Override public EntityDescriptor<Solution_> getEntityDescriptor() { return childEntitySelector.getEntityDescriptor(); } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return true; } @Override public long getSize() { return cachedEntityMap.size(); } @Override public Iterator<Object> iterator() { return new Iterator<>() { @Override public boolean hasNext() { return true; } @Override public Object next() { double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal); Map.Entry<Double, Object> entry = cachedEntityMap.floorEntry(randomOffset); // entry is never null because randomOffset < probabilityWeightTotal return entry.getValue(); } @Override public void remove() { throw new UnsupportedOperationException("The optional operation remove() is not supported."); } }; } @Override public ListIterator<Object> listIterator() { throw new IllegalStateException("The selector (" + this + ") does not support a ListIterator with randomSelection (true)."); } @Override public ListIterator<Object> listIterator(int index) { throw new IllegalStateException("The selector (" + this + ") does not support a ListIterator with randomSelection (true)."); } @Override public Iterator<Object> endingIterator() { return childEntitySelector.endingIterator(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ProbabilityEntitySelector<?> that = (ProbabilityEntitySelector<?>) other; return Objects.equals(childEntitySelector, that.childEntitySelector) && cacheType == that.cacheType && Objects.equals(probabilityWeightFactory, that.probabilityWeightFactory); } @Override public int hashCode() { return Objects.hash(childEntitySelector, cacheType, probabilityWeightFactory); } @Override public String toString() { return "Probability(" + childEntitySelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/DestinationSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import ai.timefold.solver.core.impl.heuristic.selector.IterableSelector; public interface DestinationSelector<Solution_> extends IterableSelector<Solution_, ElementLocation> { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/DestinationSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import java.util.Objects; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.common.nearby.NearbySelectionConfig; import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig; import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public final class DestinationSelectorFactory<Solution_> extends AbstractSelectorFactory<Solution_, DestinationSelectorConfig> { public static <Solution_> DestinationSelectorFactory<Solution_> create(DestinationSelectorConfig destinationSelectorConfig) { return new DestinationSelectorFactory<>(destinationSelectorConfig); } private DestinationSelectorFactory(DestinationSelectorConfig destinationSelectorConfig) { super(destinationSelectorConfig); } public DestinationSelector<Solution_> buildDestinationSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); var entitySelector = EntitySelectorFactory.<Solution_> create(Objects.requireNonNull(config.getEntitySelectorConfig())) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); var valueSelector = buildEntityIndependentValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder); var baseDestinationSelector = new ElementDestinationSelector<>(entitySelector, valueSelector, selectionOrder.toRandomSelectionBoolean()); return applyNearbySelection(configPolicy, minimumCacheType, selectionOrder, baseDestinationSelector); } private EntityIndependentValueSelector<Solution_> buildEntityIndependentValueSelector( HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { ValueSelector<Solution_> valueSelector = ValueSelectorFactory .<Solution_> create(Objects.requireNonNull(config.getValueSelectorConfig())) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder, // Do not override reinitializeVariableFilterEnabled. configPolicy.isReinitializeVariableFilterEnabled(), /* * Filter assigned values (but only if this filtering type is allowed by the configPolicy). * * The destination selector requires the child value selector to only select assigned values. * To guarantee this during CH, where not all values are assigned, the UnassignedValueSelector filter * must be applied. * * In the LS phase, not only is the filter redundant because there are no unassigned values, * but it would also crash if the base value selector inherits random selection order, * because the filter cannot work on a never-ending child value selector. * Therefore, it must not be applied even though it is requested here. This is accomplished by * the configPolicy that only allows this filtering type in the CH phase. */ ValueSelectorFactory.ListValueFilteringType.ACCEPT_ASSIGNED); if (!(valueSelector instanceof EntityIndependentValueSelector)) { throw new IllegalArgumentException("The destinationSelector (" + config + ") for a list variable needs to be based on an " + EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } return (EntityIndependentValueSelector<Solution_>) valueSelector; } private DestinationSelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder, ElementDestinationSelector<Solution_> destinationSelector) { NearbySelectionConfig nearbySelectionConfig = config.getNearbySelectionConfig(); if (nearbySelectionConfig == null) { return destinationSelector; } return TimefoldSolverEnterpriseService .loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION) .applyNearbySelection(config, configPolicy, minimumCacheType, resolvedSelectionOrder, destinationSelector); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/ElementDestinationSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex; import java.util.Collections; import java.util.Iterator; import java.util.Objects; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * Selects destinations for list variable change moves. The destination specifies a future position in a list variable, * expressed as an {@link LocationInList}, where a moved element or subList can be inserted. * <p> * Destination completeness is achieved by using both entity and value child selectors. * When an entity <em>A</em> is selected, the destination becomes <em>A[0]</em>. * When a value <em>x</em> is selected, its current position <em>A[i]</em> is determined using inverse and index supplies and * the destination becomes <em>A[i + 1]</em>. * <p> * Fairness in random selection is achieved by first deciding between entity and value selector with a probability that is * proportional to the entity/value ratio. The child entity and value selectors are assumed to be fair. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ElementDestinationSelector<Solution_> extends AbstractSelector<Solution_> implements DestinationSelector<Solution_> { private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final EntitySelector<Solution_> entitySelector; private final EntityIndependentValueSelector<Solution_> valueSelector; private final boolean randomSelection; private ListVariableStateSupply<Solution_> listVariableStateSupply; private EntityIndependentValueSelector<Solution_> movableValueSelector; public ElementDestinationSelector(EntitySelector<Solution_> entitySelector, EntityIndependentValueSelector<Solution_> valueSelector, boolean randomSelection) { this.listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor(); this.entitySelector = entitySelector; this.valueSelector = valueSelector; // At this point, guaranteed to only return assigned values. this.randomSelection = randomSelection; phaseLifecycleSupport.addEventListener(entitySelector); phaseLifecycleSupport.addEventListener(valueSelector); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); var supplyManager = solverScope.getScoreDirector().getSupplyManager(); listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand()); movableValueSelector = filterPinnedListPlanningVariableValuesWithIndex(valueSelector, listVariableStateSupply); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); listVariableStateSupply = null; movableValueSelector = null; } @Override public long getSize() { if (entitySelector.getSize() == 0) { return 0; } return entitySelector.getSize() + getEffectiveValueSelector().getSize(); } private EntityIndependentValueSelector<Solution_> getEffectiveValueSelector() { // Simplify tests. return Objects.requireNonNullElse(movableValueSelector, valueSelector); } @Override public Iterator<ElementLocation> iterator() { if (randomSelection) { var allowsUnassignedValues = listVariableDescriptor.allowsUnassignedValues(); // In case of list var which allows unassigned values, we need to exclude unassigned elements. var effectiveValueSelector = getEffectiveValueSelector(); var totalValueSize = effectiveValueSelector.getSize() - (allowsUnassignedValues ? listVariableStateSupply.getUnassignedCount() : 0); var totalSize = Math.addExact(entitySelector.getSize(), totalValueSize); return new ElementLocationRandomIterator<>(listVariableStateSupply, entitySelector, effectiveValueSelector, workingRandom, totalSize, allowsUnassignedValues); } else { if (entitySelector.getSize() == 0) { return Collections.emptyIterator(); } // If the list variable allows unassigned values, add the option of unassigning. var stream = listVariableDescriptor.allowsUnassignedValues() ? Stream.of(ElementLocation.unassigned()) : Stream.<ElementLocation> empty(); // Start with the first unpinned value of each entity, or zero if no pinning. // Entity selector is guaranteed to return only unpinned entities. stream = Stream.concat(stream, StreamSupport.stream(entitySelector.spliterator(), false) .map(entity -> ElementLocation.of(entity, listVariableDescriptor.getFirstUnpinnedIndex(entity)))); // Filter guarantees that we only get values that are actually in one of the lists. // Value selector guarantees only unpinned values. stream = Stream.concat(stream, StreamSupport.stream(getEffectiveValueSelector().spliterator(), false) .map(v -> listVariableStateSupply.getLocationInList(v)) .flatMap(elementLocation -> elementLocation instanceof LocationInList locationInList ? Stream.of(locationInList) : Stream.empty()) .map(locationInList -> ElementLocation.of(locationInList.entity(), locationInList.index() + 1))); return (Iterator<ElementLocation>) stream.iterator(); } } @Override public boolean isCountable() { return entitySelector.isCountable() && getEffectiveValueSelector().isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || entitySelector.isNeverEnding() || getEffectiveValueSelector().isNeverEnding(); } public ListVariableDescriptor<Solution_> getVariableDescriptor() { return (ListVariableDescriptor<Solution_>) getEffectiveValueSelector().getVariableDescriptor(); } public EntityDescriptor<Solution_> getEntityDescriptor() { return entitySelector.getEntityDescriptor(); } public Iterator<Object> endingIterator() { EntityIndependentValueSelector<Solution_> effectiveValueSelector = getEffectiveValueSelector(); return Stream.concat( StreamSupport.stream(Spliterators.spliterator(entitySelector.endingIterator(), entitySelector.getSize(), 0), false), StreamSupport.stream(Spliterators.spliterator(effectiveValueSelector.endingIterator(null), effectiveValueSelector.getSize(), 0), false)) .iterator(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ElementDestinationSelector<?> that = (ElementDestinationSelector<?>) o; return randomSelection == that.randomSelection && Objects.equals(entitySelector, that.entitySelector) && Objects.equals(valueSelector, that.valueSelector); } @Override public int hashCode() { return Objects.hash(entitySelector, valueSelector, randomSelection); } @Override public String toString() { return getClass().getSimpleName() + "(" + entitySelector + ", " + valueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/ElementLocation.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; /** * A supertype for {@link LocationInList} and {@link UnassignedLocation}. * <p> * {@link PlanningListVariable#allowsUnassignedValues()} introduces {@link UnassignedLocation}, * and the handling of unassigned values is brittle. * These values may leak into code which expects {@link LocationInList} instead. * Therefore, we use {@link ElementLocation} and we force calling code to cast to either of the two subtypes. * This prevents accidental use of {@link UnassignedLocation} in places where {@link LocationInList} is expected, * catching this error as early as possible. */ public sealed interface ElementLocation permits LocationInList, UnassignedLocation { static LocationInList of(Object entity, int index) { return new LocationInList(entity, index); } static UnassignedLocation unassigned() { return UnassignedLocation.INSTANCE; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/ElementLocationRandomIterator.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import java.util.Iterator; import java.util.Random; 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.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector; import ai.timefold.solver.core.impl.solver.random.RandomUtils; final class ElementLocationRandomIterator<Solution_> implements Iterator<ElementLocation> { private final ListVariableStateSupply<Solution_> listVariableStateSupply; private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final EntitySelector<Solution_> entitySelector; private final EntityIndependentValueSelector<Solution_> valueSelector; private final Iterator<Object> entityIterator; private final Random workingRandom; private final long totalSize; private final boolean allowsUnassignedValues; private Iterator<Object> valueIterator; public ElementLocationRandomIterator(ListVariableStateSupply<Solution_> listVariableStateSupply, EntitySelector<Solution_> entitySelector, EntityIndependentValueSelector<Solution_> valueSelector, Random workingRandom, long totalSize, boolean allowsUnassignedValues) { this.listVariableStateSupply = listVariableStateSupply; this.listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); this.entitySelector = entitySelector; this.valueSelector = getEffectiveValueSelector(valueSelector, allowsUnassignedValues); this.entityIterator = entitySelector.iterator(); this.workingRandom = workingRandom; this.totalSize = totalSize; if (totalSize < 1) { throw new IllegalStateException("Impossible state: totalSize (%d) < 1" .formatted(totalSize)); } this.allowsUnassignedValues = allowsUnassignedValues; this.valueIterator = null; } private EntityIndependentValueSelector<Solution_> getEffectiveValueSelector( EntityIndependentValueSelector<Solution_> valueSelector, boolean allowsUnassignedValues) { var effectiveValueSelector = valueSelector; if (allowsUnassignedValues) { /* * In case of list variable that allows unassigned values, * unassigned elements will show up in the valueSelector. * These skew the selection probability, so we need to exclude them. * The option to unassign needs to be added to the iterator once later, * to make sure that it can get selected. * * Example: for destination elements [A, B, C] where C is not initialized, * the probability of unassigning a source element is 1/3 as it should be. * (If destination is not initialized, it means source will be unassigned.) * However, if B and C were not initialized, the probability of unassigning goes up to 2/3. * The probability should be 1/2 instead. * (Either select A as the destination, or unassign.) * If we always remove unassigned elements from the iterator, * and always add one option to unassign at the end, * we can keep the correct probabilities throughout. */ effectiveValueSelector = (EntityIndependentValueSelector<Solution_>) FilteringValueSelector .of(effectiveValueSelector, (ScoreDirector<Solution_> scoreDirector, Object selection) -> listVariableStateSupply.getInverseSingleton(selection) != null); } return effectiveValueSelector; } @Override public boolean hasNext() { // The valueSelector's hasNext() is insignificant. // The next random destination exists if and only if there is a next entity. return entityIterator.hasNext(); } @Override public ElementLocation next() { // This code operates under the assumption that the entity selector already filtered out all immovable entities. // At this point, entities are only partially pinned, or not pinned at all. var entitySize = entitySelector.getSize(); var entityBoundary = allowsUnassignedValues ? entitySize + 1 : entitySize; long random = RandomUtils.nextLong(workingRandom, totalSize); if (allowsUnassignedValues && random == 0) { // We have already excluded all unassigned elements, // the only way to get an unassigned destination is to explicitly add it. return ElementLocation.unassigned(); } else if (random < entityBoundary) { // Start with the first unpinned value of each entity, or zero if no pinning. var entity = entityIterator.next(); return new LocationInList(entity, listVariableDescriptor.getFirstUnpinnedIndex(entity)); } else { // Value selector already returns only unpinned values. if (valueIterator == null) { valueIterator = valueSelector.iterator(); } var value = valueIterator.hasNext() ? valueIterator.next() : null; if (value == null) { // No more values are available; happens with pinning and/or unassigned. // This is effectively an off-by-N error where the filtering selectors report incorrect sizes // on account of not knowing how many values are going to be filtered out. // As a fallback, start picking random unpinned destinations until the iteration stops externally. // This skews the selection probability towards entities with fewer unpinned values, // but at this point, there is no other thing we could possibly do. var entity = entityIterator.next(); int unpinnedSize = listVariableDescriptor.getUnpinnedSubListSize(entity); if (unpinnedSize == 0) { // Only the last destination remains. return new LocationInList(entity, listVariableDescriptor.getListSize(entity)); } else { // +1 to include the destination after the final element in the list. int randomIndex = workingRandom.nextInt(unpinnedSize + 1); return new LocationInList(entity, listVariableDescriptor.getFirstUnpinnedIndex(entity) + randomIndex); } } else { // +1 to include the destination after the final element in the list. var elementLocation = (LocationInList) listVariableStateSupply.getLocationInList(value); return new LocationInList(elementLocation.entity(), elementLocation.index() + 1); } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/LocationInList.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import java.util.Objects; /** * Points to a list variable position specified by an entity and an index. */ public record LocationInList(Object entity, int index) implements ElementLocation { public LocationInList { Objects.requireNonNull(entity); if (index < 0) { throw new IllegalArgumentException("Impossible state: index (%d) not positive." .formatted(index)); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/RandomSubListSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import static ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelector.filterPinnedListPlanningVariableValuesWithIndex; import java.util.Iterator; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class RandomSubListSelector<Solution_> extends AbstractSelector<Solution_> implements SubListSelector<Solution_> { private final EntitySelector<Solution_> entitySelector; private final EntityIndependentValueSelector<Solution_> valueSelector; private final ListVariableDescriptor<Solution_> listVariableDescriptor; private final int minimumSubListSize; private final int maximumSubListSize; private TriangleElementFactory triangleElementFactory; private ListVariableStateSupply<Solution_> listVariableStateSupply; private EntityIndependentValueSelector<Solution_> movableValueSelector; public RandomSubListSelector( EntitySelector<Solution_> entitySelector, EntityIndependentValueSelector<Solution_> valueSelector, int minimumSubListSize, int maximumSubListSize) { this.entitySelector = entitySelector; this.valueSelector = valueSelector; this.listVariableDescriptor = (ListVariableDescriptor<Solution_>) valueSelector.getVariableDescriptor(); if (minimumSubListSize < 1) { // TODO raise this to 2 in Timefold Solver 2.0 throw new IllegalArgumentException( "The minimumSubListSize (" + minimumSubListSize + ") must be greater than 0."); } if (minimumSubListSize > maximumSubListSize) { throw new IllegalArgumentException("The minimumSubListSize (" + minimumSubListSize + ") must be less than or equal to the maximumSubListSize (" + maximumSubListSize + ")."); } this.minimumSubListSize = minimumSubListSize; this.maximumSubListSize = maximumSubListSize; phaseLifecycleSupport.addEventListener(entitySelector); phaseLifecycleSupport.addEventListener(valueSelector); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { super.solvingStarted(solverScope); triangleElementFactory = new TriangleElementFactory(minimumSubListSize, maximumSubListSize, workingRandom); var supplyManager = solverScope.getScoreDirector().getSupplyManager(); listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand()); movableValueSelector = filterPinnedListPlanningVariableValuesWithIndex(valueSelector, listVariableStateSupply); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); listVariableStateSupply = null; } @Override public ListVariableDescriptor<Solution_> getVariableDescriptor() { return listVariableDescriptor; } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return true; } @Override public long getSize() { long subListCount = 0; for (Object entity : ((Iterable<Object>) entitySelector::endingIterator)) { int listSize = listVariableDescriptor.getUnpinnedSubListSize(entity); // Add subLists bigger than minimum subList size. if (listSize >= minimumSubListSize) { subListCount += TriangularNumbers.nthTriangle(listSize - minimumSubListSize + 1); // Subtract moves with subLists bigger than maximum subList size. if (listSize > maximumSubListSize) { subListCount -= TriangularNumbers.nthTriangle(listSize - maximumSubListSize); } } } return subListCount; } @Override public Iterator<Object> endingValueIterator() { // Child value selector is entity independent, so passing null entity is OK. return movableValueSelector.endingIterator(null); } @Override public long getValueCount() { return movableValueSelector.getSize(); } @Override public Iterator<SubList> iterator() { // TODO make this incremental https://issues.redhat.com/browse/PLANNER-2507 int biggestListSize = 0; for (Object entity : ((Iterable<Object>) entitySelector::endingIterator)) { biggestListSize = Math.max(biggestListSize, listVariableDescriptor.getUnpinnedSubListSize(entity)); } if (biggestListSize < minimumSubListSize) { return new UpcomingSelectionIterator<>() { @Override protected SubList createUpcomingSelection() { return noUpcomingSelection(); } }; } return new RandomSubListIterator(movableValueSelector.iterator()); } private final class RandomSubListIterator extends UpcomingSelectionIterator<SubList> { private final Iterator<Object> valueIterator; private RandomSubListIterator(Iterator<Object> valueIterator) { this.valueIterator = valueIterator; } @Override protected SubList createUpcomingSelection() { Object sourceEntity = null; int listSize = 0; var firstUnpinnedIndex = 0; while (listSize < minimumSubListSize) { if (!valueIterator.hasNext()) { throw new IllegalStateException("The valueIterator (" + valueIterator + ") should never end."); } // Using valueSelector instead of entitySelector is fairer // because entities with bigger list variables will be selected more often. var value = valueIterator.next(); sourceEntity = listVariableStateSupply.getInverseSingleton(value); if (sourceEntity == null) { // Ignore values which are unassigned. continue; } firstUnpinnedIndex = listVariableDescriptor.getFirstUnpinnedIndex(sourceEntity); listSize = listVariableDescriptor.getListSize(sourceEntity) - firstUnpinnedIndex; } TriangleElementFactory.TriangleElement triangleElement = triangleElementFactory.nextElement(listSize); int subListLength = listSize - triangleElement.level() + 1; if (subListLength < 1) { throw new IllegalStateException("Impossible state: The subListLength (%s) must be greater than 0." .formatted(subListLength)); } int sourceIndex = triangleElement.indexOnLevel() - 1 + firstUnpinnedIndex; return new SubList(sourceEntity, sourceIndex, subListLength); } } public int getMinimumSubListSize() { return minimumSubListSize; } public int getMaximumSubListSize() { return maximumSubListSize; } @Override public String toString() { return getClass().getSimpleName() + "(" + valueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/SubListSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.list; import java.util.Objects; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; 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.common.nearby.NearbySelectionConfig; import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService; import ai.timefold.solver.core.impl.AbstractFromConfigFactory; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.MimicRecordingSubListSelector; import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.MimicReplayingSubListSelector; import ai.timefold.solver.core.impl.heuristic.selector.list.mimic.SubListMimicRecorder; import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public final class SubListSelectorFactory<Solution_> extends AbstractFromConfigFactory<Solution_, SubListSelectorConfig> { private static final int DEFAULT_MINIMUM_SUB_LIST_SIZE = 1; // TODO Bump this to 2 in Timefold Solver 2.0 private static final int DEFAULT_MAXIMUM_SUB_LIST_SIZE = Integer.MAX_VALUE; private SubListSelectorFactory(SubListSelectorConfig config) { super(config); } public static <Solution_> SubListSelectorFactory<Solution_> create(SubListSelectorConfig subListSelectorConfig) { return new SubListSelectorFactory<>(subListSelectorConfig); } public SubListSelector<Solution_> buildSubListSelector( HeuristicConfigPolicy<Solution_> configPolicy, EntitySelector<Solution_> entitySelector, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { if (config.getMimicSelectorRef() != null) { return buildMimicReplaying(configPolicy); } if (inheritedSelectionOrder != SelectionOrder.RANDOM) { throw new IllegalArgumentException("The subListSelector (" + config + ") has an inheritedSelectionOrder(" + inheritedSelectionOrder + ") which is not supported. SubListSelector only supports random selection order."); } EntityIndependentValueSelector<Solution_> valueSelector = buildEntityIndependentValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, inheritedSelectionOrder); int minimumSubListSize = Objects.requireNonNullElse(config.getMinimumSubListSize(), DEFAULT_MINIMUM_SUB_LIST_SIZE); int maximumSubListSize = Objects.requireNonNullElse(config.getMaximumSubListSize(), DEFAULT_MAXIMUM_SUB_LIST_SIZE); RandomSubListSelector<Solution_> baseSubListSelector = new RandomSubListSelector<>(entitySelector, valueSelector, minimumSubListSize, maximumSubListSize); SubListSelector<Solution_> subListSelector = applyNearbySelection(configPolicy, minimumCacheType, inheritedSelectionOrder, baseSubListSelector); subListSelector = applyMimicRecording(configPolicy, subListSelector); return subListSelector; } SubListSelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Solution_> configPolicy) { if (config.getId() != null || config.getMinimumSubListSize() != null || config.getMaximumSubListSize() != null || config.getValueSelectorConfig() != null || config.getNearbySelectionConfig() != null) { throw new IllegalArgumentException("The subListSelectorConfig (" + config + ") with mimicSelectorRef (" + config.getMimicSelectorRef() + ") has another property that is not null."); } SubListMimicRecorder<Solution_> subListMimicRecorder = configPolicy.getSubListMimicRecorder(config.getMimicSelectorRef()); if (subListMimicRecorder == null) { throw new IllegalArgumentException("The subListSelectorConfig (" + config + ") has a mimicSelectorRef (" + config.getMimicSelectorRef() + ") for which no subListSelector with that id exists (in its solver phase)."); } return new MimicReplayingSubListSelector<>(subListMimicRecorder); } private SubListSelector<Solution_> applyMimicRecording(HeuristicConfigPolicy<Solution_> configPolicy, SubListSelector<Solution_> subListSelector) { if (config.getId() != null) { if (config.getId().isEmpty()) { throw new IllegalArgumentException("The subListSelectorConfig (" + config + ") has an empty id (" + config.getId() + ")."); } MimicRecordingSubListSelector<Solution_> mimicRecordingSubListSelector = new MimicRecordingSubListSelector<>(subListSelector); configPolicy.addSubListMimicRecorder(config.getId(), mimicRecordingSubListSelector); subListSelector = mimicRecordingSubListSelector; } return subListSelector; } private SubListSelector<Solution_> applyNearbySelection(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder, RandomSubListSelector<Solution_> subListSelector) { NearbySelectionConfig nearbySelectionConfig = config.getNearbySelectionConfig(); if (nearbySelectionConfig == null) { return subListSelector; } return TimefoldSolverEnterpriseService .loadOrFail(TimefoldSolverEnterpriseService.Feature.NEARBY_SELECTION) .applyNearbySelection(config, configPolicy, minimumCacheType, resolvedSelectionOrder, subListSelector); } private EntityIndependentValueSelector<Solution_> buildEntityIndependentValueSelector( HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { ValueSelectorConfig valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); ValueSelector<Solution_> valueSelector = ValueSelectorFactory .<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, inheritedSelectionOrder); GenuineVariableDescriptor<Solution_> solutionGenuineVariableDescriptor = valueSelector.getVariableDescriptor(); if (!solutionGenuineVariableDescriptor.isListVariable()) { throw new IllegalArgumentException("The subListSelector (" + config + ") can only be used when the domain model has a list variable." + " Check your @" + PlanningEntity.class.getSimpleName() + " and make sure it has a @" + PlanningListVariable.class.getSimpleName() + "."); } if (!(valueSelector instanceof EntityIndependentValueSelector)) { throw new IllegalArgumentException("The subListSelector (" + config + ") for a list variable needs to be based on an " + EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } return (EntityIndependentValueSelector<Solution_>) valueSelector; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/TriangularNumbers.java
package ai.timefold.solver.core.impl.heuristic.selector.list; public final class TriangularNumbers { /** * This is the highest <em>n</em> for which the <em>n</em>th triangular number can be calculated using int arithmetic. */ static final int HIGHEST_SAFE_N = 46340; /** * Calculate <em>n</em>th <a href="https://en.wikipedia.org/wiki/Triangular_number">triangular number</a>. * This is used to calculate the number of subLists for a given list variable of size <em>n</em>. * To be able to use {@code int} arithmetic to calculate the triangular number, <em>n</em> must be less than or equal to * {@link #HIGHEST_SAFE_N}. If the <em>n</em> is higher, the method throws an exception. * * @param n size of the triangle (the length of its side) * @return <em>n</em>th triangular number * @throws ArithmeticException if {@code n} is higher than {@link #HIGHEST_SAFE_N} */ public static int nthTriangle(int n) throws ArithmeticException { return Math.multiplyExact(n, n + 1) / 2; } static double triangularRoot(int x) { return (Math.sqrt(8L * x + 1) - 1) / 2; } private TriangularNumbers() { } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/UnassignedLocation.java
package ai.timefold.solver.core.impl.heuristic.selector.list; public record UnassignedLocation() implements ElementLocation { public static final UnassignedLocation INSTANCE = new UnassignedLocation(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/list/mimic/MimicReplayingSubListSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.list.mimic; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelector; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.SelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.list.SubList; import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; public class MimicReplayingSubListSelector<Solution_> extends AbstractSelector<Solution_> implements SubListSelector<Solution_> { protected final SubListMimicRecorder<Solution_> subListMimicRecorder; protected boolean hasRecordingCreated; protected boolean hasRecording; protected boolean recordingCreated; protected SubList recording; protected boolean recordingAlreadyReturned; public MimicReplayingSubListSelector(SubListMimicRecorder<Solution_> subListMimicRecorder) { this.subListMimicRecorder = subListMimicRecorder; // No PhaseLifecycleSupport because the MimicRecordingSubListSelector is hooked up elsewhere too subListMimicRecorder.addMimicReplayingSubListSelector(this); // Precondition for iterator(Object)'s current implementation if (!subListMimicRecorder.getVariableDescriptor().isValueRangeEntityIndependent()) { throw new IllegalArgumentException( "The current implementation support only an entityIndependent variable (" + subListMimicRecorder.getVariableDescriptor() + ")."); } } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); // Doing this in phaseStarted instead of stepStarted due to QueuedValuePlacer compatibility hasRecordingCreated = false; recordingCreated = false; } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); // Doing this in phaseEnded instead of stepEnded due to QueuedValuePlacer compatibility hasRecordingCreated = false; hasRecording = false; recordingCreated = false; recording = null; } @Override public ListVariableDescriptor<Solution_> getVariableDescriptor() { return subListMimicRecorder.getVariableDescriptor(); } @Override public boolean isCountable() { return subListMimicRecorder.isCountable(); } @Override public boolean isNeverEnding() { return subListMimicRecorder.isNeverEnding(); } @Override public long getSize() { return subListMimicRecorder.getSize(); } @Override public Iterator<Object> endingValueIterator() { // No replaying, because the endingIterator() is used for determining size return subListMimicRecorder.endingValueIterator(); } @Override public long getValueCount() { return subListMimicRecorder.getValueCount(); } @Override public Iterator<SubList> iterator() { return new ReplayingSubListIterator(); } public void recordedHasNext(boolean hasNext) { hasRecordingCreated = true; hasRecording = hasNext; recordingCreated = false; recording = null; recordingAlreadyReturned = false; } public void recordedNext(SubList next) { hasRecordingCreated = true; hasRecording = true; recordingCreated = true; recording = next; recordingAlreadyReturned = false; } private class ReplayingSubListIterator extends SelectionIterator<SubList> { private ReplayingSubListIterator() { // Reset so the last recording plays again even if it has already played recordingAlreadyReturned = false; } @Override public boolean hasNext() { if (!hasRecordingCreated) { throw new IllegalStateException("Replay must occur after record." + " The recordingSubListSelector (" + subListMimicRecorder + ")'s hasNext() has not been called yet. "); } return hasRecording && !recordingAlreadyReturned; } @Override public SubList next() { if (!recordingCreated) { throw new IllegalStateException("Replay must occur after record." + " The recordingSubListSelector (" + subListMimicRecorder + ")'s next() has not been called yet. "); } if (recordingAlreadyReturned) { throw new NoSuchElementException("The recordingAlreadyReturned (" + recordingAlreadyReturned + ") is impossible. Check if hasNext() returns true before this call."); } // Until the recorder records something, this iterator has no next. recordingAlreadyReturned = true; return recording; } @Override public String toString() { if (hasRecordingCreated && !hasRecording) { return "No next replay"; } return "Next replay (" + (recordingCreated ? recording : "?") + ")"; } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; MimicReplayingSubListSelector<?> that = (MimicReplayingSubListSelector<?>) other; return Objects.equals(subListMimicRecorder, that.subListMimicRecorder); } @Override public int hashCode() { return Objects.hash(subListMimicRecorder); } @Override public String toString() { return "Replaying(" + subListMimicRecorder + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/AbstractMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move; import java.util.Comparator; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.AbstractSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.WeightFactorySelectionSorter; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.CachingMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.FilteringMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.ProbabilityMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.SelectedCountLimitMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.ShufflingMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.SortingMoveSelector; public abstract class AbstractMoveSelectorFactory<Solution_, MoveSelectorConfig_ extends MoveSelectorConfig<MoveSelectorConfig_>> extends AbstractSelectorFactory<Solution_, MoveSelectorConfig_> implements MoveSelectorFactory<Solution_> { public AbstractMoveSelectorFactory(MoveSelectorConfig_ moveSelectorConfig) { super(moveSelectorConfig); } /** * Builds a base {@link MoveSelector} without any advanced capabilities (filtering, sorting, ...). * * @param configPolicy never null * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching * and less would be pointless. * @param randomSelection true is equivalent to {@link SelectionOrder#RANDOM}, * false is equivalent to {@link SelectionOrder#ORIGINAL} * @return never null */ protected abstract MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection); /** * {@inheritDoc} */ @Override public MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, boolean skipNonDoableMoves) { MoveSelectorConfig<?> unfoldedMoveSelectorConfig = buildUnfoldedMoveSelectorConfig(configPolicy); if (unfoldedMoveSelectorConfig != null) { return MoveSelectorFactory.<Solution_> create(unfoldedMoveSelectorConfig) .buildMoveSelector(configPolicy, minimumCacheType, inheritedSelectionOrder, skipNonDoableMoves); } SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(config.getCacheType(), minimumCacheType); SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(config.getSelectionOrder(), inheritedSelectionOrder); validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder); validateSorting(resolvedSelectionOrder); validateProbability(resolvedSelectionOrder); validateSelectedLimit(minimumCacheType); boolean randomMoveSelection = determineBaseRandomSelection(resolvedCacheType, resolvedSelectionOrder); SelectionCacheType selectionCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType); MoveSelector<Solution_> moveSelector = buildBaseMoveSelector(configPolicy, selectionCacheType, randomMoveSelection); validateResolvedCacheType(resolvedCacheType, moveSelector); moveSelector = applyFiltering(moveSelector, skipNonDoableMoves); moveSelector = applySorting(resolvedCacheType, resolvedSelectionOrder, moveSelector); moveSelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, moveSelector); moveSelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, moveSelector); moveSelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, moveSelector); moveSelector = applySelectedLimit(moveSelector); return moveSelector; } /** * To provide unfolded MoveSelectorConfig, override this method in a subclass. * * @param configPolicy never null * @return null if no unfolding is needed */ protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig( HeuristicConfigPolicy<Solution_> configPolicy) { return null; } protected static void checkUnfolded(String configPropertyName, Object configProperty) { if (configProperty == null) { throw new IllegalStateException("The " + configPropertyName + " (" + configProperty + ") should haven been initialized during unfolding."); } } private void validateResolvedCacheType(SelectionCacheType resolvedCacheType, MoveSelector<Solution_> moveSelector) { if (!moveSelector.supportsPhaseAndSolverCaching() && resolvedCacheType.compareTo(SelectionCacheType.PHASE) >= 0) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") has a resolvedCacheType (" + resolvedCacheType + ") that is not supported.\n" + "Maybe don't use a <cacheType> on this type of moveSelector."); } } protected boolean determineBaseRandomSelection(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { switch (resolvedSelectionOrder) { case ORIGINAL: return false; case SORTED: case SHUFFLED: case PROBABILISTIC: // baseValueSelector and lower should be ORIGINAL if they are going to get cached completely return false; case RANDOM: // Predict if caching will occur return resolvedCacheType.isNotCached() || (isBaseInherentlyCached() && !hasFiltering()); default: throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder + ") is not implemented."); } } protected boolean isBaseInherentlyCached() { return false; } private boolean hasFiltering() { return config.getFilterClass() != null; } private MoveSelector<Solution_> applyFiltering(MoveSelector<Solution_> moveSelector, boolean skipNonDoableMoves) { /* * Do not filter out pointless moves in Construction Heuristics and Exhaustive Search, * because the original value of the entity is irrelevant. * If the original value is null and the variable allows unassigned values, * the change move to null must be done too. */ SelectionFilter<Solution_, Move<Solution_>> baseFilter = skipNonDoableMoves ? DoableMoveSelectionFilter.INSTANCE : null; if (hasFiltering()) { SelectionFilter<Solution_, Move<Solution_>> selectionFilter = ConfigUtils.newInstance(config, "filterClass", config.getFilterClass()); SelectionFilter<Solution_, Move<Solution_>> finalFilter = baseFilter == null ? selectionFilter : SelectionFilter.compose(baseFilter, selectionFilter); return FilteringMoveSelector.of(moveSelector, finalFilter); } else if (baseFilter != null) { return FilteringMoveSelector.of(moveSelector, baseFilter); } else { return moveSelector; } } protected void validateSorting(SelectionOrder resolvedSelectionOrder) { if ((config.getSorterComparatorClass() != null || config.getSorterWeightFactoryClass() != null || config.getSorterOrder() != null || config.getSorterClass() != null) && resolvedSelectionOrder != SelectionOrder.SORTED) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with sorterComparatorClass (" + config.getSorterComparatorClass() + ") and sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ") and sorterOrder (" + config.getSorterOrder() + ") and sorterClass (" + config.getSorterClass() + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") that is not " + SelectionOrder.SORTED + "."); } if (config.getSorterComparatorClass() != null && config.getSorterWeightFactoryClass() != null) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") has both a sorterComparatorClass (" + config.getSorterComparatorClass() + ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ")."); } if (config.getSorterComparatorClass() != null && config.getSorterClass() != null) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") has both a sorterComparatorClass (" + config.getSorterComparatorClass() + ") and a sorterClass (" + config.getSorterClass() + ")."); } if (config.getSorterWeightFactoryClass() != null && config.getSorterClass() != null) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") has both a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ") and a sorterClass (" + config.getSorterClass() + ")."); } if (config.getSorterClass() != null && config.getSorterOrder() != null) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with sorterClass (" + config.getSorterClass() + ") has a non-null sorterOrder (" + config.getSorterOrder() + ")."); } } protected MoveSelector<Solution_> applySorting(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) { if (resolvedSelectionOrder == SelectionOrder.SORTED) { SelectionSorter<Solution_, Move<Solution_>> sorter; if (config.getSorterComparatorClass() != null) { Comparator<Move<Solution_>> sorterComparator = ConfigUtils.newInstance(config, "sorterComparatorClass", config.getSorterComparatorClass()); sorter = new ComparatorSelectionSorter<>(sorterComparator, SelectionSorterOrder.resolve(config.getSorterOrder())); } else if (config.getSorterWeightFactoryClass() != null) { SelectionSorterWeightFactory<Solution_, Move<Solution_>> sorterWeightFactory = ConfigUtils.newInstance(config, "sorterWeightFactoryClass", config.getSorterWeightFactoryClass()); sorter = new WeightFactorySelectionSorter<>(sorterWeightFactory, SelectionSorterOrder.resolve(config.getSorterOrder())); } else if (config.getSorterClass() != null) { sorter = ConfigUtils.newInstance(config, "sorterClass", config.getSorterClass()); } else { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs a sorterComparatorClass (" + config.getSorterComparatorClass() + ") or a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ") or a sorterClass (" + config.getSorterClass() + ")."); } moveSelector = new SortingMoveSelector<>(moveSelector, resolvedCacheType, sorter); } return moveSelector; } private void validateProbability(SelectionOrder resolvedSelectionOrder) { if (config.getProbabilityWeightFactoryClass() != null && resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass() + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") that is not " + SelectionOrder.PROBABILISTIC + "."); } } private MoveSelector<Solution_> applyProbability(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) { if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) { if (config.getProbabilityWeightFactoryClass() == null) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with resolvedSelectionOrder (" + resolvedSelectionOrder + ") needs a probabilityWeightFactoryClass (" + config.getProbabilityWeightFactoryClass() + ")."); } SelectionProbabilityWeightFactory<Solution_, Move<Solution_>> probabilityWeightFactory = ConfigUtils.newInstance(config, "probabilityWeightFactoryClass", config.getProbabilityWeightFactoryClass()); moveSelector = new ProbabilityMoveSelector<>(moveSelector, resolvedCacheType, probabilityWeightFactory); } return moveSelector; } private MoveSelector<Solution_> applyShuffling(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) { if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) { moveSelector = new ShufflingMoveSelector<>(moveSelector, resolvedCacheType); } return moveSelector; } private MoveSelector<Solution_> applyCaching(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, MoveSelector<Solution_> moveSelector) { if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(moveSelector.getCacheType()) > 0) { moveSelector = new CachingMoveSelector<>(moveSelector, resolvedCacheType, resolvedSelectionOrder.toRandomSelectionBoolean()); } return moveSelector; } private void validateSelectedLimit(SelectionCacheType minimumCacheType) { if (config.getSelectedCountLimit() != null && minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with selectedCountLimit (" + config.getSelectedCountLimit() + ") has a minimumCacheType (" + minimumCacheType + ") that is higher than " + SelectionCacheType.JUST_IN_TIME + "."); } } private MoveSelector<Solution_> applySelectedLimit(MoveSelector<Solution_> moveSelector) { if (config.getSelectedCountLimit() != null) { moveSelector = new SelectedCountLimitMoveSelector<>(moveSelector, config.getSelectedCountLimit()); } return moveSelector; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/MoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig; import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveListFactoryConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.KOptMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.composite.CartesianProductMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.composite.UnionMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.factory.MoveIteratorFactoryFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.factory.MoveListFactoryFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.ChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.PillarChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.PillarSwapMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.SwapMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.KOptMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListSwapMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.SubListChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.SubListSwapMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorFactory; public interface MoveSelectorFactory<Solution_> { static <Solution_> AbstractMoveSelectorFactory<Solution_, ?> create(MoveSelectorConfig<?> moveSelectorConfig) { if (ChangeMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new ChangeMoveSelectorFactory<>((ChangeMoveSelectorConfig) moveSelectorConfig); } else if (SwapMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new SwapMoveSelectorFactory<>((SwapMoveSelectorConfig) moveSelectorConfig); } else if (ListChangeMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new ListChangeMoveSelectorFactory<>((ListChangeMoveSelectorConfig) moveSelectorConfig); } else if (ListSwapMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new ListSwapMoveSelectorFactory<>((ListSwapMoveSelectorConfig) moveSelectorConfig); } else if (PillarChangeMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new PillarChangeMoveSelectorFactory<>((PillarChangeMoveSelectorConfig) moveSelectorConfig); } else if (PillarSwapMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new PillarSwapMoveSelectorFactory<>((PillarSwapMoveSelectorConfig) moveSelectorConfig); } else if (UnionMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new UnionMoveSelectorFactory<>((UnionMoveSelectorConfig) moveSelectorConfig); } else if (CartesianProductMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new CartesianProductMoveSelectorFactory<>((CartesianProductMoveSelectorConfig) moveSelectorConfig); } else if (SubListChangeMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new SubListChangeMoveSelectorFactory<>((SubListChangeMoveSelectorConfig) moveSelectorConfig); } else if (SubListSwapMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new SubListSwapMoveSelectorFactory<>((SubListSwapMoveSelectorConfig) moveSelectorConfig); } else if (SubChainChangeMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new SubChainChangeMoveSelectorFactory<>((SubChainChangeMoveSelectorConfig) moveSelectorConfig); } else if (SubChainSwapMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new SubChainSwapMoveSelectorFactory<>((SubChainSwapMoveSelectorConfig) moveSelectorConfig); } else if (TailChainSwapMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new TailChainSwapMoveSelectorFactory<>((TailChainSwapMoveSelectorConfig) moveSelectorConfig); } else if (MoveIteratorFactoryConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new MoveIteratorFactoryFactory<>((MoveIteratorFactoryConfig) moveSelectorConfig); } else if (MoveListFactoryConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new MoveListFactoryFactory<>((MoveListFactoryConfig) moveSelectorConfig); } else if (KOptMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new KOptMoveSelectorFactory<>((KOptMoveSelectorConfig) moveSelectorConfig); } else if (KOptListMoveSelectorConfig.class.isAssignableFrom(moveSelectorConfig.getClass())) { return new KOptListMoveSelectorFactory<>((KOptListMoveSelectorConfig) moveSelectorConfig); } else { throw new IllegalArgumentException(String.format("Unknown %s type: (%s).", MoveSelectorConfig.class.getSimpleName(), moveSelectorConfig.getClass().getName())); } } /** * Builds {@link MoveSelector} from the {@link MoveSelectorConfig} and provided parameters. * * @param configPolicy never null * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching * and less would be pointless. * @param inheritedSelectionOrder never null * @param skipNonDoableMoves * @return never null */ MoveSelector<Solution_> buildMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder, boolean skipNonDoableMoves); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/AbstractCompositeMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.composite; import java.util.List; import java.util.stream.Collectors; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelectorFactory; abstract class AbstractCompositeMoveSelectorFactory<Solution_, MoveSelectorConfig_ extends MoveSelectorConfig<MoveSelectorConfig_>> extends AbstractMoveSelectorFactory<Solution_, MoveSelectorConfig_> { public AbstractCompositeMoveSelectorFactory(MoveSelectorConfig_ moveSelectorConfig) { super(moveSelectorConfig); } protected List<MoveSelector<Solution_>> buildInnerMoveSelectors(List<MoveSelectorConfig> innerMoveSelectorList, HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { return innerMoveSelectorList.stream() .map(moveSelectorConfig -> { AbstractMoveSelectorFactory<Solution_, ?> moveSelectorFactory = MoveSelectorFactory.create(moveSelectorConfig); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); return moveSelectorFactory.buildMoveSelector(configPolicy, minimumCacheType, selectionOrder, false); }).collect(Collectors.toList()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/composite/UnionMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.composite; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.NearbyAutoConfigurationMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; public class UnionMoveSelectorFactory<Solution_> extends AbstractCompositeMoveSelectorFactory<Solution_, UnionMoveSelectorConfig> { public UnionMoveSelectorFactory(UnionMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { var moveSelectorConfigList = new LinkedList<>(config.getMoveSelectorList()); if (configPolicy.getNearbyDistanceMeterClass() != null) { for (var selectorConfig : config.getMoveSelectorList()) { if (selectorConfig instanceof NearbyAutoConfigurationMoveSelectorConfig nearbySelectorConfig) { if (nearbySelectorConfig.hasNearbySelectionConfig()) { throw new IllegalArgumentException( """ The selector configuration (%s) already includes the Nearby Selection setting, making it incompatible with the top-level property nearbyDistanceMeterClass (%s). Remove the Nearby setting from the selector configuration or remove the top-level nearbyDistanceMeterClass.""" .formatted(nearbySelectorConfig, configPolicy.getNearbyDistanceMeterClass())); } // Add a new configuration with Nearby Selection enabled moveSelectorConfigList .add(nearbySelectorConfig.enableNearbySelection(configPolicy.getNearbyDistanceMeterClass(), configPolicy.getRandom())); } } } List<MoveSelector<Solution_>> moveSelectorList = buildInnerMoveSelectors(moveSelectorConfigList, configPolicy, minimumCacheType, randomSelection); SelectionProbabilityWeightFactory<Solution_, MoveSelector<Solution_>> selectorProbabilityWeightFactory; if (config.getSelectorProbabilityWeightFactoryClass() != null) { if (!randomSelection) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") with selectorProbabilityWeightFactoryClass (" + config.getSelectorProbabilityWeightFactoryClass() + ") has non-random randomSelection (" + randomSelection + ")."); } selectorProbabilityWeightFactory = ConfigUtils.newInstance(config, "selectorProbabilityWeightFactoryClass", config.getSelectorProbabilityWeightFactoryClass()); } else if (randomSelection) { Map<MoveSelector<Solution_>, Double> fixedProbabilityWeightMap = new HashMap<>(moveSelectorConfigList.size()); for (int i = 0; i < moveSelectorConfigList.size(); i++) { MoveSelectorConfig<?> innerMoveSelectorConfig = moveSelectorConfigList.get(i); MoveSelector<Solution_> moveSelector = moveSelectorList.get(i); Double fixedProbabilityWeight = innerMoveSelectorConfig.getFixedProbabilityWeight(); if (fixedProbabilityWeight != null) { fixedProbabilityWeightMap.put(moveSelector, fixedProbabilityWeight); } } if (fixedProbabilityWeightMap.isEmpty()) { // Will end up using UniformRandomUnionMoveIterator. selectorProbabilityWeightFactory = null; } else { // Will end up using BiasedRandomUnionMoveIterator. selectorProbabilityWeightFactory = new FixedSelectorProbabilityWeightFactory<>(fixedProbabilityWeightMap); } } else { selectorProbabilityWeightFactory = null; } return new UnionMoveSelector<>(moveSelectorList, randomSelection, selectorProbabilityWeightFactory); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/FilteringMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.decorator; import java.util.Iterator; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; public final class FilteringMoveSelector<Solution_> extends AbstractMoveSelector<Solution_> { public static <Solution_> FilteringMoveSelector<Solution_> of(MoveSelector<Solution_> moveSelector, SelectionFilter<Solution_, Move<Solution_>> filter) { if (moveSelector instanceof FilteringMoveSelector<Solution_> filteringMoveSelector) { return new FilteringMoveSelector<>(filteringMoveSelector.childMoveSelector, SelectionFilter.compose(filteringMoveSelector.filter, filter)); } return new FilteringMoveSelector<>(moveSelector, filter); } private final MoveSelector<Solution_> childMoveSelector; private final SelectionFilter<Solution_, Move<Solution_>> filter; private final boolean bailOutEnabled; private ScoreDirector<Solution_> scoreDirector = null; private FilteringMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionFilter<Solution_, Move<Solution_>> filter) { this.childMoveSelector = childMoveSelector; this.filter = filter; bailOutEnabled = childMoveSelector.isNeverEnding(); phaseLifecycleSupport.addEventListener(childMoveSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { super.phaseStarted(phaseScope); scoreDirector = phaseScope.getScoreDirector(); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { super.phaseEnded(phaseScope); scoreDirector = null; } @Override public boolean isCountable() { return childMoveSelector.isCountable(); } @Override public boolean isNeverEnding() { return childMoveSelector.isNeverEnding(); } @Override public long getSize() { return childMoveSelector.getSize(); } @Override public Iterator<Move<Solution_>> iterator() { return new JustInTimeFilteringMoveIterator(childMoveSelector.iterator(), determineBailOutSize()); } private class JustInTimeFilteringMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> { private final Iterator<Move<Solution_>> childMoveIterator; private final long bailOutSize; public JustInTimeFilteringMoveIterator(Iterator<Move<Solution_>> childMoveIterator, long bailOutSize) { this.childMoveIterator = childMoveIterator; this.bailOutSize = bailOutSize; } @Override protected Move<Solution_> createUpcomingSelection() { Move<Solution_> next; long attemptsBeforeBailOut = bailOutSize; do { if (!childMoveIterator.hasNext()) { return noUpcomingSelection(); } if (bailOutEnabled) { // if childMoveIterator is neverEnding and nothing is accepted, bail out of the infinite loop if (attemptsBeforeBailOut <= 0L) { logger.debug("Bailing out of neverEnding selector ({}) after ({}) attempts to avoid infinite loop.", FilteringMoveSelector.this, bailOutSize); return noUpcomingSelection(); } attemptsBeforeBailOut--; } next = childMoveIterator.next(); } while (!accept(scoreDirector, next)); return next; } } private long determineBailOutSize() { if (!bailOutEnabled) { return -1L; } try { return childMoveSelector.getSize() * 10L; } catch (Exception ex) { /* * Some move selectors throw an exception when getSize() is called. * In this case, we choose to disregard it and pick a large-enough bail-out size anyway. * The ${bailOutSize+1}th move could in theory show up where previous ${bailOutSize} moves did not, * but we consider this to be an acceptable risk, * outweighed by the benefit of the solver never running into an endless loop. */ long bailOutSize = Short.MAX_VALUE * 10L; logger.trace( " Never-ending move selector ({}) failed to provide size, choosing a bail-out size of ({}) attempts.", childMoveSelector, bailOutSize, ex); return bailOutSize; } } private boolean accept(ScoreDirector<Solution_> scoreDirector, Move<Solution_> move) { if (filter != null) { if (!filter.accept(scoreDirector, move)) { logger.trace(" Move ({}) filtered out by a selection filter ({}).", move, filter); return false; } } return true; } @Override public String toString() { return "Filtering(" + childMoveSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/decorator/ProbabilityMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.decorator; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge; import ai.timefold.solver.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.solver.random.RandomUtils; import ai.timefold.solver.core.impl.solver.scope.SolverScope; public class ProbabilityMoveSelector<Solution_> extends AbstractMoveSelector<Solution_> implements SelectionCacheLifecycleListener<Solution_> { protected final MoveSelector<Solution_> childMoveSelector; protected final SelectionCacheType cacheType; protected final SelectionProbabilityWeightFactory<Solution_, Move<Solution_>> probabilityWeightFactory; protected NavigableMap<Double, Move<Solution_>> cachedMoveMap = null; protected double probabilityWeightTotal = -1.0; public ProbabilityMoveSelector(MoveSelector<Solution_> childMoveSelector, SelectionCacheType cacheType, SelectionProbabilityWeightFactory<Solution_, ? extends Move<Solution_>> probabilityWeightFactory) { this.childMoveSelector = childMoveSelector; this.cacheType = cacheType; this.probabilityWeightFactory = (SelectionProbabilityWeightFactory<Solution_, Move<Solution_>>) probabilityWeightFactory; if (childMoveSelector.isNeverEnding()) { throw new IllegalStateException("The selector (" + this + ") has a childMoveSelector (" + childMoveSelector + ") with neverEnding (" + childMoveSelector.isNeverEnding() + ")."); } phaseLifecycleSupport.addEventListener(childMoveSelector); if (cacheType.isNotCached()) { throw new IllegalArgumentException("The selector (" + this + ") does not support the cacheType (" + cacheType + ")."); } phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge(cacheType, this)); } @Override public SelectionCacheType getCacheType() { return cacheType; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public void constructCache(SolverScope<Solution_> solverScope) { cachedMoveMap = new TreeMap<>(); ScoreDirector<Solution_> scoreDirector = solverScope.getScoreDirector(); double probabilityWeightOffset = 0L; for (Move<Solution_> entity : childMoveSelector) { double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(scoreDirector, entity); cachedMoveMap.put(probabilityWeightOffset, entity); probabilityWeightOffset += probabilityWeight; } probabilityWeightTotal = probabilityWeightOffset; } @Override public void disposeCache(SolverScope<Solution_> solverScope) { probabilityWeightTotal = -1.0; } @Override public boolean isCountable() { return true; } @Override public boolean isNeverEnding() { return true; } @Override public long getSize() { return cachedMoveMap.size(); } @Override public Iterator<Move<Solution_>> iterator() { return new Iterator<Move<Solution_>>() { @Override public boolean hasNext() { return true; } @Override public Move<Solution_> next() { double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal); Map.Entry<Double, Move<Solution_>> entry = cachedMoveMap.floorEntry(randomOffset); // entry is never null because randomOffset < probabilityWeightTotal return entry.getValue(); } @Override public void remove() { throw new UnsupportedOperationException("The optional operation remove() is not supported."); } }; } @Override public String toString() { return "Probability(" + childMoveSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveIteratorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.factory; import java.util.Iterator; import java.util.Random; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.impl.heuristic.move.Move; /** * An interface to generate an {@link Iterator} of custom {@link Move}s. * <p> * For a more simple version, see {@link MoveListFactory}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public interface MoveIteratorFactory<Solution_, Move_ extends Move<Solution_>> { /** * Called when the phase (for example Local Search) starts. * * @param scoreDirector never null */ default void phaseStarted(ScoreDirector<Solution_> scoreDirector) { } /** * Called when the phase (for example Local Search) ends, * to clean up anything cached since {@link #phaseStarted(ScoreDirector)}. * * @param scoreDirector never null */ default void phaseEnded(ScoreDirector<Solution_> scoreDirector) { } /** * @param scoreDirector never null, the {@link ScoreDirector} * which has the {@link ScoreDirector#getWorkingSolution()} of which the {@link Move}s need to be generated * @return the approximate number of elements generated by {@link #createOriginalMoveIterator(ScoreDirector)} * @throws UnsupportedOperationException if not supported */ long getSize(ScoreDirector<Solution_> scoreDirector); /** * When it is called depends on the configured {@link SelectionCacheType}. * * @param scoreDirector never null, the {@link ScoreDirector} * which has the {@link ScoreDirector#getWorkingSolution()} of which the {@link Move}s need to be generated * @return never null, an {@link Iterator} that will end sooner or later * @throws UnsupportedOperationException if only {@link #createRandomMoveIterator(ScoreDirector, Random)} is * supported */ Iterator<Move_> createOriginalMoveIterator(ScoreDirector<Solution_> scoreDirector); /** * When it is called depends on the configured {@link SelectionCacheType}. * * @param scoreDirector never null, the {@link ScoreDirector} * which has the {@link ScoreDirector#getWorkingSolution()} of which the {@link Move}s need to be generated * @param workingRandom never null, the {@link Random} to use when any random number is needed, * so {@link EnvironmentMode#REPRODUCIBLE} works correctly * @return never null, an {@link Iterator} that is allowed (or even presumed) to be never ending * @throws UnsupportedOperationException if only {@link #createOriginalMoveIterator(ScoreDirector)} is supported */ Iterator<Move_> createRandomMoveIterator(ScoreDirector<Solution_> scoreDirector, Random workingRandom); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveIteratorFactoryFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.factory; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; public class MoveIteratorFactoryFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, MoveIteratorFactoryConfig> { public MoveIteratorFactoryFactory(MoveIteratorFactoryConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { if (config.getMoveIteratorFactoryClass() == null) { throw new IllegalArgumentException("The moveIteratorFactoryConfig (" + config + ") lacks a moveListFactoryClass (" + config.getMoveIteratorFactoryClass() + ")."); } MoveIteratorFactory moveIteratorFactory = ConfigUtils.newInstance(config, "moveIteratorFactoryClass", config.getMoveIteratorFactoryClass()); ConfigUtils.applyCustomProperties(moveIteratorFactory, "moveIteratorFactoryClass", config.getMoveIteratorFactoryCustomProperties(), "moveIteratorFactoryCustomProperties"); return new MoveIteratorFactoryToMoveSelectorBridge<>(moveIteratorFactory, randomSelection); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/factory/MoveListFactoryFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.factory; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveListFactoryConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; public class MoveListFactoryFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, MoveListFactoryConfig> { public MoveListFactoryFactory(MoveListFactoryConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override public MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { if (config.getMoveListFactoryClass() == null) { throw new IllegalArgumentException("The moveListFactoryConfig (" + config + ") lacks a moveListFactoryClass (" + config.getMoveListFactoryClass() + ")."); } MoveListFactory<Solution_> moveListFactory = ConfigUtils.newInstance(config, "moveListFactoryClass", config.getMoveListFactoryClass()); ConfigUtils.applyCustomProperties(moveListFactory, "moveListFactoryClass", config.getMoveListFactoryCustomProperties(), "moveListFactoryCustomProperties"); // MoveListFactoryToMoveSelectorBridge caches by design, so it uses the minimumCacheType if (minimumCacheType.compareTo(SelectionCacheType.STEP) < 0) { // cacheType upgrades to SelectionCacheType.STEP (without shuffling) because JIT is not supported minimumCacheType = SelectionCacheType.STEP; } return new MoveListFactoryToMoveSelectorBridge<>(moveListFactory, minimumCacheType, randomSelection); } @Override protected boolean isBaseInherentlyCached() { return true; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/ChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Collection; import java.util.Collections; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class ChangeMove<Solution_> extends AbstractMove<Solution_> { protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final Object entity; protected final Object toPlanningValue; public ChangeMove(GenuineVariableDescriptor<Solution_> variableDescriptor, Object entity, Object toPlanningValue) { this.variableDescriptor = variableDescriptor; this.entity = entity; this.toPlanningValue = toPlanningValue; } public String getVariableName() { return variableDescriptor.getVariableName(); } public Object getEntity() { return entity; } public Object getToPlanningValue() { return toPlanningValue; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { Object oldValue = variableDescriptor.getValue(entity); return !Objects.equals(oldValue, toPlanningValue); } @Override public ChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { Object oldValue = variableDescriptor.getValue(entity); return new ChangeMove<>(variableDescriptor, entity, oldValue); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; innerScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue); } @Override public ChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new ChangeMove<>(variableDescriptor, destinationScoreDirector.lookUpWorkingObject(entity), destinationScoreDirector.lookUpWorkingObject(toPlanningValue)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<? extends Object> getPlanningEntities() { return Collections.singletonList(entity); } @Override public Collection<? extends Object> getPlanningValues() { return Collections.singletonList(toPlanningValue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ChangeMove<?> other = (ChangeMove<?>) o; return Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(entity, other.entity) && Objects.equals(toPlanningValue, other.toPlanningValue); } @Override public int hashCode() { return Objects.hash(variableDescriptor, entity, toPlanningValue); } @Override public String toString() { Object oldValue = variableDescriptor.getValue(entity); return entity + " {" + oldValue + " -> " + toPlanningValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/ChangeMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.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.move.generic.list.ListChangeMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChangeMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, ChangeMoveSelectorConfig> { private static final Logger LOGGER = LoggerFactory.getLogger(ChangeMoveSelectorFactory.class); public ChangeMoveSelectorFactory(ChangeMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { checkUnfolded("entitySelectorConfig", config.getEntitySelectorConfig()); checkUnfolded("valueSelectorConfig", config.getValueSelectorConfig()); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); EntitySelector<Solution_> entitySelector = EntitySelectorFactory .<Solution_> create(config.getEntitySelectorConfig()) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); ValueSelector<Solution_> valueSelector = ValueSelectorFactory .<Solution_> create(config.getValueSelectorConfig()) .buildValueSelector(configPolicy, entitySelector.getEntityDescriptor(), minimumCacheType, selectionOrder); return new ChangeMoveSelector<>(entitySelector, valueSelector, randomSelection); } @Override protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { Collection<EntityDescriptor<Solution_>> entityDescriptors; EntityDescriptor<Solution_> onlyEntityDescriptor = config.getEntitySelectorConfig() == null ? null : EntitySelectorFactory.<Solution_> create(config.getEntitySelectorConfig()) .extractEntityDescriptor(configPolicy); if (onlyEntityDescriptor != null) { entityDescriptors = Collections.singletonList(onlyEntityDescriptor); } else { entityDescriptors = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors(); } List<GenuineVariableDescriptor<Solution_>> variableDescriptorList = new ArrayList<>(); for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptors) { GenuineVariableDescriptor<Solution_> onlyVariableDescriptor = config.getValueSelectorConfig() == null ? null : ValueSelectorFactory.<Solution_> create(config.getValueSelectorConfig()) .extractVariableDescriptor(configPolicy, entityDescriptor); if (onlyVariableDescriptor != null) { if (onlyEntityDescriptor != null) { if (onlyVariableDescriptor.isListVariable()) { return buildListChangeMoveSelectorConfig((ListVariableDescriptor<?>) onlyVariableDescriptor, true); } // No need for unfolding or deducing return null; } variableDescriptorList.add(onlyVariableDescriptor); } else { variableDescriptorList.addAll(entityDescriptor.getGenuineVariableDescriptorList()); } } return buildUnfoldedMoveSelectorConfig(variableDescriptorList); } protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig( List<GenuineVariableDescriptor<Solution_>> variableDescriptorList) { List<MoveSelectorConfig> moveSelectorConfigList = new ArrayList<>(variableDescriptorList.size()); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { if (variableDescriptor.isListVariable()) { // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() ListChangeMoveSelectorConfig childMoveSelectorConfig = buildListChangeMoveSelectorConfig((ListVariableDescriptor<?>) variableDescriptor, false); moveSelectorConfigList.add(childMoveSelectorConfig); } else { // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() ChangeMoveSelectorConfig childMoveSelectorConfig = new ChangeMoveSelectorConfig(); // Different EntitySelector per child because it is a union EntitySelectorConfig childEntitySelectorConfig = new EntitySelectorConfig(config.getEntitySelectorConfig()); if (childEntitySelectorConfig.getMimicSelectorRef() == null) { childEntitySelectorConfig.setEntityClass(variableDescriptor.getEntityDescriptor().getEntityClass()); } childMoveSelectorConfig.setEntitySelectorConfig(childEntitySelectorConfig); ValueSelectorConfig childValueSelectorConfig = new ValueSelectorConfig(config.getValueSelectorConfig()); if (childValueSelectorConfig.getMimicSelectorRef() == null) { childValueSelectorConfig.setVariableName(variableDescriptor.getVariableName()); } childMoveSelectorConfig.setValueSelectorConfig(childValueSelectorConfig); moveSelectorConfigList.add(childMoveSelectorConfig); } } MoveSelectorConfig<?> unfoldedMoveSelectorConfig; if (moveSelectorConfigList.size() == 1) { unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0); } else { unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList); } unfoldedMoveSelectorConfig.inheritFolded(config); return unfoldedMoveSelectorConfig; } private ListChangeMoveSelectorConfig buildListChangeMoveSelectorConfig(ListVariableDescriptor<?> variableDescriptor, boolean inheritFoldedConfig) { LOGGER.warn( """ The changeMoveSelectorConfig ({}) is being used for a list variable. We are keeping this option through the 1.x release stream for backward compatibility reasons. Please update your solver config to use {} now.""", config, ListChangeMoveSelectorConfig.class.getSimpleName()); ListChangeMoveSelectorConfig listChangeMoveSelectorConfig = ListChangeMoveSelectorFactory.buildChildMoveSelectorConfig( variableDescriptor, config.getValueSelectorConfig(), new DestinationSelectorConfig() .withEntitySelectorConfig(config.getEntitySelectorConfig()) .withValueSelectorConfig(config.getValueSelectorConfig())); if (inheritFoldedConfig) { listChangeMoveSelectorConfig.inheritFolded(config); } return listChangeMoveSelectorConfig; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarChangeMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.valuerange.ValueRange; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * This {@link Move} is not cacheable. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class PillarChangeMove<Solution_> extends AbstractMove<Solution_> { protected final GenuineVariableDescriptor<Solution_> variableDescriptor; protected final List<Object> pillar; protected final Object toPlanningValue; public PillarChangeMove(List<Object> pillar, GenuineVariableDescriptor<Solution_> variableDescriptor, Object toPlanningValue) { this.pillar = pillar; this.variableDescriptor = variableDescriptor; this.toPlanningValue = toPlanningValue; } public List<Object> getPillar() { return pillar; } public String getVariableName() { return variableDescriptor.getVariableName(); } public Object getToPlanningValue() { return toPlanningValue; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { Object oldValue = variableDescriptor.getValue(pillar.get(0)); if (Objects.equals(oldValue, toPlanningValue)) { return false; } if (!variableDescriptor.isValueRangeEntityIndependent()) { ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); Solution_ workingSolution = scoreDirector.getWorkingSolution(); for (Object entity : pillar) { ValueRange rightValueRange = valueRangeDescriptor.extractValueRange(workingSolution, entity); if (!rightValueRange.contains(toPlanningValue)) { return false; } } } return true; } @Override public PillarChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { Object oldValue = variableDescriptor.getValue(pillar.get(0)); return new PillarChangeMove<>(pillar, variableDescriptor, oldValue); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; for (Object entity : pillar) { innerScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue); } } @Override public PillarChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new PillarChangeMove<>(rebaseList(pillar, destinationScoreDirector), variableDescriptor, destinationScoreDirector.lookUpWorkingObject(toPlanningValue)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<? extends Object> getPlanningEntities() { return pillar; } @Override public Collection<? extends Object> getPlanningValues() { return Collections.singletonList(toPlanningValue); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final PillarChangeMove<?> other = (PillarChangeMove<?>) o; return Objects.equals(variableDescriptor, other.variableDescriptor) && Objects.equals(pillar, other.pillar) && Objects.equals(toPlanningValue, other.toPlanningValue); } @Override public int hashCode() { return Objects.hash(variableDescriptor, pillar, toPlanningValue); } @Override public String toString() { Object oldValue = variableDescriptor.getValue(pillar.get(0)); return pillar.toString() + " {" + oldValue + " -> " + toPlanningValue + "}"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarChangeMoveSelector.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Collections; import java.util.Iterator; import java.util.List; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; public class PillarChangeMoveSelector<Solution_> extends GenericMoveSelector<Solution_> { protected final PillarSelector<Solution_> pillarSelector; protected final ValueSelector<Solution_> valueSelector; protected final boolean randomSelection; public PillarChangeMoveSelector(PillarSelector<Solution_> pillarSelector, ValueSelector<Solution_> valueSelector, boolean randomSelection) { this.pillarSelector = pillarSelector; this.valueSelector = valueSelector; this.randomSelection = randomSelection; GenuineVariableDescriptor<Solution_> variableDescriptor = valueSelector.getVariableDescriptor(); boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (isChained) { throw new IllegalStateException("The selector (%s) has a variableDescriptor (%s) which is chained (%s)." .formatted(this, variableDescriptor, isChained)); } phaseLifecycleSupport.addEventListener(pillarSelector); phaseLifecycleSupport.addEventListener(valueSelector); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isCountable() { return pillarSelector.isCountable() && valueSelector.isCountable(); } @Override public boolean isNeverEnding() { return randomSelection || pillarSelector.isNeverEnding() || valueSelector.isNeverEnding(); } @Override public long getSize() { if (!(valueSelector instanceof EntityIndependentValueSelector)) { throw new IllegalArgumentException("To use the method getSize(), the moveSelector (" + this + ") needs to be based on an " + EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")." + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); } return pillarSelector.getSize() * ((EntityIndependentValueSelector) valueSelector).getSize(); } @Override public Iterator<Move<Solution_>> iterator() { if (!randomSelection) { return new OriginalPillarChangeMoveIterator(); } else { return new RandomPillarChangeMoveIterator(); } } private class OriginalPillarChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> { private Iterator<List<Object>> pillarIterator; private Iterator<Object> valueIterator; private List<Object> upcomingPillar; private OriginalPillarChangeMoveIterator() { pillarIterator = pillarSelector.iterator(); // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording) valueIterator = Collections.emptyIterator(); } @Override protected Move<Solution_> createUpcomingSelection() { if (!valueIterator.hasNext()) { if (!pillarIterator.hasNext()) { return noUpcomingSelection(); } upcomingPillar = pillarIterator.next(); valueIterator = valueSelector.iterator(upcomingPillar.get(0)); if (!valueIterator.hasNext()) { // valueSelector is completely empty return noUpcomingSelection(); } } Object toValue = valueIterator.next(); return new PillarChangeMove<>(upcomingPillar, valueSelector.getVariableDescriptor(), toValue); } } private class RandomPillarChangeMoveIterator extends UpcomingSelectionIterator<Move<Solution_>> { private Iterator<List<Object>> pillarIterator; private Iterator<Object> valueIterator; private RandomPillarChangeMoveIterator() { pillarIterator = pillarSelector.iterator(); // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording) valueIterator = Collections.emptyIterator(); } @Override protected Move<Solution_> createUpcomingSelection() { // Ideally, this code should have read: // Object pillar = pillarIterator.next(); // Object toValue = valueIterator.next(); // But empty selectors and ending selectors (such as non-random or shuffled) make it more complex if (!pillarIterator.hasNext()) { pillarIterator = pillarSelector.iterator(); if (!pillarIterator.hasNext()) { // pillarSelector is completely empty return noUpcomingSelection(); } } List<Object> pillar = pillarIterator.next(); if (!valueIterator.hasNext()) { valueIterator = valueSelector.iterator(pillar.get(0)); if (!valueIterator.hasNext()) { // valueSelector is completely empty return noUpcomingSelection(); } } Object toValue = valueIterator.next(); return new PillarChangeMove<>(pillar, valueSelector.getVariableDescriptor(), toValue); } } @Override public String toString() { return getClass().getSimpleName() + "(" + pillarSelector + ", " + valueSelector + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarChangeMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.pillar.PillarSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector; import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; public class PillarChangeMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, PillarChangeMoveSelectorConfig> { public PillarChangeMoveSelectorFactory(PillarChangeMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { PillarSelectorConfig pillarSelectorConfig = Objects.requireNonNullElseGet(config.getPillarSelectorConfig(), PillarSelectorConfig::new); ValueSelectorConfig valueSelectorConfig = Objects.requireNonNullElseGet(config.getValueSelectorConfig(), ValueSelectorConfig::new); List<String> variableNameIncludeList = config.getValueSelectorConfig() == null || config.getValueSelectorConfig().getVariableName() == null ? null : Collections.singletonList(config.getValueSelectorConfig().getVariableName()); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); PillarSelector<Solution_> pillarSelector = PillarSelectorFactory.<Solution_> create(pillarSelectorConfig) .buildPillarSelector(configPolicy, config.getSubPillarType(), (Class<? extends Comparator<Object>>) config.getSubPillarSequenceComparatorClass(), minimumCacheType, selectionOrder, variableNameIncludeList); ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig) .buildValueSelector(configPolicy, pillarSelector.getEntityDescriptor(), minimumCacheType, selectionOrder); return new PillarChangeMoveSelector<>(pillarSelector, valueSelector, randomSelection); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarSwapMove.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.valuerange.ValueRange; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * This {@link Move} is not cacheable. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class PillarSwapMove<Solution_> extends AbstractMove<Solution_> { protected final List<GenuineVariableDescriptor<Solution_>> variableDescriptorList; protected final List<Object> leftPillar; protected final List<Object> rightPillar; public PillarSwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList, List<Object> leftPillar, List<Object> rightPillar) { this.variableDescriptorList = variableDescriptorList; this.leftPillar = leftPillar; this.rightPillar = rightPillar; } public List<String> getVariableNameList() { List<String> variableNameList = new ArrayList<>(variableDescriptorList.size()); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { variableNameList.add(variableDescriptor.getVariableName()); } return variableNameList; } public List<Object> getLeftPillar() { return leftPillar; } public List<Object> getRightPillar() { return rightPillar; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { boolean movable = false; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { Object leftValue = variableDescriptor.getValue(leftPillar.get(0)); Object rightValue = variableDescriptor.getValue(rightPillar.get(0)); if (!Objects.equals(leftValue, rightValue)) { movable = true; if (!variableDescriptor.isValueRangeEntityIndependent()) { ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); Solution_ workingSolution = scoreDirector.getWorkingSolution(); for (Object rightEntity : rightPillar) { ValueRange rightValueRange = valueRangeDescriptor.extractValueRange(workingSolution, rightEntity); if (!rightValueRange.contains(leftValue)) { return false; } } for (Object leftEntity : leftPillar) { ValueRange leftValueRange = valueRangeDescriptor.extractValueRange(workingSolution, leftEntity); if (!leftValueRange.contains(rightValue)) { return false; } } } } } return movable; } @Override public PillarSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { return new PillarSwapMove<>(variableDescriptorList, rightPillar, leftPillar); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { Object oldLeftValue = variableDescriptor.getValue(leftPillar.get(0)); Object oldRightValue = variableDescriptor.getValue(rightPillar.get(0)); if (!Objects.equals(oldLeftValue, oldRightValue)) { for (Object leftEntity : leftPillar) { innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); } for (Object rightEntity : rightPillar) { innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); } } } } @Override public PillarSwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new PillarSwapMove<>(variableDescriptorList, rebaseList(leftPillar, destinationScoreDirector), rebaseList(rightPillar, destinationScoreDirector)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { StringBuilder moveTypeDescription = new StringBuilder(20 * (variableDescriptorList.size() + 1)); moveTypeDescription.append(getClass().getSimpleName()).append("("); String delimiter = ""; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { moveTypeDescription.append(delimiter).append(variableDescriptor.getSimpleEntityAndVariableName()); delimiter = ", "; } moveTypeDescription.append(")"); return moveTypeDescription.toString(); } @Override public Collection<? extends Object> getPlanningEntities() { return CollectionUtils.concat(leftPillar, rightPillar); } @Override public Collection<? extends Object> getPlanningValues() { List<Object> values = new ArrayList<>(variableDescriptorList.size() * 2); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { values.add(variableDescriptor.getValue(leftPillar.get(0))); values.add(variableDescriptor.getValue(rightPillar.get(0))); } return values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final PillarSwapMove<?> other = (PillarSwapMove<?>) o; return Objects.equals(variableDescriptorList, other.variableDescriptorList) && Objects.equals(leftPillar, other.leftPillar) && Objects.equals(rightPillar, other.rightPillar); } @Override public int hashCode() { return Objects.hash(variableDescriptorList, leftPillar, rightPillar); } @Override public String toString() { StringBuilder s = new StringBuilder(variableDescriptorList.size() * 16); s.append(leftPillar).append(" {"); appendVariablesToString(s, leftPillar); s.append("} <-> "); s.append(rightPillar).append(" {"); appendVariablesToString(s, rightPillar); s.append("}"); return s.toString(); } protected void appendVariablesToString(StringBuilder s, List<Object> pillar) { boolean first = true; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { if (!first) { s.append(", "); } s.append(variableDescriptor.getValue(pillar.get(0))); first = false; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/PillarSwapMoveSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector.move.generic; import java.util.Comparator; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.config.heuristic.selector.entity.pillar.PillarSelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelector; import ai.timefold.solver.core.impl.heuristic.selector.entity.pillar.PillarSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; public class PillarSwapMoveSelectorFactory<Solution_> extends AbstractMoveSelectorFactory<Solution_, PillarSwapMoveSelectorConfig> { public PillarSwapMoveSelectorFactory(PillarSwapMoveSelectorConfig moveSelectorConfig) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { PillarSelectorConfig leftPillarSelectorConfig = Objects.requireNonNullElseGet(config.getPillarSelectorConfig(), PillarSelectorConfig::new); PillarSelectorConfig rightPillarSelectorConfig = Objects.requireNonNullElse(config.getSecondaryPillarSelectorConfig(), leftPillarSelectorConfig); PillarSelector<Solution_> leftPillarSelector = buildPillarSelector(leftPillarSelectorConfig, configPolicy, minimumCacheType, randomSelection); PillarSelector<Solution_> rightPillarSelector = buildPillarSelector(rightPillarSelectorConfig, configPolicy, minimumCacheType, randomSelection); List<GenuineVariableDescriptor<Solution_>> variableDescriptorList = deduceVariableDescriptorList(leftPillarSelector.getEntityDescriptor(), config.getVariableNameIncludeList()); return new PillarSwapMoveSelector<>(leftPillarSelector, rightPillarSelector, variableDescriptorList, randomSelection); } private PillarSelector<Solution_> buildPillarSelector(PillarSelectorConfig pillarSelectorConfig, HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { return PillarSelectorFactory.<Solution_> create(pillarSelectorConfig) .buildPillarSelector(configPolicy, config.getSubPillarType(), (Class<? extends Comparator<Object>>) config.getSubPillarSequenceComparatorClass(), minimumCacheType, SelectionOrder.fromRandomSelectionBoolean(randomSelection), config.getVariableNameIncludeList()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.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.domain.valuerange.ValueRange; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; import ai.timefold.solver.core.impl.heuristic.move.AbstractMove; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public 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) { boolean movable = false; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { Object leftValue = variableDescriptor.getValue(leftEntity); Object rightValue = variableDescriptor.getValue(rightEntity); if (!Objects.equals(leftValue, rightValue)) { movable = true; if (!variableDescriptor.isValueRangeEntityIndependent()) { ValueRangeDescriptor<Solution_> valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); Solution_ workingSolution = scoreDirector.getWorkingSolution(); ValueRange rightValueRange = valueRangeDescriptor.extractValueRange(workingSolution, rightEntity); if (!rightValueRange.contains(leftValue)) { return false; } ValueRange leftValueRange = valueRangeDescriptor.extractValueRange(workingSolution, leftEntity); if (!leftValueRange.contains(rightValue)) { return false; } } } } return movable; } @Override public SwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { return new SwapMove<>(variableDescriptorList, rightEntity, leftEntity); } @Override public SwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { return new SwapMove<>(variableDescriptorList, destinationScoreDirector.lookUpWorkingObject(leftEntity), destinationScoreDirector.lookUpWorkingObject(rightEntity)); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { Object oldLeftValue = variableDescriptor.getValue(leftEntity); Object oldRightValue = variableDescriptor.getValue(rightEntity); if (!Objects.equals(oldLeftValue, oldRightValue)) { innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); } } } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { StringBuilder moveTypeDescription = new StringBuilder(20 * (variableDescriptorList.size() + 1)); moveTypeDescription.append(getClass().getSimpleName()).append("("); String delimiter = ""; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { moveTypeDescription.append(delimiter).append(variableDescriptor.getSimpleEntityAndVariableName()); delimiter = ", "; } moveTypeDescription.append(")"); return moveTypeDescription.toString(); } @Override public Collection<? extends Object> getPlanningEntities() { return Arrays.asList(leftEntity, rightEntity); } @Override public Collection<? extends Object> getPlanningValues() { List<Object> values = new ArrayList<>(variableDescriptorList.size() * 2); for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { values.add(variableDescriptor.getValue(leftEntity)); values.add(variableDescriptor.getValue(rightEntity)); } return values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SwapMove<?> swapMove = (SwapMove<?>) o; return Objects.equals(variableDescriptorList, swapMove.variableDescriptorList) && Objects.equals(leftEntity, swapMove.leftEntity) && Objects.equals(rightEntity, swapMove.rightEntity); } @Override public int hashCode() { return Objects.hash(variableDescriptorList, leftEntity, rightEntity); } @Override public String toString() { StringBuilder s = new StringBuilder(variableDescriptorList.size() * 16); s.append(leftEntity).append(" {"); appendVariablesToString(s, leftEntity); s.append("} <-> "); s.append(rightEntity).append(" {"); appendVariablesToString(s, rightEntity); s.append("}"); return s.toString(); } protected void appendVariablesToString(StringBuilder s, Object entity) { boolean first = true; for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) { if (!first) { s.append(", "); } s.append(variableDescriptor.getValue(entity)); first = false; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.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.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.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.impl.domain.entity.descriptor.EntityDescriptor; 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.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 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) { super(moveSelectorConfig); } @Override protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { EntitySelectorConfig entitySelectorConfig = Objects.requireNonNullElseGet(config.getEntitySelectorConfig(), EntitySelectorConfig::new); EntitySelectorConfig secondaryEntitySelectorConfig = Objects.requireNonNullElse(config.getSecondaryEntitySelectorConfig(), entitySelectorConfig); SelectionOrder selectionOrder = SelectionOrder.fromRandomSelectionBoolean(randomSelection); EntitySelector<Solution_> leftEntitySelector = EntitySelectorFactory.<Solution_> create(entitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); EntitySelector<Solution_> rightEntitySelector = EntitySelectorFactory.<Solution_> create(secondaryEntitySelectorConfig) .buildEntitySelector(configPolicy, minimumCacheType, selectionOrder); EntityDescriptor<Solution_> entityDescriptor = leftEntitySelector.getEntityDescriptor(); List<GenuineVariableDescriptor<Solution_>> variableDescriptorList = deduceVariableDescriptorList(entityDescriptor, config.getVariableNameIncludeList()); return new SwapMoveSelector<>(leftEntitySelector, rightEntitySelector, variableDescriptorList, randomSelection); } @Override protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { EntityDescriptor<Solution_> onlyEntityDescriptor = config.getEntitySelectorConfig() == null ? null : EntitySelectorFactory.<Solution_> create(config.getEntitySelectorConfig()) .extractEntityDescriptor(configPolicy); if (config.getSecondaryEntitySelectorConfig() != null) { EntityDescriptor<Solution_> onlySecondaryEntityDescriptor = EntitySelectorFactory.<Solution_> create(config.getSecondaryEntitySelectorConfig()) .extractEntityDescriptor(configPolicy); if (onlyEntityDescriptor != onlySecondaryEntityDescriptor) { throw new IllegalArgumentException("The entitySelector (" + config.getEntitySelectorConfig() + ")'s entityClass (" + (onlyEntityDescriptor == null ? null : onlyEntityDescriptor.getEntityClass()) + ") and secondaryEntitySelectorConfig (" + config.getSecondaryEntitySelectorConfig() + ")'s entityClass (" + (onlySecondaryEntityDescriptor == null ? null : onlySecondaryEntityDescriptor.getEntityClass()) + ") must be the same entity class."); } } if (onlyEntityDescriptor != null) { List<GenuineVariableDescriptor<Solution_>> variableDescriptorList = onlyEntityDescriptor.getGenuineVariableDescriptorList(); // If there is a single list variable, unfold to list swap move selector config. if (variableDescriptorList.size() == 1 && variableDescriptorList.get(0).isListVariable()) { return buildListSwapMoveSelectorConfig(variableDescriptorList.get(0), true); } // Otherwise, make sure there is no list variable, because SwapMove is not supposed to swap list variables. failIfHasAnyGenuineListVariables(onlyEntityDescriptor); // No need for unfolding or deducing return null; } Collection<EntityDescriptor<Solution_>> entityDescriptors = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors(); return buildUnfoldedMoveSelectorConfig(entityDescriptors); } protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(Collection<EntityDescriptor<Solution_>> entityDescriptors) { List<MoveSelectorConfig> moveSelectorConfigList = new ArrayList<>(entityDescriptors.size()); List<GenuineVariableDescriptor<Solution_>> variableDescriptorList = entityDescriptors.iterator().next().getGenuineVariableDescriptorList(); // Only unfold into list swap move selector for the basic scenario with 1 entity and 1 list variable. if (entityDescriptors.size() == 1 && variableDescriptorList.size() == 1 && variableDescriptorList.get(0).isListVariable()) { // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() ListSwapMoveSelectorConfig childMoveSelectorConfig = buildListSwapMoveSelectorConfig(variableDescriptorList.get(0), false); moveSelectorConfigList.add(childMoveSelectorConfig); } else { // More complex scenarios do not support unfolding into list swap => fail fast if there is any list variable. for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptors) { failIfHasAnyGenuineListVariables(entityDescriptor); // No childMoveSelectorConfig.inherit() because of unfoldedMoveSelectorConfig.inheritFolded() SwapMoveSelectorConfig childMoveSelectorConfig = new SwapMoveSelectorConfig(); EntitySelectorConfig childEntitySelectorConfig = new EntitySelectorConfig(config.getEntitySelectorConfig()); if (childEntitySelectorConfig.getMimicSelectorRef() == null) { childEntitySelectorConfig.setEntityClass(entityDescriptor.getEntityClass()); } childMoveSelectorConfig.setEntitySelectorConfig(childEntitySelectorConfig); if (config.getSecondaryEntitySelectorConfig() != null) { EntitySelectorConfig childSecondaryEntitySelectorConfig = new EntitySelectorConfig(config.getSecondaryEntitySelectorConfig()); if (childSecondaryEntitySelectorConfig.getMimicSelectorRef() == null) { childSecondaryEntitySelectorConfig.setEntityClass(entityDescriptor.getEntityClass()); } childMoveSelectorConfig.setSecondaryEntitySelectorConfig(childSecondaryEntitySelectorConfig); } childMoveSelectorConfig.setVariableNameIncludeList(config.getVariableNameIncludeList()); moveSelectorConfigList.add(childMoveSelectorConfig); } } MoveSelectorConfig<?> unfoldedMoveSelectorConfig; if (moveSelectorConfigList.size() == 1) { unfoldedMoveSelectorConfig = moveSelectorConfigList.get(0); } else { unfoldedMoveSelectorConfig = new UnionMoveSelectorConfig(moveSelectorConfigList); } unfoldedMoveSelectorConfig.inheritFolded(config); return unfoldedMoveSelectorConfig; } private static void failIfHasAnyGenuineListVariables(EntityDescriptor<?> entityDescriptor) { if (entityDescriptor.hasAnyGenuineListVariables()) { throw new IllegalArgumentException( "The variableDescriptorList (" + entityDescriptor.getGenuineVariableDescriptorList() + ") has multiple variables and one or more of them is a @" + PlanningListVariable.class.getSimpleName() + ", which is currently not supported."); } } private ListSwapMoveSelectorConfig buildListSwapMoveSelectorConfig(VariableDescriptor<?> variableDescriptor, boolean inheritFoldedConfig) { LOGGER.warn( """ The swapMoveSelectorConfig ({}) is being used for a list variable. 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()); ListSwapMoveSelectorConfig listSwapMoveSelectorConfig = new ListSwapMoveSelectorConfig(); ValueSelectorConfig 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-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/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.InnerScoreDirector; /** * @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 public ChainedChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { Object oldValue = variableDescriptor.getValue(entity); return new ChainedChangeMove<>(variableDescriptor, entity, oldValue, newTrailingEntity, oldTrailingEntity); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; Object oldValue = variableDescriptor.getValue(entity); // Close the old chain if (oldTrailingEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingEntity, oldValue); } // Change the entity innerScoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue); // Reroute the new chain if (newTrailingEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, entity); } } @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-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/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.InnerScoreDirector; /** * @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 public ChainedSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { return new ChainedSwapMove<>(variableDescriptorList, rightEntity, leftEntity, oldLeftTrailingEntityList, oldRightTrailingEntityList); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { for (int i = 0; i < variableDescriptorList.size(); i++) { GenuineVariableDescriptor<Solution_> variableDescriptor = variableDescriptorList.get(i); Object oldLeftValue = variableDescriptor.getValue(leftEntity); Object oldRightValue = variableDescriptor.getValue(rightEntity); if (!Objects.equals(oldLeftValue, oldRightValue)) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; boolean isChained = variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor && basicVariableDescriptor.isChained(); if (!isChained) { innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); } else { Object oldLeftTrailingEntity = oldLeftTrailingEntityList.get(i); Object oldRightTrailingEntity = oldRightTrailingEntityList.get(i); if (oldRightValue == leftEntity) { // Change the right entity innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); // Change the left entity innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightEntity); // Reroute the new left chain if (oldRightTrailingEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, oldRightTrailingEntity, leftEntity); } } else if (oldLeftValue == rightEntity) { // Change the right entity innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); // Change the left entity innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftEntity); // Reroute the new left chain if (oldLeftTrailingEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, oldLeftTrailingEntity, rightEntity); } } else { // Change the left entity innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, oldRightValue); // Change the right entity innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, oldLeftValue); // Reroute the new left chain if (oldRightTrailingEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, oldRightTrailingEntity, leftEntity); } // Reroute the new right chain if (oldLeftTrailingEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, oldLeftTrailingEntity, rightEntity); } } } } } } @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-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/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.InnerScoreDirector; /** * @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 public KOptMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { Object[] undoValues = new Object[values.length]; undoValues[0] = variableDescriptor.getValue(entity); for (int i = 1; i < values.length; i++) { undoValues[i] = values[values.length - i]; } return new KOptMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, entity, undoValues); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; Object firstValue = variableDescriptor.getValue(entity); Object formerEntity = entity; for (int i = 0; i < values.length; i++) { Object value = values[i]; if (formerEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, formerEntity, value); } formerEntity = inverseVariableSupply.getInverseSingleton(value); } if (formerEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, formerEntity, firstValue); } } @Override public KOptMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) { throw new UnsupportedOperationException("https://issues.redhat.com/browse/PLANNER-1250"); // TODO test also disabled // return new KOptMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, // destinationScoreDirector.lookUpWorkingObject(entity), // rebaseArray(values, destinationScoreDirector)); } // ************************************************************************ // Introspection methods // ************************************************************************ @Override public String getSimpleMoveTypeDescription() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } @Override public Collection<? extends Object> getPlanningEntities() { List<Object> allEntityList = new ArrayList<>(values.length + 1); allEntityList.add(entity); for (int i = 0; i < values.length; i++) { Object value = values[i]; allEntityList.add(inverseVariableSupply.getInverseSingleton(value)); } return allEntityList; } @Override public Collection<? extends Object> getPlanningValues() { List<Object> allValueList = new ArrayList<>(values.length + 1); allValueList.add(variableDescriptor.getValue(entity)); Collections.addAll(allValueList, values); return allValueList; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final KOptMove<?> kOptMove = (KOptMove<?>) o; return Objects.equals(entity, kOptMove.entity) && Arrays.equals(values, kOptMove.values); } @Override public int hashCode() { return Objects.hash(entity, Arrays.hashCode(values)); } @Override public String toString() { Object leftValue = variableDescriptor.getValue(entity); StringBuilder builder = new StringBuilder(80 * values.length); builder.append(entity).append(" {").append(leftValue); for (int i = 0; i < values.length; i++) { Object value = values[i]; Object oldEntity = inverseVariableSupply.getInverseSingleton(value); builder.append("} -kOpt-> ").append(oldEntity).append(" {").append(value); } builder.append("}"); return builder.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/heuristic/selector/move/generic/chained/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.InnerScoreDirector; /** * @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 public SubChainChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity()); return new SubChainChangeMove<>(subChain, variableDescriptor, oldFirstValue, newTrailingEntity, oldTrailingLastEntity); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) { Object firstEntity = subChain.getFirstEntity(); Object lastEntity = subChain.getLastEntity(); Object oldFirstValue = variableDescriptor.getValue(firstEntity); // Close the old chain InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector; if (oldTrailingLastEntity != null) { innerScoreDirector.changeVariableFacade(variableDescriptor, oldTrailingLastEntity, oldFirstValue); } // Change the entity innerScoreDirector.changeVariableFacade(variableDescriptor, firstEntity, toPlanningValue); // Reroute the new chain if (newTrailingEntity != null) { innerScoreDirector.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 + "}"; } }