index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/EntityVariableUpdaterLookup.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.impl.util.MutableReference; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public class EntityVariableUpdaterLookup<Solution_> { private final Map<Object, Lookup<Solution_>> variableToEntityLookup; private final Supplier<Lookup<Solution_>> entityLookupSupplier; private int nextId = 0; private interface LookupGetter<Solution_> { List<VariableUpdaterInfo<Solution_>> get(Object entity, VariableMetaModel<Solution_, ?, ?> variableMetaModel); } private interface LookupSetter<Solution_> { void putIfMissing(Object entity, VariableMetaModel<Solution_, ?, ?> variableMetaModel, Supplier<List<VariableUpdaterInfo<Solution_>>> valueSupplier); } private record Lookup<Solution_>( LookupGetter<Solution_> getter, LookupSetter<Solution_> setter) { List<VariableUpdaterInfo<Solution_>> getUpdaters(Object entity, VariableMetaModel<Solution_, ?, ?> variableMetaModel) { return getter.get(entity, variableMetaModel); } void setUpdaters(Object entity, VariableMetaModel<Solution_, ?, ?> variableMetaModel, Supplier<List<VariableUpdaterInfo<Solution_>>> updatersSupplier) { setter.putIfMissing(entity, variableMetaModel, updatersSupplier); } } private EntityVariableUpdaterLookup(Supplier<Lookup<Solution_>> entityLookupSupplier) { this.variableToEntityLookup = new LinkedHashMap<>(); this.entityLookupSupplier = entityLookupSupplier; } public static <Solution_> EntityVariableUpdaterLookup<Solution_> entityIndependentLookup() { Supplier<Lookup<Solution_>> lookupSupplier = () -> { var sharedValue = new MutableReference<List<VariableUpdaterInfo<Solution_>>>(null); return new Lookup<>((ignored1, ignored2) -> sharedValue.getValue(), (ignored1, ignored2, valueSupplier) -> { if (sharedValue.getValue() == null) { sharedValue.setValue(valueSupplier.get()); } }); }; return new EntityVariableUpdaterLookup<>(lookupSupplier); } public static <Solution_> EntityVariableUpdaterLookup<Solution_> entityDependentLookup() { Supplier<Lookup<Solution_>> lookupSupplier = () -> { var valueMap = new IdentityHashMap<Object, List<VariableUpdaterInfo<Solution_>>>(); return new Lookup<>((entity, ignored) -> valueMap.get(entity), (entity, ignored, valueSupplier) -> valueMap.computeIfAbsent(entity, ignored2 -> valueSupplier.get())); }; return new EntityVariableUpdaterLookup<>(lookupSupplier); } public static <Solution_> EntityVariableUpdaterLookup<Solution_> groupedEntityDependentLookup( Function<VariableMetaModel<Solution_, ?, ?>, @Nullable Function<Object, @Nullable Object>> variableToAlignmentKeyMapper) { Supplier<Lookup<Solution_>> lookupSupplier = () -> { var valueMap = new IdentityHashMap<Object, List<VariableUpdaterInfo<Solution_>>>(); var alignmentKeyToUpdaters = new LinkedHashMap<Object, List<VariableUpdaterInfo<Solution_>>>(); LookupGetter<Solution_> valueReader = (entity, variableMetaModel) -> { var alignmentKeyMapper = variableToAlignmentKeyMapper.apply(variableMetaModel); if (alignmentKeyMapper != null) { var alignmentKey = alignmentKeyMapper.apply(entity); if (alignmentKey != null) { return alignmentKeyToUpdaters.get(alignmentKey); } } return valueMap.get(entity); }; LookupSetter<Solution_> valueSetter = (entity, variableMetaModel, valueSupplier) -> { var alignmentKeyMapper = variableToAlignmentKeyMapper.apply(variableMetaModel); if (alignmentKeyMapper != null) { var alignmentKey = alignmentKeyMapper.apply(entity); if (alignmentKey != null) { alignmentKeyToUpdaters.computeIfAbsent(alignmentKey, ignored -> valueSupplier.get()); return; } } valueMap.computeIfAbsent(entity, ignored -> valueSupplier.get()); }; return new Lookup<>(valueReader, valueSetter); }; return new EntityVariableUpdaterLookup<>(lookupSupplier); } public List<VariableUpdaterInfo<Solution_>> computeUpdatersForVariableOnEntity( VariableMetaModel<Solution_, ?, ?> variableMetaModel, Object entity, Supplier<List<VariableUpdaterInfo<Solution_>>> updatersSupplier) { var entityLookup = variableToEntityLookup.computeIfAbsent(variableMetaModel, ignored -> entityLookupSupplier.get()); entityLookup.setUpdaters(entity, variableMetaModel, updatersSupplier); return entityLookup.getUpdaters(entity, variableMetaModel); } public int getNextId() { return nextId++; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/ExternalizedShadowVariableInconsistentProcessor.java
package ai.timefold.solver.core.impl.domain.variable.declarative; public final class ExternalizedShadowVariableInconsistentProcessor<Solution_> { private final ShadowVariablesInconsistentVariableDescriptor<Solution_> shadowVariablesInconsistentVariableDescriptor; public ExternalizedShadowVariableInconsistentProcessor( ShadowVariablesInconsistentVariableDescriptor<Solution_> shadowVariablesInconsistentVariableDescriptor) { this.shadowVariablesInconsistentVariableDescriptor = shadowVariablesInconsistentVariableDescriptor; } Boolean getIsEntityInconsistent(Object entity) { return shadowVariablesInconsistentVariableDescriptor.getValue(entity); } void setIsEntityInconsistent(ChangedVariableNotifier<Solution_> changedVariableNotifier, Object entity, boolean isInconsistent) { changedVariableNotifier.beforeVariableChanged().accept(shadowVariablesInconsistentVariableDescriptor, entity); shadowVariablesInconsistentVariableDescriptor.setValue(entity, isInconsistent); changedVariableNotifier.afterVariableChanged().accept(shadowVariablesInconsistentVariableDescriptor, entity); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/FixedVariableReferenceGraph.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.BitSet; import java.util.PriorityQueue; import java.util.function.IntFunction; import org.jspecify.annotations.NonNull; public final class FixedVariableReferenceGraph<Solution_> extends AbstractVariableReferenceGraph<Solution_, PriorityQueue<BaseTopologicalOrderGraph.NodeTopologicalOrder>> { // These are immutable private final ChangedVariableNotifier<Solution_> changedVariableNotifier; // These are mutable private boolean isFinalized = false; public FixedVariableReferenceGraph(VariableReferenceGraphBuilder<Solution_> outerGraph, IntFunction<TopologicalOrderGraph> graphCreator) { super(outerGraph, graphCreator); // We don't use a bit set to store changes, so pass a one-use instance graph.commitChanges(new BitSet(nodeList.size())); isFinalized = true; // Now that we know the topological order of nodes, add // each node to changed. changedVariableNotifier = outerGraph.changedVariableNotifier; for (var node = 0; node < nodeList.size(); node++) { changeSet.add(graph.getTopologicalOrder(node)); var variableReference = nodeList.get(node).variableReferences().get(0); var entityConsistencyState = variableReference.entityConsistencyState(); if (variableReference.groupEntities() != null) { for (var groupEntity : variableReference.groupEntities()) { entityConsistencyState.setEntityIsInconsistent(changedVariableNotifier, groupEntity, false); } } else { for (var shadowEntity : outerGraph.entityToEntityId.keySet()) { if (variableReference.variableDescriptor().getEntityDescriptor().getEntityClass() .isInstance(shadowEntity)) { entityConsistencyState.setEntityIsInconsistent(changedVariableNotifier, shadowEntity, false); } } } } } @Override protected PriorityQueue<BaseTopologicalOrderGraph.NodeTopologicalOrder> createChangeSet(int instanceCount) { return new PriorityQueue<>(instanceCount); } @Override public void markChanged(@NonNull GraphNode<Solution_> node) { // Before the graph is finalized, ignore changes, since // we don't know the topological order yet if (isFinalized) { changeSet.add(graph.getTopologicalOrder(node.graphNodeId())); } } @Override public void updateChanged() { BitSet visited; if (!changeSet.isEmpty()) { visited = new BitSet(nodeList.size()); visited.set(changeSet.peek().nodeId()); } else { return; } // NOTE: This assumes the user did not add any fixed loops to // their graph (i.e. have two variables ALWAYS depend on one-another). while (!changeSet.isEmpty()) { var changedNode = changeSet.poll(); var entityVariable = nodeList.get(changedNode.nodeId()); var entity = entityVariable.entity(); var shadowVariableReferences = entityVariable.variableReferences(); for (var shadowVariableReference : shadowVariableReferences) { var isVariableChanged = shadowVariableReference.updateIfChanged(entity, changedVariableNotifier); if (isVariableChanged) { for (var iterator = graph.nodeForwardEdges(changedNode.nodeId()); iterator.hasNext();) { var nextNode = iterator.next(); if (visited.get(nextNode)) { continue; } visited.set(nextNode); changeSet.add(graph.getTopologicalOrder(nextNode)); } } } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/GraphChangeType.java
package ai.timefold.solver.core.impl.domain.variable.declarative; public enum GraphChangeType { NO_CHANGE(false), ADD_EDGE(true), REMOVE_EDGE(true); private final boolean affectsGraph; GraphChangeType(boolean affectsGraph) { this.affectsGraph = affectsGraph; } public boolean affectsGraph() { return affectsGraph; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/GraphNode.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.List; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public record GraphNode<Solution_>(Object entity, List<VariableUpdaterInfo<Solution_>> variableReferences, int graphNodeId, int entityId, @Nullable int[] groupEntityIds) { @Override public boolean equals(Object object) { if (!(object instanceof GraphNode<?> that)) return false; return graphNodeId == that.graphNodeId; } @Override public int hashCode() { return Integer.hashCode(graphNodeId); } @Override public String toString() { return entity + ":" + variableReferences.stream().map(VariableUpdaterInfo::id).toList(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/GraphStructure.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.Arrays; import java.util.List; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.util.MutableInt; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @NullMarked public enum GraphStructure { /** * A graph structure that only accepts the empty graph. */ EMPTY, /** * A graph structure without dynamic edges. The topological order * of such a graph is fixed, since edges are neither added nor removed. */ NO_DYNAMIC_EDGES, /** * A graph structure where there is at most * one directional parent for each graph node, and * no indirect parents. * For example, when the only input variable from * a different entity is previous. This allows us * to use a successor function to find affected entities. * Since there is at most a single parent node, such a graph * cannot be inconsistent. */ SINGLE_DIRECTIONAL_PARENT, /** * A graph structure that accepts all graphs that only have a single * entity that uses declarative shadow variables with all directional * parents being the same type. */ ARBITRARY_SINGLE_ENTITY_AT_MOST_ONE_DIRECTIONAL_PARENT_TYPE, /** * A graph structure that accepts all graphs. */ ARBITRARY; private static final Logger LOGGER = LoggerFactory.getLogger(GraphStructure.class); public record GraphStructureAndDirection(GraphStructure structure, @Nullable VariableMetaModel<?, ?, ?> parentMetaModel, @Nullable ParentVariableType direction) { } public static <Solution_> GraphStructureAndDirection determineGraphStructure( SolutionDescriptor<Solution_> solutionDescriptor, Object... entities) { var declarativeShadowVariableDescriptors = solutionDescriptor.getDeclarativeShadowVariableDescriptors(); if (declarativeShadowVariableDescriptors.isEmpty()) { return new GraphStructureAndDirection(EMPTY, null, null); } if (!doEntitiesUseDeclarativeShadowVariables(declarativeShadowVariableDescriptors, entities)) { return new GraphStructureAndDirection(EMPTY, null, null); } var multipleDeclarativeEntityClasses = declarativeShadowVariableDescriptors.stream() .map(variable -> variable.getEntityDescriptor().getEntityClass()) .distinct().count() > 1; final var arbitraryGraphStructure = new GraphStructureAndDirection( multipleDeclarativeEntityClasses ? ARBITRARY : ARBITRARY_SINGLE_ENTITY_AT_MOST_ONE_DIRECTIONAL_PARENT_TYPE, null, null); var rootVariableSources = declarativeShadowVariableDescriptors.stream() .flatMap(descriptor -> Arrays.stream(descriptor.getSources())) .toList(); ParentVariableType directionalType = null; VariableMetaModel<?, ?, ?> parentMetaModel = null; var isArbitrary = multipleDeclarativeEntityClasses; for (var variableSource : rootVariableSources) { var parentVariableType = variableSource.parentVariableType(); LOGGER.trace("{} has parentVariableType {}", variableSource, parentVariableType); switch (parentVariableType) { case GROUP -> { var groupMemberCount = new MutableInt(0); for (var entity : entities) { if (variableSource.rootEntity().isInstance(entity)) { variableSource.valueEntityFunction().accept(entity, fromEntity -> groupMemberCount.increment()); } } if (groupMemberCount.intValue() != 0) { isArbitrary = true; var groupParentVariableType = variableSource.groupParentVariableType(); if (groupParentVariableType != null && groupParentVariableType.isDirectional()) { var groupParentVariableMetamodel = variableSource.variableSourceReferences().get(0).variableMetaModel(); if (parentMetaModel == null) { parentMetaModel = groupParentVariableMetamodel; } else if (!parentMetaModel .equals(variableSource.variableSourceReferences().get(0).variableMetaModel())) { return new GraphStructureAndDirection(GraphStructure.ARBITRARY, null, null); } } } // The group variable is unused/always empty } // CHAINED_NEXT has a complex comparator function; // so use ARBITRARY despite the fact it can be represented using SINGLE_DIRECTIONAL_PARENT case INDIRECT, INVERSE, VARIABLE, CHAINED_NEXT -> isArbitrary = true; case NEXT, PREVIOUS -> { if (parentMetaModel == null) { parentMetaModel = variableSource.variableSourceReferences().get(0).variableMetaModel(); directionalType = parentVariableType; } else if (!parentMetaModel.equals(variableSource.variableSourceReferences().get(0).variableMetaModel())) { return new GraphStructureAndDirection(GraphStructure.ARBITRARY, null, null); } } case NO_PARENT -> { // Do nothing } } } if (isArbitrary) { return arbitraryGraphStructure; } if (directionalType == null) { return new GraphStructureAndDirection(NO_DYNAMIC_EDGES, null, null); } else { // Cannot use a single successor function if there are multiple entity classes return new GraphStructureAndDirection(SINGLE_DIRECTIONAL_PARENT, parentMetaModel, directionalType); } } private static <Solution_> boolean doEntitiesUseDeclarativeShadowVariables( List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptors, Object... entities) { boolean anyDeclarativeEntities = false; for (var declarativeShadowVariable : declarativeShadowVariableDescriptors) { var entityClass = declarativeShadowVariable.getEntityDescriptor().getEntityClass(); for (var entity : entities) { if (entityClass.isInstance(entity)) { anyDeclarativeEntities = true; break; } if (anyDeclarativeEntities) { break; } } } return anyDeclarativeEntities; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/LoopedStatus.java
package ai.timefold.solver.core.impl.domain.variable.declarative; public enum LoopedStatus { UNKNOWN, NOT_LOOPED, LOOPED }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/LoopedTracker.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import static ai.timefold.solver.core.impl.util.DynamicIntArray.ClearingStrategy.PARTIAL; import java.util.Arrays; import ai.timefold.solver.core.impl.util.DynamicIntArray; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public final class LoopedTracker { // For some reason, the array was getting re-created on every values() call. // So, we cache a single instance. private static final LoopedStatus[] VALUES = LoopedStatus.values(); private final DynamicIntArray looped; private final int[][] entityIdToNodes; // Needed so we can update all nodes in a cycle or depended on a cycle // (only nodes that formed a cycle get marked as changed by the graph; // their dependents don't) private final boolean[] entityInconsistentStatusChanged; public LoopedTracker(int nodeCount, int[][] entityIdToNodes) { this.entityIdToNodes = entityIdToNodes; this.entityInconsistentStatusChanged = new boolean[entityIdToNodes.length]; // We never fully clear the array, as that was shown to cause too much GC pressure. this.looped = new DynamicIntArray(nodeCount, PARTIAL); } public void mark(int node, LoopedStatus status) { looped.set(node, status.ordinal()); } public boolean isEntityInconsistent(BaseTopologicalOrderGraph graph, int entityId, @Nullable Boolean wasEntityInconsistent) { for (var entityNode : entityIdToNodes[entityId]) { if (graph.isLooped(this, entityNode)) { if (wasEntityInconsistent == null || !wasEntityInconsistent) { entityInconsistentStatusChanged[entityId] = true; } return true; } } if (wasEntityInconsistent == null || wasEntityInconsistent) { entityInconsistentStatusChanged[entityId] = true; } return false; } public boolean didEntityInconsistentStatusChange(int entityId) { return entityInconsistentStatusChanged[entityId]; } public LoopedStatus status(int node) { // When in the unallocated part of the dynamic array, the value returned is zero. // Therefore it is imperative that LoopedStatus.UNKNOWN be the first element in the enum. return VALUES[looped.get(node)]; } public void clear() { Arrays.fill(entityInconsistentStatusChanged, false); looped.clear(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/ParentVariableType.java
package ai.timefold.solver.core.impl.domain.variable.declarative; public enum ParentVariableType { /** * A variable accessed from the root object. */ NO_PARENT(false, false), /** * A variable accessed from another variable. */ VARIABLE(false, false), /** * Variable on the inverse accessed from the root object. */ INVERSE(false, false), /** * Variable on a next element variable accessed from the root object. */ NEXT(true, false), /** * Variable on a previous element variable accessed from the root object. */ PREVIOUS(true, false), /* * Previous element variable accessed from the root object in a chained model * (i.e. PlanningVariable(graphType = PlanningVariableGraphType.CHAINED)) * is not included, since it would require a source path to accept properties * that are only included on subclasses of the property's type (since the * value of a chained value is either an entity (which has the property) or * an anchor (which does not have the property)). */ /** * Variable on a next element variable accessed from the root object in a chained model. */ CHAINED_NEXT(true, false), /** * A variable accessed indirectly from a fact or variable. */ INDIRECT(false, true), /** * Variables accessed from a group. */ GROUP(false, true); /** * True if the parent variable has a well-defined successor function. * For instance, the successor of a variable with a previous variable * is next. */ private final boolean isDirectional; /** * True if the variable is accessed indirectly from a fact or * a group. */ private final boolean isIndirect; ParentVariableType(boolean isDirectional, boolean isIndirect) { this.isDirectional = isDirectional; this.isIndirect = isIndirect; } public boolean isDirectional() { return isDirectional; } public boolean isIndirect() { return isIndirect; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/PathPart.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.lang.reflect.Member; import java.lang.reflect.Type; public record PathPart(int index, String name, Member member, Class<?> memberType, Type memberGenericType, boolean isCollection) { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/PathPartIterator.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Iterator; import java.util.NoSuchElementException; import ai.timefold.solver.core.api.domain.variable.ShadowSources; import ai.timefold.solver.core.config.util.ConfigUtils; class PathPartIterator implements Iterator<PathPart> { private final Class<?> rootEntity; private final String[] parts; private final String path; private PathPart previous; public PathPartIterator(Class<?> rootEntity, String[] parts, String path) { this.rootEntity = rootEntity; this.parts = parts; this.path = path; previous = new PathPart(-1, "", null, rootEntity, rootEntity, false); } @Override public boolean hasNext() { return previous.index() < parts.length - 1; } @Override public PathPart next() { if (!hasNext()) { throw new NoSuchElementException(); } var index = previous.index() + 1; var name = parts[index]; var isCollection = false; if (name.endsWith(RootVariableSource.COLLECTION_REFERENCE_SUFFIX)) { name = name.substring(0, name.length() - RootVariableSource.COLLECTION_REFERENCE_SUFFIX.length()); isCollection = true; } Class<?> previousType; if (previous.isCollection()) { previousType = ConfigUtils.extractGenericTypeParameterOrFail(ShadowSources.class.getSimpleName(), previous.memberType(), previous.memberType(), previous.memberGenericType(), ShadowSources.class, previous.name()); } else { previousType = previous.memberType(); } var member = RootVariableSource.getMember(rootEntity, path, previousType, name); Class<?> memberType; Type memberGenericType; if (member instanceof Field field) { memberType = field.getType(); memberGenericType = field.getGenericType(); } else if (member instanceof Method method) { memberType = method.getReturnType(); memberGenericType = method.getGenericReturnType(); } else { throw new IllegalStateException("Unsupported member type: " + member.getClass()); } var out = new PathPart(index, name, member, memberType, memberGenericType, isCollection); previous = out; return out; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/RootVariableSource.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.lang.annotation.Annotation; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.Consumer; import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable; import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariableGraphType; import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable; import ai.timefold.solver.core.api.domain.variable.ShadowSources; import ai.timefold.solver.core.api.domain.variable.ShadowVariable; import ai.timefold.solver.core.api.domain.variable.ShadowVariablesInconsistent; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.common.ReflectionHelper; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public record RootVariableSource<Entity_, Value_>( Class<? extends Entity_> rootEntity, List<MemberAccessor> listMemberAccessors, BiConsumer<Object, Consumer<Value_>> valueEntityFunction, List<VariableSourceReference> variableSourceReferences, String variablePath, ParentVariableType parentVariableType, @Nullable ParentVariableType groupParentVariableType) { public static final String COLLECTION_REFERENCE_SUFFIX = "[]"; public static final String MEMBER_SEPERATOR_REGEX = "\\."; private record VariablePath(Class<?> variableEntityClass, String variableName, List<MemberAccessor> memberAccessorsBeforeEntity, List<MemberAccessor> memberAccessorsAfterEntity) { public @Nullable Object findTargetEntity(Object entity) { var currentEntity = entity; for (var member : memberAccessorsAfterEntity) { currentEntity = member.executeGetter(currentEntity); if (currentEntity == null) { return null; } } return currentEntity; } } public static Iterator<PathPart> pathIterator(Class<?> rootEntity, String path) { final var parts = path.split(MEMBER_SEPERATOR_REGEX); return new PathPartIterator(rootEntity, parts, path); } public static <Entity_, Value_> RootVariableSource<Entity_, Value_> from( PlanningSolutionMetaModel<?> solutionMetaModel, Class<? extends Entity_> rootEntityClass, String targetVariableName, String variablePath, MemberAccessorFactory memberAccessorFactory, DescriptorPolicy descriptorPolicy) { List<MemberAccessor> chainToVariable = new ArrayList<>(); List<MemberAccessor> listMemberAccessors = new ArrayList<>(); var hasListMemberAccessor = false; List<List<MemberAccessor>> chainStartingFromSourceVariableList = new ArrayList<>(); List<Integer> factCountAfterSourceVariableToNextVariableList = new ArrayList<>(); boolean isAfterVariable = false; Class<?> currentEntity = rootEntityClass; var factCountSinceLastVariable = 0; ParentVariableType parentVariableType = null; ParentVariableType groupParentVariableType = null; for (var iterator = pathIterator(rootEntityClass, variablePath); iterator.hasNext();) { var pathPart = iterator.next(); if (pathPart.isCollection()) { if (isAfterVariable) { throw new IllegalArgumentException( "The source path (%s) starting from root class (%s) accesses a collection (%s[]) after a variable (%s), which is not allowed." .formatted(variablePath, rootEntityClass.getSimpleName(), pathPart.name(), chainStartingFromSourceVariableList.get(0).get(0).getName())); } if (hasListMemberAccessor) { throw new IllegalArgumentException( "The source path (%s) starting from root class (%s) accesses a collection (%s[]) after another collection (%s), which is not allowed." .formatted(variablePath, rootEntityClass.getSimpleName(), pathPart.name(), listMemberAccessors.get(listMemberAccessors.size() - 1).getName())); } var memberAccessor = getMemberAccessor(pathPart.member(), memberAccessorFactory, descriptorPolicy); listMemberAccessors.add(memberAccessor); chainToVariable = new ArrayList<>(); factCountSinceLastVariable = 0; currentEntity = ConfigUtils.extractGenericTypeParameterOrFail(ShadowSources.class.getSimpleName(), currentEntity, memberAccessor.getType(), memberAccessor.getGenericType(), ShadowSources.class, memberAccessor.getName()); parentVariableType = ParentVariableType.GROUP; hasListMemberAccessor = true; } else { var memberAccessor = getMemberAccessor(pathPart.member(), memberAccessorFactory, descriptorPolicy); if (!hasListMemberAccessor) { listMemberAccessors.add(memberAccessor); } var isVariable = isVariable(solutionMetaModel, memberAccessor.getDeclaringClass(), pathPart.name()); chainToVariable.add(memberAccessor); for (var chain : chainStartingFromSourceVariableList) { chain.add(memberAccessor); } if (isVariable) { List<MemberAccessor> chainStartingFromSourceVariable = new ArrayList<>(); chainStartingFromSourceVariable.add(memberAccessor); chainStartingFromSourceVariableList.add(chainStartingFromSourceVariable); factCountAfterSourceVariableToNextVariableList.add(factCountSinceLastVariable); isAfterVariable = true; factCountSinceLastVariable = 0; if (parentVariableType == null) { parentVariableType = determineParentVariableType(rootEntityClass, variablePath, chainToVariable, memberAccessor); } if (hasListMemberAccessor && groupParentVariableType == null) { groupParentVariableType = determineParentVariableType(rootEntityClass, variablePath, chainToVariable, memberAccessor); } } else { factCountSinceLastVariable++; if (factCountSinceLastVariable == 2) { throw new IllegalArgumentException( "The source path (%s) starting from root entity (%s) referencing multiple facts (%s, %s) in a row." .formatted(variablePath, rootEntityClass.getSimpleName(), chainToVariable.get(chainToVariable.size() - 2).getName(), chainToVariable.get(chainToVariable.size() - 1).getName())); } } currentEntity = memberAccessor.getType(); } } BiConsumer<Object, Consumer<Value_>> valueEntityFunction; List<MemberAccessor> chainToVariableEntity = chainToVariable.subList(0, chainToVariable.size() - 1); if (!hasListMemberAccessor) { valueEntityFunction = getRegularSourceEntityVisitor(chainToVariableEntity); listMemberAccessors.clear(); } else { valueEntityFunction = getCollectionSourceEntityVisitor(listMemberAccessors, chainToVariableEntity); } List<VariableSourceReference> variableSourceReferences = new ArrayList<>(); for (var i = 0; i < chainStartingFromSourceVariableList.size(); i++) { var chainStartingFromSourceVariable = chainStartingFromSourceVariableList.get(i); var newSourceReference = createVariableSourceReferenceFromChain(variablePath, listMemberAccessors, solutionMetaModel, rootEntityClass, targetVariableName, chainStartingFromSourceVariable, chainToVariable, factCountAfterSourceVariableToNextVariableList.get(i), i == 0, i == chainStartingFromSourceVariableList.size() - 1); variableSourceReferences.add(newSourceReference); } if (variableSourceReferences.isEmpty()) { throw new IllegalArgumentException( "The source path (%s) starting from root entity class (%s) does not reference any variables." .formatted(variablePath, rootEntityClass.getSimpleName())); } if (factCountSinceLastVariable != 0) { throw new IllegalArgumentException( "The source path (%s) starting from root entity class (%s) does not end on a variable." .formatted(variablePath, rootEntityClass.getSimpleName())); } for (var variableSourceReference : variableSourceReferences) { assertIsValidVariableReference(rootEntityClass, variablePath, variableSourceReference); } if (!parentVariableType.isIndirect() && variableSourceReferences.size() == 1) { // No variables are accessed from the parent, so there no // parent variable. parentVariableType = ParentVariableType.NO_PARENT; } if (!parentVariableType.isIndirect() && chainToVariable.size() > 2) { // Child variable is accessed from a fact from the parent, // so it is an indirect variable. parentVariableType = ParentVariableType.INDIRECT; } if (variableSourceReferences.size() > 2) { throw new IllegalArgumentException(""" The source path (%s) starting from root class (%s) \ references (%d) variables while a maximum of 2 is allowed." """.formatted(variablePath, rootEntityClass.getCanonicalName(), variableSourceReferences.size())); } return new RootVariableSource<>(rootEntityClass, listMemberAccessors, valueEntityFunction, variableSourceReferences, variablePath, parentVariableType, groupParentVariableType); } public @NonNull BiConsumer<Object, Consumer<Object>> getEntityVisitor(List<MemberAccessor> chainToEntity) { if (listMemberAccessors.isEmpty()) { return getRegularSourceEntityVisitor(chainToEntity); } else { return getCollectionSourceEntityVisitor(listMemberAccessors, chainToEntity); } } private static <Value_> @NonNull BiConsumer<Object, Consumer<Value_>> getRegularSourceEntityVisitor( List<MemberAccessor> finalChainToVariable) { return (entity, consumer) -> { Object current = entity; for (var accessor : finalChainToVariable) { current = accessor.executeGetter(current); if (current == null) { return; } } consumer.accept((Value_) current); }; } private static <Value_> @NonNull BiConsumer<Object, Consumer<Value_>> getCollectionSourceEntityVisitor( List<MemberAccessor> listMemberAccessors, List<MemberAccessor> finalChainToVariable) { var entityListMemberAccessor = RootVariableSource.<Iterable<Object>> getRegularSourceEntityVisitor(listMemberAccessors); var elementSourceEntityVisitor = RootVariableSource.<Value_> getRegularSourceEntityVisitor(finalChainToVariable); return (entity, consumer) -> entityListMemberAccessor.accept(entity, iterable -> { for (var item : iterable) { elementSourceEntityVisitor.accept(item, consumer); } }); } private static <Entity_> @NonNull VariableSourceReference createVariableSourceReferenceFromChain( String variablePath, List<MemberAccessor> listMemberAccessors, PlanningSolutionMetaModel<?> solutionMetaModel, Class<? extends Entity_> rootEntityClass, String targetVariableName, List<MemberAccessor> afterChain, List<MemberAccessor> chainToVariable, int factCountTillNextVariable, boolean isTopLevel, boolean isBottomLevel) { var variableMemberAccessor = afterChain.get(0); var sourceVariablePath = new VariablePath(variableMemberAccessor.getDeclaringClass(), variableMemberAccessor.getName(), chainToVariable.subList(0, chainToVariable.size() - afterChain.size()), afterChain); VariableMetaModel<?, ?, ?> downstreamDeclarativeVariable = null; var maybeDownstreamVariable = afterChain.remove(afterChain.size() - 1); if (isDeclarativeShadowVariable(maybeDownstreamVariable)) { downstreamDeclarativeVariable = solutionMetaModel.entity(maybeDownstreamVariable.getDeclaringClass()) .variable(maybeDownstreamVariable.getName()); } var isDeclarative = isDeclarativeShadowVariable(variableMemberAccessor); if (!isDeclarative && !isTopLevel && factCountTillNextVariable != 0) { throw new IllegalArgumentException( """ The source path (%s) starting from root class (%s) \ has a non-declarative variable (%s) accessed via a fact after another variable." """.formatted(variablePath, rootEntityClass.getCanonicalName(), variableMemberAccessor.getName())); } return new VariableSourceReference( solutionMetaModel.entity(variableMemberAccessor.getDeclaringClass()).variable(variableMemberAccessor.getName()), sourceVariablePath.memberAccessorsBeforeEntity, isTopLevel && sourceVariablePath.memberAccessorsBeforeEntity.isEmpty() && listMemberAccessors.isEmpty(), isTopLevel, isBottomLevel, isDeclarative, solutionMetaModel.entity(rootEntityClass).variable(targetVariableName), downstreamDeclarativeVariable, sourceVariablePath::findTargetEntity); } private static void assertIsValidVariableReference(Class<?> rootEntityClass, String variablePath, VariableSourceReference variableSourceReference) { var sourceVariableId = variableSourceReference.variableMetaModel(); if (variableSourceReference.isDeclarative() && variableSourceReference.downstreamDeclarativeVariableMetamodel() != null && !variableSourceReference.isBottomLevel()) { throw new IllegalArgumentException( "The source path (%s) starting from root entity class (%s) accesses a declarative shadow variable (%s) from another declarative shadow variable (%s)." .formatted(variablePath, rootEntityClass.getSimpleName(), variableSourceReference.downstreamDeclarativeVariableMetamodel().name(), sourceVariableId.name())); } } public static Member getMember(Class<?> rootClass, String sourcePath, Class<?> declaringClass, String memberName) { var field = ReflectionHelper.getDeclaredField(declaringClass, memberName); var getterMethod = ReflectionHelper.getDeclaredGetterMethod(declaringClass, memberName); if (field == null && getterMethod == null) { throw new IllegalArgumentException( "The source path (%s) starting from root class (%s) references a member (%s) on class (%s) that does not exist." .formatted(sourcePath, rootClass.getSimpleName(), memberName, declaringClass.getSimpleName())); } else if (field != null && getterMethod == null) { return field; } else if (field == null) { // method is not guaranteed to not be null return getterMethod; } else { var fieldType = field.getType(); var methodType = getterMethod.getReturnType(); if (fieldType.equals(methodType)) { // Prefer getter if types are the same return getterMethod; } else if (fieldType.isAssignableFrom(methodType)) { // Getter is more specific than field return getterMethod; } else if (methodType.isAssignableFrom(fieldType)) { // Field is more specific than getter return field; } else { // Field and getter are not covariant; prefer method return getterMethod; } } } private static MemberAccessor getMemberAccessor(Member member, MemberAccessorFactory memberAccessorFactory, DescriptorPolicy descriptorPolicy) { return memberAccessorFactory.buildAndCacheMemberAccessor(member, MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD, descriptorPolicy.getDomainAccessType()); } public static boolean isVariable(PlanningSolutionMetaModel<?> metaModel, Class<?> declaringClass, String memberName) { if (!metaModel.hasEntity(declaringClass)) { return false; } return metaModel.entity(declaringClass).hasVariable(memberName); } private static ParentVariableType determineParentVariableType(Class<?> rootClass, String variablePath, List<MemberAccessor> chain, MemberAccessor memberAccessor) { var isIndirect = chain.size() > 1; var declaringClass = memberAccessor.getDeclaringClass(); var memberName = memberAccessor.getName(); if (isIndirect) { return ParentVariableType.INDIRECT; } if (getAnnotation(declaringClass, memberName, PreviousElementShadowVariable.class) != null) { return ParentVariableType.PREVIOUS; } if (getAnnotation(declaringClass, memberName, NextElementShadowVariable.class) != null) { return ParentVariableType.NEXT; } if (getAnnotation(declaringClass, memberName, InverseRelationShadowVariable.class) != null) { // inverse can be both directional and undirectional; // it is directional in chained models, undirectional otherwise var inverseVariable = Objects.requireNonNull(getAnnotation(declaringClass, memberName, InverseRelationShadowVariable.class)); var sourceClass = memberAccessor.getType(); var variableName = inverseVariable.sourceVariableName(); PlanningVariable sourcePlanningVariable = getAnnotation(sourceClass, variableName, PlanningVariable.class); if (sourcePlanningVariable == null) { // Must have a PlanningListVariable instead return ParentVariableType.INVERSE; } if (sourcePlanningVariable.graphType() == PlanningVariableGraphType.CHAINED) { return ParentVariableType.CHAINED_NEXT; } else { return ParentVariableType.INVERSE; } } if (getAnnotation(declaringClass, memberName, PlanningVariable.class) != null) { return ParentVariableType.VARIABLE; } if (getAnnotation(declaringClass, memberName, ShadowVariablesInconsistent.class) != null) { throw new IllegalArgumentException(""" The source path (%s) starting from root class (%s) accesses a @%s property (%s). Supplier methods are only called when all of their dependencies are consistent, so reading @%s properties are not needed since they are guaranteed to be false when the supplier is called. Maybe remove the source path (%s) from the @%s? """.formatted( variablePath, rootClass.getCanonicalName(), ShadowVariablesInconsistent.class.getSimpleName(), memberName, ShadowVariablesInconsistent.class.getSimpleName(), variablePath, ShadowSources.class.getSimpleName())); } return ParentVariableType.NO_PARENT; } @Nullable private static <T extends Annotation> T getAnnotation(Class<?> declaringClass, String memberName, Class<? extends T> annotationClass) { var currentClass = declaringClass; while (currentClass != null) { var field = ReflectionHelper.getDeclaredField(currentClass, memberName); var getterMethod = ReflectionHelper.getDeclaredGetterMethod(currentClass, memberName); if (field != null && field.getAnnotation(annotationClass) != null) { return field.getAnnotation(annotationClass); } if (getterMethod != null && getterMethod.getAnnotation(annotationClass) != null) { return getterMethod.getAnnotation(annotationClass); } // Need to also check superclass to support extended models; // the subclass might have overridden an annotated method. currentClass = currentClass.getSuperclass(); } return null; } private static boolean isDeclarativeShadowVariable(MemberAccessor memberAccessor) { var shadowVariable = getAnnotation(memberAccessor.getDeclaringClass(), memberAccessor.getName(), ShadowVariable.class); if (shadowVariable == null) { return false; } return !shadowVariable.supplierName().isEmpty(); } @Override public @NonNull String toString() { return variablePath; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/ShadowVariablesInconsistentVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.Collection; import java.util.Collections; import java.util.List; 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.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; public class ShadowVariablesInconsistentVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { public ShadowVariablesInconsistentVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } @Override public void processAnnotations(DescriptorPolicy descriptorPolicy) { // no action needed } @Override public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() { return Collections.emptyList(); } @Override public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() { return Collections.emptyList(); } @Override public Demand<?> getProvidedDemand() { return null; } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { return Collections.emptyList(); } @Override public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { // no action needed } @Override public boolean isListVariableSource() { return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/SingleDirectionalParentVariableReferenceGraph.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import java.util.function.UnaryOperator; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; public final class SingleDirectionalParentVariableReferenceGraph<Solution_> implements VariableReferenceGraph { private final Set<VariableMetaModel<?, ?, ?>> monitoredSourceVariableSet; private final VariableUpdaterInfo<Solution_>[] sortedVariableUpdaterInfos; private final UnaryOperator<Object> successorFunction; private final Comparator<Object> topologicalOrderComparator; private final UnaryOperator<Object> keyFunction; private final ChangedVariableNotifier<Solution_> changedVariableNotifier; private final List<Object> changedEntities; private final Class<?> monitoredEntityClass; private boolean isUpdating; @SuppressWarnings("unchecked") public SingleDirectionalParentVariableReferenceGraph( ConsistencyTracker<Solution_> consistencyTracker, List<DeclarativeShadowVariableDescriptor<Solution_>> sortedDeclarativeShadowVariableDescriptors, TopologicalSorter topologicalSorter, ChangedVariableNotifier<Solution_> changedVariableNotifier, Object[] entities) { monitoredEntityClass = sortedDeclarativeShadowVariableDescriptors.get(0).getEntityDescriptor().getEntityClass(); sortedVariableUpdaterInfos = new VariableUpdaterInfo[sortedDeclarativeShadowVariableDescriptors.size()]; monitoredSourceVariableSet = new HashSet<>(); changedEntities = new ArrayList<>(); isUpdating = false; this.successorFunction = topologicalSorter.successor(); this.topologicalOrderComparator = topologicalSorter.comparator(); this.keyFunction = topologicalSorter.key(); this.changedVariableNotifier = changedVariableNotifier; var shadowEntities = Arrays.stream(entities).filter(monitoredEntityClass::isInstance) .sorted(topologicalOrderComparator).toArray(); var entityConsistencyState = consistencyTracker.getDeclarativeEntityConsistencyState( sortedDeclarativeShadowVariableDescriptors.get(0).getEntityDescriptor()); var updaterIndex = 0; for (var variableDescriptor : sortedDeclarativeShadowVariableDescriptors) { var variableMetaModel = variableDescriptor.getVariableMetaModel(); var variableUpdaterInfo = new VariableUpdaterInfo<>( variableMetaModel, updaterIndex, variableDescriptor, entityConsistencyState, variableDescriptor.getMemberAccessor(), variableDescriptor.getCalculator()::executeGetter); sortedVariableUpdaterInfos[updaterIndex++] = variableUpdaterInfo; for (var source : variableDescriptor.getSources()) { for (var sourceReference : source.variableSourceReferences()) { monitoredSourceVariableSet.add(sourceReference.variableMetaModel()); } } } changedEntities.addAll(List.of(shadowEntities)); for (var shadowEntity : shadowEntities) { entityConsistencyState.setEntityIsInconsistent(changedVariableNotifier, shadowEntity, false); } updateChanged(); } @Override public void updateChanged() { isUpdating = true; changedEntities.sort(topologicalOrderComparator); var processed = new IdentityHashMap<>(); for (var changedEntity : changedEntities) { var key = keyFunction.apply(changedEntity); var lastProcessed = processed.get(key); if (lastProcessed == null || topologicalOrderComparator.compare(lastProcessed, changedEntity) < 0) { lastProcessed = updateChanged(changedEntity); processed.put(key, lastProcessed); } } isUpdating = false; changedEntities.clear(); } /** * Update entities and its successor until one of them does not change. * * @param entity The first entity to process. * @return The last processed entity (i.e. the first entity that did not change). */ private Object updateChanged(Object entity) { var current = entity; var previous = current; while (current != null) { var anyChanged = false; for (var updater : sortedVariableUpdaterInfos) { anyChanged |= updater.updateIfChanged(current, changedVariableNotifier); } if (anyChanged) { previous = current; current = successorFunction.apply(current); } else { return current; } } return previous; } @Override public void beforeVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) { // Do nothing } @Override public void afterVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) { if (!isUpdating && monitoredSourceVariableSet.contains(variableReference) && monitoredEntityClass.isInstance(entity)) { changedEntities.add(entity); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/TopologicalOrderGraph.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.BitSet; import java.util.List; public interface TopologicalOrderGraph extends BaseTopologicalOrderGraph { /** * Called when all edge modifications are queued. * After this method returns, {@link #getTopologicalOrder(int)} * must be accurate for every node in the graph. */ void commitChanges(BitSet changed); /** * Called on graph creation to supply metadata about the graph nodes. * * @param nodes A list of entity/variable pairs, where the nth item in the list * corresponds to the node with id n in the graph. */ default <Solution_> void withNodeData(List<GraphNode<Solution_>> nodes) { } /** * Called when a graph edge is added. * The operation is added to a batch and only executed when {@link #commitChanges(BitSet)} is called. * <p> * {@link #getTopologicalOrder(int)} is allowed to be invalid * when this method returns. */ void addEdge(int from, int to); /** * Called when a graph edge is removed. * The operation is added to a batch and only executed when {@link #commitChanges(BitSet)} is called. * <p> * {@link #getTopologicalOrder(int)} is allowed to be invalid * when this method returns. */ void removeEdge(int from, int to); void forEachEdge(EdgeConsumer edgeConsumer); @FunctionalInterface interface EdgeConsumer { void accept(int from, int to); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/TopologicalSorter.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.Comparator; import java.util.function.UnaryOperator; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public record TopologicalSorter(UnaryOperator<@Nullable Object> successor, Comparator<Object> comparator, UnaryOperator<Object> key) { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/VariableReferenceGraph.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; public sealed interface VariableReferenceGraph permits AbstractVariableReferenceGraph, EmptyVariableReferenceGraph, SingleDirectionalParentVariableReferenceGraph { void updateChanged(); void beforeVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity); void afterVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/VariableReferenceGraphBuilder.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.IntFunction; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.variable.ShadowSources; import ai.timefold.solver.core.api.domain.variable.ShadowVariable; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NonNull; public final class VariableReferenceGraphBuilder<Solution_> { final ChangedVariableNotifier<Solution_> changedVariableNotifier; final Map<VariableMetaModel<?, ?, ?>, List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>>> variableReferenceToBeforeProcessor; final Map<VariableMetaModel<?, ?, ?>, List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>>> variableReferenceToAfterProcessor; final List<GraphNode<Solution_>> nodeList; final Map<Object, Integer> entityToEntityId; final Map<GraphNode<Solution_>, List<GraphNode<Solution_>>> fixedEdges; final Map<VariableMetaModel<?, ?, ?>, Map<Object, GraphNode<Solution_>>> variableReferenceToContainingNodeMap; final Map<Integer, Map<Object, GraphNode<Solution_>>> variableGroupIdToContainingNodeMap; boolean isGraphFixed; public VariableReferenceGraphBuilder(ChangedVariableNotifier<Solution_> changedVariableNotifier) { this.changedVariableNotifier = changedVariableNotifier; nodeList = new ArrayList<>(); variableReferenceToContainingNodeMap = new HashMap<>(); variableGroupIdToContainingNodeMap = new HashMap<>(); variableReferenceToBeforeProcessor = new HashMap<>(); variableReferenceToAfterProcessor = new HashMap<>(); fixedEdges = new HashMap<>(); entityToEntityId = new IdentityHashMap<>(); isGraphFixed = true; } public <Entity_> void addVariableReferenceEntity(Entity_ entity, List<VariableUpdaterInfo<Solution_>> variableReferences) { var groupId = variableReferences.get(0).groupId(); var isGroup = variableReferences.get(0).groupEntities() != null; var entityRepresentative = entity; if (isGroup) { entityRepresentative = (Entity_) variableReferences.get(0).groupEntities()[0]; } var instanceMap = variableGroupIdToContainingNodeMap.get(groupId); var instance = instanceMap == null ? null : instanceMap.get(entityRepresentative); if (instance != null) { return; } if (instanceMap == null) { instanceMap = new IdentityHashMap<>(); variableGroupIdToContainingNodeMap.put(groupId, instanceMap); } var entityId = entityToEntityId.computeIfAbsent(entityRepresentative, ignored -> entityToEntityId.size()); int[] groupEntityIds = null; if (isGroup) { var groupEntities = variableReferences.get(0).groupEntities(); groupEntityIds = new int[groupEntities.length]; for (var i = 0; i < groupEntityIds.length; i++) { var groupEntity = variableReferences.get(0).groupEntities()[i]; groupEntityIds[i] = entityToEntityId.computeIfAbsent(groupEntity, ignored -> entityToEntityId.size()); } } var node = new GraphNode<>(entityRepresentative, variableReferences, nodeList.size(), entityId, groupEntityIds); if (isGroup) { for (var groupEntity : variableReferences.get(0).groupEntities()) { addToInstanceMaps(instanceMap, groupEntity, node, variableReferences); } } else { addToInstanceMaps(instanceMap, entity, node, variableReferences); } nodeList.add(node); } private void addToInstanceMaps(Map<Object, GraphNode<Solution_>> instanceMap, Object entity, GraphNode<Solution_> node, List<VariableUpdaterInfo<Solution_>> variableReferences) { instanceMap.put(entity, node); for (var variable : variableReferences) { var variableInstanceMap = variableReferenceToContainingNodeMap.computeIfAbsent(variable.id(), ignored -> new IdentityHashMap<>()); variableInstanceMap.put(entity, node); } } public void addFixedEdge(@NonNull GraphNode<Solution_> from, @NonNull GraphNode<Solution_> to) { if (from.graphNodeId() == to.graphNodeId()) { return; } fixedEdges.computeIfAbsent(from, k -> new ArrayList<>()).add(to); } public void addBeforeProcessor(GraphChangeType graphChangeType, VariableMetaModel<?, ?, ?> variableId, BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object> consumer) { isGraphFixed &= !graphChangeType.affectsGraph(); variableReferenceToBeforeProcessor.computeIfAbsent(variableId, k -> new ArrayList<>()) .add(consumer); } public void addAfterProcessor(GraphChangeType graphChangeType, VariableMetaModel<?, ?, ?> variableId, BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object> consumer) { isGraphFixed &= !graphChangeType.affectsGraph(); variableReferenceToAfterProcessor.computeIfAbsent(variableId, k -> new ArrayList<>()) .add(consumer); } public VariableReferenceGraph build(IntFunction<TopologicalOrderGraph> graphCreator) { assertNoFixedLoops(); if (nodeList.isEmpty()) { return EmptyVariableReferenceGraph.INSTANCE; } if (isGraphFixed) { return new FixedVariableReferenceGraph<>(this, graphCreator); } return new DefaultVariableReferenceGraph<>(this, graphCreator); } public @NonNull GraphNode<Solution_> lookupOrError(VariableMetaModel<?, ?, ?> variableId, Object entity) { var out = variableReferenceToContainingNodeMap.getOrDefault(variableId, Collections.emptyMap()).get(entity); if (out == null) { throw new IllegalArgumentException(); } return out; } private void assertNoFixedLoops() { var graph = new DefaultTopologicalOrderGraph(nodeList.size()); for (var fixedEdge : fixedEdges.entrySet()) { var fromNodeId = fixedEdge.getKey().graphNodeId(); for (var toNode : fixedEdge.getValue()) { var toNodeId = toNode.graphNodeId(); graph.addEdge(fromNodeId, toNodeId); } } var changedBitSet = new BitSet(); graph.commitChanges(changedBitSet); if (changedBitSet.cardinality() == 0) { // No node's loop status changed, so the graph does // not have any fixed loops. return; } // At least one node's loop status has changed, // and since the empty graph has no loops, that // mean there is at least one fixed loop in the graph. var loopedComponents = graph.getLoopedComponentList(); var limit = 3; var isLimited = loopedComponents.size() > limit; var loopedVariables = new LinkedHashSet<VariableMetaModel<?, ?, ?>>(); var nodeCycleList = loopedComponents.stream() .map(nodeIds -> nodeIds.stream().mapToInt(Integer::intValue).mapToObj(nodeList::get).toList()) .toList(); for (var cycle : nodeCycleList) { cycle.stream().flatMap(node -> node.variableReferences().stream()) .map(VariableUpdaterInfo::id) .forEach(loopedVariables::add); } var out = new StringBuilder("There are fixed dependency loops in the graph for variables %s:%n" .formatted(loopedVariables)); for (var cycle : nodeCycleList) { out.append(cycle.stream() .map(GraphNode::toString) .collect(Collectors.joining(", ", "- [", "] "))); } if (isLimited) { out.append("- ...("); out.append(loopedComponents.size() - limit); out.append(" more)%n"); } out.append( """ Fixed dependency loops indicate a problem in either the input problem or in the @%s of the looped @%s. There are two kinds of fixed dependency loops: - You have two shadow variables whose sources refer to each other; this is called a source-induced fixed loop. In code, this situation looks like this: @ShadowVariable(supplierName="variable1Supplier") String variable1; @ShadowVariable(supplierName="variable2Supplier") String variable2; // ... @ShadowSources("variable2") String variable1Supplier() { /* ... */ } @ShadowSources("variable1") String variable2Supplier() { /* ... */ } - You have a shadow variable whose sources refer to itself transitively via a fact; this is called a fact-induced fixed loop. In code, this situation looks like this: @PlanningEntity public class Entity { Entity dependency; @ShadowVariable(supplierName="variableSupplier") String variable; @ShadowSources("dependency.variable") String variableSupplier() { /* ... */ } // ... } Entity a = new Entity(); Entity b = new Entity(); a.setDependency(b); b.setDependency(a); // a depends on b, and b depends on a, which is invalid. The solver cannot break a fixed loop since the loop is caused by sources or facts instead of variables. Fixed loops should not be confused with variable-induced loops, which can be broken by the solver: @PlanningEntity public class Entity { Entity dependency; @PreviousElementShadowVariable(/* ... */) Entity previous; @ShadowVariable(supplierName="variableSupplier") String variable; @ShadowSources({"previous.variable", "dependency.variable"}) String variable1Supplier() { /* ... */ } // ... } Entity a = new Entity(); Entity b = new Entity(); b.setDependency(a); a.setPrevious(b); // b depends on a via a fact, and a depends on b via a variable // The solver can break this loop by moving a after b. Maybe check none of your @%s form a loop on the same entity. """ .formatted(ShadowSources.class.getSimpleName(), ShadowVariable.class.getSimpleName(), ShadowSources.class.getSimpleName())); throw new IllegalArgumentException(out.toString()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/VariableSourceReference.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.List; import java.util.function.Function; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public record VariableSourceReference(VariableMetaModel<?, ?, ?> variableMetaModel, List<MemberAccessor> chainFromRootEntityToVariableEntity, boolean onRootEntity, boolean isTopLevel, boolean isBottomLevel, boolean isDeclarative, VariableMetaModel<?, ?, ?> targetVariableMetamodel, @Nullable VariableMetaModel<?, ?, ?> downstreamDeclarativeVariableMetamodel, Function<Object, @Nullable Object> targetEntityFunctionStartingFromVariableEntity) { public boolean affectGraphEdges() { return downstreamDeclarativeVariableMetamodel != null; } public @Nullable Object findTargetEntity(Object entity) { return targetEntityFunctionStartingFromVariableEntity.apply(entity); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/VariableUpdaterInfo.java
package ai.timefold.solver.core.impl.domain.variable.declarative; import java.util.Arrays; import java.util.Objects; import java.util.function.Function; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public record VariableUpdaterInfo<Solution_>( VariableMetaModel<Solution_, ?, ?> id, int groupId, DeclarativeShadowVariableDescriptor<Solution_> variableDescriptor, EntityConsistencyState<Solution_, Object> entityConsistencyState, MemberAccessor memberAccessor, Function<Object, Object> calculator, @Nullable Object[] groupEntities) { public VariableUpdaterInfo(VariableMetaModel<Solution_, ?, ?> id, int groupId, DeclarativeShadowVariableDescriptor<Solution_> variableDescriptor, EntityConsistencyState<Solution_, Object> entityConsistencyState, MemberAccessor memberAccessor, Function<Object, Object> calculator) { this(id, groupId, variableDescriptor, entityConsistencyState, memberAccessor, calculator, null); } public VariableUpdaterInfo<Solution_> withGroupId(int groupId) { return new VariableUpdaterInfo<>(id, groupId, variableDescriptor, entityConsistencyState, memberAccessor, calculator, groupEntities); } public VariableUpdaterInfo<Solution_> withGroupEntities(Object[] groupEntities) { return new VariableUpdaterInfo<>(id, groupId, variableDescriptor, entityConsistencyState, memberAccessor, calculator, groupEntities); } public boolean updateIfChanged(Object entity, ChangedVariableNotifier<Solution_> changedVariableNotifier) { return updateIfChanged(entity, calculator.apply(entity), changedVariableNotifier); } public boolean updateIfChanged(Object entity, @Nullable Object newValue, ChangedVariableNotifier<Solution_> changedVariableNotifier) { var oldValue = variableDescriptor.getValue(entity); if (!Objects.equals(oldValue, newValue)) { if (groupEntities == null) { changedVariableNotifier.beforeVariableChanged().accept(variableDescriptor, entity); variableDescriptor.setValue(entity, newValue); changedVariableNotifier.afterVariableChanged().accept(variableDescriptor, entity); } else { for (var groupEntity : groupEntities) { changedVariableNotifier.beforeVariableChanged().accept(variableDescriptor, groupEntity); variableDescriptor.setValue(groupEntity, newValue); changedVariableNotifier.afterVariableChanged().accept(variableDescriptor, groupEntity); } } return true; } return false; } @Override public boolean equals(Object o) { if (!(o instanceof VariableUpdaterInfo<?> that)) return false; return groupId == that.groupId && Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id, groupId); } @Override public String toString() { return (groupEntities == null) ? "%s (%d)".formatted(id.name(), groupId) : "%s (%d) %s".formatted(id.name(), groupId, Arrays.toString(groupEntities)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/declarative/package-info.java
/** * Provided shadow variables work by calculating the topological order * of each shadow variable. * <br/> * The nodes in the graph are paths to each shadow variable, bound to a * particular entity instance. * <ul> * <li> * The path `e1:Entity.#id.a` is the source path for the shadow variable `a` on entity e1. * </li> * <li> * If `e2.previous = e1`, then the path `e2:Entity.#id.#previous.a` is an alias path for the shadow * variable `a` on e1. * </li> * <li> * The path can have multiple parts; like * `e1:Entity.#id.#previous.#previous.a`. In this case, * `e1:Entity.#id.#previous` is the parent of * `e1:Entity.#id.#previous.#previous`. * </li> * </ul> * The edges in the graph are the aliases and dependencies for each shadow variable: * <ul> * <li> * There is a fixed edge from the parent to each of its children. * (i.e. `e1:Entity.#id.#previous` -> `e1:Entity.#id.#previous.a`) * </li> * <li> * There is a fixed edge from the direct dependencies of a shadow variable to the shadow variable. * (i.e. `e1:Entity.#id.#previous.readyTime` -> `e1:Entity.#id.#startTime`) * </li> * <li> * There is a dynamic edge from each shadow variable to all its aliases. * (i.e. `e1:Entity.#id.startTime` -> * `e2:Entity.#id.#previous.startTime`, if e1 is the previous of e2.) * </li> * </ul> * Once the topological order of each node is known, to update from * a set of changes: * <ol> * <li> * Pick a changed node with the minimum topological order that was not * visited. * </li> * <li> * Update the changed node. * </li> * <li> * If the value of the node changed, marked all its children as changed. * </li> * </ol> */ package ai.timefold.solver.core.impl.domain.variable.declarative;
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.hasEffectiveMovableEntityFilter()) { 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/descriptor/GenuineVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; import static ai.timefold.solver.core.config.util.ConfigUtils.newInstance; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; 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.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.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); for (var valueRangeProviderMemberAccessor : valueRangeProviderMemberAccessors) { valueRangeDescriptorList.add(buildValueRangeDescriptor(descriptorPolicy, valueRangeProviderMemberAccessor)); } if (valueRangeDescriptorList.size() == 1) { valueRangeDescriptor = valueRangeDescriptorList.get(0); } else { valueRangeDescriptor = descriptorPolicy.buildCompositeValueRangeDescriptor(this, valueRangeDescriptorList); } } private MemberAccessor[] findAnonymousValueRangeMemberAccessors(DescriptorPolicy descriptorPolicy) { var supportsValueRangeProviderFromEntity = !isListVariable(); var 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. */ var variableType = isListVariable() ? (Class<?>) ((ParameterizedType) variableMemberAccessor.getGenericType()) .getActualTypeArguments()[0] : variableMemberAccessor.getType(); // We expect either ValueRange, Collection or an array. var valueRangeType = valueRangeProviderAccessor.getGenericType(); if (valueRangeType instanceof ParameterizedType parameterizedValueRangeType) { return ConfigUtils .extractGenericTypeParameter("solutionClass", entityDescriptor.getSolutionDescriptor().getSolutionClass(), valueRangeProviderAccessor.getType(), parameterizedValueRangeType, ValueRangeProvider.class, valueRangeProviderAccessor.getName()) .map(variableType::isAssignableFrom) .orElse(false); } else { var clz = (Class<?>) valueRangeType; if (clz.isArray()) { var 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 { var 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) { if (descriptorPolicy.isFromSolutionValueRangeProvider(valueRangeProviderMemberAccessor)) { return descriptorPolicy.buildFromSolutionPropertyValueRangeDescriptor(this, valueRangeProviderMemberAccessor); } else if (descriptorPolicy.isFromEntityValueRangeProvider(valueRangeProviderMemberAccessor)) { return descriptorPolicy.buildFromEntityPropertyValueRangeDescriptor(this, valueRangeProviderMemberAccessor); } else { throw new IllegalStateException("Impossible state: member accessor (%s) is not a value range provider." .formatted(valueRangeProviderMemberAccessor)); } } 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 = newInstance(this::toString, "strengthComparatorClass", strengthComparatorClass); increasingStrengthSorter = new ComparatorSelectionSorter<>(strengthComparator, SelectionSorterOrder.ASCENDING); decreasingStrengthSorter = new ComparatorSelectionSorter<>(strengthComparator, SelectionSorterOrder.DESCENDING); } if (strengthWeightFactoryClass != null) { SelectionSorterWeightFactory<Solution_, Object> strengthWeightFactory = 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; } /** * Returns true if the value range can be directly extracted from the solution. * * @see FromSolutionPropertyValueRangeDescriptor */ public boolean canExtractValueRangeFromSolution() { return valueRangeDescriptor.canExtractValueRangeFromSolution(); } // ************************************************************************ // 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) { var value = getValue(entity); return value == null; } public SelectionSorter<Solution_, Object> getIncreasingStrengthSorter() { return increasingStrengthSorter; } public SelectionSorter<Solution_, Object> getDecreasingStrengthSorter() { return decreasingStrengthSorter; } @Override public String toString() { return getSimpleEntityAndVariableName() + " variable"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/descriptor/ListVariableDescriptor.java
package ai.timefold.solver.core.impl.domain.variable.descriptor; 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.variable.InverseRelationShadowVariable; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; 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.move.director.MoveDirector; import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataFilter; public final class ListVariableDescriptor<Solution_> extends GenuineVariableDescriptor<Solution_> { private final ListVariableStateDemand<Solution_> stateDemand = new ListVariableStateDemand<>(this); private final BiPredicate<Object, Object> inListPredicate = (element, entity) -> { var list = getValue(entity); return list.contains(element); }; private final BiDataFilter<Solution_, Object, Object> entityContainsPinnedValuePredicate = (solutionView, value, entity) -> { var moveDirector = (MoveDirector<Solution_, ?>) solutionView; return moveDirector.isPinned(this, value); }; private boolean allowsUnassignedValues = true; public ListVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { super(ordinal, entityDescriptor, variableMemberAccessor); } public ListVariableStateDemand<Solution_> getStateDemand() { return stateDemand; } @SuppressWarnings("unchecked") public <A> BiPredicate<A, Object> getInListPredicate() { return (BiPredicate<A, Object>) inListPredicate; } @SuppressWarnings("unchecked") public <A, B> BiDataFilter<Solution_, A, B> getEntityContainsPinnedValuePredicate() { return (BiDataFilter<Solution_, A, B>) entityContainsPinnedValuePredicate; } public boolean allowsUnassignedValues() { return allowsUnassignedValues; } @Override protected void processPropertyAnnotations(DescriptorPolicy descriptorPolicy) { PlanningListVariable planningVariableAnnotation = variableMemberAccessor.getAnnotation(PlanningListVariable.class); allowsUnassignedValues = planningVariableAnnotation.allowsUnassignedValues(); processValueRangeRefs(descriptorPolicy, planningVariableAnnotation.valueRangeProviderRefs()); } @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.extractGenericTypeParameterOrFail("entityClass", entityDescriptor.getEntityClass(), variableMemberAccessor.getType(), variableMemberAccessor.getGenericType(), PlanningListVariable.class, variableMemberAccessor.getName()); } public InverseRelationShadowVariableDescriptor<Solution_> getInverseRelationShadowVariableDescriptor() { var inverseRelationEntityDescriptor = getEntityDescriptor().getSolutionDescriptor().findEntityDescriptor(getElementType()); if (inverseRelationEntityDescriptor == null) { return null; } var applicableShadowDescriptors = inverseRelationEntityDescriptor.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(inverseRelationEntityDescriptor.getEntityClass().getCanonicalName(), getSimpleEntityAndVariableName(), InverseRelationShadowVariable.class.getSimpleName(), applicableShadowDescriptors.stream() .map(ShadowVariableDescriptor::getSimpleEntityAndVariableName) .collect(Collectors.joining(", ", "[", "]")))); } else { return (InverseRelationShadowVariableDescriptor<Solution_>) applicableShadowDescriptors.get(0); } } @SuppressWarnings("unchecked") @Override public List<Object> getValue(Object entity) { Object value = super.getValue(entity); if (value == null) { throw new IllegalStateException("The planning list variable (%s) of entity (%s) is null." .formatted(this, entity)); } 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); } @SuppressWarnings("unchecked") public <Value_> Value_ 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 (Value_) values.get(index); } @SuppressWarnings("unchecked") public <Value_> Value_ setElement(Object entity, int index, Value_ element) { return (Value_) getValue(entity).set(index, element); } public int getListSize(Object entity) { return getValue(entity).size(); } public boolean supportsPinning() { return entityDescriptor.supportsPinning(); } public boolean isElementPinned(Solution_ workingSolution, Object entity, int index) { if (!supportsPinning()) { return false; } else if (!entityDescriptor.isMovable(workingSolution, 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(entity); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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, true); } 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; } /** * return true if the source variable is a list variable; otherwise, return false. */ public abstract boolean isListVariableSource(); /** * @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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; /** * @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 VariableMetaModel<Solution_, ?, ?> cachedMetamodel = null; protected List<ShadowVariableDescriptor<Solution_>> sinkVariableDescriptorList = new ArrayList<>(4); // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ protected VariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor) { this(ordinal, entityDescriptor, variableMemberAccessor, false); } protected VariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, MemberAccessor variableMemberAccessor, boolean allowPrimitive) { if (!allowPrimitive && variableMemberAccessor.getType().isPrimitive()) { // uninitialized variables only apply to genuine planning variables; // shadow variables can use primitives 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; } 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; } public boolean canBeUsedAsSource() { return true; } 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()); } @SuppressWarnings("unchecked") public <Value_> Value_ getValue(Object entity) { return (Value_) 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); } public VariableMetaModel<Solution_, ?, ?> getVariableMetaModel() { if (cachedMetamodel != null) { return cachedMetamodel; } cachedMetamodel = entityDescriptor.getEntityMetaModel() .variable(variableName); return cachedMetamodel; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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 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.ListVariableStateSupply; 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; 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 (%s) has an @%s-annotated member (%s) of type (%s) which cannot represent an index in a list. The @%s-annotated member type must be %s or %s.""" .formatted(entityDescriptor.getEntityClass().getName(), IndexShadowVariable.class.getSimpleName(), variableMemberAccessor, variableMemberAccessor.getType(), IndexShadowVariable.class.getSimpleName(), Integer.class, 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)) .toList(); if (entitiesWithSourceVariable.isEmpty()) { throw new IllegalArgumentException(""" The entityClass (%s) has an @%s-annotated property (%s) with sourceVariableName (%s) \ which is not a valid planning variable on any of the entity classes (%s).""" .formatted(entityDescriptor.getEntityClass(), IndexShadowVariable.class.getSimpleName(), variableMemberAccessor, sourceVariableName, entityDescriptor.getSolutionDescriptor().getEntityDescriptors())); } if (entitiesWithSourceVariable.size() > 1) { throw new IllegalArgumentException(""" The entityClass (%s) has an @%s-annotated property (%s) with sourceVariableName (%s) \ which is not a unique planning variable. A planning variable with the name (%s) exists on multiple entity classes (%s).""" .formatted(entityDescriptor.getEntityClass(), IndexShadowVariable.class.getSimpleName(), variableMemberAccessor, sourceVariableName, sourceVariableName, entitiesWithSourceVariable)); } VariableDescriptor<Solution_> variableDescriptor = entitiesWithSourceVariable.get(0).getVariableDescriptor(sourceVariableName); if (variableDescriptor == null) { throw new IllegalStateException(""" Impossible state: variableDescriptor (%s) is null but previous checks indicate that \ the entityClass (%s) has a planning variable with sourceVariableName (%s).""" .formatted(variableDescriptor, entityDescriptor.getEntityClass(), sourceVariableName)); } if (!(variableDescriptor instanceof ListVariableDescriptor)) { throw new IllegalArgumentException( "The entityClass (%s) has an @%s-annotated property (%s) with sourceVariableName (%s) which is not a @%s." .formatted(entityDescriptor.getEntityClass(), IndexShadowVariable.class.getSimpleName(), variableMemberAccessor, sourceVariableName, 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() { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } @Override public Demand<?> getProvidedDemand() { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } @SuppressWarnings("unchecked") @Override public Integer getValue(Object entity) { return super.getValue(entity); } @Override public boolean isListVariableSource() { return true; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; /** * Only supported for {@link PlanningListVariable list variables}. */ 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/CollectionInverseVariableDemand.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.AbstractVariableDescriptorBasedDemand; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; /** * To get an instance, demand a {@link CollectionInverseVariableDemand} from {@link InnerScoreDirector#getSupplyManager()}. */ public final class CollectionInverseVariableDemand<Solution_> extends AbstractVariableDescriptorBasedDemand<Solution_, CollectionInverseVariableSupply> { public CollectionInverseVariableDemand(VariableDescriptor<Solution_> sourceVariableDescriptor) { super(sourceVariableDescriptor); } // ************************************************************************ // Creation method // ************************************************************************ @Override public CollectionInverseVariableSupply createExternalizedSupply(SupplyManager supplyManager) { return new ExternalizedCollectionInverseVariableSupply<>(variableDescriptor); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import org.jspecify.annotations.NonNull; 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(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { // Do nothing } @Override public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { // Do nothing } protected void insert(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) { Object shadowEntity = sourceVariableDescriptor.getValue(entity); if (shadowEntity != null) { Collection<Object> shadowCollection = shadowVariableDescriptor.getValue(shadowEntity); if (scoreDirector.expectShadowVariablesInCorrectState() && shadowCollection == null) { throw new IllegalStateException(""" The entity (%s) has a variable (%s) with value (%s) which has a sourceVariableName variable (%s) \ with a value (%s) which is null. Verify the consistency of your input problem for that bi-directional relationship. Non-singleton inverse variable can never be null, at the very least it should be an empty %s.""" .formatted(entity, sourceVariableDescriptor.getVariableName(), shadowEntity, shadowVariableDescriptor.getVariableName(), shadowCollection, Collection.class.getSimpleName())); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, shadowEntity); boolean added = shadowCollection.add(entity); if (scoreDirector.expectShadowVariablesInCorrectState() && !added) { throw new IllegalStateException(""" The entity (%s) has a variable (%s) with value (%s) which has a sourceVariableName variable (%s) \ with a value (%s) which already contained the entity (%s). Verify the consistency of your input problem for that bi-directional relationship.""" .formatted(entity, sourceVariableDescriptor.getVariableName(), shadowEntity, shadowVariableDescriptor.getVariableName(), shadowCollection, entity)); } scoreDirector.afterVariableChanged(shadowVariableDescriptor, shadowEntity); } } protected void retract(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) { Object shadowEntity = sourceVariableDescriptor.getValue(entity); if (shadowEntity != null) { Collection<Object> shadowCollection = shadowVariableDescriptor.getValue(shadowEntity); if (scoreDirector.expectShadowVariablesInCorrectState() && shadowCollection == null) { throw new IllegalStateException(""" The entity (%s) has a variable (%s) with value (%s) which has a sourceVariableName variable (%s) \ with a value (%s) which is null. Verify the consistency of your input problem for that bi-directional relationship. Non-singleton inverse variable can never be null, at the very least it should be an empty %s.""" .formatted(entity, sourceVariableDescriptor.getVariableName(), shadowEntity, shadowVariableDescriptor.getVariableName(), shadowCollection, Collection.class.getSimpleName())); } scoreDirector.beforeVariableChanged(shadowVariableDescriptor, shadowEntity); boolean removed = shadowCollection.remove(entity); if (scoreDirector.expectShadowVariablesInCorrectState() && !removed) { throw new IllegalStateException(""" The entity (%s) has a variable (%s) with value (%s) which has a sourceVariableName variable (%s) \ with a value (%s) which did not contain the entity (%s) Verify the consistency of your input problem for that bi-directional relationship.""" .formatted(entity, sourceVariableDescriptor.getVariableName(), shadowEntity, shadowVariableDescriptor.getVariableName(), shadowCollection, entity)); } scoreDirector.afterVariableChanged(shadowVariableDescriptor, shadowEntity); } } @Override public Collection<?> getInverseCollection(Object planningValue) { return shadowVariableDescriptor.getValue(planningValue); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/CollectionInverseVariableSupply.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import java.util.Collection; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; public interface CollectionInverseVariableSupply extends Supply { /** * If entity1.varA = x then an inverse of x is entity1. * * @param planningValue never null * @return never null, a {@link Collection} of entities for which the planning variable is the planningValue. */ Collection<?> getInverseCollection(Object planningValue); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import org.jspecify.annotations.NonNull; /** * 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(@NonNull ScoreDirector<Solution_> scoreDirector) { inverseEntitySetMap = new IdentityHashMap<>(); sourceVariableDescriptor.getEntityDescriptor().visitAllEntities(scoreDirector.getWorkingSolution(), this::insert); } @Override public void close() { inverseEntitySetMap = null; } @Override public void beforeEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { // Do nothing } @Override public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert(entity); } @Override public void beforeVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract(entity); } @Override public void afterVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert(entity); } @Override public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract(entity); } @Override public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import org.jspecify.annotations.NonNull; /** * 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(@NonNull ScoreDirector<Solution_> scoreDirector) { inverseEntityMap = new IdentityHashMap<>(); sourceVariableDescriptor.getEntityDescriptor().visitAllEntities(scoreDirector.getWorkingSolution(), this::insert); } @Override public void close() { inverseEntityMap = null; } @Override public void beforeEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { // Do nothing } @Override public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert(entity); } @Override public void beforeVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract(entity); } @Override public void afterVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert(entity); } @Override public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract(entity); } @Override public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.ListVariableStateSupply; 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 .extractGenericTypeParameter("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 { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } } else { return Collections.singleton(CollectionInverseVariableListener.class); } } // ************************************************************************ // Worker methods // ************************************************************************ @Override public Demand<?> getProvidedDemand() { if (singleton) { if (chained) { return new SingletonInverseVariableDemand<>(sourceVariableDescriptor); } else { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } } 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 { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } } else { return new CollectionInverseVariableListener<>(this, sourceVariableDescriptor); } } public boolean isSingleton() { return singleton; } @Override public boolean isListVariableSource() { return sourceVariableDescriptor instanceof ListVariableDescriptor<Solution_>; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/inverserelation/SingletonInverseVariableDemand.java
package ai.timefold.solver.core.impl.domain.variable.inverserelation; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.AbstractVariableDescriptorBasedDemand; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; public final class SingletonInverseVariableDemand<Solution_> extends AbstractVariableDescriptorBasedDemand<Solution_, SingletonInverseVariableSupply> { public SingletonInverseVariableDemand(VariableDescriptor<Solution_> sourceVariableDescriptor) { super(sourceVariableDescriptor); } // ************************************************************************ // Creation method // ************************************************************************ @Override public SingletonInverseVariableSupply createExternalizedSupply(SupplyManager supplyManager) { return new ExternalizedSingletonInverseVariableSupply<>(variableDescriptor); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import org.jspecify.annotations.NonNull; 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(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { // Do nothing } @Override public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { retract((InnerScoreDirector<Solution_, ?>) scoreDirector, entity); } @Override public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; /** * Currently only supported for chained variables and {@link PlanningListVariable list variables}, * which guarantee that no 2 entities use the same planningValue. */ 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/SourcedVariableListener.java
package ai.timefold.solver.core.impl.domain.variable.listener; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; /** * Used to externalize data for a {@link Supply} from the domain model itself. */ public interface SourcedVariableListener<Solution_> extends AbstractVariableListener<Solution_, Object>, Supply { VariableDescriptor<Solution_> getSourceVariableDescriptor(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/VariableListenerWithSources.java
package ai.timefold.solver.core.impl.domain.variable.listener; import java.util.Collection; import java.util.Collections; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * Holds a variable listener and all its source variable descriptors. * * @param <Solution_> */ public final class VariableListenerWithSources<Solution_> { private final AbstractVariableListener<Solution_, Object> variableListener; private final Collection<VariableDescriptor<Solution_>> sourceVariableDescriptors; public VariableListenerWithSources(AbstractVariableListener<Solution_, Object> variableListener, Collection<VariableDescriptor<Solution_>> sourceVariableDescriptors) { this.variableListener = variableListener; this.sourceVariableDescriptors = sourceVariableDescriptors; } public VariableListenerWithSources(AbstractVariableListener<Solution_, Object> variableListener, VariableDescriptor<Solution_> sourceVariableDescriptor) { this(variableListener, Collections.singleton(sourceVariableDescriptor)); } public AbstractVariableListener<Solution_, Object> getVariableListener() { return variableListener; } public Collection<VariableDescriptor<Solution_>> getSourceVariableDescriptors() { return sourceVariableDescriptors; } public Collection<VariableListenerWithSources<Solution_>> toCollection() { return Collections.singleton(this); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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 { var 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 clearAllNotifications() { notificationQueue.clear(); } @Override public void triggerAllNotifications() { var notifiedCount = 0; for (var notification : notificationQueue) { notification.triggerAfter(variableListener, scoreDirector); notifiedCount++; } if (notifiedCount != notificationQueue.size()) { throw new IllegalStateException( """ The variableListener (%s) has been notified with notifiedCount (%d) but after being triggered, its notificationCount (%d) is different. Maybe that variableListener (%s) changed an upstream shadow variable (which is illegal).""" .formatted(variableListener.getClass(), notifiedCount, notificationQueue.size(), variableListener.getClass())); } notificationQueue.clear(); } @Override public String toString() { return "(%d) %s".formatted(globalOrder, variableListener); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; } public Object getEntity() { return 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/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/BasicVariableNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.VariableListener; public interface BasicVariableNotification<Solution_> extends Notification<Solution_, VariableListener<Solution_, Object>> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/ElementUnassignedNotification.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 ElementUnassignedNotification<Solution_> implements ListVariableNotification<Solution_> { private final Object element; ElementUnassignedNotification(Object element) { this.element = element; } @Override public void triggerBefore(ListVariableListener<Solution_, Object, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { throw new UnsupportedOperationException("ListVariableListeners do not listen for this event."); } @Override public void triggerAfter(ListVariableListener<Solution_, Object, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.afterListVariableElementUnassigned(scoreDirector, element); } @Override public String toString() { return "ElementUnassigned(" + element + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/EntityAddedNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; final class EntityAddedNotification<Solution_> extends AbstractNotification implements EntityNotification<Solution_> { EntityAddedNotification(Object entity) { super(entity); } @Override public void triggerBefore(AbstractVariableListener<Solution_, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.beforeEntityAdded(scoreDirector, entity); } @Override public void triggerAfter(AbstractVariableListener<Solution_, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.afterEntityAdded(scoreDirector, entity); } @Override public String toString() { return "EntityAdded(" + entity + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/EntityNotifiable.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; /** * A notifiable listening for {@link EntityNotification}s. Every variable listener's notifiable is not only registered for * the listener's source variable notifications but also for the planning entity declaring the source variable. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public interface EntityNotifiable<Solution_> extends Notifiable { void notifyBefore(EntityNotification<Solution_> notification); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/EntityNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; public interface EntityNotification<Solution_> extends Notification<Solution_, AbstractVariableListener<Solution_, Object>> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/EntityRemovedNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; final class EntityRemovedNotification<Solution_> extends AbstractNotification implements EntityNotification<Solution_> { EntityRemovedNotification(Object entity) { super(entity); } @Override public void triggerBefore(AbstractVariableListener<Solution_, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.beforeEntityRemoved(scoreDirector, entity); } @Override public void triggerAfter(AbstractVariableListener<Solution_, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.afterEntityRemoved(scoreDirector, entity); } @Override public String toString() { return "EntityRemoved(" + entity + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; public 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; } public int getFromIndex() { return fromIndex; } public int getToIndex() { return 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/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/ListVariableListenerNotifiable.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import java.util.Collection; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * A notifiable specialized to receive {@link ListVariableNotification}s and trigger them on a given * {@link ListVariableListener}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ final class ListVariableListenerNotifiable<Solution_> extends AbstractNotifiable<Solution_, ListVariableListener<Solution_, Object, Object>> { ListVariableListenerNotifiable( ScoreDirector<Solution_> scoreDirector, ListVariableListener<Solution_, Object, Object> variableListener, Collection<Notification<Solution_, ? super ListVariableListener<Solution_, Object, Object>>> notificationQueue, int globalOrder) { super(scoreDirector, variableListener, notificationQueue, globalOrder); } public void notifyBefore(ListVariableNotification<Solution_> notification) { triggerBefore(notification); } public void notifyAfter(ListVariableNotification<Solution_> notification) { storeForLater(notification); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/ListVariableNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.ListVariableListener; public interface ListVariableNotification<Solution_> extends Notification<Solution_, ListVariableListener<Solution_, Object, Object>> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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(); /** * Clear all notifications without triggering any related event logic. */ void clearAllNotifications(); /** * Trigger all queued notifications. */ void triggerAllNotifications(); /** * Close the variable listener. */ void closeVariableListener(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/NotifiableRegistry.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; 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; final class NotifiableRegistry<Solution_> { private final List<Notifiable> notifiableList = new ArrayList<>(); private final Set<EntityNotifiable<Solution_>>[] sourceEntityToNotifiableSetArray; private final List<Notifiable>[][] sourceVariableToNotifiableListArray; NotifiableRegistry(SolutionDescriptor<Solution_> solutionDescriptor) { var entityDescriptorList = solutionDescriptor.getEntityDescriptors(); int entityDescriptorListSize = entityDescriptorList.size(); sourceEntityToNotifiableSetArray = new Set[entityDescriptorListSize]; sourceVariableToNotifiableListArray = new List[entityDescriptorListSize][]; for (var entityDescriptor : solutionDescriptor.getEntityDescriptors()) { var declaredVariableDescriptorList = entityDescriptor.getDeclaredVariableDescriptors(); var array = new List[declaredVariableDescriptorList.size()]; for (var variableDescriptor : declaredVariableDescriptorList) { array[variableDescriptor.getOrdinal()] = new ArrayList<>(); } var entityDescriptorId = entityDescriptor.getOrdinal(); sourceVariableToNotifiableListArray[entityDescriptorId] = array; sourceEntityToNotifiableSetArray[entityDescriptorId] = new LinkedHashSet<>(); } } void registerNotifiable(VariableDescriptor<Solution_> source, EntityNotifiable<Solution_> notifiable) { registerNotifiable(Collections.singletonList(source), notifiable); } void registerNotifiable(Collection<VariableDescriptor<Solution_>> sources, EntityNotifiable<Solution_> notifiable) { for (VariableDescriptor<?> source : sources) { var entityDescriptorId = source.getEntityDescriptor().getOrdinal(); sourceVariableToNotifiableListArray[entityDescriptorId][source.getOrdinal()].add(notifiable); sourceEntityToNotifiableSetArray[entityDescriptorId].add(notifiable); } notifiableList.add(notifiable); } Iterable<Notifiable> getAll() { return notifiableList; } Collection<EntityNotifiable<Solution_>> get(EntityDescriptor<?> entityDescriptor) { return sourceEntityToNotifiableSetArray[entityDescriptor.getOrdinal()]; } Collection<VariableListenerNotifiable<Solution_>> get(VariableDescriptor<?> variableDescriptor) { var notifiables = sourceVariableToNotifiableListArray[variableDescriptor.getEntityDescriptor().getOrdinal()][variableDescriptor .getOrdinal()]; if (notifiables == null) { return Collections.emptyList(); } return (Collection) notifiables; } Collection<ListVariableListenerNotifiable<Solution_>> get(ListVariableDescriptor<?> variableDescriptor) { var notifiables = sourceVariableToNotifiableListArray[variableDescriptor.getEntityDescriptor().getOrdinal()][variableDescriptor .getOrdinal()]; if (notifiables == null) { return Collections.emptyList(); } return (Collection) notifiables; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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_> ListVariableChangedNotification<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/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/ShadowVariableType.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; public enum ShadowVariableType { BASIC, // index, inverse element, anchor element, previous element, and next element CUSTOM_LISTENER, CASCADING_UPDATE, DECLARATIVE }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/VariableChangedNotification.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; final class VariableChangedNotification<Solution_> extends AbstractNotification implements BasicVariableNotification<Solution_> { VariableChangedNotification(Object entity) { super(entity); } @Override public void triggerBefore(VariableListener<Solution_, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.beforeVariableChanged(scoreDirector, entity); } @Override public void triggerAfter(VariableListener<Solution_, Object> variableListener, ScoreDirector<Solution_> scoreDirector) { variableListener.afterVariableChanged(scoreDirector, entity); } @Override public String toString() { return "VariableChanged(" + entity + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/VariableListenerNotifiable.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import java.util.Collection; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * A notifiable specialized to receive {@link BasicVariableNotification}s and trigger them on a given {@link VariableListener}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ final class VariableListenerNotifiable<Solution_> extends AbstractNotifiable<Solution_, VariableListener<Solution_, Object>> { VariableListenerNotifiable( ScoreDirector<Solution_> scoreDirector, VariableListener<Solution_, Object> variableListener, Collection<Notification<Solution_, ? super VariableListener<Solution_, Object>>> notificationQueue, int globalOrder) { super(scoreDirector, variableListener, notificationQueue, globalOrder); } public void notifyBefore(BasicVariableNotification<Solution_> notification) { if (storeForLater(notification)) { triggerBefore(notification); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/VariableListenerSupport.java
package ai.timefold.solver.core.impl.domain.variable.listener.support; import static ai.timefold.solver.core.impl.domain.variable.listener.support.ShadowVariableType.BASIC; import static ai.timefold.solver.core.impl.domain.variable.listener.support.ShadowVariableType.CASCADING_UPDATE; import static ai.timefold.solver.core.impl.domain.variable.listener.support.ShadowVariableType.CUSTOM_LISTENER; import static ai.timefold.solver.core.impl.domain.variable.listener.support.ShadowVariableType.DECLARATIVE; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.IntFunction; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.cascade.CascadingUpdateShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.declarative.ConsistencyTracker; import ai.timefold.solver.core.impl.domain.variable.declarative.DefaultShadowVariableSession; import ai.timefold.solver.core.impl.domain.variable.declarative.DefaultShadowVariableSessionFactory; import ai.timefold.solver.core.impl.domain.variable.declarative.DefaultTopologicalOrderGraph; import ai.timefold.solver.core.impl.domain.variable.declarative.TopologicalOrderGraph; 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.index.IndexShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor; 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.nextprev.NextElementShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor; 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; import ai.timefold.solver.core.impl.util.LinkedIdentityHashSet; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * This class is not thread-safe. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ @NullMarked public final class VariableListenerSupport<Solution_> implements SupplyManager { public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDirector<Solution_, ?> scoreDirector) { return new VariableListenerSupport<>(scoreDirector, new NotifiableRegistry<>(scoreDirector.getSolutionDescriptor()), TimefoldSolverEnterpriseService.buildOrDefault(service -> service::buildTopologyGraph, () -> DefaultTopologicalOrderGraph::new)); } private static final int SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT = 3; private final InnerScoreDirector<Solution_, ?> scoreDirector; private final NotifiableRegistry<Solution_> notifiableRegistry; private final Map<Demand<?>, SupplyWithDemandCount> supplyMap = new HashMap<>(); private final @Nullable ListVariableDescriptor<Solution_> listVariableDescriptor; private final List<ListVariableChangedNotification<Solution_>> listVariableChangedNotificationList; private final Set<Object> unassignedValueWithEmptyInverseEntitySet; private final List<CascadingUpdateShadowVariableDescriptor<Solution_>> cascadingUpdateShadowVarDescriptorList; @NonNull private final IntFunction<TopologicalOrderGraph> shadowVariableGraphCreator; private boolean notificationQueuesAreEmpty = true; private int nextGlobalOrder = 0; @Nullable private DefaultShadowVariableSession<Solution_> shadowVariableSession = null; private ConsistencyTracker<Solution_> consistencyTracker = new ConsistencyTracker<>(); @Nullable private ListVariableStateSupply<Solution_> listVariableStateSupply = null; private final List<ShadowVariableType> supportedShadowVariableTypeList; VariableListenerSupport(InnerScoreDirector<Solution_, ?> scoreDirector, NotifiableRegistry<Solution_> notifiableRegistry, @NonNull IntFunction<TopologicalOrderGraph> shadowVariableGraphCreator) { this.scoreDirector = Objects.requireNonNull(scoreDirector); this.notifiableRegistry = Objects.requireNonNull(notifiableRegistry); // Fields specific to list variable; will be ignored if not necessary. this.listVariableDescriptor = scoreDirector.getSolutionDescriptor().getListVariableDescriptor(); this.cascadingUpdateShadowVarDescriptorList = listVariableDescriptor != null ? scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream() .flatMap(e -> e.getDeclaredCascadingUpdateShadowVariableDescriptors().stream()) .toList() : Collections.emptyList(); var hasCascadingUpdates = !cascadingUpdateShadowVarDescriptorList.isEmpty(); this.listVariableChangedNotificationList = new ArrayList<>(); this.unassignedValueWithEmptyInverseEntitySet = hasCascadingUpdates ? new LinkedIdentityHashSet<>() : Collections.emptySet(); this.shadowVariableGraphCreator = shadowVariableGraphCreator; // Existing dependencies rely on this list // to ensure consistency in supporting all available shadow variable types // See ShadowVariableUpdateHelper this.supportedShadowVariableTypeList = List.of(BASIC, CUSTOM_LISTENER, CASCADING_UPDATE, DECLARATIVE); } public List<ShadowVariableType> getSupportedShadowVariableTypes() { return supportedShadowVariableTypeList; } public void linkVariableListeners() { listVariableStateSupply = listVariableDescriptor == null ? null : demand(listVariableDescriptor.getStateDemand()); scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream() .map(EntityDescriptor::getDeclaredShadowVariableDescriptors) .flatMap(Collection::stream) .filter(ShadowVariableDescriptor::hasVariableListener) .sorted(Comparator.comparingInt(ShadowVariableDescriptor::getGlobalShadowOrder)) .forEach(descriptor -> { // All information about elements in all shadow variables is tracked in a centralized place. // Therefore, all list-related shadow variables need to be connected to that centralized place. // Shadow variables which are not related to a list variable are processed normally. if (listVariableStateSupply == null) { processShadowVariableDescriptorWithoutListVariable(descriptor); } else { // When multiple variable types are used, // the shadow variable process needs to account for each variable // and process them according to their types. if (descriptor.isListVariableSource()) { processShadowVariableDescriptorWithListVariable(descriptor, listVariableStateSupply); } else { processShadowVariableDescriptorWithoutListVariable(descriptor); } } }); } private void processShadowVariableDescriptorWithListVariable(ShadowVariableDescriptor<Solution_> shadowVariableDescriptor, ListVariableStateSupply<Solution_> listVariableStateSupply) { if (shadowVariableDescriptor instanceof IndexShadowVariableDescriptor<Solution_> indexShadowVariableDescriptor) { listVariableStateSupply.externalize(indexShadowVariableDescriptor); } else if (shadowVariableDescriptor instanceof InverseRelationShadowVariableDescriptor<Solution_> inverseRelationShadowVariableDescriptor) { listVariableStateSupply.externalize(inverseRelationShadowVariableDescriptor); } else if (shadowVariableDescriptor instanceof PreviousElementShadowVariableDescriptor<Solution_> previousElementShadowVariableDescriptor) { listVariableStateSupply.externalize(previousElementShadowVariableDescriptor); } else if (shadowVariableDescriptor instanceof NextElementShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor) { listVariableStateSupply.externalize(nextElementShadowVariableDescriptor); } else { // The list variable supply supports no other shadow variables. processShadowVariableDescriptorWithoutListVariable(shadowVariableDescriptor); } } private void processShadowVariableDescriptorWithoutListVariable(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; } } @SuppressWarnings("unchecked") @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; } } @SuppressWarnings("unchecked") 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; } } public ConsistencyTracker<Solution_> getConsistencyTracker() { return consistencyTracker; } public void setConsistencyTracker(ConsistencyTracker<Solution_> consistencyTracker) { this.consistencyTracker = consistencyTracker; } // ************************************************************************ // Lifecycle methods // ************************************************************************ public void resetWorkingSolution() { for (var notifiable : notifiableRegistry.getAll()) { notifiable.resetWorkingSolution(); } if (!scoreDirector.getSolutionDescriptor().getDeclarativeShadowVariableDescriptors().isEmpty() && !consistencyTracker.isFrozen()) { var shadowVariableSessionFactory = new DefaultShadowVariableSessionFactory<>( scoreDirector.getSolutionDescriptor(), scoreDirector, shadowVariableGraphCreator); shadowVariableSession = shadowVariableSessionFactory.forSolution(consistencyTracker, scoreDirector.getWorkingSolution()); } } public void close() { for (var notifiable : notifiableRegistry.getAll()) { notifiable.closeVariableListener(); } } public void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) { var notifiables = notifiableRegistry.get(entityDescriptor); if (!notifiables.isEmpty()) { EntityNotification<Solution_> notification = Notification.entityAdded(entity); for (var notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) { var notifiables = notifiableRegistry.get(entityDescriptor); if (!notifiables.isEmpty()) { EntityNotification<Solution_> notification = Notification.entityRemoved(entity); for (var notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { var notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { BasicVariableNotification<Solution_> notification = Notification.variableChanged(entity); for (var notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } if (shadowVariableSession != null) { shadowVariableSession.beforeVariableChanged(variableDescriptor, entity); notificationQueuesAreEmpty = false; } } public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { if (shadowVariableSession != null) { shadowVariableSession.afterVariableChanged(variableDescriptor, entity); } } public void afterElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { var notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.elementUnassigned(element); for (var notifiable : notifiables) { notifiable.notifyAfter(notification); } notificationQueuesAreEmpty = false; } if (!cascadingUpdateShadowVarDescriptorList.isEmpty()) { // Only necessary if there is a cascade. unassignedValueWithEmptyInverseEntitySet.add(element); } } public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { var notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex); for (var notifiable : notifiables) { notifiable.notifyBefore(notification); } notificationQueuesAreEmpty = false; } } public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { var notifiables = notifiableRegistry.get(variableDescriptor); var notification = Notification.<Solution_> listVariableChanged(entity, fromIndex, toIndex); if (!notifiables.isEmpty()) { for (var notifiable : notifiables) { notifiable.notifyAfter(notification); } notificationQueuesAreEmpty = false; } if (!cascadingUpdateShadowVarDescriptorList.isEmpty()) { // Only necessary if there is a cascade. listVariableChangedNotificationList.add(notification); } } public InnerScoreDirector<Solution_, ?> getScoreDirector() { return scoreDirector; } public void triggerVariableListenersInNotificationQueues() { if (notificationQueuesAreEmpty) { // Shortcut in case the trigger is called multiple times in a row, // without any notifications inbetween. // This is better than trying to ensure that the situation never ever occurs. return; } for (var notifiable : notifiableRegistry.getAll()) { notifiable.triggerAllNotifications(); } if (listVariableDescriptor != null) { // If there is no cascade, skip the whole thing. // If there are no events and no newly unassigned variables, skip the whole thing as well. if (!cascadingUpdateShadowVarDescriptorList.isEmpty() && !(listVariableChangedNotificationList.isEmpty() && unassignedValueWithEmptyInverseEntitySet.isEmpty())) { triggerCascadingUpdateShadowVariableUpdate(); } listVariableChangedNotificationList.clear(); } if (shadowVariableSession != null) { shadowVariableSession.updateVariables(); // Some internal variable listeners (such as those used // to check for solution corruption) might have a declarative // shadow variable as a source and need to be triggered here. for (var notifiable : notifiableRegistry.getAll()) { notifiable.triggerAllNotifications(); } } notificationQueuesAreEmpty = true; } /** * Triggers all cascading update shadow variable user-logic. */ private void triggerCascadingUpdateShadowVariableUpdate() { if (listVariableChangedNotificationList.isEmpty() || cascadingUpdateShadowVarDescriptorList.isEmpty()) { return; } for (var cascadingUpdateShadowVariableDescriptor : cascadingUpdateShadowVarDescriptorList) { cascadeListVariableChangedNotifications(cascadingUpdateShadowVariableDescriptor); // When the unassigned element has no inverse entity, // it indicates that it is not reverting to a previous entity. // In this case, we need to invoke the cascading logic, // or its related shadow variables will remain unchanged. cascadeUnassignedValues(cascadingUpdateShadowVariableDescriptor); } unassignedValueWithEmptyInverseEntitySet.clear(); } private void cascadeListVariableChangedNotifications( CascadingUpdateShadowVariableDescriptor<Solution_> cascadingUpdateShadowVariableDescriptor) { for (var notification : listVariableChangedNotificationList) { cascadeListVariableValueUpdates( listVariableDescriptor.getValue(notification.getEntity()), notification.getFromIndex(), notification.getToIndex(), cascadingUpdateShadowVariableDescriptor); } } private void cascadeListVariableValueUpdates(List<Object> values, int fromIndex, int toIndex, CascadingUpdateShadowVariableDescriptor<Solution_> cascadingUpdateShadowVariableDescriptor) { for (int currentIndex = fromIndex; currentIndex < values.size(); currentIndex++) { var value = values.get(currentIndex); // The value is present in the unassigned values, // but the cascade logic is triggered by a list event. // So, we can remove it from the unassigned list // since the entity will be reverted to a previous entity. unassignedValueWithEmptyInverseEntitySet.remove(value); // Force updates within the range. // Outside the range, only update while the values keep changing. var forceUpdate = currentIndex < toIndex; if (!cascadingUpdateShadowVariableDescriptor.update(scoreDirector, value) && !forceUpdate) { break; } } } private void cascadeUnassignedValues( CascadingUpdateShadowVariableDescriptor<Solution_> cascadingUpdateShadowVariableDescriptor) { for (var unassignedValue : unassignedValueWithEmptyInverseEntitySet) { cascadingUpdateShadowVariableDescriptor.update(scoreDirector, unassignedValue); } } /** * @return null if there are no violations */ public @Nullable String createShadowVariablesViolationMessage() { var workingSolution = scoreDirector.getWorkingSolution(); var snapshot = ShadowVariablesAssert.takeSnapshot(scoreDirector.getSolutionDescriptor(), workingSolution); forceTriggerAllVariableListeners(workingSolution); 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(); } /** * Clear all variable listeners without triggering any logic. * The goal is to clear all queues and avoid executing custom listener logic. */ public void clearAllVariableListenerEvents() { notifiableRegistry.getAll().forEach(Notifiable::clearAllNotifications); notificationQueuesAreEmpty = true; } 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 descriptor = (ListVariableDescriptor<Solution_>) variableDescriptor; var size = descriptor.getValue(entity).size(); beforeListVariableChanged(descriptor, entity, 0, size); afterListVariableChanged(descriptor, 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 (%s) so any shadow variables might be stale so score calculation is unreliable. Maybe a %s.before*() method was called without calling %s.triggerVariableListeners(), before calling %s.calculateScore().""" .formatted(notificationQueuesAreEmpty, ScoreDirector.class.getSimpleName(), ScoreDirector.class.getSimpleName(), ScoreDirector.class.getSimpleName())); } } private record SupplyWithDemandCount(Supply supply, long demandCount) { } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import org.jspecify.annotations.NonNull; /** * 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(@NonNull ScoreDirector<Solution_> scoreDirector) { beforeVariableChangedEntityList.clear(); afterVariableChangedEntityList.clear(); } @Override public void beforeEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { } @Override public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { } @Override public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { } @Override public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { } @Override public void afterListVariableElementUnassigned(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object element) { } @Override public void beforeListVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity, int fromIndex, int toIndex) { beforeVariableChangedEntityList.add(entity); } @Override public void afterListVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull 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/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/ShadowVariableSnapshot.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.variable.ShadowVariable; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; final class ShadowVariableSnapshot { private final ShadowVariableDescriptor<?> shadowVariableDescriptor; private final Object entity; private final Object originalValue; private ShadowVariableSnapshot(ShadowVariableDescriptor<?> shadowVariableDescriptor, Object entity, Object originalValue) { this.shadowVariableDescriptor = shadowVariableDescriptor; this.entity = entity; this.originalValue = originalValue; } static ShadowVariableSnapshot of(ShadowVariableDescriptor<?> shadowVariableDescriptor, Object entity) { return new ShadowVariableSnapshot(shadowVariableDescriptor, entity, shadowVariableDescriptor.getValue(entity)); } void validate(Consumer<String> violationMessageConsumer) { Object newValue = shadowVariableDescriptor.getValue(entity); if (!Objects.equals(originalValue, newValue)) { violationMessageConsumer.accept(" The entity (" + entity + ")'s shadow variable (" + shadowVariableDescriptor.getSimpleEntityAndVariableName() + ")'s corrupted value (" + originalValue + ") changed to uncorrupted value (" + newValue + ") after all variable listeners were triggered without changes to the genuine variables.\n" + " Maybe one of the listeners (" + shadowVariableDescriptor.getVariableListenerClasses().stream() .map(Class::getSimpleName) .collect(Collectors.toList()) + ") for that shadow variable (" + shadowVariableDescriptor.getSimpleEntityAndVariableName() + ") forgot to update it when one of its sourceVariables (" + shadowVariableDescriptor.getSourceVariableDescriptorList().stream() .map(VariableDescriptor::getSimpleEntityAndVariableName) .collect(Collectors.toList()) + ") changed.\n" + " Or vice versa, maybe one of the listeners computes this shadow variable using a planning variable" + " that is not declared as its source." + " Use the repeatable @" + ShadowVariable.class.getSimpleName() + " annotation for each source variable that is used to compute this shadow variable." + "\n"); } } ShadowVariableDescriptor<?> getShadowVariableDescriptor() { return shadowVariableDescriptor; } @Override public String toString() { return entity + "." + shadowVariableDescriptor.getVariableName() + " = " + originalValue; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/ShadowVariablesAssert.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import static java.util.Comparator.comparing; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; /** * Serves for detecting shadow variables' corruption. When a snapshot is created, it records the state of all shadow variables * of all entities. The {@link #createShadowVariablesViolationMessage} method takes a look at the shadow variables again, * compares their state with the recorded one and describes the difference in a violation message. */ public final class ShadowVariablesAssert { private final List<ShadowVariableSnapshot> shadowVariableSnapshots; private ShadowVariablesAssert(List<ShadowVariableSnapshot> shadowVariableSnapshots) { this.shadowVariableSnapshots = shadowVariableSnapshots; } public static <Solution_> ShadowVariablesAssert takeSnapshot( SolutionDescriptor<Solution_> solutionDescriptor, Solution_ workingSolution) { List<ShadowVariableSnapshot> shadowVariableSnapshots = new ArrayList<>(); solutionDescriptor.visitAllEntities(workingSolution, entity -> solutionDescriptor.findEntityDescriptorOrFail(entity.getClass()) .getShadowVariableDescriptors().stream() .map(shadowVariableDescriptor -> ShadowVariableSnapshot.of(shadowVariableDescriptor, entity)) .forEach(shadowVariableSnapshots::add)); return new ShadowVariablesAssert(shadowVariableSnapshots); } public static <Solution_> void resetShadowVariables( SolutionDescriptor<Solution_> solutionDescriptor, Solution_ workingSolution) { solutionDescriptor.visitAllEntities(workingSolution, entity -> solutionDescriptor.findEntityDescriptorOrFail(entity.getClass()) .getShadowVariableDescriptors() .forEach(descriptor -> descriptor.setValue(entity, null))); } /** * Takes a look at the shadow variables of all entities and compares them against the recorded state. Every difference * is added to the violation message. The first N differences up to the {@code violationDisplayLimit} are displayed * in detail; the number of violations exceeding the display limit is reported at the end. The limit applies per each * shadow variable descriptor. * <p> * This method should be called after a forceful trigger of variable listeners. * * @param violationDisplayLimit maximum number of violations reported per shadow variable descriptor * @return description of the violations or {@code null} if there are none */ public String createShadowVariablesViolationMessage(long violationDisplayLimit) { Map<ShadowVariableDescriptor<?>, List<String>> violationListMap = collectViolations(); if (violationListMap.isEmpty()) { return null; } return format(violationListMap, violationDisplayLimit); } private Map<ShadowVariableDescriptor<?>, List<String>> collectViolations() { Map<ShadowVariableDescriptor<?>, List<String>> violationListMap = new TreeMap<>( comparing(ShadowVariableDescriptor::getGlobalShadowOrder)); for (ShadowVariableSnapshot shadowVariableSnapshot : shadowVariableSnapshots) { shadowVariableSnapshot.validate(violationMessage -> violationListMap .computeIfAbsent(shadowVariableSnapshot.getShadowVariableDescriptor(), k -> new ArrayList<>()) .add(violationMessage)); } return violationListMap; } private String format(Map<ShadowVariableDescriptor<?>, List<String>> violationListMap, long violationDisplayLimit) { StringBuilder message = new StringBuilder(); violationListMap.forEach((shadowVariableDescriptor, violationList) -> { violationList.stream().limit(violationDisplayLimit).forEach(message::append); if (violationList.size() >= violationDisplayLimit) { message.append(" ... ").append(violationList.size() - violationDisplayLimit) .append(" more\n"); } }); return message.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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 record SolutionCorruptionResult(boolean isCorrupted, String message) { public static SolutionCorruptionResult untracked() { return new SolutionCorruptionResult(false, ""); } } public SolutionCorruptionResult buildSolutionCorruptionResult() { if (beforeMoveSolution == null) { return new SolutionCorruptionResult(false, ""); } 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))); } var isCorrupted = !out.isEmpty(); if (isCorrupted) { return new SolutionCorruptionResult(isCorrupted, out.toString()); } else { return new SolutionCorruptionResult(false, "Genuine and shadow variables agree with from scratch calculation after the undo move and match the state prior to the move."); } } public String buildScoreCorruptionMessage() { return buildSolutionCorruptionResult().message; } 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/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/VariableId.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * A {@link VariableId} is an entity/variable of a given solution. * {@link VariableId} cannot be compared across different solution instances, * since variableDescriptor and entity are compared by reference equality. * * @param variableDescriptor The variable this {@link VariableId} refers to. * @param entity The entity this {@link VariableId} refers to. */ public record VariableId<Solution_>(VariableDescriptor<Solution_> variableDescriptor, Object entity) { @Override public boolean equals(Object other) { if (other instanceof VariableId<?> variableId) { return variableDescriptor == variableId.variableDescriptor && entity == variableId.entity; } return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/VariableSnapshot.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import java.util.ArrayList; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * A {@link VariableSnapshot} is a snapshot of the value of a variable for a given entity. * Only {@link VariableSnapshot} from the same solution instance can be compared. * * @param variableId The entity/variable pair that is recorded. * @param value The recorded value of the variable for the given entity. * @param <Solution_> */ public record VariableSnapshot<Solution_>(VariableId<Solution_> variableId, Object value) { public VariableSnapshot(VariableDescriptor<Solution_> variableDescriptor, Object entity) { this(new VariableId<>(variableDescriptor, entity), variableDescriptor.isListVariable() ? new ArrayList<>((List<?>) variableDescriptor.getValue(entity)) : variableDescriptor.getValue(entity)); } public VariableDescriptor<Solution_> getVariableDescriptor() { return variableId.variableDescriptor(); } public Object getEntity() { return variableId.entity(); } public Object getValue() { return value; } public VariableId<Solution_> getVariableId() { return variableId; } public void restore() { variableId.variableDescriptor().setValue(variableId.entity(), value); } public boolean isDifferentFrom(VariableSnapshot<Solution_> other) { if (!Objects.equals(variableId, other.variableId)) { throw new IllegalArgumentException( "The variable/entity pair for the other snapshot (%s) differs from the variable/entity pair for this snapshot (%s)." .formatted(other.variableId, this.variableId)); } return !Objects.equals(value, other.value); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support/violation/VariableSnapshotTotal.java
package ai.timefold.solver.core.impl.domain.variable.listener.support.violation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.VariableDescriptor; /** * Serves for detecting undo move corruption. * When a snapshot is created, it records the state of all variables (genuine and shadow) for all entities. */ public final class VariableSnapshotTotal<Solution_> { private final Map<VariableId<Solution_>, VariableSnapshot<Solution_>> variableIdToSnapshot = new HashMap<>(); private VariableSnapshotTotal() { } public static <Solution_> VariableSnapshotTotal<Solution_> takeSnapshot( SolutionDescriptor<Solution_> solutionDescriptor, Solution_ workingSolution) { VariableSnapshotTotal<Solution_> out = new VariableSnapshotTotal<>(); solutionDescriptor.visitAllEntities(workingSolution, entity -> { EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass()); for (var variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) { out.recordVariable(variableDescriptor, entity); } }); return out; } private void recordVariable(VariableDescriptor<Solution_> variableDescriptor, Object entity) { VariableSnapshot<Solution_> snapshot = new VariableSnapshot<>(variableDescriptor, entity); variableIdToSnapshot.put(snapshot.getVariableId(), snapshot); } public List<VariableId<Solution_>> changedVariablesFrom(VariableSnapshotTotal<Solution_> before) { List<VariableId<Solution_>> out = new ArrayList<>(); for (VariableId<Solution_> variableId : variableIdToSnapshot.keySet()) { VariableSnapshot<Solution_> variableBefore = before.variableIdToSnapshot.get(variableId); VariableSnapshot<Solution_> variableAfter = this.variableIdToSnapshot.get(variableId); if (variableBefore.isDifferentFrom(variableAfter)) { out.add(variableAfter.getVariableId()); } } return out; } public VariableSnapshot<Solution_> getVariableSnapshot(VariableId<Solution_> variableId) { return variableIdToSnapshot.get(variableId); } public void restore() { variableIdToSnapshot.values().forEach(VariableSnapshot::restore); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/listener/support
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import org.jspecify.annotations.NonNull; /** * 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(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object object) { } @Override public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object object) { } @Override public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object object) { } @Override public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object object) { } @Override public void resetWorkingSolution(@NonNull ScoreDirector<Solution_> scoreDirector) { beforeVariableChangedEntityList.clear(); afterVariableChangedEntityList.clear(); } @Override public void beforeVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) { beforeVariableChangedEntityList.add(entity); } @Override public void afterVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull 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/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.ListVariableStateSupply; 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("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } @Override public boolean isListVariableSource() { return true; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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 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.ListVariableStateSupply; 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() { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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 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.ListVariableStateSupply; 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() { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { throw new UnsupportedOperationException("Impossible state: Handled by %s." .formatted(ListVariableStateSupply.class.getSimpleName())); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/supply/AbstractVariableDescriptorBasedDemand.java
package ai.timefold.solver.core.impl.domain.variable.supply; import java.util.Objects; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * Some {@link Demand} implementation classes are defined by their {@link VariableDescriptor} and nothing else. * However, they still must not equal (and therefore have the same {@link #hashCode()}) * as other {@link Demand} implementation classes defined by the same {@link VariableDescriptor}. * This helper abstraction exists so that this logic can be shared across all such {@link Demand} implementations. * * @param <Solution_> * @param <Supply_> */ public abstract class AbstractVariableDescriptorBasedDemand<Solution_, Supply_ extends Supply> implements Demand<Supply_> { protected final VariableDescriptor<Solution_> variableDescriptor; protected AbstractVariableDescriptorBasedDemand(VariableDescriptor<Solution_> variableDescriptor) { this.variableDescriptor = Objects.requireNonNull(variableDescriptor); } @Override public final boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; AbstractVariableDescriptorBasedDemand<?, ?> that = (AbstractVariableDescriptorBasedDemand<?, ?>) other; return Objects.equals(variableDescriptor, that.variableDescriptor); } @Override public final int hashCode() { // Don't use Objects.hashCode(...) as that would create varargs array on the hot path. int result = this.getClass().getName().hashCode(); result = 31 * result + variableDescriptor.hashCode(); return result; } @Override public final String toString() { return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/supply/Demand.java
package ai.timefold.solver.core.impl.domain.variable.supply; /** * A subsystem submits a demand for a {@link Supply}. * Implementations must overwrite {@link Object#equals(Object)} and {@link Object#hashCode()}. * * @param <Supply_> Subclass of {@link Supply} * @see Supply * @see SupplyManager */ public interface Demand<Supply_ extends Supply> { /** * Only called if the domain model doesn't already support the demand (through a shadow variable usually). * Equal demands share the same {@link Supply}. * * @param supplyManager never null * @return never null */ Supply_ createExternalizedSupply(SupplyManager supplyManager); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/supply/Supply.java
package ai.timefold.solver.core.impl.domain.variable.supply; /** * Supplies something for 1 or multiple subsystems. * Subsystems need to submit a {@link Demand} to get a supply, * so the supply can be shared or reused from the domain model. * * @see Demand * @see SupplyManager */ public interface Supply { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/supply/SupplyManager.java
package ai.timefold.solver.core.impl.domain.variable.supply; /** * Provides a {@link Supply} for subsystems that submit a {@link Demand}. */ public interface SupplyManager { /** * Returns the {@link Supply} for a {@link Demand}, preferably an existing one. * If the {@link Supply} doesn't exist yet (as part of the domain model or externalized), it creates and attaches it. * If two {@link Demand} instances {@link Object#equals(Object) are equal}, * they will result in the same {@link Supply} instance. * Each supply instance keeps a counter of how many times it was requested, * which can be decremented by {@link #cancel(Demand)}. * * @param demand never null * @param <Supply_> Subclass of {@link Supply} * @return never null */ <Supply_ extends Supply> Supply_ demand(Demand<Supply_> demand); /** * Cancel an active {@link #demand(Demand)}. * Once the number of active demands reaches zero, the {@link Supply} in question is removed. * <p> * This operation is optional. * Supplies with active demands will live for as long as the {@link SupplyManager} lives, * and get garbage-collected together with it. * * @param demand never null * @param <Supply_> * @return true if the counter was decremented, false if there is no such supply */ <Supply_ extends Supply> boolean cancel(Demand<Supply_> demand); /** * @param demand * @return 0 when there is no active {@link Supply} for the given {@link Demand}, more when there is one. * @param <Supply_> */ <Supply_ extends Supply> long getActiveCount(Demand<Supply_> demand); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.TreeSet; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.config.solver.EnvironmentMode; 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.scope.ExhaustiveSearchPhaseScope; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchStepScope; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.CompositeMove; import ai.timefold.solver.core.impl.phase.AbstractPhase; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.PhaseTermination; import ai.timefold.solver.core.preview.api.move.Move; /** * 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) { var expandableNodeQueue = new TreeSet<>(nodeComparator); var phaseScope = new ExhaustiveSearchPhaseScope<>(solverScope, phaseIndex); phaseScope.setExpandableNodeQueue(expandableNodeQueue); phaseStarted(phaseScope); while (!expandableNodeQueue.isEmpty() && !phaseTermination.isPhaseTerminated(phaseScope)) { var stepScope = new ExhaustiveSearchStepScope<>(phaseScope); var 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) { var stepScope = new ExhaustiveSearchStepScope<>(phaseScope); entitySelector.stepStarted(stepScope); var 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."); } var layerList = new ArrayList<ExhaustiveSearchLayer>((int) entitySize); var depth = 0; for (var entity : entitySelector) { var layer = new ExhaustiveSearchLayer(depth, entity); // Keep in sync with ExhaustiveSearchPhaseConfig.buildMoveSelectorConfig() // which includes all genuineVariableDescriptors var reinitializeVariableCount = entitySelector.getEntityDescriptor().countReinitializableVariables(entity); // Ignore entities with only initialized variables to avoid confusing bound decisions if (reinitializeVariableCount == 0) { continue; } depth++; layerList.add(layer); } var lastLayer = new ExhaustiveSearchLayer(depth, null); layerList.add(lastLayer); entitySelector.stepEnded(stepScope); phaseScope.setLayerList(layerList); } private <Score_ extends Score<Score_>> void initStartNode(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { var startLayer = phaseScope.getLayerList().get(0); var startNode = new ExhaustiveSearchNode(startLayer, null); if (decider.isScoreBounderEnabled()) { var scoreDirector = phaseScope.<Score_> getScoreDirector(); var score = scoreDirector.calculateScore(); startNode.setScore(score); var scoreBounder = decider.<Score_> 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 <Score_ extends Score<Score_>> void restoreWorkingSolution(ExhaustiveSearchStepScope<Solution_> stepScope) { var phaseScope = stepScope.getPhaseScope(); var oldNode = phaseScope.getLastCompletedStepScope().getExpandingNode(); var newNode = stepScope.getExpandingNode(); var oldMoveList = new ArrayList<Move<Solution_>>(oldNode.getDepth()); var newMoveList = new ArrayList<Move<Solution_>>(newNode.getDepth()); while (oldNode != newNode) { var oldDepth = oldNode.getDepth(); var newDepth = newNode.getDepth(); if (oldDepth < newDepth) { newMoveList.add(newNode.getMove()); newNode = newNode.getParent(); } else { oldMoveList.add(oldNode.getUndoMove()); oldNode = oldNode.getParent(); } } var restoreMoveList = new ArrayList<Move<Solution_>>(oldMoveList.size() + newMoveList.size()); restoreMoveList.addAll(oldMoveList); Collections.reverse(newMoveList); restoreMoveList.addAll(newMoveList); if (restoreMoveList.isEmpty()) { // No moves to restore, so the working solution is already correct return; } var compositeMove = CompositeMove.buildMove(restoreMoveList); phaseScope.getScoreDirector().executeMove(compositeMove); var startingStepScore = stepScope.<Score_> getStartingStepScore(); phaseScope.getSolutionDescriptor().setScore(phaseScope.getWorkingSolution(), (startingStepScore == null ? null : startingStepScore.raw())); if (assertWorkingSolutionScoreFromScratch) { // In BRUTE_FORCE the stepScore can be null because it was not calculated if (stepScope.getStartingStepScore() != null) { phaseScope.assertPredictedScoreFromScratch(stepScope.<Score_> getStartingStepScore(), restoreMoveList); } } if (assertExpectedWorkingSolutionScore) { // In BRUTE_FORCE the stepScore can be null because it was not calculated if (stepScope.getStartingStepScore() != null) { phaseScope.assertExpectedWorkingScore(stepScope.<Score_> getStartingStepScore(), restoreMoveList); } } } public void stepEnded(ExhaustiveSearchStepScope<Solution_> stepScope) { super.stepEnded(stepScope); // Skip entitySelector.stepEnded(stepScope) decider.stepEnded(stepScope); if (logger.isDebugEnabled()) { var 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().raw(), 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 ({})," + " move evaluation speed ({}/sec), step total ({}).", logIndentation, phaseIndex, phaseScope.calculateSolverTimeMillisSpentUpToNow(), phaseScope.getBestScore().raw(), phaseScope.getPhaseMoveEvaluationSpeed(), phaseScope.getNextStepIndex()); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); entitySelector.solvingEnded(solverScope); decider.solvingEnded(solverScope); } public static class Builder<Solution_> extends AbstractPhaseBuilder<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, PhaseTermination<Solution_> phaseTermination, Comparator<ExhaustiveSearchNode> nodeComparator, EntitySelector<Solution_> entitySelector, ExhaustiveSearchDecider<Solution_> decider) { super(phaseIndex, logIndentation, phaseTermination); this.nodeComparator = nodeComparator; this.entitySelector = entitySelector; this.decider = decider; } @Override public Builder<Solution_> enableAssertions(EnvironmentMode environmentMode) { super.enableAssertions(environmentMode); assertWorkingSolutionScoreFromScratch = environmentMode.isFullyAsserted(); assertExpectedWorkingSolutionScore = environmentMode.isIntrusivelyAsserted(); return this; } @Override public DefaultExhaustiveSearchPhase<Solution_> build() { return new DefaultExhaustiveSearchPhase<>(this); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.move.MoveSelectorBasedMoveRepository; 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.PhaseTermination; import ai.timefold.solver.core.impl.solver.termination.SolverTermination; public class DefaultExhaustiveSearchPhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, ExhaustiveSearchPhaseConfig> { public DefaultExhaustiveSearchPhaseFactory(ExhaustiveSearchPhaseConfig phaseConfig) { super(phaseConfig); } @Override public ExhaustiveSearchPhase<Solution_> buildPhase(int phaseIndex, boolean lastInitializingPhase, HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller, SolverTermination<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(); PhaseTermination<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); return new DefaultExhaustiveSearchPhase.Builder<>(phaseIndex, solverConfigPolicy.getLogIndentation(), phaseTermination, nodeExplorationType_.buildNodeComparator(scoreBounderEnabled), entitySelector, buildDecider(phaseConfigPolicy, entitySelector, bestSolutionRecaller, phaseTermination, scoreBounderEnabled)) .enableAssertions(phaseConfigPolicy.getEnvironmentMode()) .build(); } private EntitySelectorConfig buildEntitySelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) { var result = Objects.requireNonNullElseGet( phaseConfig.getEntitySelectorConfig(), () -> { var entityDescriptor = deduceEntityDescriptor(configPolicy.getSolutionDescriptor()); var entitySelectorConfig = new EntitySelectorConfig() .withEntityClass(entityDescriptor.getEntityClass()); if (EntitySelectorConfig.hasSorter(configPolicy.getEntitySorterManner(), entityDescriptor)) { entitySelectorConfig = entitySelectorConfig.withCacheType(SelectionCacheType.PHASE) .withSelectionOrder(SelectionOrder.SORTED) .withSorterManner(configPolicy.getEntitySorterManner()); } return entitySelectorConfig; }); var cacheType = result.getCacheType(); if (cacheType != null && cacheType.compareTo(SelectionCacheType.PHASE) < 0) { throw new IllegalArgumentException( "The phaseConfig (%s) cannot have an entitySelectorConfig (%s) with a cacheType (%s) lower than %s." .formatted(phaseConfig, result, cacheType, SelectionCacheType.PHASE)); } return result; } 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, PhaseTermination<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, new MoveSelectorBasedMoveRepository<>(moveSelector), scoreBounderEnabled, scoreBounder); EnvironmentMode environmentMode = configPolicy.getEnvironmentMode(); if (environmentMode.isFullyAsserted()) { decider.setAssertMoveScoreFromScratch(true); } if (environmentMode.isIntrusivelyAsserted()) { 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.canExtractValueRangeFromSolution() ? 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/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/ExhaustiveSearchPhase.java
package ai.timefold.solver.core.impl.exhaustivesearch; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.phase.AbstractPhase; import ai.timefold.solver.core.impl.phase.Phase; /** * A {@link ExhaustiveSearchPhase} is a {@link Phase} which uses an exhaustive algorithm, such as Brute Force. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see Phase * @see AbstractPhase * @see DefaultExhaustiveSearchPhase */ public interface ExhaustiveSearchPhase<Solution_> extends Phase<Solution_> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.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.selector.entity.mimic.ManualEntityMimicRecorder; import ai.timefold.solver.core.impl.move.MoveRepository; import ai.timefold.solver.core.impl.phase.scope.SolverLifecyclePoint; import ai.timefold.solver.core.impl.score.director.InnerScore; 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.PhaseTermination; 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 PhaseTermination<Solution_> termination; private final ManualEntityMimicRecorder<Solution_> manualEntityMimicRecorder; private final MoveRepository<Solution_> moveRepository; private final boolean scoreBounderEnabled; private final ScoreBounder<?> scoreBounder; private boolean assertMoveScoreFromScratch = false; private boolean assertExpectedUndoMoveScore = false; public ExhaustiveSearchDecider(String logIndentation, BestSolutionRecaller<Solution_> bestSolutionRecaller, PhaseTermination<Solution_> termination, ManualEntityMimicRecorder<Solution_> manualEntityMimicRecorder, MoveRepository<Solution_> moveRepository, boolean scoreBounderEnabled, ScoreBounder<?> scoreBounder) { this.logIndentation = logIndentation; this.bestSolutionRecaller = bestSolutionRecaller; this.termination = termination; this.manualEntityMimicRecorder = manualEntityMimicRecorder; this.moveRepository = moveRepository; this.scoreBounderEnabled = scoreBounderEnabled; this.scoreBounder = scoreBounder; } public MoveRepository<Solution_> getMoveRepository() { return moveRepository; } public boolean isScoreBounderEnabled() { return scoreBounderEnabled; } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> ScoreBounder<Score_> getScoreBounder() { return (ScoreBounder<Score_>) 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) { moveRepository.solvingStarted(solverScope); } @Override public void phaseStarted(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { moveRepository.phaseStarted(phaseScope); } @Override public void stepStarted(ExhaustiveSearchStepScope<Solution_> stepScope) { moveRepository.stepStarted(stepScope); } @Override public void stepEnded(ExhaustiveSearchStepScope<Solution_> stepScope) { moveRepository.stepEnded(stepScope); } @Override public void phaseEnded(ExhaustiveSearchPhaseScope<Solution_> phaseScope) { moveRepository.phaseEnded(phaseScope); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { moveRepository.solvingEnded(solverScope); } public void expandNode(ExhaustiveSearchStepScope<Solution_> stepScope) { var expandingNode = stepScope.getExpandingNode(); manualEntityMimicRecorder.setRecordedEntity(expandingNode.getEntity()); var moveIndex = 0; var phaseScope = stepScope.getPhaseScope(); var moveLayer = phaseScope.getLayerList().get(expandingNode.getDepth() + 1); for (var move : moveRepository) { var 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); phaseScope.addMoveEvaluationCount(move, 1); // TODO in the lowest level (and only in that level) QuitEarly can be useful // No QuitEarly because lower layers might be promising phaseScope.getSolverScope().checkYielding(); if (termination.isPhaseTerminated(stepScope.getPhaseScope())) { break; } } stepScope.setSelectedMoveCount((long) moveIndex); } @SuppressWarnings("unchecked") private <Score_ extends Score<Score_>> void doMove(ExhaustiveSearchStepScope<Solution_> stepScope, ExhaustiveSearchNode moveNode) { var scoreDirector = stepScope.<Score_> getScoreDirector(); var move = moveNode.getMove(); var undoMove = scoreDirector.getMoveDirector().executeTemporary(move, (score, undo) -> { processMove(stepScope, moveNode); return undo; }); moveNode.setUndoMove(undoMove); var executionPoint = SolverLifecyclePoint.of(stepScope, moveNode.getTreeId()); if (assertExpectedUndoMoveScore) { var startingStepScore = stepScope.<Score_> getStartingStepScore(); // In BRUTE_FORCE a stepScore can be null because it was not calculated if (startingStepScore != null) { scoreDirector.assertExpectedUndoMoveScore(move, startingStepScore, executionPoint); } } var nodeScore = moveNode.getScore(); LOGGER.trace("{} Move treeId ({}), score ({}), expandable ({}), move ({}).", logIndentation, executionPoint.treeId(), nodeScore == null ? "null" : nodeScore, moveNode.isExpandable(), moveNode.getMove()); } @SuppressWarnings("unchecked") private <Score_ extends Score<Score_>> void processMove(ExhaustiveSearchStepScope<Solution_> stepScope, ExhaustiveSearchNode moveNode) { var phaseScope = stepScope.getPhaseScope(); var lastLayer = moveNode.isLastLayer(); if (!scoreBounderEnabled) { if (lastLayer) { var score = phaseScope.<Score_> calculateScore(); moveNode.setScore(score); if (assertMoveScoreFromScratch) { phaseScope.assertWorkingScoreFromScratch(score, moveNode.getMove()); } bestSolutionRecaller.processWorkingSolutionDuringMove(score, stepScope); } else { phaseScope.addExpandableNode(moveNode); } } else { var innerScore = phaseScope.<Score_> calculateScore(); moveNode.setScore(innerScore); if (assertMoveScoreFromScratch) { phaseScope.assertWorkingScoreFromScratch(innerScore, moveNode.getMove()); } if (lastLayer) { // There is no point in bounding a fully initialized score phaseScope.registerPessimisticBound(innerScore); bestSolutionRecaller.processWorkingSolutionDuringMove(innerScore, stepScope); } else { var scoreDirector = phaseScope.<Score_> getScoreDirector(); var castScoreBounder = this.<Score_> getScoreBounder(); var optimisticBound = castScoreBounder.calculateOptimisticBound(scoreDirector, innerScore); moveNode.setOptimisticBound(optimisticBound); var bestPessimisticBound = (InnerScore<Score_>) phaseScope.getBestPessimisticBound(); if (optimisticBound.compareTo(bestPessimisticBound) > 0) { // It's still worth investigating this node further (no need to prune it) phaseScope.addExpandableNode(moveNode); var pessimisticBound = castScoreBounder.calculatePessimisticBound(scoreDirector, innerScore); phaseScope.registerPessimisticBound(pessimisticBound); } } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/event/ExhaustiveSearchPhaseLifecycleListener.java
package ai.timefold.solver.core.impl.exhaustivesearch.event; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchPhaseScope; import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchStepScope; import ai.timefold.solver.core.impl.solver.event.SolverLifecycleListener; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public interface ExhaustiveSearchPhaseLifecycleListener<Solution_> extends SolverLifecycleListener<Solution_> { void phaseStarted(ExhaustiveSearchPhaseScope<Solution_> phaseScope); void stepStarted(ExhaustiveSearchStepScope<Solution_> stepScope); void stepEnded(ExhaustiveSearchStepScope<Solution_> stepScope); void phaseEnded(ExhaustiveSearchPhaseScope<Solution_> phaseScope); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node/ExhaustiveSearchLayer.java
package ai.timefold.solver.core.impl.exhaustivesearch.node; public class ExhaustiveSearchLayer { private final int depth; private final Object entity; private long nextBreadth; public ExhaustiveSearchLayer(int depth, Object entity) { this.depth = depth; this.entity = entity; nextBreadth = 0L; } public int getDepth() { return depth; } public Object getEntity() { return entity; } // ************************************************************************ // Calculated methods // ************************************************************************ public boolean isLastLayer() { return entity == null; } public long assignBreadth() { long breadth = nextBreadth; nextBreadth++; return breadth; } @Override public String toString() { return depth + (isLastLayer() ? " last layer" : " (" + entity + ")"); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.score.director.InnerScore; import ai.timefold.solver.core.preview.api.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 InnerScore<?> score; /** * Never worse than the best possible score a leaf node below this node might lead to. * * @see ScoreBounder#calculateOptimisticBound(ScoreDirector, InnerScore) */ private InnerScore<?> 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; } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> InnerScore<Score_> getScore() { return (InnerScore<Score_>) score; } public <Score_ extends Score<Score_>> void setInitializedScore(Score_ score) { setScore(InnerScore.fullyAssigned(score)); } public void setScore(InnerScore<?> score) { this.score = score; } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> InnerScore<Score_> getOptimisticBound() { return (InnerScore<Score_>) optimisticBound; } public void setOptimisticBound(InnerScore<?> 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/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.director.InnerScore; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public interface ScoreBounder<Score_ extends Score<Score_>> { /** * 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) */ InnerScore<Score_> calculateOptimisticBound(ScoreDirector<?> scoreDirector, InnerScore<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) */ InnerScore<Score_> calculatePessimisticBound(ScoreDirector<?> scoreDirector, InnerScore<Score_> score); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.director.InnerScore; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public final class TrendBasedScoreBounder<Score_ extends Score<Score_>> implements ScoreBounder<Score_> { private final ScoreDefinition<Score_> scoreDefinition; private final InitializingScoreTrend initializingScoreTrend; public TrendBasedScoreBounder(ScoreDefinition<Score_> scoreDefinition, InitializingScoreTrend initializingScoreTrend) { this.scoreDefinition = scoreDefinition; this.initializingScoreTrend = initializingScoreTrend; } @Override public InnerScore<Score_> calculateOptimisticBound(ScoreDirector<?> scoreDirector, InnerScore<Score_> score) { return new InnerScore<>(scoreDefinition.buildOptimisticBound(initializingScoreTrend, score.raw()), 0); } @Override public InnerScore<Score_> calculatePessimisticBound(ScoreDirector<?> scoreDirector, InnerScore<Score_> score) { return new InnerScore<>(scoreDefinition.buildPessimisticBound(initializingScoreTrend, score.raw()), 0); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import ai.timefold.solver.core.impl.score.director.InnerScore; /** * 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, InnerScore)} * 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; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate shallower nodes first var aDepth = a.getDepth(); var 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) Score aScore = a.getScore().raw(); Score bScore = b.getScore().raw(); var scoreComparison = aScore.compareTo(bScore); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } if (scoreBounderEnabled) { // Investigate better optimistic bound first var 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/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.api.score.Score; 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; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate deeper first var aDepth = a.getDepth(); var 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) Score aScore = a.getScore().raw(); Score bScore = b.getScore().raw(); var scoreComparison = aScore.compareTo(bScore); 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 var 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) var aParentBreadth = a.getParentBreadth(); var 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/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.api.score.Score; 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 %s only works if scoreBounderEnabled (%s) is true." .formatted(getClass().getSimpleName(), scoreBounderEnabled)); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate better optimistic bound first (ignore initScore to avoid depth first ordering) var optimisticBoundComparison = a.getOptimisticBound().compareTo(b.getOptimisticBound()); if (optimisticBoundComparison < 0) { return -1; } else if (optimisticBoundComparison > 0) { return 1; } // Investigate better score first Score aScore = a.getScore().raw(); Score bScore = b.getScore().raw(); var scoreComparison = aScore.compareTo(bScore); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } // Investigate deeper first var aDepth = a.getDepth(); var 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) var aParentBreadth = a.getParentBreadth(); var 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/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node/comparator/OriginalOrderNodeComparator.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, in order. */ public class OriginalOrderNodeComparator implements Comparator<ExhaustiveSearchNode> { @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 lower breadth index first (to respect ValueSortingManner) return Long.compare(b.getBreadth(), a.getBreadth()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch/node
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.api.score.Score; 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."); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public int compare(ExhaustiveSearchNode a, ExhaustiveSearchNode b) { // Investigate better score first (ignore initScore to avoid depth first ordering) Score aScore = a.getScore().raw(); Score bScore = b.getScore().raw(); var scoreComparison = aScore.compareTo(bScore); if (scoreComparison < 0) { return -1; } else if (scoreComparison > 0) { return 1; } // Investigate better optimistic bound first var optimisticBoundComparison = a.getOptimisticBound().compareTo(b.getOptimisticBound()); if (optimisticBoundComparison < 0) { return -1; } else if (optimisticBoundComparison > 0) { return 1; } // Investigate deeper first var aDepth = a.getDepth(); var 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) var aParentBreadth = a.getParentBreadth(); var 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/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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.score.director.InnerScore; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final class ExhaustiveSearchPhaseScope<Solution_> extends AbstractPhaseScope<Solution_> { private List<ExhaustiveSearchLayer> layerList; private SortedSet<ExhaustiveSearchNode> expandableNodeQueue; private InnerScore<?> bestPessimisticBound; private ExhaustiveSearchStepScope<Solution_> lastCompletedStepScope; public ExhaustiveSearchPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex) { super(solverScope, phaseIndex, false); 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; } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> InnerScore<Score_> getBestPessimisticBound() { return (InnerScore<Score_>) bestPessimisticBound; } public void setBestPessimisticBound(InnerScore<?> 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 <Score_ extends Score<Score_>> void registerPessimisticBound(InnerScore<Score_> pessimisticBound) { var castBestPessimisticBound = this.<Score_> getBestPessimisticBound(); if (pessimisticBound.compareTo(castBestPessimisticBound) > 0) { bestPessimisticBound = pessimisticBound; // Prune the queue // TODO optimize this because expandableNodeQueue is too long to iterate expandableNodeQueue.removeIf(node -> { var optimistic = node.<Score_> getOptimisticBound(); return optimistic.compareTo(pessimisticBound) <= 0; }); } } public void addExpandableNode(ExhaustiveSearchNode moveNode) { expandableNodeQueue.add(moveNode); moveNode.setExpandable(true); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/exhaustivesearch
java-sources/ai/timefold/solver/timefold-solver-core/1.26.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; import ai.timefold.solver.core.impl.score.director.InnerScore; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public final 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_ extends Score<Score_>> InnerScore<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/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/HeuristicConfigPolicy.java
package ai.timefold.solver.core.impl.heuristic; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; 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.solver.PreviewFeature; 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 Set<PreviewFeature> previewFeatureSet; 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.previewFeatureSet = builder.previewFeatureSet; 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<Solution_>() .withPreviewFeatureSet(previewFeatureSet) .withEnvironmentMode(environmentMode) .withMoveThreadCount(moveThreadCount) .withMoveThreadBufferSize(moveThreadBufferSize) .withThreadFactoryClass(threadFactoryClass) .withNearbyDistanceMeterClass(nearbyDistanceMeterClass) .withRandom(random) .withInitializingScoreTrend(initializingScoreTrend) .withSolutionDescriptor(solutionDescriptor) .withClassInstanceCache(classInstanceCache) .withLogIndentation(logIndentation); } public HeuristicConfigPolicy<Solution_> copyConfigPolicy() { return cloneBuilder() .withEntitySorterManner(entitySorterManner) .withValueSorterManner(valueSorterManner) .withReinitializeVariableFilterEnabled(reinitializeVariableFilterEnabled) .withInitializedChainedValueFilterEnabled(initializedChainedValueFilterEnabled) .withUnassignedValuesAllowed(unassignedValuesAllowed) .build(); } public HeuristicConfigPolicy<Solution_> createPhaseConfigPolicy() { return cloneBuilder().build(); } public HeuristicConfigPolicy<Solution_> copyConfigPolicyWithoutNearbySetting() { return cloneBuilder() .withNearbyDistanceMeterClass(null) .build(); } public HeuristicConfigPolicy<Solution_> createChildThreadConfigPolicy(ChildThreadType childThreadType) { return cloneBuilder() .withLogIndentation(logIndentation + " ") .build(); } // ************************************************************************ // Worker methods // ************************************************************************ public void addEntityMimicRecorder(String id, EntityMimicRecorder<Solution_> mimicRecordingEntitySelector) { var put = entityMimicRecorderMap.put(id, mimicRecordingEntitySelector); if (put != null) { throw new IllegalStateException( """ Multiple %ss (usually %ss) have the same id (%s). Maybe specify a variable name for the mimicking selector in situations with multiple variables on the same entity?""" .formatted(EntityMimicRecorder.class.getSimpleName(), EntitySelector.class.getSimpleName(), id)); } } public EntityMimicRecorder<Solution_> getEntityMimicRecorder(String id) { return entityMimicRecorderMap.get(id); } public void addSubListMimicRecorder(String id, SubListMimicRecorder<Solution_> mimicRecordingSubListSelector) { var put = subListMimicRecorderMap.put(id, mimicRecordingSubListSelector); if (put != null) { throw new IllegalStateException( """ Multiple %ss (usually %ss) have the same id (%s). Maybe specify a variable name for the mimicking selector in situations with multiple variables on the same entity?""" .formatted(SubListMimicRecorder.class.getSimpleName(), SubListSelector.class.getSimpleName(), id)); } } public SubListMimicRecorder<Solution_> getSubListMimicRecorder(String id) { return subListMimicRecorderMap.get(id); } public void addValueMimicRecorder(String id, ValueMimicRecorder<Solution_> mimicRecordingValueSelector) { var put = valueMimicRecorderMap.put(id, mimicRecordingValueSelector); if (put != null) { throw new IllegalStateException( """ Multiple %ss (usually %ss) have the same id (%s). Maybe specify a variable name for the mimicking selector in situations with multiple variables on the same entity?""" .formatted(ValueMimicRecorder.class.getSimpleName(), ValueSelector.class.getSimpleName(), id)); } } 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 { var threadPrefix = switch (childThreadType) { case MOVE_THREAD -> "MoveThread"; case PART_THREAD -> "PartThread"; }; return new DefaultSolverThreadFactory(threadPrefix); } } public void ensurePreviewFeature(PreviewFeature previewFeature) { ensurePreviewFeature(previewFeature, previewFeatureSet); } public static void ensurePreviewFeature(PreviewFeature previewFeature, Collection<PreviewFeature> previewFeatureCollection) { if (previewFeatureCollection == null || !previewFeatureCollection.contains(previewFeature)) { throw new IllegalStateException(""" The preview feature %s is not enabled. Maybe add %s to <enablePreviewFeature> in your configuration file?""" .formatted(previewFeature, previewFeature)); } } @Override public String toString() { return getClass().getSimpleName() + "(" + environmentMode + ")"; } public static class Builder<Solution_> { private Set<PreviewFeature> previewFeatureSet; private EnvironmentMode environmentMode; private Integer moveThreadCount; private Integer moveThreadBufferSize; private Class<? extends ThreadFactory> threadFactoryClass; private InitializingScoreTrend initializingScoreTrend; private SolutionDescriptor<Solution_> solutionDescriptor; private 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 Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass; private Random random; public Builder<Solution_> withPreviewFeatureSet(Set<PreviewFeature> previewFeatureSet) { this.previewFeatureSet = previewFeatureSet; return this; } public Builder<Solution_> withEnvironmentMode(EnvironmentMode environmentMode) { this.environmentMode = environmentMode; return this; } public Builder<Solution_> withMoveThreadCount(Integer moveThreadCount) { this.moveThreadCount = moveThreadCount; return this; } public Builder<Solution_> withMoveThreadBufferSize(Integer moveThreadBufferSize) { this.moveThreadBufferSize = moveThreadBufferSize; return this; } public Builder<Solution_> withThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryClass) { this.threadFactoryClass = threadFactoryClass; return this; } public Builder<Solution_> withNearbyDistanceMeterClass(Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass) { this.nearbyDistanceMeterClass = nearbyDistanceMeterClass; return this; } public Builder<Solution_> withRandom(Random random) { this.random = random; return this; } public Builder<Solution_> withInitializingScoreTrend(InitializingScoreTrend initializingScoreTrend) { this.initializingScoreTrend = initializingScoreTrend; return this; } public Builder<Solution_> withSolutionDescriptor(SolutionDescriptor<Solution_> solutionDescriptor) { this.solutionDescriptor = solutionDescriptor; return this; } public Builder<Solution_> withClassInstanceCache(ClassInstanceCache classInstanceCache) { this.classInstanceCache = classInstanceCache; return this; } 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/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/move/AbstractMove.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; 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.move.director.VariableChangeRecordingScoreDirector; import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector; /** * Abstract superclass for {@link Move}, requiring implementation of undo moves. * * @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 void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { var recordingScoreDirector = scoreDirector instanceof VariableChangeRecordingScoreDirector<Solution_, ?> variableChangeRecordingScoreDirector ? variableChangeRecordingScoreDirector : new VariableChangeRecordingScoreDirector<>(scoreDirector); doMoveOnGenuineVariables(recordingScoreDirector); 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. * @deprecated The solver automatically generates undo moves, this method is no longer used. */ @Deprecated(forRemoval = true, since = "1.16.0") protected Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) { throw new UnsupportedOperationException("Operation requires an undo move, which is no longer supported."); } /** * 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); protected <Value_> ValueRange<Value_> extractValueRangeFromEntity(ScoreDirector<Solution_> scoreDirector, ValueRangeDescriptor<Solution_> valueRangeDescriptor, Object entity) { var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; return castScoreDirector.getValueRangeManager() .getFromEntity(valueRangeDescriptor, entity); } // ************************************************************************ // Util methods // ************************************************************************ public static <E> List<E> rebaseList(List<E> externalObjectList, ScoreDirector<?> destinationScoreDirector) { var rebasedObjectList = new ArrayList<E>(externalObjectList.size()); for (var entity : externalObjectList) { rebasedObjectList.add(destinationScoreDirector.lookUpWorkingObject(entity)); } return rebasedObjectList; } public static <E> Set<E> rebaseSet(Set<E> externalObjectSet, ScoreDirector<?> destinationScoreDirector) { var rebasedObjectSet = new LinkedHashSet<E>(externalObjectSet.size()); for (var entity : externalObjectSet) { rebasedObjectSet.add(destinationScoreDirector.lookUpWorkingObject(entity)); } return rebasedObjectSet; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/move/AbstractSimplifiedMove.java
package ai.timefold.solver.core.impl.heuristic.move; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.move.director.VariableChangeRecordingScoreDirector; /** * 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_> * @deprecated In favor of {@link AbstractMove}, which no longer requires undo moves to be implemented either. */ @Deprecated(forRemoval = true, since = "1.16.0") public abstract class AbstractSimplifiedMove<Solution_> implements Move<Solution_> { @Override public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { var recordingScoreDirector = scoreDirector instanceof VariableChangeRecordingScoreDirector<Solution_, ?> variableChangeRecordingScoreDirector ? variableChangeRecordingScoreDirector : new VariableChangeRecordingScoreDirector<>(scoreDirector); doMoveOnGenuineVariables(recordingScoreDirector); recordingScoreDirector.triggerVariableListeners(); } protected abstract void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector); @Override public String toString() { return getSimpleMoveTypeDescription(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/move/AbstractUndoMove.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.Collection; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Abstract superclass for {@link Move}, suggested starting point to implement undo moves. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see Move * @deprecated Undo moves are automatically generated by the solver. * Implementations of this class no longer have any effect any may be removed. */ @Deprecated(forRemoval = true, since = "1.16.0") public abstract class AbstractUndoMove<Solution_> implements Move<Solution_> { protected final Move<Solution_> parentMove; protected AbstractUndoMove(Move<Solution_> parentMove) { this.parentMove = Objects.requireNonNull(parentMove); } @Override public final boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { return true; // Undo moves are always doable; the parent move was already done. } @Override public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) { doMoveOnGenuineVariables(scoreDirector); scoreDirector.triggerVariableListeners(); } /** * 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); @Override public final Collection<?> getPlanningEntities() { return parentMove.getPlanningEntities(); } @Override public final Collection<?> getPlanningValues() { return parentMove.getPlanningValues(); } @Override public String getSimpleMoveTypeDescription() { return "Undo(" + parentMove.getSimpleMoveTypeDescription() + ")"; } @Override public String toString() { return getSimpleMoveTypeDescription(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/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_> extends AbstractMove<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 protected void doMoveOnGenuineVariables(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/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/move/LegacyMoveAdapter.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.Collection; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.move.InnerMutableSolutionView; import ai.timefold.solver.core.impl.move.director.MoveDirector; import ai.timefold.solver.core.preview.api.move.Move; import ai.timefold.solver.core.preview.api.move.MutableSolutionView; import ai.timefold.solver.core.preview.api.move.Rebaser; import ai.timefold.solver.core.preview.api.move.SolutionView; import org.jspecify.annotations.NullMarked; /** * Adapts {@link ai.timefold.solver.core.impl.heuristic.move.Move a legacy move} * to {@link Move a new move}. * Once the move selector framework is removed, this may be removed as well. * * @param legacyMove the move to adapt * @param <Solution_> */ @NullMarked public record LegacyMoveAdapter<Solution_>( ai.timefold.solver.core.impl.heuristic.move.Move<Solution_> legacyMove) implements Move<Solution_> { /** * Used to determine if a move is doable. * A move is only doable if: * * <ul> * <li>It is a new {@link Move}.</li> * <li>It is a legacy move and its {@link AbstractMove#isMoveDoable(ScoreDirector)} return {@code true}.</li> * </ul> * * @param moveDirector never null * @param move never null * @return true if the move is doable */ public static <Solution_> boolean isDoable(MoveDirector<Solution_, ?> moveDirector, Move<Solution_> move) { if (move instanceof LegacyMoveAdapter<Solution_> legacyMoveAdapter) { return legacyMoveAdapter.isMoveDoable(moveDirector); } else { return true; // New moves are always doable. } } @Override public void execute(MutableSolutionView<Solution_> solutionView) { var scoreDirector = getScoreDirector(solutionView); legacyMove.doMoveOnly(scoreDirector); } private ScoreDirector<Solution_> getScoreDirector(SolutionView<Solution_> solutionView) { return ((InnerMutableSolutionView<Solution_>) solutionView).getScoreDirector(); } @SuppressWarnings("unchecked") private ScoreDirector<Solution_> getScoreDirector(Rebaser rebaser) { return ((InnerMutableSolutionView<Solution_>) rebaser).getScoreDirector(); } public boolean isMoveDoable(SolutionView<Solution_> solutionView) { return legacyMove.isMoveDoable(getScoreDirector(solutionView)); } @Override public String describe() { return legacyMove.getSimpleMoveTypeDescription(); } @Override public Move<Solution_> rebase(Rebaser rebaser) { return new LegacyMoveAdapter<>(legacyMove.rebase(getScoreDirector(rebaser))); } @Override public Collection<?> extractPlanningEntities() { return legacyMove.getPlanningEntities(); } @Override public Collection<?> extractPlanningValues() { return legacyMove.getPlanningValues(); } @Override public String toString() { return legacyMove.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/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.solution.ProblemFactProperty; 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 #doMoveOnly(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. * It is highly recommended to override {@link #getPlanningEntities()} and {@link #getPlanningValues()}, * otherwise the resulting move will throw an exception when used with Tabu search. * * @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 * @deprecated Prefer {@link #doMoveOnly(ScoreDirector)} instead, undo moves no longer have any effect. */ @Deprecated(forRemoval = true, since = "1.16.0") default Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { throw new UnsupportedOperationException("Operation requires an undo move, which is no longer supported."); } /** * 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, * or the move may not be correctly undone. * <p> * This method must end with calling {@link ScoreDirector#triggerVariableListeners()} * to ensure all shadow variables are updated. * * @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 inverted, 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 {@link ProblemFactProperty problem facts}, * which are 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 #doMoveOnly(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 extractPlanningEntities() 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 #doMoveOnly(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 extractPlanningEntities() method, so Value Tabu Search is impossible." .formatted(getClass())); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/move/NoChangeMove.java
package ai.timefold.solver.core.impl.heuristic.move; import java.util.Collection; import java.util.Collections; 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 AbstractMove<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 Collection<?> getPlanningEntities() { return Collections.emptyList(); } @Override public Collection<?> getPlanningValues() { return Collections.emptyList(); } @Override public String getSimpleMoveTypeDescription() { return "No change"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/AbstractDemandEnabledSelector.java
package ai.timefold.solver.core.impl.heuristic.selector; import ai.timefold.solver.core.impl.domain.variable.supply.Demand; /** * It is expected that if two instances share the same properties, * they are {@link Object#equals(Object) equal} to one another. * This is necessary for proper performance of {@link Demand}-based caches, * such as pillar cache or nearby distance matrix cache. * * @param <Solution_> */ public abstract class AbstractDemandEnabledSelector<Solution_> extends AbstractSelector<Solution_> { @Override public abstract boolean equals(Object other); @Override public abstract int hashCode(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/AbstractSelector.java
package ai.timefold.solver.core.impl.heuristic.selector; import java.util.Random; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleSupport; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract superclass for {@link Selector}. * * @see AbstractDemandEnabledSelector */ public abstract class AbstractSelector<Solution_> implements Selector<Solution_> { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport = new PhaseLifecycleSupport<>(); protected Random workingRandom = null; @Override public void solvingStarted(SolverScope<Solution_> solverScope) { workingRandom = solverScope.getWorkingRandom(); phaseLifecycleSupport.fireSolvingStarted(solverScope); } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { phaseLifecycleSupport.firePhaseStarted(phaseScope); } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { phaseLifecycleSupport.fireStepStarted(stepScope); } @Override public void stepEnded(AbstractStepScope<Solution_> stepScope) { phaseLifecycleSupport.fireStepEnded(stepScope); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { phaseLifecycleSupport.firePhaseEnded(phaseScope); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { phaseLifecycleSupport.fireSolvingEnded(solverScope); workingRandom = null; } @Override public SelectionCacheType getCacheType() { return SelectionCacheType.JUST_IN_TIME; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/AbstractSelectorFactory.java
package ai.timefold.solver.core.impl.heuristic.selector; import ai.timefold.solver.core.config.heuristic.selector.SelectorConfig; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; import ai.timefold.solver.core.impl.AbstractFromConfigFactory; public abstract class AbstractSelectorFactory<Solution_, SelectorConfig_ extends SelectorConfig<SelectorConfig_>> extends AbstractFromConfigFactory<Solution_, SelectorConfig_> { protected AbstractSelectorFactory(SelectorConfig_ selectorConfig) { super(selectorConfig); } protected void validateCacheTypeVersusSelectionOrder(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { switch (resolvedSelectionOrder) { case INHERIT: throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") which should have been resolved by now."); case ORIGINAL: case RANDOM: break; case SORTED: case SHUFFLED: case PROBABILISTIC: if (resolvedCacheType.isNotCached()) { throw new IllegalArgumentException("The moveSelectorConfig (" + config + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder + ") which does not support the resolvedCacheType (" + resolvedCacheType + ")."); } break; default: throw new IllegalStateException("The resolvedSelectionOrder (" + resolvedSelectionOrder + ") is not implemented."); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/heuristic/selector/IterableSelector.java
package ai.timefold.solver.core.impl.heuristic.selector; import java.util.Spliterator; import java.util.Spliterators; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; public interface IterableSelector<Solution_, T> extends Selector<Solution_>, Iterable<T> { /** * A random JIT {@link Selector} with {@link #isNeverEnding()} true should return a size * as if it would be able to return each distinct element only once, * because the size can be used in {@link SelectionProbabilityWeightFactory}. * * @return the approximate number of elements generated by this {@link Selector}, always {@code >= 0} * @throws IllegalStateException if {@link #isCountable} returns false, * but not if only {@link #isNeverEnding()} returns true */ long getSize(); @Override default Spliterator<T> spliterator() { if (isCountable()) { return Spliterators.spliterator(iterator(), getSize(), Spliterator.ORDERED); } else { return Iterable.super.spliterator(); } } }